thread pool not executing in service - vb.net

Hi stackoverflow community...
I am a little stumped. I have written an application to control collect printing stats, each print job is managed by a new thread and as a console application the code works a treat. When I try initialize the same thread queue worker in a service, it does not run through the class it is meant to launch. This only happens on Windows 8 works stations.
Here are some code snippets.
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Dim tmp As New pmon_Audit
objwriter.AutoFlush = True
tmp.StartAudit()
End Sub
Imports SpoolMonitor
Imports System.Printing
Imports System.Threading
Imports Amib.Threading
Imports System.Net.Sockets
Public Class pmon_Audit
Friend WithEvents pmon As New PrinterMonitorComponent
Public ThreadPool As New SmartThreadPool(10, 1000, 0)
Public Sub StartAudit()
pmon.MonitorJobAddedEvent = True
'' Add printer to monitor
Try
For Each p As PrinterInformation In New PrinterInformationCollection
Try
pmon.AddPrinter(p.PrinterName)
WriteLog(String.Format("Printer {0} added to monitor", p.PrinterName))
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Next p
Catch ex As Exception
WriteLog(ex.ToString)
End Try
End Sub
''' <summary>
''' Event that gets fired each time a job is added
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub pmon_jobAdded(ByVal sender As Object, ByVal e As PrintJobEventArgs) Handles pmon.JobAdded
Dim myPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Try
Dim pq As PrintQueue = myPrintServer.GetPrintQueue(e.PrintJob.PrinterName)
Dim jobAdded As New pmon_JobAdded(e.PrintJob)
pq.GetJob(e.PrintJob.JobId).Pause()
WriteLog("JobID " + e.PrintJob.JobId.ToString + " is paused")
ThreadPool.QueueWorkItem(New Amib.Threading.Action(AddressOf jobAdded.run))
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Public Function run()
Dim myPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Dim pq As PrintQueue = myPrintServer.GetPrintQueue(pjReceived.PrinterName)
curPT = pq.CurrentJobSettings.CurrentPrintTicket
If jb Is Nothing Then
Throw New ArgumentNullException("printJobRecord", "printJobRecord is null.")
End If
Try
WriteLog("JobID " + pjReceived.JobId.ToString + " added to monitor")
jb.JobID = pjReceived.JobId
While pjReceived.Spooling
Thread.Sleep(800)
pjReceived.Update()
End While
Try
If pjReceived.Color = True Then
jb.Colour = 2
Else
jb.Colour = 0
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Colour = " + jb.Colour.ToString)
Catch ex As Exception
jb.Colour = 1
End Try
Try
jb.Account = pjReceived.UserName
WriteLog("JobID " + pjReceived.JobId.ToString + " Account = " + jb.Account)
Catch ex As Exception
jb.Account = "Admin"
End Try
Try
jb.Application = pjReceived.Document
WriteLog("JobID " + pjReceived.JobId.ToString + " Application = " + jb.Application)
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Try
If pq.CurrentJobSettings.CurrentPrintTicket.CopyCount > pjReceived.Copies Then
jb.Copies = pq.CurrentJobSettings.CurrentPrintTicket.CopyCount
ElseIf pq.UserPrintTicket.CopyCount > pjReceived.Copies Then
jb.Copies = pq.UserPrintTicket.CopyCount
Else
jb.Copies = pjReceived.Copies
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Copies = " + jb.Copies.ToString)
Catch ex As Exception
jb.Copies = 1
End Try
Try
jb.DeviceName = pjReceived.PrinterName
WriteLog("JobID " + pjReceived.JobId.ToString + " PrinterName = " + jb.DeviceName)
Catch ex As Exception
End Try
Try
jb.DataType = pjReceived.DataType
Catch ex As Exception
End Try
Try
jb.Document = pjReceived.Document
WriteLog("JobID " + pjReceived.JobId.ToString + " Document = " + jb.Document)
Catch ex As Exception
jb.Document = "UNKNOWN"
End Try
Try
jb.Driver = pjReceived.DriverName
WriteLog("JobID " + pjReceived.JobId.ToString + " Driver = " + jb.Driver)
Catch ex As Exception
jb.Driver = "UNKOWN"
End Try
Try
If pq.CurrentJobSettings.CurrentPrintTicket.Duplexing > pq.UserPrintTicket.Duplexing Then
jb.Duplex = pq.CurrentJobSettings.CurrentPrintTicket.Duplexing
Else
jb.Duplex = pq.UserPrintTicket.Duplexing
End If
If jb.Duplex = "twoSided" Then
jb.Duplex = "1"
Else
jb.Duplex = "0"
End If
WriteLog("JobID " + pjReceived.JobId.ToString + " Duplex = " + jb.Duplex)
Catch ex As Exception
jb.Duplex = "0"
End Try
Try
jb.JobDate = pjReceived.Submitted
WriteLog("JobID " + pjReceived.JobId.ToString + " JobDate = " + jb.JobDate)
Catch ex As Exception
jb.JobDate = Date.Now
End Try
Try
jb.JobSize = pjReceived.JobSize
Catch ex As Exception
jb.JobSize = "0"
End Try
Try
jb.Location = Dns.GetHostName.ToUpper
WriteLog("JobID " + pjReceived.JobId.ToString + " Location = " + jb.Location)
Catch ex As Exception
jb.Location = "UNKOWN"
End Try
Try
jb.Media = pq.CurrentJobSettings.CurrentPrintTicket.PageMediaSize.PageMediaSizeName
jb.Media = pjReceived.PaperKind
WriteLog("JobID " + pjReceived.JobId.ToString + " Media = " + jb.Media)
Catch ex As Exception
jb.Media = "201"
End Try
Try
jb.NUP = pq.CurrentJobSettings.CurrentPrintTicket.PagesPerSheet
Catch ex As Exception
jb.NUP = 0
End Try
Try
jb.PageCount = pjReceived.TotalPages
WriteLog("JobID " + pjReceived.JobId.ToString + " PageCount = " + jb.PageCount.ToString)
Catch ex As Exception
jb.PageCount = 1
End Try
Try
jb.PortName = pq.QueuePort.Name
Catch ex As Exception
End Try
Try
myPrintServer.Dispose()
Catch ex As Exception
WriteLog(ex.ToString)
End Try
Catch ex As Exception
pq.GetJob(pjReceived.JobId).Resume()
myPrintServer.Dispose()
WriteLog(ex.ToString)
End Try
GC.Collect()
Return 0
End Function

