problem with .net windows service - windows

have written a windows service. while the code worked for a simple form app, its not working in a windows service. here;s the code
Imports System.Text.RegularExpressions
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Service1
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://google.com"), HttpWebRequest)
myWebRequest.Proxy = New WebProxy(Proxy, False)
myWebRequest.Timeout = 10000
Try
Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)
Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream())
Return True
Catch ex As WebException
If (ex.Status = WebExceptionStatus.ConnectFailure) Then
End If
Return False
End Try
End Function
Protected Overrides Sub OnStart(ByVal args() As String)
System.IO.File.AppendAllText("C:\AuthorLog.txt",
"AuthorLogService has been started at " & Now.ToString())
MsgBox("1")
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
MsgBox("2")
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("Evoain Proxy Bot") Then
Diagnostics.EventLog.CreateEventSource("MyService", "Myservice Log") ' Create Log
End If
' Write to the Log
Diagnostics.EventLog.WriteEntry("MyService Log", "This is log on " & _
CStr(TimeOfDay), EventLogEntryType.Information)
Dim ProxyURLList As New Chilkat.CkString
Dim ProxyListPath As New Chilkat.CkString
Dim WorkingProxiesFileData As New Chilkat.CkString
Dim ProxyArray(10000000) As String
Dim event1 As New Chilkat.CkString
event1.setString("started")
event1.saveToFile("B:\serv.txt", "utf-8")
Dim ns As Integer = 0
'Read Configuration File
Dim sFileName As String
Dim srFileReader As System.IO.StreamReader
Dim sInputLine As String
sFileName = "config.ini"
srFileReader = System.IO.File.OpenText(sFileName)
sInputLine = srFileReader.ReadLine()
Dim temp As New Chilkat.CkString
Do Until sInputLine Is Nothing
temp.setString(sInputLine)
If temp.containsSubstring("proxyurllist=") = True Then
'Read Proxy-URL-List
ProxyURLList.setString(sInputLine)
If ProxyURLList.containsSubstring("proxyurllist=") = True Then
ProxyURLList.replaceFirstOccurance("proxyurllist=", "")
End If
ElseIf temp.containsSubstring("finalproxylistpath=") = True Then
'Read Proxy-List-Path
ProxyListPath.setString(sInputLine)
If ProxyListPath.containsSubstring("finalproxylistpath=") = True Then
ProxyListPath.replaceFirstOccurance("finalproxylistpath=", "")
End If
End If
sInputLine = srFileReader.ReadLine()
Loop
'*********Scrape URLs From Proxy-URL-List*********************
Dim ProxyURLFileData As New Chilkat.CkString
ProxyURLFileData.loadFile(ProxyURLList.getString, "utf-8")
Dim MultiLineString As String = ProxyURLFileData.getString
Dim ProxyURLArray() As String = MultiLineString.Split(Environment.NewLine.ToCharArray, System.StringSplitOptions.RemoveEmptyEntries)
Dim i As Integer
For i = 0 To ProxyURLArray.Count - 1
'********Scrape Proxies From Proxy URLs***********************
Dim http As New Chilkat.Http()
Dim success As Boolean
' Any string unlocks the component for the 1st 30-days.
success = http.UnlockComponent("Anything for 30-day trial")
If (success <> True) Then
Exit Sub
End If
' Send the HTTP GET and return the content in a string.
Dim html As String
html = http.QuickGetStr(ProxyURLArray(i))
Dim links As MatchCollection
links = Regex.Matches(html, "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5}")
For Each match As Match In links
Dim matchUrl As String = match.Groups(0).Value
ProxyArray(ns) = matchUrl
ns = ns + 1
Next
Next
'*************CHECK URLs*****************
Dim cnt As Integer = 0
For cnt = 0 To 1
Dim ProxyStatus As Boolean = CheckProxy("http://" + ProxyArray(cnt) + "/")
If ProxyStatus = True Then
WorkingProxiesFileData.append(Environment.NewLine)
WorkingProxiesFileData.append(ProxyArray(cnt))
End If
Next
WorkingProxiesFileData.saveToFile(ProxyListPath.getString, "utf-8")
End Sub
End Class
what are the basic thing i cannot do in a windows service? oh, and i am using the chilkat library too..
why can't i use all of my code in OnStart? i did so and the services stops just as it starts.
can i use something else except a timer and put an endless loop?

