File watcher Plugin  Topic is solved

Discussions relating to plugin development, and the Jiwa API.

File watcher Plugin

Postby JohnBiddick » Fri Aug 01, 2014 11:03 am

Our File watcher Plug in contains errors. The method we were advised to use was to copy the code from the existing File Watcher Plug in, and name the plug in differently. This was to avoid any issues with changes made to the standard File watcher plug in, in future issues. We copied the code, compiled the code and received a number of errors. We are on V072
The code is
Imports JiwaFinancials.Jiwa
Imports Microsoft.VisualBasic
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Data
Imports System.IO
Imports Microsoft.VisualBasic.FileIO.TextFieldParser

Public Class FormPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaFormPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub SetupBeforeHandlers(ByVal JiwaForm As JiwaApplication.IJiwaForm, ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaFormPlugin.SetupBeforeHandlers
End Sub

Public Sub Setup(ByVal JiwaForm As JiwaApplication.IJiwaForm, ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaFormPlugin.Setup
End Sub
End Class

Public Class BusinessLogicPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaBusinessLogicPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub Setup(ByVal JiwaBusinessLogic As JiwaApplication.IJiwaBusinessLogic, ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaBusinessLogicPlugin.Setup
End Sub

End Class

Public Class ApplicationManagerPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaApplicationManagerPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub Setup(ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaApplicationManagerPlugin.Setup
End Sub

End Class

Public Class CustomFieldPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaCustomFieldPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub FormatCell(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal HostObject As JiwaApplication.IJiwaCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaCustomFieldPlugin.FormatCell
End Sub

Public Sub ReadData(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Row As Integer, ByVal HostObject As JiwaApplication.IJiwaCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaCustomFieldPlugin.ReadData
End Sub

Public Sub ButtonClicked(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal HostObject As JiwaApplication.IJiwaCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaCustomFieldPlugin.ButtonClicked
End Sub

End Class

Public Class LineCustomFieldPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaLineCustomFieldPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub FormatCell(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal HostItem As JiwaApplication.IJiwaLineCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaLineCustomFieldPlugin.FormatCell
End Sub

Public Sub ReadData(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Row As Integer, ByVal HostItem As JiwaApplication.IJiwaLineCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaLineCustomFieldPlugin.ReadData
End Sub

Public Sub ButtonClicked(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal HostItem As JiwaApplication.IJiwaLineCustomFieldValues, ByVal CustomField As JiwaApplication.CustomFields.CustomField, ByVal CustomFieldValue As JiwaApplication.CustomFields.CustomFieldValue) Implements JiwaApplication.IJiwaLineCustomFieldPlugin.ButtonClicked
End Sub

End Class

Public Class SystemSettingPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaSystemSettingPlugin

Public Overrides Function InitializeLifetimeService() As Object
' returning null here will prevent the lease manager
' from deleting the Object.
Return Nothing
End Function

Public Sub FormatCell(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal SystemSetting As JiwaApplication.SystemSettings.Setting) Implements JiwaApplication.IJiwaSystemSettingPlugin.FormatCell
End Sub

Public Sub ReadData(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Row As Integer, ByVal SystemSetting As JiwaApplication.SystemSettings.Setting) Implements JiwaApplication.IJiwaSystemSettingPlugin.ReadData
End Sub

Public Sub ButtonClicked(ByVal BusinessLogicHost As JiwaApplication.IJiwaBusinessLogic, ByVal GridObject As JiwaApplication.Controls.JiwaGrid, ByVal FormObject As JiwaApplication.IJiwaForm, ByVal Col As Integer, ByVal Row As Integer, ByVal SystemSetting As JiwaApplication.SystemSettings.Setting) Implements JiwaApplication.IJiwaSystemSettingPlugin.ButtonClicked
End Sub

End Class

Public Class ScheduledExecutionPlugin
Inherits System.MarshalByRefObject
Implements JiwaApplication.IJiwaScheduledExecutionPlugin

Private _plugin As JiwaApplication.Plugin.Plugin
Private XMLWatcher As JiwaFileWatcher
Private CSVSalesOrderWatcher As JiwaFileWatcher
Private CSVPaxarWatcher As JiwaFileWatcher
Private CSVWageEasyWatcher As JiwaFileWatcher
Private CSVJournalWatcher As JiwaFileWatcher
Private CSVPurchaseOrderWatcher As JiwaFileWatcher
Private XMLQueueWatcher As JiwaFileWatcher

Public Sub Execute(ByVal Plugin As JiwaApplication.Plugin.Plugin, ByVal Schedule As JiwaApplication.Schedule.Schedule) Implements JiwaApplication.IJiwaScheduledExecutionPlugin.Execute

End Sub

Public Sub OnServiceStart(ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaScheduledExecutionPlugin.OnServiceStart
_plugin = Plugin

' Start watching the folders
XMLWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\XML")
AddHandler XMLWatcher.FileImport, AddressOf XMLFileImport
XMLWatcher.ImportAllFilesInWatchFolder()

CSVSalesOrderWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\CSV\Sales Orders")
AddHandler CSVSalesOrderWatcher.FileImport, AddressOf CSVSalesOrderImport
CSVSalesOrderWatcher.ImportAllFilesInWatchFolder()

CSVPaxarWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\CSV\Paxar")
AddHandler CSVPaxarWatcher.FileImport, AddressOf CSVPaxarImport
CSVPaxarWatcher.ImportAllFilesInWatchFolder()

CSVWageEasyWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\CSV\Wage Easy Journals")
AddHandler CSVWageEasyWatcher.FileImport, AddressOf CSVWageEasyImport
CSVWageEasyWatcher.ImportAllFilesInWatchFolder()

CSVJournalWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\CSV\Journals")
AddHandler CSVJournalWatcher.FileImport, AddressOf CSVJournalImport
CSVJournalWatcher.ImportAllFilesInWatchFolder()

CSVPurchaseOrderWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\CSV\Purchase Orders")
AddHandler CSVPurchaseOrderWatcher.FileImport, AddressOf CSVPurchaseOrderImport
CSVPurchaseOrderWatcher.ImportAllFilesInWatchFolder()

XMLQueueWatcher = New JiwaFileWatcher(Plugin, "C:\ProgramData\Jiwa Financials\Jiwa 7\Import\XML Queue")
AddHandler XMLQueueWatcher.FileImport, AddressOf XMLQueueImport
XMLQueueWatcher.ImportAllFilesInWatchFolder()
End Sub

Public Sub OnServiceStopping(ByVal Plugin As JiwaApplication.Plugin.Plugin) Implements JiwaApplication.IJiwaScheduledExecutionPlugin.OnServiceStopping
If Not XMLWatcher Is Nothing Then
XMLWatcher.StopWatching
End If

If Not CSVSalesOrderWatcher Is Nothing Then
CSVSalesOrderWatcher.StopWatching
End If

If Not CSVPaxarWatcher Is Nothing Then
CSVPaxarWatcher.StopWatching
End If

If Not CSVWageEasyWatcher Is Nothing Then
CSVWageEasyWatcher.StopWatching
End If

If Not CSVJournalWatcher Is Nothing Then
CSVJournalWatcher.StopWatching
End If

If Not CSVPurchaseOrderWatcher Is Nothing Then
CSVPurchaseOrderWatcher.StopWatching
End If

If Not XMLQueueWatcher Is Nothing Then
XMLQueueWatcher.StopWatching
End If
End Sub

Private Sub XMLFileImport(ByVal FileName As String)
' Import the file using the import queue manager
Dim importQueueManager As JiwaImportQManager.ImportQueueItemCollection = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaImportQManager.ImportQueueItemCollection)

Dim queueItem As New JiwaImportQManager.ImportQueueItem
queueItem.TransformedXML = File.ReadAllText(FileName)
queueItem.Status = JiwaImportQManager.ImportQueueItem.ImportQueueItemStatuses.ReadyForImport
importQueueManager.Add(queueItem)
queueItem.Process()
End Sub

Private Sub CSVSalesOrderImport(ByVal FileName As String)
'SAMPLE CSV INPUT FILE
'=======================================================================
'OrderNo,OrderDate,DebtorAccountNo,PartNo,QuantityOrdered,PriceExGST
'
'File contents:
'
'000100,2006-05-30,1001,1170,5,15.45
'000100,2006-05-30,1001,1171,5,15.45
'000100,2006-05-30,1001,1172,5,15.45
'000100,2006-05-30,1001,1173,5,15.45
'000101,2006-06-01,1002,1170,5,15.45
'000101,2006-06-01,1002,1171,5,15.45
'000101,2006-06-01,1002,1172,5,15.45
'000102,2006-06-02,1003,1173,5,15.45
'
'=======================================================================
Dim salesOrder As JiwaSales.SalesOrder.SalesOrder = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaSales.SalesOrder.SalesOrder)

Using csvParser As New FileIO.TextFieldParser(FileName)
csvParser.TextFieldType = FileIO.FieldType.Delimited
csvParser.Delimiters = New String() {","}
csvParser.HasFieldsEnclosedInQuotes = False

Dim csvFields As String()
Dim previousOrderNo As String = Nothing
Dim newKey As String = ""
Dim debtor As JiwaApplication.Entities.Debtor.Debtor = New JiwaApplication.Entities.Debtor.Debtor
Dim inventory As JiwaApplication.Entities.Inventory.Inventory = New JiwaApplication.Entities.Inventory.Inventory

Do While Not csvParser.EndOfData
csvFields = csvParser.ReadFields

If Not previousOrderNo Is Nothing AndAlso csvFields(0) <> previousOrderNo Then
' The order No. has changed - save the currently assembled sales order
salesOrder.Save()
CSVSalesOrderWatcher.LogToEventLog(String.Format("Imported Sales Order Invoice No. '{0}' With Order No. '{1}' from File '{2}'", salesOrder.InvoiceNo, salesOrder.OrderNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

If previousOrderNo Is Nothing OrElse csvFields(0) <> previousOrderNo Then
' Create a new order
debtor.ReadRecordFromAccountNo(csvFields(2))
salesOrder.CreateNew(JiwaSales.SalesOrder.SalesOrder.NewSalesOrderTypes.e_NewSalesOrder, debtor.DebtorID)
salesOrder.OrderNo = csvFields(0)
salesOrder.InitiatedDate = csvFields(1)
End If

inventory.ReadRecordFromPartNo(csvFields(3))

salesOrder.SalesOrderLines.AddInventoryItem(inventory.InventoryID, JiwaSales.SalesOrder.SalesOrderLineCollection.SalesOrderLineInventorySeedTypes.e_SalesOrderLineInventoryID, newKey)
salesOrder.SalesOrderLines(newKey).QuantityOrdered = csvFields(4)
salesOrder.SalesOrderLines(newKey).DiscountedPrice = csvFields(5)

previousOrderNo = csvFields(0)
Loop

If salesOrder.SalesOrderLines.Count > 0 Then
salesOrder.Save()
CSVSalesOrderWatcher.LogToEventLog(String.Format("Imported Sales Order Invoice No. '{0}' With Order No. '{1}' from File '{2}'", salesOrder.InvoiceNo, salesOrder.OrderNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

End Using
End Sub

Private Sub CSVPaxarImport(ByVal FileName As String)
'SAMPLE CSV INPUT FILE
'=======================================================================
'Column 3 = Invoice No.
'Column 35 = Quantity Picked
'Column 36 = Invoice Line ID
'
'File contents:
'
',,100487,20060919,1436,8667020004748,,331771,20060919,C,331771,20060919,20060919,20060919,09A735096C074FB7A,1.0,0.05,1,Toll Ipec,,,,,,09A735096C074FB7A,331771,D01 - Inserted By Mathew 19/09,brodie,2,VSM-On-M,,,9336920000013,B22B,1,0577553ac5564f7da934,,,,,
',,100487,20060919,1436,8667020004748,,331771,20060919,C,331771,20060919,20060919,20060919,09A735096C074FB7A,1.0,0.05,1,Toll Ipec,,,,,,09A735096C074FB7A,331771,D01 - Inserted By Mathew 19/09,brodie,3,VSM-On-XL,,,9336920000037,B22B,2,5e4181ee9f2441f99f69,,,,,
'
'=======================================================================
Dim salesOrder As JiwaSales.SalesOrder.SalesOrder = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaSales.SalesOrder.SalesOrder)

Using csvParser As New FileIO.TextFieldParser(FileName)
csvParser.TextFieldType = FileIO.FieldType.Delimited
csvParser.Delimiters = New String() {","}
csvParser.HasFieldsEnclosedInQuotes = False

Dim csvFields As String()
Dim previousInvoiceNo As String = Nothing

Do While Not csvParser.EndOfData
csvFields = csvParser.ReadFields

If Not previousInvoiceNo Is Nothing AndAlso csvFields(2) <> previousInvoiceNo Then
' The order No. has changed - save the sales order
salesOrder.Save()
CSVPaxarWatcher.LogToEventLog(String.Format("Updated Sales Order Invoice No. '{0}' from Paxar CSV File '{1}'", salesOrder.InvoiceNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

If previousInvoiceNo Is Nothing OrElse csvFields(2) <> previousInvoiceNo Then
' Read the order
salesOrder.Find(JiwaApplication.IJiwaNavigable.ReadModes.Actual, "SO_Main.InvoiceNo", csvFields(2), "")
End If

For Each salesOrderLine As JiwaSales.SalesOrder.SalesOrderLine In SalesOrder.SalesOrderLines
If salesOrderLine.RecID = csvFields(35) Then
salesOrderLine.QuantityThisDelivery = CDec(csvFields(34))
salesOrderLine.QuantityDemand = salesOrderLine.QuantityBackOrdered ' Force any backorders onto demand.
salesOrderLine.Picked = True
Exit For
End If
Next

previousInvoiceNo = csvFields(2)
Loop

If salesOrder.SalesOrderLines.Count > 0 Then
salesOrder.Save()
CSVPaxarWatcher.LogToEventLog(String.Format("Updated Sales Order Invoice No. '{0}' from Paxar CSV File '{1}'", salesOrder.InvoiceNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

End Using
End Sub

Private Sub CSVWageEasyImport(ByVal FileName As String)
'1) 2 digit number between 1 & 12 entered by the user. No specific use
'2) Date dd/mm/yyyy
'3) "G" - stands For general ledger batch
'4) G/L account code - up To 20 chars
'5) batch reference - will always contain the word "PAY" + the 2 digit number
'In 1st column above
'6) transaction reference - a description Of Each line item
'7) amount - negative (ie credit) amounts will contain preceeding -sign
'8) 0,0,"","" - these fields are Not used by payroll so will always contain
'these same settings
'
'SAMPLE CSV INPUT FILE
'=======================================================================
'Unused, TransPostDateTime/PostDateTime, Unused, AccountNo, Description, Reference, Amount, Unused, Unused, Unused, Unused
'
'File contents:
'
'"01","24/10/2014","G","4160-900-00","PAY (01)","Super (SS) ",-300.00,0,0,"",""
'"01","24/10/2014","G","4160-900-00","PAY (01)","Super Contr. ",-85.00,0,0,"",""
'"01","24/10/2014","G","4160-900-00","PAY (01)","Social Club ",-4.00,0,0,"",""
'"01","24/10/2014","G","4160-900-00","PAY (01)","Super (SS) ",-150.00,0,0,"",""
'"01","24/10/2014","G","4160-900-00","PAY (01)","Social Club ",-4.00,0,0,"",""
'"01","24/10/2014","G","6010-200-00","PAY (01)","Ordinary",13333.35,0,0,"",""
'"01","24/10/2014","G","6010-200-00","PAY (01)","Ordinary",5700.02,0,0,"",""
'"01","24/10/2014","G","6010-200-00","PAY (01)","Ordinary",3032.27,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Net",-10345.35,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Tax",-2599.00,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Net",-3890.02,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Tax",-1656.00,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Net",-1618.27,0,0,"",""
'"01","24/10/2014","G","4140-900-00","PAY (01)","Tax",-1414.00,0,0,"",""
'
'=======================================================================
Dim journalSet As JiwaJournalSets.JournalSet = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaJournalSets.JournalSet)

Using csvParser As New FileIO.TextFieldParser(FileName)
csvParser.TextFieldType = FileIO.FieldType.Delimited
csvParser.Delimiters = New String() {","}
csvParser.HasFieldsEnclosedInQuotes = True

Dim csvFields As String()
journalSet.CreateNew

Do While Not csvParser.EndOfData
csvFields = csvParser.ReadFields

Dim journalLine As New JiwaJournalSets.Line
journalLine.GLAccount.ReadRecordFromAccountNo(csvFields(3))
journalLine.TransPostDateTime = csvFields(1)
journalLine.Reference = csvFields(4)
If CDec(csvFields(6)) > 0 Then
journalLine.DebitAmount = System.Math.Abs(CDec(csvFields(6)))
Else
journalLine.CreditAmount = System.Math.Abs(CDec(csvFields(6)))
End If

journalSet.Lines.Add(journalLine)
Loop

If journalSet.Lines.count > 0 Then
journalSet.PostedDate = journalSet.Lines(1).TransPostDateTime
journalSet.Description = journalSet.Lines(1).Reference
journalSet.Save()
CSVWageEasyWatcher.LogToEventLog(String.Format("Created Journal Set No. '{0}' from Wage Easy CSV File '{1}'", journalSet.SetNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

End Using
End Sub

Private Sub CSVJournalImport(ByVal FileName As String)
'1) Set Type (Normal / Pending / Errored)
'2) Date dd/mm/yyyy
'3) G/L account code - up To 20 chars
'4) Batch reference
'5) Transaction reference - a description Of Each line item
'6) Amount - negative (ie credit) amounts will contain preceeding -sign
'these same settings
'
'SAMPLE CSV INPUT FILE
'=======================================================================
'SetType, TransPostDateTime/PostDateTime, AccountNo, Description, Reference, Amount
'
'File contents:
'
'"Pending","24/10/2012","2015-200-00","PAY (01)","Super (SS)",-300.00
'"Pending","24/10/2012","2810-000-03","PAY (01)","Other",200.00
'"Pending","24/10/2012","2810-000-02","PAY (01)","Sundry",100.00
'
'=======================================================================
Dim journalSet As JiwaJournalSets.JournalSet = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaJournalSets.JournalSet)

Using csvParser As New FileIO.TextFieldParser(FileName)
csvParser.TextFieldType = FileIO.FieldType.Delimited
csvParser.Delimiters = New String() {","}
csvParser.HasFieldsEnclosedInQuotes = True

Dim csvFields As String()
journalSet.CreateNew

Do While Not csvParser.EndOfData
csvFields = csvParser.ReadFields

Dim journalLine As New JiwaJournalSets.Line
journalLine.GLAccount.ReadRecordFromAccountNo(csvFields(2))
journalLine.TransPostDateTime = csvFields(1)
journalLine.Reference = csvFields(3)
journalLine.Remark = csvFields(4)
If CDec(csvFields(5)) > 0 Then
journalLine.DebitAmount = System.Math.Abs(CDec(csvFields(5)))
Else
journalLine.CreditAmount = System.Math.Abs(CDec(csvFields(5)))
End If

Select Case csvFields(0).ToString.ToLower
Case "pending"
journalset.SetType = JiwaJournalSets.JournalSet.SetTypes.Pending
End Select

journalSet.Lines.Add(journalLine)
Loop

If journalSet.Lines.count > 0 Then
journalSet.PostedDate = journalSet.Lines(1).TransPostDateTime
journalSet.Description = journalSet.Lines(1).Reference
journalSet.Save()
CSVJournalWatcher.LogToEventLog(String.Format("Created Journal Set No. '{0}' from CSV File '{1}'", journalSet.SetNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

End Using
End Sub

Private Sub CSVPurchaseOrderImport(ByVal FileName As String)
'SAMPLE CSV INPUT FILE
'=======================================================================
'AccountNo,OrderNo,OrderedDate,PartNo,Quantity,HomeLandedCost
'
'File contents:
'
'5001,100600,28/05/2014,1170,3,105
'5001,100601,23/06/2014,1171,1,80.85
'5001,100602,23/06/2014,1171,2,80.85
'5001,100603,19/06/2014,1171,2,80.85
'5001,100604,19/06/2014,1170,2,105
'5001,100605,25/06/2014,1171,8,80.85
'5010,100606,24/06/2014,1172,4,55
'5010,100607,26/06/2014,1172,60,55
'5015,100608,30/05/2014,120173,1,788
'5015,100609,19/06/2014,12609,2,890
'5015,100610,19/06/2014,12611,2,46.5
'
'=======================================================================
Dim purchaseOrder As JiwaPurchaseOrders.PurchaseOrder = JiwaApplication.Manager.Instance.BusinessLogicFactory.CreateBusinessLogic(Of JiwaPurchaseOrders.PurchaseOrder)

Using csvParser As New FileIO.TextFieldParser(FileName)
csvParser.TextFieldType = FileIO.FieldType.Delimited
csvParser.Delimiters = New String() {","}
csvParser.HasFieldsEnclosedInQuotes = False

Dim csvFields As String()
Dim previousOrderNo As String = Nothing
Dim inventory As JiwaApplication.Entities.Inventory.Inventory = New JiwaApplication.Entities.Inventory.Inventory
Dim NewLineKey As String = ""

Do While Not csvParser.EndOfData
csvFields = csvParser.ReadFields

If Not previousOrderNo Is Nothing AndAlso csvFields(1) <> previousOrderNo Then
' The order No. has changed - save the currently assembled purchase order
purchaseOrder.Save()
CSVPurchaseOrderWatcher.LogToEventLog(String.Format("Imported Purchase Order No. '{0}' from File '{1}'", purchaseOrder.OrderNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

If previousOrderNo Is Nothing OrElse csvFields(1) <> previousOrderNo Then
' Create a new order
purchaseOrder.CreateNew(JiwaPurchaseOrders.PurchaseOrder.SupplierType.Creditor, JiwaPurchaseOrders.PurchaseOrder.NewOrderSeedTypes.CreditorAccountNo, csvFields(0), JiwaPurchaseOrders.PurchaseOrder.PurchaseOrderType.DefaultOrderType)
purchaseOrder.OrderNo = csvFields(1)
purchaseOrder.OrderDate = csvFields(2)
End If

inventory.ReadRecordFromPartNo(csvFields(3))
purchaseOrder.Lines.AddInventoryItem(inventory.InventoryID, NewLineKey)
purchaseOrder.Lines(NewLineKey).Quantity = CDec(csvFields(4))
purchaseOrder.Lines(NewLineKey).Cost = CDec(csvFields(5))

previousOrderNo = csvFields(1)
Loop

If purchaseOrder.Lines.Count > 0 Then
purchaseOrder.Save()
CSVPurchaseOrderWatcher.LogToEventLog(String.Format("Imported Purchase Order No. '{0}' from File '{1}'", purchaseOrder.OrderNo, FileName), System.Diagnostics.EventLogEntryType.SuccessAudit)
End If

End Using
End Sub

Public Sub XMLQueueImport(ByVal FileName As String)
Dim SQLParam As SqlParameter

' Read the file contents
Dim fileText As String = File.ReadAllText(FileName)
Dim XMLDocument As New System.Xml.XmlDocument
XMLDocument.LoadXml(fileText)

' Insert into the table
With JiwaApplication.Manager.Instance.Database
Dim SQL As String = "INSERT INTO IM_ImportQueue(ImportQueueID, OriginalXML, TransformedXML, Status, AddedToQueueDateTime, AddedToQueueByStaffID, LastSavedDateTime, LastSavedByStaffID, ImportErrorMessage, ImportBatchID, BatchNo, ItemNo, ImportSuccessMessage) " &
"SELECT NewID()" &
", @OriginalXML" &
", @TransformedXML" &
", @Status" &
", @AddedToQueueDateTime" &
", @AddedToQueueByStaffID" &
", @LastSavedDateTime" &
", @LastSavedByStaffID" &
", @ImportErrorMessage" &
", @ImportBatchID" &
", @BatchNo" &
", @ItemNo" &
", @ImportSuccessMessage"

Using SQLCmd As SqlCommand = New SqlCommand(SQL, .SQLConnection, .SQLTransaction)
SQLParam = New SqlParameter("@OriginalXML", System.Data.SqlDbType.Text)
SQLParam.Value = XMLDocument.OuterXml
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@TransformedXML", System.Data.SqlDbType.Text)
SQLParam.Value = XMLDocument.OuterXml
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@Status", System.Data.SqlDbType.TinyInt)
SQLParam.Value = 0
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@AddedToQueueDateTime", System.Data.SqlDbType.DateTime)
SQLParam.Value = Now
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@AddedToQueueByStaffID", System.Data.SqlDbType.Char)
SQLParam.Value = JiwaApplication.Manager.Instance.Staff.RecID
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@LastSavedDateTime", System.Data.SqlDbType.DateTime)
SQLParam.Value = Now
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@LastSavedByStaffID", System.Data.SqlDbType.Char)
SQLParam.Value = JiwaApplication.Manager.Instance.Staff.RecID
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@ImportErrorMessage", System.Data.SqlDbType.VarChar)
SQLParam.Value = ""
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@ImportBatchID", System.Data.SqlDbType.Char)
SQLParam.Value = ""
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@BatchNo", System.Data.SqlDbType.Char)
SQLParam.Value = ""
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@ItemNo", System.Data.SqlDbType.Int)
SQLParam.Value = 0
SQLCmd.Parameters.Add(SQLParam)

SQLParam = New SqlParameter("@ImportSuccessMessage", System.Data.SqlDbType.VarChar)
SQLParam.Value = ""
SQLCmd.Parameters.Add(SQLParam)

SQLCmd.ExecuteNonQuery()
End Using
End With
End Sub
End Class

Public Class JiwaFileWatcher
Private Plugin As JiwaApplication.Plugin.Plugin
Public Property FileSystemWatcher As FileSystemWatcher
Public Property BaseFolder As String

Public Event FileImport(ByVal FullPath As String)

Public ReadOnly Property WatchFolder As String
Get
Return Path.Combine(BaseFolder, "Watch")
End Get
End Property

Public ReadOnly Property PendingFolder As String
Get
Return Path.Combine(BaseFolder, "Pending")
End Get
End Property

Public ReadOnly Property FailedFolder As String
Get
Return Path.Combine(BaseFolder, "Failed")
End Get
End Property

Public ReadOnly Property SucceededFolder As String
Get
Return Path.Combine(BaseFolder, "Succeeded")
End Get
End Property

Public Sub New(Plugin As JiwaApplication.Plugin.Plugin, ByVal BaseFolder As String)
Me.BaseFolder = BaseFolder
Me.Plugin = Plugin

If Not System.IO.Directory.Exists(Me.BaseFolder) Then
System.IO.Directory.CreateDirectory(Me.BaseFolder)
End If

If Not System.IO.Directory.Exists(Me.WatchFolder) Then
System.IO.Directory.CreateDirectory(Me.WatchFolder)
End If

If Not System.IO.Directory.Exists(Me.PendingFolder) Then
System.IO.Directory.CreateDirectory(Me.PendingFolder)
End If

If Not System.IO.Directory.Exists(Me.FailedFolder) Then
System.IO.Directory.CreateDirectory(Me.FailedFolder)
End If

If Not System.IO.Directory.Exists(Me.SucceededFolder) Then
System.IO.Directory.CreateDirectory(Me.SucceededFolder)
End If

FileSystemWatcher = New FileSystemWatcher
FileSystemWatcher.Path = Me.WatchFolder
FileSystemWatcher.NotifyFilter = (NotifyFilters.LastWrite Or NotifyFilters.FileName)
FileSystemWatcher.Filter = "*.*"
FileSystemWatcher.EnableRaisingEvents = True

AddHandler FileSystemWatcher.Created, AddressOf OnCreated

LogToEventLog(String.Format("Started monitoring folder: '{0}'", Me.WatchFolder), System.Diagnostics.EventLogEntryType.SuccessAudit)
End Sub

Public Sub ImportAllFilesInWatchFolder()
' Import any files already in the watch folder
For Each file As String In System.IO.Directory.EnumerateFiles(Me.WatchFolder)
OnFileImport(file)
Next
End Sub

Private Sub OnFileImport(ByVal FullPath As String)
If System.IO.File.Exists(FullPath) Then
Dim pendingFileNameAndPath As String = Path.Combine(Me.PendingFolder, System.IO.Path.GetFileName(FullPath)) & "." & now.ToString("yyyy-MM-ddTHmmss.FFF")

Try
' Wait until we can get exclusive access, or until we exceed the retry period.
Dim retryCount As Integer = 0
Dim maxRetries As Integer = 5

Do While True
Try
Using fs As New FileStream(FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 100)
fs.ReadByte
Exit Do
End Using
Catch ex As System.Exception
If retryCount > maxRetries Then
Exit Do
Else
retryCount += 1
System.Threading.Thread.Sleep(500)
End If
End Try
Loop

' Move to pending folder
System.IO.File.Move(Path.Combine(Me.WatchFolder, System.IO.Path.GetFileName(FullPath)), pendingFileNameAndPath)

' Raise the event so the work is done
RaiseEvent FileImport(pendingFileNameAndPath)

' Move to succeeded folder
System.IO.File.Move(pendingFileNameAndPath, Path.Combine(Me.SucceededFolder, System.IO.Path.GetFileName(pendingFileNameAndPath)))

LogToEventLog(String.Format("Imported File '{0}'", FullPath), System.Diagnostics.EventLogEntryType.SuccessAudit)
Catch ex As System.Exception
' Move to failed folder
System.IO.File.Move(pendingFileNameAndPath, Path.Combine(Me.FailedFolder, System.IO.Path.GetFileName(pendingFileNameAndPath)))
LogToEventLog(String.Format("Failed to import File '{0}' - Error: {1}", FullPath, ex.Message), System.Diagnostics.EventLogEntryType.FailureAudit)

'Dim email As JiwaApplication.JiwaEmail.EmailMessage = JiwaApplication.BusinessLogicFactory.Instance.CreateBusinessLogic(Of JiwaApplication.JiwaEmail.EmailMessage)
'email.SystemSettings.UseOutlookForEmail = False ' Cannot use outlook from within a Windows Service - make sure your other system settings like SMTP server are configured.
'email.CreateNew()
'email.EmailTo = "[email protected]"
'email.EmailSubject = "test email"
'email.EmailBody = String.Format("Document '{0}' failed to import - error message is '{1}'", pendingFileNameAndPath, ex.Message)
'email.Save()
End Try
End If
End Sub

Private Sub OnCreated(source As Object, e As FileSystemEventArgs)
OnFileImport(e.FullPath)
End Sub

Public Sub StopWatching()
RemoveHandler FileSystemWatcher.Created, AddressOf OnCreated
End Sub

Public Sub LogToEventLog(ByVal Message As String, ByVal EventLogEntryType As System.Diagnostics.EventLogEntryType)
Dim Log As New System.Diagnostics.EventLog("Application")
Log.Source = String.Format("Jiwa Plugin : {0}", Me.Plugin.Name )
Log.WriteEntry(Message, EventLogEntryType)
Log.Close()
End Sub

End Class

Errors include to "Jiwa Sales is not declared" It may be inaccessible due to its protection level and
"Jiwa journal sets.journal set is not defined
There are other similar errors

Please advise

Thanks
JohnBiddick
I'm new here
I'm new here
 
Posts: 8
Joined: Wed Jul 30, 2014 5:34 pm

Re: File watcher Plugin  Topic is solved

Postby Mike.Sheen » Fri Aug 01, 2014 11:17 am

Hi John,

When you copied the plugin, did you just copy and paste the code contents, or did you copy the plugin using the copy tool on the ribbon ? If you just copied and pasted the code, then you'll be missing the references to the required Jiwa assemblies - which would explain your error.

You can either add the references manually (on the references tab of the plugin maintenance form), or start again by copying the standard Jiwa File Watcher plugin using the copy tool on the ribbon.

Mike
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2440
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 755

Re: File watcher Plugin

Postby JohnBiddick » Mon Aug 04, 2014 1:22 pm

Hi Mike
I have corrected the method of copying, and the Plugin has compiled correctly. However, there appears to be no Import File Folders created. I have enabled the plug in also.

Are the watched files supposed to be created by the plugin, or do we need to create them manually?
JohnBiddick
I'm new here
I'm new here
 
Posts: 8
Joined: Wed Jul 30, 2014 5:34 pm

Re: File watcher Plugin

Postby Mike.Sheen » Mon Aug 04, 2014 1:52 pm

JohnBiddick wrote:Hi Mike
I have corrected the method of copying, and the Plugin has compiled correctly. However, there appears to be no Import File Folders created. I have enabled the plug in also.

Are the watched files supposed to be created by the plugin, or do we need to create them manually?


You don't need to manually create the folders, the plugin will create them.

Check the C:\ProgramData\Jiwa Financials\Jiwa 7\Import\ folder location. The exact path is controlled by some code in the plugin.

Mike
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2440
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 755


Return to Technical and or Programming

Who is online

Users browsing this forum: No registered users and 3 guests

cron