Imports System.ComponentModel.Design Imports System.Data.SqlClient Imports System.Net Imports System.Reflection Imports System.ServiceModel.Security Imports System.Threading Imports System.Windows.Forms Imports System.Windows.Forms.VisualStyles.VisualStyleElement Imports Chilkat Imports iTextSharp.text Imports Newtonsoft.Json.Linq Imports Org.BouncyCastle.Bcpg Imports VERAG_PROG_ALLGEMEIN.cCreditSafeAPI Public Class cDigicustSessions Public Property session_Id As Integer Public Property token As String Public Property datetime As DateTime = Now() Public Property refresh_token As String Public Property token_validuntil As DateTime Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL Public hasEntry As Boolean Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("session_Id", session_Id, , True, True)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("token", token)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("datetime", datetime)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("refresh_token", refresh_token)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("token_validuntil", token_validuntil)) Return list End Function Sub New() LOAD() End Sub Sub New(token As String, refreshtoken As String, timestamp As DateTime) Me.token = token Me.refresh_token = refreshtoken token_validuntil = timestamp SAVE() End Sub Public Function SAVE(Optional errHinweis = "") As Boolean Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList() Dim sqlstr = " BEGIN TRAN " & getInsertCmd() & " commit tran " Dim IdTMP = session_Id IdTMP = SQL.doSQLVarListID(IdTMP, sqlstr, "FMZOLL", , list, , errHinweis) If session_Id <= 0 Then session_Id = IdTMP Return session_Id > 0 End Function Public Function getInsertCmd() As String Try Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList() Dim str As String = "" Dim values As String = "" For Each i In list If Not i.isPrimaryParam Then str &= "[" & i.Text & "]," values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & "," End If Next str = str.Substring(0, str.Length - 1) 'wg. ',' values = values.Substring(0, values.Length - 1) 'wg. ',' Return (" INSERT INTO tblDigicust_Sessions (" & str & ") VALUES(" & values & ") ") Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try Return "" End Function Public Sub LOAD() Try hasEntry = False Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL() Using cmd As New SqlCommand("SELECT TOP(1) * FROM tblDigicust_Sessions where token_validuntil >= GetDate() order by datetime desc ", conn) Dim dr = cmd.ExecuteReader() If dr.Read Then For Each li In getParameterList() Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable) If dr.Item(li.Text) Is DBNull.Value Then propInfo.SetValue(Me, Nothing) Else propInfo.SetValue(Me, dr.Item(li.Text)) End If Next hasEntry = True End If dr.Close() End Using End Using Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try End Sub End Class Public Class cDigicustSettings Public Property Id As Integer Public Property customerId As String Public Property projectId As String Public Property executionStrategyId As String Public Property validUntil As DateTime Public Property valid As Boolean Public Property companyId As Integer Public Property description As String Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL Public hasEntry As Boolean Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Id", Id, , True, True)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("customerId", customerId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("projectId", projectId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("executionStrategyId", executionStrategyId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("validUntil", validUntil)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("valid", valid)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("companyId", companyId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("description", description)) Return list End Function Sub New(id) Me.Id = id LOAD() End Sub Public Sub LOAD() Try hasEntry = False Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL() Using cmd As New SqlCommand("SELECT * FROM tblDigicust_Settings where Id = @Id ", conn) cmd.Parameters.AddWithValue("@Id", Id) Dim dr = cmd.ExecuteReader() If dr.Read Then For Each li In getParameterList() Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable) If dr.Item(li.Text) Is DBNull.Value Then propInfo.SetValue(Me, Nothing) Else propInfo.SetValue(Me, dr.Item(li.Text)) End If Next hasEntry = True End If dr.Close() End Using End Using Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try End Sub End Class Public Class cDigicustSendungen Public Property Id As Integer Public Property reference As String Public Property digicustId As String Public Property status As String Public Property createdAt As DateTime Public Property modifiedAt As DateTime Public Property avisoId As Integer Public Property uploadedDocuments As Integer Public Property projectId As String Public Property companyId As String Public Property consignor_eori As String Public Property consignor_name As String Public Property consignor_address As String Public Property consignor_city_name As String Public Property consignor_country_id As String Public Property consignor_postcode As String Public Property consignee_eori As String Public Property consignee_name As String Public Property consignee_address As String Public Property consignee_city_name As String Public Property consignee_country_id As String Public Property consignee_postcode As String Public Property prepaper As String Public Property prepaper_code As String Public Property licencePlate As String Public Property lkwCountryId As String Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL Public hasEntry As Boolean Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Id", Id, , True, True)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("reference", reference)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("digicustId", digicustId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("status", status)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("createdAt", createdAt)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("modifiedAt", modifiedAt)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("avisoId", avisoId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("uploadedDocuments", uploadedDocuments)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("projectId", projectId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("companyId", companyId)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_eori", consignee_eori)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_name", consignee_name)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_address", consignee_address)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_city_name", consignee_city_name)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_country_id", consignee_country_id)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignee_postcode", consignee_postcode)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_eori", consignor_eori)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_name", consignor_name)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_address", consignor_address)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_city_name", consignor_city_name)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_country_id", consignor_country_id)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("consignor_postcode", consignor_postcode)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("prepaper", prepaper)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("prepaper_code", prepaper_code)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("licencePlate", licencePlate)) list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("lkwCountryId", lkwCountryId)) Return list End Function Sub New() End Sub Sub New(id As Integer) Me.Id = id LOAD() End Sub Public Function SAVE(Optional errHinweis = "") As Boolean Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList() Dim sqlstr = " BEGIN TRAN IF EXISTS(SELECT * FROM tblDigicust_Sendungen WITH(updlock,serializable) WHERE Id=@Id) " & " BEGIN " & getUpdateCmd() & " END " & " Else " & " BEGIN " & getInsertCmd() & " END " & " commit tran " Dim IdTMP = Id IdTMP = SQL.doSQLVarListID(IdTMP, sqlstr, "FMZOLL", , list, , errHinweis) If Id <= 0 Then Id = IdTMP Return Id > 0 End Function Public Function getInsertCmd() As String Try Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList() Dim str As String = "" Dim values As String = "" For Each i In list If Not i.isPrimaryParam Then str &= "[" & i.Text & "]," values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & "," End If Next str = str.Substring(0, str.Length - 1) 'wg. ',' values = values.Substring(0, values.Length - 1) 'wg. ',' Return (" INSERT INTO tblDigicust_Sendungen (" & str & ") VALUES(" & values & ") ") Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try Return "" End Function Public Function getUpdateCmd() As String Try Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList() Dim str As String = "" For Each i In list If Not i.isPrimaryParam Then str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & "," End If Next str = str.Substring(0, str.Length - 1) 'wg. ',' Return (" UPDATE [tblDigicust_Sendungen] SET " & str & " WHERE Id=@Id ") Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try Return "" End Function Public Sub LOAD() Try hasEntry = False Using conn As SqlConnection = SQL.GetNewOpenConnectionFMZOLL() Using cmd As New SqlCommand("SELECT * FROM tblDigicust_Sendungen where Id = @Id ", conn) cmd.Parameters.AddWithValue("@Id", Id) Dim dr = cmd.ExecuteReader() If dr.Read Then For Each li In getParameterList() Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable) If dr.Item(li.Text) Is DBNull.Value Then propInfo.SetValue(Me, Nothing) Else propInfo.SetValue(Me, dr.Item(li.Text)) End If Next hasEntry = True End If dr.Close() End Using End Using Catch ex As Exception VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try End Sub End Class Public Class cDigicustAPI 'PROD Shared API_STRING As String = "https://api.digicust.com" Shared token As String = "" Shared refresh_token As String = "" Public dataTable As New DataTable() Shared Function SendRequestAuthentificationToken(ByVal myuri As String, ByVal contentType As String, ByVal method As String, ByRef _token As String) As String Try Dim session = New cDigicustSessions() If Not IsDBNull(session.token) AndAlso session.token IsNot Nothing Then _token = session.token token = _token Return "200" End If VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat() Dim rest As New Chilkat.Rest Dim success As Boolean Dim bTls As Boolean = True Dim port As Integer = 443 Dim bAutoReconnect As Boolean = True success = rest.Connect(API_STRING, port, bTls, bAutoReconnect) If (success <> True) Then Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason) Debug.WriteLine(rest.LastErrorText) Return rest.LastErrorText End If Dim json As New Chilkat.JsonObject success = json.UpdateString("username", "edv@verag.ag") success = json.UpdateString("password", "hbG&%RhpE6kjV@r") rest.AddHeader("Content-Type", contentType) Dim sbRequestBody As New Chilkat.StringBuilder json.EmitSb(sbRequestBody) Dim sbResponseBody As New Chilkat.StringBuilder Dim ResponseStr = rest.FullRequestSb(method, myuri, sbRequestBody, sbResponseBody) If (rest.ResponseStatusCode <> 200) Then Return rest.ResponseStatusCode & " " & rest.ResponseStatusText End If Dim jsonResp = New Chilkat.JsonObject() jsonResp.LoadSb(sbResponseBody) _token = jsonResp.StringOf("access_token") token = _token refresh_token = jsonResp.StringOf("refresh_token") Dim now As DateTime = DateTime.Now() now = now.AddSeconds(jsonResp.IntOf("expires_in")) session = New cDigicustSessions(_token, refresh_token, now.ToString("yyyy-MM-dd HH:mm:ss")) Return rest.ResponseStatusCode & " " & rest.ResponseStatusText Catch ex As WebException VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name) End Try End Function Shared Function authenticate(ByRef token As String) As String Dim myUri As String = "/generic/api/auth/authenticate" Dim response = SendRequestAuthentificationToken(myUri, "application/json", "POST", token) Return response End Function Shared Function uploadingCase(dig As cDigicustSendungen, settings As cDigicustSettings, dgv As DataGridView) As Boolean Dim rest As New Chilkat.Rest Dim success As Boolean ' URL: https://api.digicust.com/upload/api/{customerId}/{projectId}/new Dim bTls As Boolean = True Dim port As Integer = 443 Dim bAutoReconnect As Boolean = True success = rest.Connect(API_STRING, port, bTls, bAutoReconnect) If (success <> True) Then Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason) Debug.WriteLine(rest.LastErrorText) Return False End If rest.VerboseLogging = True Dim counter As Integer = 1 Dim jsonFileArray = New Chilkat.JsonArray() For Each r As DataGridViewRow In dgv.Rows Dim isSelected = IIf(DBNull.Value Is r.Cells("anh_selekt").Value, False, r.Cells("anh_selekt").Value) If isSelected Then Dim j = 0 Dim json As Chilkat.JsonObject Dim filePath = VERAG_PROG_ALLGEMEIN.cDATENSERVER.GET_PDFPath_BY_DocID(r.Cells("anh_docId").Value) Dim filename = New System.IO.FileInfo(filePath).Name rest.PartSelector = counter Dim fileStream As New Chilkat.Stream fileStream.SourceFile = filePath rest.AddHeader("Content-Disposition", "form-data; name=""files[]""; filename=""" & filename & """") rest.AddHeader("Content-Type", "application/pdf") rest.SetMultipartBodyStream(fileStream) jsonFileArray.AddObjectAt(j) json = jsonFileArray.ObjectAt(j) json.UpdateString("fileName", filename) json.UpdateString("documentType", r.Cells("anh_Art").Value) Debug.WriteLine(jsonFileArray.Emit) counter += 1 j += 1 End If Next rest.PartSelector = counter rest.AddHeader("Content-Disposition", "form-data; name=""classifications""") rest.SetMultipartBodyString(jsonFileArray.Emit) counter += 1 rest.PartSelector = counter rest.AddHeader("Content-Disposition", "form-data; name=""executionStrategyId""") rest.SetMultipartBodyString(settings.executionStrategyId) counter += 1 rest.PartSelector = counter rest.AddHeader("Content-Disposition", "form-data; name=""reference""") rest.SetMultipartBodyString(dig.reference) counter += 1 ' createUserinput(rest, counter, dig) rest.PartSelector = "0" rest.AddHeader("Content-Type", "multipart/form-data") rest.AddHeader("Authorization", "Bearer " & token) rest.AddHeader("Expect", "100-continue") 'Debuging 'rest.DebugMode = True rest.IdleTimeoutMs = 60000 rest.SendReqMultipart("POST", "/upload/api/" & settings.customerId & "/" & settings.projectId & "/new") Dim responseStatusCode = rest.ReadResponseHeader() If (responseStatusCode < 0) Then For i = 0 To 15 'Versuche den Header 16x abzufragen (funktioniert ab und zu nicht). responseStatusCode = rest.ReadResponseHeader() If responseStatusCode > 0 Then Exit For Thread.Sleep(3000) i = i + 1 Next If rest.ResponseStatusCode <> 200 Then MsgBox(rest.LastErrorText) Return False End If End If If (rest.LastMethodSuccess <> True) Then MsgBox(rest.LastErrorText) Return False End If Dim responseBodyStr As String = rest.ReadRespBodyString() If (rest.LastMethodSuccess <> True) Then MsgBox(rest.LastErrorText) Return False End If Dim respStatusCode As Integer = rest.ResponseStatusCode Debug.WriteLine("response status code = " & respStatusCode) If (respStatusCode >= 400) Then Debug.WriteLine("Response Status Code = " & respStatusCode) Debug.WriteLine("Response Header:") Debug.WriteLine(rest.ResponseHeader) Debug.WriteLine("Response Body:") Debug.WriteLine(responseBodyStr) Return False End If Dim jsonResp = New Chilkat.JsonObject() jsonResp.Load(responseBodyStr) Dim dateTime As New Chilkat.CkDateTime Dim getAsLocal As Boolean = False jsonResp.DateOf("result.createdAt", dateTime) dig.createdAt = dateTime.GetAsTimestamp(getAsLocal) dig.modifiedAt = dateTime.GetAsTimestamp(getAsLocal) dig.status = jsonResp.StringOf("result.status.value") dig.digicustId = jsonResp.StringOf("result.id") dig.uploadedDocuments = jsonResp.SizeOfArray("result.uploadedFiles") dig.projectId = jsonResp.StringOf("result.projectId") dig.companyId = jsonResp.StringOf("result.customerId") Return True End Function Shared Function fetchingCase(sendung As cDigicustSendungen) As Boolean Dim rest As New Chilkat.Rest Dim success As Boolean ' URL: https://api.digicust.com/generic/api///cases/ Dim bTls As Boolean = True Dim port As Integer = 443 Dim bAutoReconnect As Boolean = True success = rest.Connect(API_STRING, port, bTls, bAutoReconnect) If (success <> True) Then Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason) Debug.WriteLine(rest.LastErrorText) Return False End If Dim session = New cDigicustSessions() If Not IsDBNull(session.token) AndAlso session.token IsNot Nothing Then token = session.token Else authenticate("") End If rest.AddHeader("accept", "application/json") rest.AddHeader("Authorization", "Bearer " & token) Dim sbResponseBody As New Chilkat.StringBuilder success = rest.FullRequestNoBodySb("GET", "/generic/api/" & sendung.companyId & "/" & sendung.projectId & "/cases/" & sendung.digicustId, sbResponseBody) If (success <> True) Then Debug.WriteLine(rest.LastErrorText) Return False End If Dim respStatusCode As Integer = rest.ResponseStatusCode Debug.WriteLine("response status code = " & respStatusCode) If (respStatusCode >= 400) Then Debug.WriteLine("Response Status Code = " & respStatusCode) Debug.WriteLine("Response Header:") Debug.WriteLine(rest.ResponseHeader) Debug.WriteLine("Response Body:") Debug.WriteLine(sbResponseBody.GetAsString()) Return False End If Dim jsonResp = New Chilkat.JsonObject() jsonResp.LoadSb(sbResponseBody) sendung.status = jsonResp.StringOf("status.value") 'Dim dateTime As New Chilkat.CkDateTime 'Dim getAsLocal As Boolean = False 'jsonResp.DateOf("status.modifiedAt", dateTime) sendung.modifiedAt = Now() sendung.uploadedDocuments = jsonResp.SizeOfArray("uploadedFiles") sendung.SAVE() End Function Shared Function createUserinput(ByRef rest As Chilkat.Rest, ByRef counter As Integer, ByVal sendung As cDigicustSendungen) 'beforeNormalization(fallback -> falls Daten nicht gelesen werden können, wird ergänzt) 'afterNormalization(overwrite -> werden mit mitgeschickten Infos überschrieben). Dim json As New Chilkat.JsonObject If sendung.licencePlate <> "" Then json.UpdateString("truckLicensePlate", sendung.licencePlate) End If If sendung.lkwCountryId <> "" Then json.UpdateString("truckNationality", sendung.lkwCountryId) End If rest.PartSelector = counter rest.AddHeader("Content-Disposition", "form-data; name=""documents""") rest.SetMultipartBodyString("[{""priority"":""afterNormalization"",""annotatedAggregated"":{" & json.Emit & "}}]") counter += 1 End Function End Class