Running as a windows service typically won't let you see any popup boxes, etc since there's no UI (Unless you check the box to allow interaction with the desktop).
Try adding a Timer1.Start in your OnStart method. Then in your Timer1_Tick method, first thing stop the timer, then at the end start it back up, this way your Tick method won't fire while you're already doing work.

I realize I'm (very) late to this party, but what kind of timer are you using? A System.Windows.Forms.Timer is designed for use in a single threaded Windows Form and will not work in a Windows Service app. Try a System.Timers.Timer instead.

Related

How to add data in UDT of SAP B1 in SDK?

I have a problem of adding record in UDT of SAP B1 in SDK.
ALL MY CODES
Public Class SystemForm
Private oCompany As SAPbobsCOM.Company
Private WithEvents SBO_Application As SAPbouiCOM.Application
Private Sub SetApplication()
Dim SboGuiApi As SAPbouiCOM.SboGuiApi
Dim sConnectionString As String
SboGuiApi = New SAPbouiCOM.SboGuiApi()
sConnectionString = Command()
SboGuiApi.Connect(sConnectionString)
SBO_Application = SboGuiApi.GetApplication()
End Sub
Public Sub New()
MyBase.New()
SetApplication()
End Sub
Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
If pVal.FormTypeEx = "UDO_FT_RPRL" AndAlso pVal.ActionSuccess = False AndAlso pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED AndAlso pVal.ItemUID = "2" AndAlso pVal.FormMode = 3 Then
Dim oUsrTbl As SAPbobsCOM.UserTable
Dim Res As Integer
oCompany = New SAPbobsCOM.Company
oUsrTbl = oCompany.UserTables.Item("#TODD")
oUsrTbl.Code = "1"
oUsrTbl.Name = "189"
oUsrTbl.UserFields.Fields.Item("U_Amount").Value = 4000
Res = oUsrTbl.Add()
If Res = 0 Then
SBO_Application.MessageBox("Added")
Else
SBO_Application.MessageBox("Error, failed to add Record")
End If
End If
End Sub
End Class
I tried to do research but not help
Actually what I want to do is if I click on Add button of UDO then it updates my UDT called #TODD, but if I click Add button above codes bring the following error message " Addon 9000058 failed with exception; Event Type: 1".
Please anyone can help me
You are missing a call to the Connect() method of DIAPI after creating the instance oCompany. Before calling this you need to set the connection context, either by specifying the server and login, or getting the session context from your UI-API connection. Assuming your UI-API object is called SBO_Application:
Dim Cookie as String = oCompany.GetContextCookie()
Dim conStr as String = SBO_Application.Company.GetConnectionContext(Cookie)
oCompany.SetSboLoginContext(conStr)
oCompany.Connect()
(untested code)
Obviously you'll probably want to check the Connect call succeeds before continuing.
This is the code I am using which connects and in my case sets up an 'oCompany' object that can be used for transactions and 'DoQuery' queries.
SAPbobsCOM.Company oCompany = new SAPbobsCOM.Company();
oCompany.CompanyDB = "DATABASE_NAME";
oCompany.Server = "FTHANA01:30015"; // Your server name goes here
oCompany.LicenseServer = "FTHANA01:30000";
oCompany.SLDServer = "FTHANA01:40000";
oCompany.DbUserName = "SAPSYSTEM";
oCompany.DbPassword = psw1;
oCompany.UserName = "SAP Username";
oCompany.Password = psw2;
// We are using a SAP Hana database
oCompany.DbServerType = SAPbobsCOM.BoDataServerTypes.dst_HANADB;
oCompany.UseTrusted = true;
int ret = oCompany.Connect();
string errMsg = oCompany.GetLastErrorDescription();
int ErrNo = oCompany.GetLastErrorCode();
if (ErrNo != 0)
(we have an error)
else
(success)
Database login credentials and user login credentials are both needed.