Related

"Response received is incomplete"

So I reversed the syntax of this send sms code from c# to vb net so I can reuse it.
The code works sometimes, but for some reason it would often give me the "response received is incomplete" exception.
I was thinking perhaps my code is processing commands faster than my GSM device, could handle, so I tried increasing the timeout response for the serial port, still ends up with this exception.
What do you think is the problem and what would you recommend I do to solve it?
Public Class SmsHelper
Public receiveNow As AutoResetEvent
#Region "Open and Close Ports"
'Open Port
Public Function OpenPort(portName As String, baudRate As Integer, dataBits As Integer, readTimeout As Integer, writeTimeout As Integer) As SerialPort
receiveNow = New AutoResetEvent(False)
Dim port As New SerialPort()
Try
port.PortName = portName
'COM1
port.BaudRate = baudRate
'9600
port.DataBits = dataBits
'8
port.StopBits = StopBits.One
'1
port.Parity = Parity.None
'None
port.ReadTimeout = readTimeout
'300
port.WriteTimeout = writeTimeout
'300
port.Encoding = Encoding.GetEncoding("iso-8859-1")
port.NewLine = vbCrLf
AddHandler port.DataReceived, AddressOf port_DataReceived
port.Open()
port.DtrEnable = True
port.RtsEnable = True
Catch ex As Exception
Throw ex
End Try
Return port
End Function
' Send AT Command
Public Function SendATCommand(port As SerialPort, command As String, responseTimeout As Integer, errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & Convert.ToString(vbCrLf))
Dim input As String = ReadResponse(port, responseTimeout)
Console.WriteLine("Received data is " & input)
If (input.Length = 0) OrElse ((Not input.EndsWith(vbCr & vbLf & "> ")) AndAlso (Not input.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
Finally
End Try
End Function
'Receive data from port
Public Sub port_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
receiveNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function ReadResponse(port As SerialPort, timeout As Integer) As String
Dim serialPortData As String = ""
Try
Do
If receiveNow.WaitOne(timeout, False) Then
Dim data As String = port.ReadLine()
serialPortData += data
Else
'Console.WriteLine("SerialPortData data is " & serialPortData)
If serialPortData.Length > 0 Then
Console.WriteLine("SerialPortData is " & serialPortData.ToString)
Throw New ApplicationException("Response received is incomplete.")
Else
Throw New ApplicationException("No data received from phone.")
End If
End If
Loop While Not serialPortData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "> ") AndAlso Not serialPortData.EndsWith(vbCr & vbLf & "ERROR" & vbCr & vbLf)
Catch ex As Exception
Throw ex
End Try
Return serialPortData
End Function
Shared readNow As New AutoResetEvent(False)
Public Function SendMessage(port As SerialPort, phoneNo As String, message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = SendATCommand(port, "AT", 3000, "No phone connected")
Dim command As String = "AT+CMGF=1" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to set message format.")
' AT Command Syntax - http://www.smssolutions.net/tutorials/gsm/sendsmsat/
command = (Convert.ToString("AT+CMGS=""") & phoneNo) + """" + Char.ConvertFromUtf32(13)
recievedData = SendATCommand(port, command, 3000, "Failed to accept phoneNo")
'wait(2)
command = message & Char.ConvertFromUtf32(26)
recievedData = SendATCommand(port, command, 3000, "Failed to send message")
Console.WriteLine("Received data is " & recievedData)
If recievedData.EndsWith(vbCr & vbLf & "OK" & vbCr & vbLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
Private Shared Sub DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Try
If e.EventType = SerialData.Chars Then
readNow.[Set]()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
#End Region
End Class

Screen capture code runs OK in WinForms but not as a service

I want to create a Windows service to screen capture but it's not working.
The process reaches the ScrenCapture.Start() but it does not do anything and does not throw an error.
If I test it in a Windows form the same code works well:
Code:
Imports Microsoft.Expression.Encoder.ScreenCapture
Imports isc.isc_utility
Public Class isc_utility_screen_capture
Dim ScrenCapture As ScreenCaptureJob = New ScreenCaptureJob()
Shared SrvDir As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location())
Function StartRecording(ByVal FileName As String)
Dim Dir = SrvDir
Dim FileToRecord As String
FileToRecord = Dir + "\" + FileName + ".wmv"
Try
ScrenCapture.OutputScreenCaptureFileName = FileToRecord
ScrenCapture.CaptureMouseCursor = True
ScrenCapture.Start()
WriteEventLogInformation("Capturing Video.... " + FileName + " " + Date.Now)
Return FileName
Catch ex As Exception
WriteEventLogError(ex.Message)
Return "-1"
End Try
End Function
Function StopRecording()
Try
ScrenCapture.Stop()
Return 1
Catch ex As Exception
WriteEventLogError(ex.Message)
Return -1
End Try
End Function
End Class
What could be happening?

exporting next image from listbox

I am trying to build an ImageConverter for my cousin (he needs that for his job) to export images in the following formats : 1. 2500x2500 , 2.1500x1500 and 3.800x800.
I only managed to export only one picture at a time in this formats , but he usually has over 50 pictures to convert in this formats daily , so I added a listbox so he can drag and drop his images in the listbox .I did managed that , but I don't know how to export the pictures that are loaded in the listbox , it needs to export one by one . The code I am using to export the images with "Export button" is here :
If (Not System.IO.Directory.Exists("C:\Users\Administrator\Desktop\" + KryptonTextBox1.Text)) Then
System.IO.Directory.CreateDirectory("C:\Users\Administrator\Desktop\" + KryptonTextBox1.Text)
Dim picturepath As String
picturepath = "C:\Users\Administrator\Desktop\" + KryptonTextBox1.Text
pathtxt.Text = picturepath
End If
Dim fileName As String = KryptonListBox1.SelectedItem.ToString()
Dim pathname As String = OpenFileDialog1.FileName
picturename = Path.GetFileNameWithoutExtension(fileName)
BildNametxt.Text = picturename
'converting picture in 2500x2500 format
Try
If (Not System.IO.Directory.Exists(pathtxt.Text + "\Amazon")) Then
System.IO.Directory.CreateDirectory(pathtxt.Text + "\Amazon")
Else
PictureBox2500.BackgroundImage.Save(pathtxt.Text + "\Amazon" + "\" + picturename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
If (Not System.IO.Directory.Exists(pathtxt.Text + "\1500")) Then
System.IO.Directory.CreateDirectory(pathtxt.Text + "\1500")
Else
PictureBox1500.BackgroundImage.Save(pathtxt.Text + "\1500" + "\" + picturename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
If (Not System.IO.Directory.Exists(pathtxt.Text + "\800")) Then
System.IO.Directory.CreateDirectory(pathtxt.Text + "\800")
Else
PictureBox800.BackgroundImage.Save(pathtxt.Text + "\800" + "\" + picturename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("Images succesfully converted!")
resizedimage2500.Dispose()
resizedimage1500.Dispose()
resizedimage800.Dispose()
So how can I do the same thing with the loaded listbox ? Any help is apreciated ! Thanks in advance

Image location won't write to file and Image won't load from file location

well I want to make the program write a an image location to a text file, and then when the user presses the "load" button, it reads that image location and sets it as the Image of the PictureBox, but so far I have had no success at all.
Private Sub Btn_Save_Click(sender As Object, e As EventArgs) Handles Btn_Save.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Dim path2 As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
Dim fs2 As FileStream = File.Create(path2)
' Add text to the file.
Dim info As Byte() =
New UTF8Encoding(True).GetBytes(
"----------Saved Card Settings----------" + vbNewLine +
"Level: " + My.Settings.Level.ToString + vbNewLine +
"NoMonster: " + My.Settings.NoMonster.ToString + vbNewLine +
"Spell: " + My.Settings.Spell.ToString + vbNewLine +
"Trap: " + My.Settings.Trap.ToString + vbNewLine +
"XYZLevel: " + My.Settings.XyzLevel.ToString + vbNewLine +
"ATKValue: " + My.Settings.ATKValue.ToString + vbNewLine +
"DEFValue: " + My.Settings.DEFValue.ToString + vbNewLine +
"AttributeID: " + My.Settings.AttributeID.ToString + vbNewLine +
"CardID: " + My.Settings.CardID.ToString)
fs.Write(info, 0, info.Length)
fs.Close()
Dim info2 As Byte() =
New UTF8Encoding(True).GetBytes(CardImage.InitialImage.ToString)
fs2.Write(info2, 0, info2.Length)
fs2.Close()
MsgBox("Configuration saved successfully!", vbInformation)
End Sub
Private Sub Btn_Load_Click(sender As Object, e As EventArgs) Handles Btn_Load.Click
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "config_card.aygo"
Try
My.Settings.Level = CInt(GetSettingItem(path, "level"))
My.Settings.NoMonster = CInt(GetSettingItem(path, "nomonster"))
My.Settings.Spell = CBool(GetSettingItem(path, "spell"))
My.Settings.Trap = CBool(GetSettingItem(path, "trap"))
If My.Settings.NoMonster = 1 Then
If My.Settings.Spell = True Then
CardFt.Card_Spell()
Else
If My.Settings.Trap = True Then
CardFt.Card_Trap()
Else
CardFt.Card_Legendary()
End If
End If
End If
My.Settings.XyzLevel = CInt(GetSettingItem(path, "xyzlevel"))
If My.Settings.XyzLevel = 1 Then
CardFt.Card_XYZ()
End If
My.Settings.ATKValue = GetSettingItem(path, "atkvalue")
ATKText.Text = GetSettingItem(path, "atkvalue")
My.Settings.DEFValue = GetSettingItem(path, "defvalue")
DEFText.Text = GetSettingItem(path, "defvalue")
My.Settings.AttributeID = CInt(GetSettingItem(path, "attributeid"))
If My.Settings.AttributeID = 1 Then
AttributeLayer.Image = My.Resources.Earth
ElseIf My.Settings.AttributeID = 2 Then
AttributeLayer.Image = My.Resources.Water
ElseIf My.Settings.AttributeID = 3 Then
AttributeLayer.Image = My.Resources.Fire
ElseIf My.Settings.AttributeID = 4 Then
AttributeLayer.Image = My.Resources.Wind
ElseIf My.Settings.AttributeID = 5 Then
AttributeLayer.Image = My.Resources.Dark
ElseIf My.Settings.AttributeID = 6 Then
AttributeLayer.Image = My.Resources.Light
ElseIf My.Settings.AttributeID = 7 Then
AttributeLayer.Image = My.Resources.Divine
End If
My.Settings.CardID = CInt(GetSettingItem(path, "cardid"))
CardFt.Card_Loader()
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo")
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
Catch ex As Exception
MsgBox("An error occured while loading the configuration file: " & vbNewLine & ex.Message & vbNewLine & vbNewLine & ex.ToString, vbExclamation)
My.Computer.Clipboard.SetText(ex.ToString)
End Try
End Sub
The error that I get from this is:
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(String filename)
at AnimeYuGiOhCardMaker.CardMaker.Btn_Load_Click(Object sender, EventArgs e) in C:\Users\Compusys\Documents\Visual Studio 2012\Projects\Anime Yu-Gi-Oh Card Maker\Anime Yu-Gi-Oh Card Maker\Form1.vb:line 521
Now then, when the Save Button is being pressed It does not write the image location to file however it writes the following:
System.Drawing.Bitmap
This is why I get the error above.
The actual error is from here:
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures + "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
The error occurs even with an actual file path.
I tried a few different ways but none of them worked. Any help would be really appreciated. Thanks.
--
Dom
The original question has changed several times, including the exception. The current state of the question has several problems, the main one being this:
If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.SpecialDirectories.MyPictures + "\Card Library\Configs\" + "set_cardimg.aygo") Then
Try
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "\Card Library\Configs\" + "set_cardimg.aygo")
' EMPTY CATCH !!!!!!
Catch ex As Exception : End Try
End If
Dim bitmap As New Bitmap(My.Computer.FileSystem.SpecialDirectories.MyPictures _
+ "Card Library\Configs\" + "set_cardimg.aygo")
CardImage.Image = CType(bitmap, System.Drawing.Image)
set_cardimg.aygo is just a config file which contains some text. it is not a valid image file, so you cannot create a bitmap from it.
You should open that file, read the contents into a variable, then if it is a valid location, create the bitmap from it, or better just set the picturebox .Location and let it load the image without you creating a bitmap first.

vb.net mutex class throw exception error

I found error code "The wait completed due to abandoned mutex..Can anyone give me any idea on how to solve it?
Here is the code:
Try
gcLog.log(" UseResource Start[1]")
ltWaitTimeSpan = New System.TimeSpan(0, 0, 20)
gcLog.log(" UseResource Start[3]")
If mut.WaitOne(ltWaitTimeSpan, True) Then
Thread_Status = True
Thread_Status_Chk_Count = 0
gcLog.log(Thread.CurrentThread.Name + " Thread Start !!![2]")
lsWorkInstID = Thread.CurrentThread.Name
gcCommon.IsWorkSheetIDExist(Thread.CurrentThread.Name)
gcMsgQue.mnDisMsgInfo2Label_Active(lsWorkInstID)
gcLog.log(" UseResource Start[2]")
Dim loSeqManage As clsSeqManage
loSeqManage = New clsSeqManage
If Not loSeqManage.bReadMsgFmDb(lsWorkInstID, lsLotID) Then
'gcLog.log(" UseResource Start[3]")
Thread_Status = False
Else
Dim loOutput2Prt As New clsOutput(lsLotID,gtMsgQueueEvent.sCryFileName)
loOutput2Prt.SetVariable()
'gcLog.log(" UseResource Start[4]")
If (loOutput2Prt.Output2PrtAuto And Not loOutput2Prt.GetMoreBatchFlag)
Then
gcLog.log(Thread.CurrentThread.Name + " Delete Record !!!")
Call loOutput2Prt.bDeleteMsgFmBuf()
End If
gcLog.log(Thread.CurrentThread.Name + " Thread Release !!![22]")
Thread_Status = False
mut.ReleaseMutex()
End If
End If
Catch ex As Exception
gcLog.log("UseResource : " + ex.Message & vbLf & ex.TargetSite.Name)
Call gfncCallError("2", "PrintFormServer", "UseResource : " + ex.Message & ""& ex.TargetSite.Name)
Thread_Status = False
End Try