Call function on Main Module - vb.net

I have a VB.NET script that creates mail accounts using smartermail webservice, i know nothing of VB.Net but i have a little knowledge of programming. I created a new project on Visual Studio 2012 and know i need to call the function that creates the accounts on the main module to run it, that's a console app project.
Main Module (Module1.vb) is as follows:
Module Module1
Sub Main()
End Sub
End Module*
My function is:
Sub fnc_CriaContas_Email_Lote()
It's on the file cria_contas_lote.vb in the same directory.
Content of cria_contas_lote.vb:
Sub fnc_CriaContas_Email_Lote()
Dim oPainelWS As PainelControle.svcSmarterMail
Dim sRetorno As String = ""
Try
'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
Catch ex As Exception
Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
Exit Sub
End Try
Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
Dim sSQL As String = ""
Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
Dim oExcel As New OleDbConnection(stringExcel)
Try
oExcel.Open()
Catch ex As Exception
Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
Console.Write(vbCrLf & "================================================")
Console.Write(vbCrLf & ex.Message)
Console.Write(vbCrLf & "================================================")
Exit Sub
End Try
Dim oDataSet As New DataSet
Try
Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
oExcelAdapter.Fill(oDataSet, "conteudo")
Catch ex As Exception
Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
oExcel.Close()
Exit Sub
End Try
oExcel.Close()
Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView
Dim lTotal As Long = 0
Dim lErro As Long = 0
Dim oLinha As DataRow
Dim iTamanhoCaixa As Integer = 1024
Dim sComCopia As String
For Each oLinha In oDataSet.Tables("conteudo").Rows
If Not (Trim(oLinha("conta").ToString) = "") Then
Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
sRetorno = ""
sComCopia = Trim(oLinha("enviar_copia").ToString)
iTamanhoCaixa = oLinha("tamanho_mb")
sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
Console.WriteLine("Retorno: " & sRetorno)
'If Not (sRetorno = "OK") Then
'Exit Sub
'End If
Threading.Thread.Sleep(100)
End If
Next
End Sub
Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String
If Not (iTamanhoCaixaKB > 1) Then
Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
End If
Dim aContaNome As String() = Split(sConta, "#")
Dim sContaNome As String = ""
Dim sDominio As String = ""
sContaNome = aContaNome(0)
sDominio = aContaNome(1)
Dim oUsuarios As New svcUserAdmin
Dim oUsuarioInfo As New SettingsRequestResult
Dim oResultado As New GenericResult
oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
If Not (sForwardTo.ToString = "") Then
Dim arrInfo(0) As String
arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
End If
Return "OK"
End Function

What have you tried? Because as it stands it sounds like all you need to do is
Module Module1
Sub Main()
fnc_CriaContas_Email_Lote()
End Sub
Sub fnc_CriaContas_Email_Lote()
' Do something.
End Sub
End Module
If "fnc_CriaContas_Email_Lote" is a class then you might have to do something like:
Module Module1
Sub Main()
dim email as new cria_contas_lote()
email.fnc_CriaContas_Email_Lote()
End Sub
End Module
Without seeing the cria_contas_lote file its hard to know.
Edit: Below is how you can call it all from just the module
Imports System.Data.OleDb
Module Module1
Sub Main()
fnc_CriaContas_Email_Lote()
End Sub
Sub fnc_CriaContas_Email_Lote()
Dim oPainelWS As PainelControle.svcSmarterMail
Dim sRetorno As String = ""
Try
'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
Catch ex As Exception
Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
Exit Sub
End Try
Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
Dim sSQL As String = ""
Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
Dim oExcel As New OleDbConnection(stringExcel)
Try
oExcel.Open()
Catch ex As Exception
Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
Console.Write(vbCrLf & "================================================")
Console.Write(vbCrLf & ex.Message)
Console.Write(vbCrLf & "================================================")
Exit Sub
End Try
Dim oDataSet As New DataSet
Try
Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
oExcelAdapter.Fill(oDataSet, "conteudo")
Catch ex As Exception
Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
oExcel.Close()
Exit Sub
End Try
oExcel.Close()
Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView
Dim lTotal As Long = 0
Dim lErro As Long = 0
Dim oLinha As DataRow
Dim iTamanhoCaixa As Integer = 1024
Dim sComCopia As String
For Each oLinha In oDataSet.Tables("conteudo").Rows
If Not (Trim(oLinha("conta").ToString) = "") Then
Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
sRetorno = ""
sComCopia = Trim(oLinha("enviar_copia").ToString)
iTamanhoCaixa = oLinha("tamanho_mb")
sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
Console.WriteLine("Retorno: " & sRetorno)
'If Not (sRetorno = "OK") Then
'Exit Sub
'End If
Threading.Thread.Sleep(100)
End If
Next
End Sub
Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String
If Not (iTamanhoCaixaKB > 1) Then
Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
End If
Dim aContaNome As String() = Split(sConta, "#")
Dim sContaNome As String = ""
Dim sDominio As String = ""
sContaNome = aContaNome(0)
sDominio = aContaNome(1)
Dim oUsuarios As New svcUserAdmin
Dim oUsuarioInfo As New SettingsRequestResult
Dim oResultado As New GenericResult
oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
If Not (sForwardTo.ToString = "") Then
Dim arrInfo(0) As String
arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
End If
Return "OK"
End Function
End Module
Your issue is your missing the following types:
PainelControle.svcSmarterMail
svcUserAdmin
SettingsRequestResult
GenericResult
These are not built in .Net types and must be defined in either another file. Once you've found the missing classes just add them into the project and you should be good to go.