Acces denied to registry on windows 8 for vb.net app

I created a small app in vb.net for a friend. The problem is that on my PC (W7 64bits) it works great (registry reading / writing) but on my friends PC (W8 64bits) it doesn't work.
It it strange but at the moment he runs my app (it checks the registry on loading) it gives him a "Access to registry denied" error. I tried to run it with admin rights but it doesn't work either.
Here is my code:
Imports Microsoft.Win32
Public Class Form1
Dim planned As Date
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
Private Sub planifier_Click(sender As Object, e As EventArgs) Handles planifier_button.Click
Dim toExecute As String = String.Format("shutdown -s -f -t {0}", 100)
Dim currentDate = System.DateTime.Now
Dim futureDate = DateTimePicker1.Value
Dim difference = futureDate - currentDate
Console.Out.WriteLine(difference)
System.Diagnostics.Process.Start("shutdown", "-s -f -t " & Math.Round(difference.TotalSeconds))
Me.planned = futureDate
saveStgFile(futureDate)
setup()
End Sub
Private Sub Shutdown_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Console.Out.WriteLine(Application.ProductName & " & " & Application.ExecutablePath)
getStgFile()
getPlanned()
setup()
Dim baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
Startup.Checked = baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).GetValue(Application.ProductName).Equals(Application.ExecutablePath)
End Sub
Private Sub cancel_button_Click(sender As Object, e As EventArgs) Handles cancel_button.Click
System.Diagnostics.Process.Start("shutdown", "-a")
Me.planned = Nothing
saveStgFile(Nothing)
setup()
End Sub
Sub setup()
If Me.planned.Equals(Nothing) Then
cancel_button.Enabled = False
planifier_button.Enabled = True
planifier_button.Text = "Planifier"
Else
cancel_button.Enabled = True
planifier_button.Enabled = False
planifier_button.Text = Me.planned.TimeOfDay.ToString()
End If
End Sub
Function getPlanned() As TimeSpan
Dim stg As String = getStgFile()
Dim fileContent As String = My.Computer.FileSystem.ReadAllText(stg)
Dim timespan As Date
If fileContent = "none" Then
Me.planned = Nothing
ElseIf Date.TryParse(fileContent, timespan) Then
Me.planned = timespan
End If
Return (Me.planned - System.DateTime.Now)
End Function
Function getStgFile() As String
Dim stgFile = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "AutoShutdown")
If My.Computer.FileSystem.DirectoryExists(stgFile) = False Then
FileSystem.MkDir(stgFile)
End If
stgFile = System.IO.Path.Combine(stgFile, "settings.ini")
If My.Computer.FileSystem.FileExists(stgFile) = False Then
My.Computer.FileSystem.WriteAllText(stgFile, "none", False)
End If
Return stgFile
End Function
Sub saveStgFile(planned As Date)
Dim stgFile As String = getStgFile()
Try
If (planned.Equals(Nothing)) Then
My.Computer.FileSystem.WriteAllText(stgFile, "none", False)
Else
My.Computer.FileSystem.WriteAllText(stgFile, planned.ToString(), False)
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Private Sub Startup_CheckedChanged(sender As Object, e As EventArgs) Handles Startup.CheckedChanged
Dim baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
If Startup.Checked Then
baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)
Console.Out.WriteLine("Add to startup")
Else
baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).DeleteValue(Application.ProductName)
Console.Out.WriteLine("Remove from startup")
End If
End Sub
End Class

How to display selected features in ArcGIS Identify Dialog using Visual Studio 2010/ArcObjects?