I think you want to make Sub Main run ENTIRE function, and DON'T EXIT as sub main is executed.
I have written answer of your question here : VB.net program with no UI
Sub Main()
'Write whatever you want, and add this code at the END:
Application.Run
End Sub

Related

itextsharp: disable clipboard for pdf

I have a function that receives a PDF file from the desktop. What I want is that, before saving the PDF, deactivate the clipboard so that they cannot copy the text or images of the document.
My code:
Dim NombreArchivo As String = System.IO.Path.GetFileName(File1.PostedFile.FileName) ' obtiene nombre archivo
Dim docsubido As New Document()
Dim SaveLocation As String = Server.MapPath("Pdf") & "\" & NombreArchivo ' obtiene ruta donde se guardara
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
File1.PostedFile.SaveAs(SaveLocation)
Response.Write("El archivo ha sido cargado.")
Catch Exc As Exception
Response.Write("Error: " & Exc.Message)
End Try
Else
Response.Write("Seleccione un archivo para cargar.")
End If
End Sub
Finally this was the solution to be able to disable the property of copying and pasting of a PDF only the option to print
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.PdfStamper
Private Sub Submit1_ServerClick(sender As Object, e As EventArgs) Handles Submit1.ServerClick
Dim NombrePdfEntrada As String = System.IO.Path.GetFileName(File1.PostedFile.FileName) ' obtiene nombre archivo
Dim SaveLocation As String = Server.MapPath("Pdf") & "\" & NombrePdfEntrada ' obtiene ruta donde se guardara
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
File1.PostedFile.SaveAs(SaveLocation)
Dim ArchivoCargado As New PdfReader(SaveLocation)
Dim rutasalida As New FileStream(Server.MapPath("Pdf") & "\Nuevo" & NombrePdfEntrada, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)
Dim stampArchivoOutput As New PdfStamper(ArchivoCargado, rutasalida)
Dim passdue As String = ""
Dim arraydueño() As Byte = System.Text.Encoding.ASCII.GetBytes(passdue)
Dim passinv As String = ""
Dim arrayinvitado() As Byte = System.Text.Encoding.ASCII.GetBytes(passinv)
stampArchivoOutput.SetEncryption(False, passdue, passinv, PdfWriter.ALLOW_PRINTING)
stampArchivoOutput.Close()
ArchivoCargado.Close()
Response.Write("El archivo ha sido cargado.")
Catch Exc As Exception
Response.Write("Error: " & Exc.Message & Exc.HelpLink
)
End Try
Else
Response.Write("Seleccione un archivo para cargar.")
End If
End Sub
End Class