I'm brand new to ArcObjects SDKs and am struggling. I have a Python Add-in performing a query to select records (works great)and now trying to call the identify dialog via an .NET addin button that displays the identify dialog box to show attributes of the selected records. Below is the code I have at this point. I currently have the identify dialog displaying, but no records appearing. I know I need to input the selected records somewhere....but not sure where. Any thoughts would be appreciated. (I'm using Visual Studio/Microsoft Visual Basic 2010 and ArcGIS 10.2.1)
Imports ESRI.ArcGIS.ArcMapUI
Imports ESRI.ArcGIS.Carto
Public Class Identify_Button
Inherits ESRI.ArcGIS.Desktop.AddIns.Button
Dim pMxDoc As IMxDocument
Dim activeView As IMap
Public Sub DoIdentify(ByVal activeView As ESRI.ArcGIS.Carto.IActiveView, ByVal x As System.Int32, ByVal y As System.Int32)
pMxDoc = My.ArcMap.Application.Document
activeView = pMxDoc.FocusMap
If activeView Is Nothing Then
Return
End If
Dim map As ESRI.ArcGIS.Carto.IMap = activeView.FocusMap
Dim identifyDialog As ESRI.ArcGIS.CartoUI.IIdentifyDialog = New ESRI.ArcGIS.CartoUI.IdentifyDialogClass
identifyDialog.Map = map
'Clear the dialog on each mouse click
identifyDialog.ClearLayers()
Dim screenDisplay As ESRI.ArcGIS.Display.IScreenDisplay = activeView.ScreenDisplay
Dim display As ESRI.ArcGIS.Display.IDisplay = screenDisplay ' Implicit Cast
identifyDialog.Display = display
Dim identifyDialogProps As ESRI.ArcGIS.CartoUI.IIdentifyDialogProps = CType(identifyDialog, ESRI.ArcGIS.CartoUI.IIdentifyDialogProps) ' Explicit Cast
Dim enumLayer As ESRI.ArcGIS.Carto.IEnumLayer = identifyDialogProps.Layers
enumLayer.Reset()
Dim layer As ESRI.ArcGIS.Carto.ILayer = enumLayer.Next
Do While Not (layer Is Nothing)
identifyDialog.AddLayerIdentifyPoint(layer, x, y)
layer = enumLayer.Next()
Loop
identifyDialog.Show()
End Sub
Public Sub New()
End Sub
Protected Overrides Sub OnClick()
DoIdentify(activeView, 300, 100)
End Sub
Protected Overrides Sub OnUpdate()
Enabled = My.ArcMap.Application IsNot Nothing
End Sub
End Class
Give the code below a try. This is executed from the OnClick event from an ArcMap command button that Inherits from BaseCommand. It displays the selected features in the map in the identifyDialog just as you were needing it to except I used AddLayerIdentifyOID() instead of AddLayerIdentifyPoint() although both should work.
Public Overrides Sub OnClick()
'VBTest.OnClick implementation
Try
Dim mxDoc As IMxDocument = m_application.Document
Dim map As ESRI.ArcGIS.Carto.IMap = mxDoc.FocusMap
Dim layer As ESRI.ArcGIS.Carto.ILayer
Dim flayer As ESRI.ArcGIS.Carto.IFeatureLayer
Dim featSelection As ESRI.ArcGIS.Carto.MapSelection = map.FeatureSelection
Dim feat As ESRI.ArcGIS.Geodatabase.IFeature = featSelection.Next()
Dim count As Int16 = 0
While feat IsNot Nothing
count += 1 ' flag for clearing layers
flayer = New ESRI.ArcGIS.Carto.FeatureLayer()
flayer.FeatureClass = feat.Class
layer = flayer
DoIdentify(layer, feat.OID, (count = 1))
feat = featSelection.Next()
End While
Catch ex As Exception
' handle error
MsgBox("Error: " + ex.Message)
End Try
End Sub
Private Sub DoIdentify(ByVal layer As ESRI.ArcGIS.Carto.ILayer, ByVal OID As Int32, Optional ByVal clearLayers As Boolean = True)
If layer Is Nothing Or OID <= 0 Then
Return
End If
Dim pMxDoc As IMxDocument = m_application.Document
Dim activeView As ESRI.ArcGIS.Carto.IActiveView = pMxDoc.ActiveView
Dim map As ESRI.ArcGIS.Carto.IMap = activeView.FocusMap
Dim identifyDialog As ESRI.ArcGIS.CartoUI.IIdentifyDialog = New ESRI.ArcGIS.CartoUI.IdentifyDialogClass()
Dim screenDisplay As ESRI.ArcGIS.Display.IScreenDisplay = activeView.ScreenDisplay
Dim display As ESRI.ArcGIS.Display.IDisplay = screenDisplay
identifyDialog.Map = map ' REQUIRED
identifyDialog.Display = display ' REQUIRED
' Clear the dialog
If clearLayers Then
identifyDialog.ClearLayers()
End If
' Add our selected feature to the dialog
identifyDialog.AddLayerIdentifyOID(layer, OID)
' Show the dialog
identifyDialog.Show()
End Sub