how to use serial port in a service application environment constantly listening for data

Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,
Application: BondTestService.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException at
System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean
ByRef) at
System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,
Boolean ByRef) at
Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,
System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at
System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at
System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at
System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?
I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?
Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.
Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration
Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10
#Region "Commport Traffic and Configuration Validations"
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
End If
Try
With serialPort
.PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
.BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
.Parity = Parity.None
End If
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
.StopBits = StopBits.One
End If
.DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
.Handshake = Handshake.None
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
.RtsEnable = True
Else
.RtsEnable = False
End If
End With
serialPort.Open()
'debug
'ErrorLog2("Listening to COM 19, SerialPort has been Opened")
Catch ex As Exception
ErrorLog2(Now.ToString & ex.tostring)
End Try
End Sub
Public Function Filelocator() As String
' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
'Dim reader As New System.IO.StreamReader(filePath)
Dim LineNumber = 4
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To LineNumber - 1
If file.ReadLine() Is Nothing Then
ErrorLog2("LineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
ErrorLog2("LineNumber")
End If
Return line
End Using
End Function
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Try
If GetBondInterfaceStatus = 1 Then
UPdateVariable()
Else
exit Sub
End If
Catch ex As Exception
Errorlog2(Ex.Tostring)
End Try
End Sub
#End Region
#Region "String Handling"
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
try
ErrorLog2(now.ToString & RawString.ToString)
InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
RawString.Clear()
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Public Function StringParser(RawString As String)As Double ()
Dim Moisture = RawString
Dim pattern As String = "[0-9],"
Dim regex As New Regex(pattern)
Dim Counter As Integer = 0
Dim dblValues(1) As Double
Dim values As String() = Moisture.Split(New Char() {" "c})
for i = 0 to values.Count - 1
if regex.IsMatch(values(i)) Then
dblValues(Counter) = CDbl(values(i).Substring(0,1))
Counter = Counter + 1
Elseif values(i) = "" Then
continue for
else
if Double.TryParse(values(i), dblValues(Counter)) Then
Counter = Counter + 1
End If
End If
Next
Return dblValues
End Function
#End Region
#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime)"
Try
conn.ExecuteNonQuery(InsertQuery)
IncrementTestPosition
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#RawString") = rawString
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime, #RawString)"
Try
conn.ExecuteNonQuery(InsertQuery)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub IncrementTestPosition()
Dim tempPosition As Integer = GetBondPosition()
Dim FrontOriginalMax = 5
Dim CenterOriginalMax = 15
Dim BackOriginalMax = 25
Dim FrontRetestOrWinderMax = 10
Dim CenterRetestOrWinderMax = 20
Dim BackRetestOrWinderMax = 30
If tempPosition = FrontOriginalMax Then
tempPosition = 11
else if tempPosition = CenterOriginalMax Then
tempPosition = 21
else if tempPosition = BackOriginalMax Then
tempPosition = 1
Else If tempPosition = FrontRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = CenterRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = BackRetestOrWinderMax then
tempPosition = 1
else
tempPosition = tempPosition + 1
End If
SetBondPosition(tempPosition.tostring)
End Sub
#End Region
#Region "Get PiValues"
Private Function GetRecordID() As Int64
Dim RecordID As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return RecordID
End Function
Private Function GetBondPosition() As Int64
Dim BondPos As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return BondPos
End Function
Private Sub SetBondPosition(pos As String)
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Function BondTestType() As String
Dim TestType As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return TestType
End Function
Private Function BondReelLoc() As String
Dim ReelLoc As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return ReelLoc
End Function
Private Function GetBondInterfaceStatus() As Integer
Dim Status As Integer = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return Status
End Function
#End Region
#Region "Debug"
Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
' For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
' Next
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
'For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
'Next
End Using
End If
End Sub
Private Sub ErrorLog2(dataArray as string)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
' Dim TestPos = StartingTestPos
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
End If
End Sub
#End Region
This is a screenshot of the errors:
Thanks in advance
Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.
According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.
Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.
This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.
The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.
Also check your power management settings on your USB port if USB-to-RS232 converter is used. Try to uncheck this option on USB device to which converter is connected.
SW bug in your code.
It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.
Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class
Shared Dim WithEvents serialPort as IO.Ports.SerialPort
and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.

how to search through sub folders vb.net with a windows service?

I'm having problems with my code, the idea is to find a file in a folder but this is a remote folder and it has many sub folders if it doesn't find it then it should look for it in another folder, but it doesn't seem to work could anyone help me please? thanks for any help :).
Dim dt2 As New System.Data.DataTable()
Dim query2 As String = "SELECT juzgado, rutaPDF FROM mismoCorreo WHERE DATEPART(DAY, BirthDate) = #Day AND DATEPART(MONTH, BirthDate) = #Month"
Dim constr2 As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr2)
Using cmd As New SqlCommand(query2)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Day", DateTime.Today.Day)
cmd.Parameters.AddWithValue("#Month", DateTime.Today.Month)
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt2)
End Using
End Using
End Using
For Each row As DataRow In dt2.Rows
Dim juzgado As String = row("juzgado").ToString()
Dim nombre_archivo As String = row("rutaPDF").ToString()
If (juzgado = "PRIMERO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J92016SEM2" & "\" & nombre_archivo & ".docx"
ElseIf (juzgado = "SEGUNDO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J102016SEM2" & "\" & nombre_archivo & ".docx"
End If
Next
For index = 0 To ListaArchivos.Count - 1
Dim wordApplication = New Microsoft.Office.Interop.Word.Application()
Dim wordDocument As Document = Nothing
Dim paramSourceDocPath As String = ListaArchivos.Item(index)
Dim paramExportFilePath As String = "\\172.16.20.101\SisInt\Convertidos" + "\" + ListaNombres.Item(index) + ".pdf"
Dim paramExportFormat As WdExportFormat =
WdExportFormat.wdExportFormatPDF
Dim paramOpenAfterExport As Boolean = False
Dim paramExportOptimizeFor As WdExportOptimizeFor =
WdExportOptimizeFor.wdExportOptimizeForPrint
Dim paramExportRange As WdExportRange =
WdExportRange.wdExportAllDocument
Dim paramStartPage As Int32 = 0
Dim paramEndPage As Int32 = 0
Dim paramExportItem As WdExportItem =
WdExportItem.wdExportDocumentContent
Dim paramIncludeDocProps As Boolean = True
Dim paramKeepIRM As Boolean = True
Dim paramCreateBookmarks As WdExportCreateBookmarks =
WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim paramDocStructureTags As Boolean = True
Dim paramBitmapMissingFonts As Boolean = True
Dim paramUseISO19005_1 As Boolean = False
Try
'Abrir documento basados en el que selecciono
wordDocument = wordApplication.Documents.Open(paramSourceDocPath)
' Exportar al formato deseado
If Not wordDocument Is Nothing Then
wordDocument.ExportAsFixedFormat(paramExportFilePath,
paramExportFormat, paramOpenAfterExport,
paramExportOptimizeFor, paramExportRange, paramStartPage,
paramEndPage, paramExportItem, paramIncludeDocProps,
paramKeepIRM, paramCreateBookmarks,
paramDocStructureTags, paramBitmapMissingFonts,
paramUseISO19005_1)
End If
Catch ex As Exception
'MessageBox.Show(ex.Message)
'Registro en base de datos fecha hora y ex.message
Finally
If Not wordDocument Is Nothing Then
wordDocument.Close(False)
wordDocument = Nothing
End If
If Not wordApplication Is Nothing Then
wordApplication.Quit()
wordApplication = Nothing
End If
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
Next

For-loop doesn't complete all iterations

I have problem with this - I try to send broadcast SMS using AT Commands in my system. After that the SMS content will be stored in my database. My store content SMS function works well. I can store all my SMS content that I send, but the send function just sends message to my first data on my datagridview.
Please help me to deal with this - I posted my code below
Private Sub ButtonKirim_Click(sender As Object, e As EventArgs) Handles ButtonKirim.Click
Dim noPel As String
Dim isiPesan As String = ""
Dim tgl As Date = Now.Date
Dim strReplace(2) As String
Dim strIsi(2) As String
Dim tagBulan As String = "<bulan>"
Dim tagtagihan As String = "<tagihan>"
Dim tagLokasi As String = "<lokasi>"
Dim pesanKirim As String = ""
My.Settings.SettingPesan = RichTextBoxPesan.Text
My.Settings.Save()
'Label4.Text = isiPesan
For pelanggan As Integer = 0 To DataGridViewKirimPesan.RowCount - 1
'mengirim pesan/send message
noPel = DataGridViewKirimPesan.Rows(pelanggan).Cells(3).Value()
strReplace(0) = tagBulan
strReplace(1) = tagtagihan
strReplace(2) = tagLokasi
strIsi(0) = DataGridViewKirimPesan.Rows(pelanggan).Cells(4).Value
strIsi(1) = DataGridViewKirimPesan.Rows(pelanggan).Cells(5).Value
strIsi(2) = DataGridViewKirimPesan.Rows(pelanggan).Cells(6).Value
isiPesan = RichTextBoxPesan.Text
For i As Integer = LBound(strReplace) To UBound(strReplace)
isiPesan = isiPesan.Replace(strReplace(i), strIsi(i))
Next
SendMessage(noPel, isiPesan)
''menyimpan pesan keluar ke sms_terkirim/this query store my content SMS to table
Dim sqlSmsKeluar As String = "INSERT INTO sms_terkirim (`tgl_sms`,`id_pelanggan`, `isi_sms`) VALUES ( NOW()," & DataGridViewKirimPesan.Rows(pelanggan).Cells(0).Value & " , '" & isiPesan & "');"
cudMethod(sqlSmsKeluar)
MsgBox(sqlSmsKeluar)
'ProgressBarKirimPesan.Increment(1)
Next
'MsgBox("Pesan Sukses Terkirim")
' Catch ex As Exception
' MsgBox("Pesan Gagal Terkirim" + ex.Message)
'End Try
' End If
End Sub
and this code is AT Command to send message
Public Sub SendMessage(ByVal NomorPelanggan As String, ByVal IsiPesan As String)
If SerialModem.IsOpen() Then
With SerialModem
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGS=" & Chr(34) & NomorPelanggan & Chr(34) & vbCrLf)
Threading.Thread.Sleep(100)
.Write(IsiPesan & vbCrLf & Chr(26))
Threading.Thread.Sleep(100)
End With
Else
MsgBox("Modem Belum Tersambung")
End If
End Sub

Why do I get the error: System.Runtime.InteropServices.COMException?

I am using VB.NET to Create Labels in Microsoft. This is my code:
Public Sub CreateLabel(ByVal StrFilter As String, ByVal Path As String)
WordApp = CreateObject("Word.Application")
''Add a new document.
WordDoc = WordApp.Documents.Add()
Dim oConn As SqlConnection = New SqlConnection(connSTR)
oConn.Open()
Dim oCmd As SqlCommand
Dim oDR As SqlDataReader
oCmd = New SqlCommand(StrFilter, oConn)
oDR = oCmd.ExecuteReader
Dim intI As Integer
Dim FilePath As String = ""
With WordDoc.MailMerge
With .Fields
Do While oDR.Read
For intI = 0 To oDR.FieldCount - 1
.Add(WordApp.Selection.Range, oDR.Item(intI))
Next
Loop
End With
Dim objAutoText As Word.AutoTextEntry = WordApp.NormalTemplate.AutoTextEntries.Add("MyLabelLayout", WordDoc.Content)
WordDoc.Content.Delete()
.MainDocumentType = Word.WdMailMergeMainDocType.wdMailingLabels
FilePath = CreateSource(StrFilter)
.OpenDataSource(FilePath)
Dim NewLabel As Word.CustomLabel = WordApp.MailingLabel.CustomLabels.Add("MyLabel", False)
WordApp.MailingLabel.CreateNewDocument(Name:="MyLabel", Address:="", AutoText:="MyLabelLayout")
objAutoText.Delete()
.Destination = Word.WdMailMergeDestination.wdSendToNewDocument
WordApp.Visible = True
.Execute()
End With
oConn.Close()
WordDoc.Close()
End Sub
Private Function CreateSource(ByVal StrFilter As String) As String
Dim CnnUser As SqlConnection = New SqlConnection(connSTR)
Dim sw As StreamWriter = File.CreateText("C:\Mail.Txt")
Dim Path As String = "C:\Mail.Txt"
Dim StrHeader As String = ""
Try
Dim SelectCMD As SqlCommand = New SqlCommand(StrFilter, CnnUser)
Dim oDR As SqlDataReader
Dim IntI As Integer
SelectCMD.CommandType = CommandType.Text
CnnUser.Open()
oDR = SelectCMD.ExecuteReader
For IntI = 0 To oDR.FieldCount - 1
StrHeader &= oDR.GetName(IntI) & " ,"
Next
StrHeader = Mid(StrHeader, 1, Len(StrHeader) - 2)
sw.WriteLine(StrHeader)
sw.Flush()
sw.Close()
StrHeader = ""
Do While oDR.Read
For IntJ As Integer = 0 To oDR.FieldCount - 1
StrHeader &= oDR.GetString(IntJ) & " ,"
Next
Loop
StrHeader = Mid(StrHeader, 1, Len(StrHeader) - 2)
sw = File.AppendText(Path)
sw.WriteLine(StrHeader)
CnnUser.Close()
sw.Flush()
sw.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "TempID", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return Path
End Function
Now when I am running the program I am getting this error. I tried hard but not able to locate what could be the problem the error is:
System.Runtime.InteropServices.COMException -->Horizontal and vertical
pitch must be greater than or equal to the label width and height,
respectively.
Even though I tried to set the Horizontal and vertical pitch programatically it gives same error.
Make sure that you have a default printer set up for the user account that the application runs under. Might not be relevant but I have had various unusual problems following that omission.
Did you install the Office Primary Interop Assemblies? (Appropriately abbreviated to PIA)
Try this