Operation is not valid, because of the current state of the object

I have an Infopath 2010 form with a button and the following event code:
Public Sub txtGetCC_Changing(ByVal sender As Object, ByVal e As XmlChangingEventArgs)
' Ensure that the constraint you are enforcing is compatible
' with the default value you set for this XML node.
Dim myNav As XPathNavigator = Me.MainDataSource.CreateNavigator
If myNav.SelectSingleNode("//my:txtGetCC", Me.NamespaceManager).ToString.Length > 0 Then
Dim myIterator As XPathNodeIterator = myNav.Select("/my:myFields/my:group11/my:group12", Me.NamespaceManager)
Dim CCnummer As String = ""
Dim CCsource As DataSource = Me.DataSources("CostCenters")
Dim email As String = ""
While myIterator.MoveNext
CCnummer = myIterator.Current.SelectSingleNode("my:cbRTcc", Me.NamespaceManager).Value
Dim myNavigator As XPathNavigator = Me.DataSources("CostCenters").CreateNavigator
Dim rows As XPathNodeIterator = myNavigator.Select("/dfs:myFields/dfs:dataFields/d:CostCenters", Me.NamespaceManager)
email = ""
While (rows.MoveNext)
Dim ccnumber As String = rows.Current.SelectSingleNode("#CCnumber", Me.NamespaceManager).Value
If ccnumber = CCnummer Then
email = rows.Current.SelectSingleNode("#Email", Me.NamespaceManager).Value
Exit While
End If
End While
myIterator.Current.SelectSingleNode("//my:txtCCowner", Me.NamespaceManager).SetValue(email)
End While
End If
End Sub
The line just before the last END WHILE is not working.
I want to update the column txtCCowner in the repeating table to be updated with the email address found in the external datasource.
Everything works except this line.
The error message I get is: Operation is not valid, because of the current state of the object.
Why do I get this error, what am I doing wrong?
Any help is greatly appreciated.
rg.
Eric

Outlook add a task

I need some help please. I have managed to create a task in outlook using VB and SendItem. My problem is the code I'm using is creating two tasks and not just the one I want.
I have tried removing the .Save as I thought this was the cause but it still adds two tasks. I have added breakpoints to the code to ensure its not cycling round twice for some obscure reason and it just executes once.
Would appreciate someone telling me the obvious please
Code snippet:
`If bNotFount = False Then
Set Ns = Application.GetNamespace("MAPI")
Set ItemT = GetCurrentItem()
Set taskFolder = Ns.GetDefaultFolder(olFolderTasks)
Set olTask = Ns.GetDefaultFolder(olFolderTasks).Items.Add(olTaskItem)
With olTask
.Subject = ItemT.Subject
.Attachments.Add ItemT
.Body = ItemT.Body
.DueDate = Now + 1
.Move taskFolder
.Save
.Display 'show the task to add notes
End With
End If'
You don't need to move it to the default task folder because you saving it there anyway.
Just remove .Move taskFolder line.
I updated your code:
Private Sub Application_ItemSend(Item As Object, ByRef Cancel As Boolean) Handles Application.ItemSend
Dim ns As Outlook.NameSpace
Dim taskFldr As Outlook.Folder
Dim olTask As Outlook.TaskItem
' If bNotFount = False Then
Ns = Application.GetNamespace("MAPI")
taskFldr = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks)
olTask = taskFldr.Items.Add
With olTask
.Subject = Item.Subject
.Attachments.Add(Item)
.Body = Item.Body
.DueDate = Now + 1
.Save()
.Display() 'show the task to add notes
End With
' End If
End Sub

Resources