I'm developing an application as a windows service. The service retrieves a path from app.config, but for some reason part of the retrieved path is changing during the execution and replaced with C:\Windows\System32.
This is my app.config
[...]
<appSettings>
<add key="Freq_Minutes" value="1" />
<add key="Connectionstring" value="Server=FENIX\SQL2005;Database=amoselprat;Uid=amos;Pwd=mosa;"/>
<add key="AMOSEsdara_Path" value="C:\TEMP\AMOS_ESDARA"/>
<add key="EsdaraAMOS_Path" value="C:\TEMP\ESDARA_AMOS"/>
</appSettings >
[...]
This is the function that retrieves the key
Public Function GetInfo(ByVal Label As String) As String
Dim Value As String
Try
Value = System.Configuration.ConfigurationManager.AppSettings(Label).ToString
Catch ex As Exception
Value = Nothing
End Try
Return Value
End Function
And this is troubled code
Public Sub Components(ByVal AutoNumber As String)
Dim sw As StreamWriter
Dim File As String
File = GetInfo("AMOSEsdara_Path") & "\AMOS_ESDA_COMP_" & Autonumber & ".xml"
Try
EventLog_AMOSEsdara.WriteEntry("AMOSEsdara Interface - Creating components file " & File)
sw = File.CreateText(File)
[...]
Catch Ex As Exception
EventLog_AMOSEsdara.WriteEntry("AMOSEsdara Interface - Error creating file " & File & " Error: " & Ex.Message)
End Try
End Sub
Running as a service EventLog is writting the below error:
AMOSEsdara Interface - Error creating file AMOS_ESDARA\AMOS_ESDA_COMP_000006.xml Error: Can not find a part of the path 'C:\Windows\system32\AMOS_ESDARA\AMOS_ESDA_COMP_000006.xml'.
I tried to use the same code into a Console Application instead Service Application and it is working fine. The retrieved path is correct and the XML file is created successfully at C:\TEMP\AMOS_ESDARA
What I'm missing? Thanks in advance.
Solved.
Public Function GetInfo(ByVal Label As String) As String
Dim Value As String
System.IO.Directory.SetCurrentDirectory((System.AppDomain.CurrentDomain.BaseDirectory))
Try
Value = System.Configuration.ConfigurationManager.AppSettings(Label).ToString
Catch ex As Exception
Value = Nothing
End Try
Return Value
End Function
Related
According to the information on MSDN I should be able to set the CustomLocation property of the FileLogTraceListener. In doing so, I'm finding that the logging stops when I go away from using the default property. I'm not real sure what I could be doing wrong here. What am I missing?
Module PackingListPrintModule
'Establish application path, replace appPath on deployment
Public appPath As String = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location)
Public Property CustomLocation As String
Public logtrace As New FileLogTraceListener
Function setCustomLogLocation() As String
logtrace.CustomLocation = appPath
setCustomLogLocation = appPath
End Function
Sub Main()
Try
'Test use the logtrace instace to write a line
logtrace.Append = True
logtrace.WriteLine("Set the log and application path to" & setCustomLogLocation())
'Test use of the Log.WriteEntry method to write a line (Works with default settings)
My.Application.Log.WriteEntry("Checking that save location exists")
logtrace = Nothing
Catch ex as Exception
msgbox(ex.Message)
Finally
logtrace = Nothing
Environment.Exit(0)
End Sub
End Module
I'm trying to upload a file to dropbox. The file gets uploaded and code works when i'm running locally. But file never gets uploaded when published on the server. I'm having the following error .
Could not load type 'System.Security.Authentication.SslProtocols' from assembly 'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*********'.
I'm trying the below code sample to upload it
public sub uploadtodropbox()
Using httpclient As New HttpClient
httpclient.Timeout = TimeSpan.FromMinutes(20)
Dim _DropboxClient = New DropboxClient(ApiKeyDropBox, config)
Dim resultstring As String = UploadToDB(_DropboxClient, dropboxdir, docName, fileBytes)
_DropboxClient.Dispose()
If Not resultstring = "RanToCompletion" Then
ErrorMsg &= "The following error occured: " & resultstring
End If
End Using
End Sub
and this is the funtion that is uploading to Dropbox
Private Function UploadToDB(_DropboxClient As DropboxClient, Directory As String, Filename As String, Content As [Byte]()) As String
Try
Dim result As String = "Unknown"
Dim trycnt As String = 0
Dim tryLimit As String = 20
Dim respnse As Task(Of FileMetadata)
Using _mStream = New MemoryStream(Content)
respnse = _DropboxClient.Files.UploadAsync(Convert.ToString(Directory & Convert.ToString("/")) & Filename, WriteMode.Overwrite.Instance, body:=_mStream)
While Not respnse.IsCompleted And trycnt < tryLimit
Threading.Thread.Sleep(1000)
trycnt += 1
result = respnse.Status.ToString()
End While
UploadToDB = result
End Using
End try
END function.
I have tried without using the httpclient then i am getting this error :
The type initializer for 'Dropbox.Api.DropboxRequestHandlerOptions' threw an exception.
Thank you
I go the answer . I have system.Net.primitives assembly that is creating a problem uploading the file to Dropbox. All i need to do is delete the reference and also the System.Net.Http has versions have been set wrong in the web.config file. Once i set that in the configuration everything works fine.
For the certificate I have set the on post back to validate and allow the certificates generated in the event handler.
While attempting to issue the SAVE of the XmlDocument class on an XML document, specifically on this line of code:
myXmlDocument.Save(strFileZillaFilePathAndName).
I get... During entry update - save of FileZilla file failed. The process cannot access the file 'C:\Program Files (x86)\FileZilla Server\FileZilla Server.xml' because it is being used by another process.
It occurs in the FindAndUpdateXMLEntries(...) method called from within my UpdateFtpAccountsProcess(...) function.
I thought that this use of the SAVE did not require a close.
It happens on a 2nd execution of the function so it seems that the file is not being closed. It should be closed by the 1st execution and it is not be being used by another process
Public Function UpdateFtpAccountsProcess(ByVal strIpAddress As String, ByVal strPassword As String, ByVal iBackupSpaceId As Integer, ByVal iFtpAccountId As Integer, ByVal strFtpAccountPassword As String, ByVal strAccountType As String) As Boolean Implements IBackupServerService.UpdateFtpAccountsProcess
Dim strErrorMessage As String = ""
' Start the backup service logging.
StartTheLog(iBackupSpaceId)
' Write an log entry.
strInputLogMessage = "In UpdateFtpAccountsProcess method."
LogAnEntry(strInputLogMessage)
' Validate the password arguement in order to use this WCF service method.
' Read the app.config files "appSettings" section to get the backup server password. If it matches, continue.
strEncryptedBackupServerPassword = GetAppSetting(strKeyPassword)
If strEncryptedBackupServerPassword = strPassword Then
' Update the FTP account's encrypted password by "backup space id" and "account type". The accounts are stored in the FileZilla Server.xml file.
' Read the app.config file to get the “FileZilla path and name”.
strFileZillaFilePathAndName = GetAppSetting(strKeyFileZilla)
' Read the app.config file to get the “FileZilla Application path and name”.
strFileZillaFileApplicationPathAndName = GetAppSetting(strKeyFileZillaApplication)
If ((strFileZillaFilePathAndName = "Not Found" Or strFileZillaFilePathAndName = "Error") Or (strFileZillaFileApplicationPathAndName = "Not Found" Or strFileZillaFileApplicationPathAndName = "Error")) Then
strErrorMessage = "During update of FTP accounts - cannot find the FileZilla entries in the app config. Space Id: " & iBackupSpaceId.ToString()
Else
Try
' Read the XML file and update the "password" of 1 of the 2 User entries [ftp accounts] - for the "backup space id".
FindAndUpdateXMLEntries(strFileZillaFilePathAndName, iBackupSpaceId, strFtpAccountPassword, strAccountType)
Try
' Execute command to run the FileZilla application to have FileZilla re-read the configuration.
ReloadFileZillaConfig(strFileZillaFileApplicationPathAndName)
Catch ex As Exception
strErrorMessage = "From: ReloadFileZillaConfig() ---> " & ex.Message
End Try
Catch ex As Exception
' Attach the message coming from the FindAndUpdateXMLEntries() method.
strErrorMessage = "During update of FTP account - Space Id: " & iBackupSpaceId.ToString() & " from: FindAndUpdateXMLEntries() ---> " & ex.Message
End Try
End If
Else
strErrorMessage = "During update of FTP accounts - invalid backup server password. It must match the app.config entry. Space Id: " & iBackupSpaceId.ToString()
End If
If strErrorMessage <> "" Then
Throw New System.Exception(strErrorMessage)
End If
' End the backup service logging.
EndTheLog()
Return bSuccess = True
End Function
Public Sub FindAndUpdateXMLEntries(ByVal strFileZillaFilePathAndName As String, ByVal iBackupSpaceId As Integer, ByVal strFtpAccountPassword As String, ByVal strAccountType As String)
Dim strErrorMessage As String = ""
Dim xmlNode1 As XmlNode
Dim xmlNode2 As XmlNode
Dim xmlNode3 As XmlNode
Dim strUserNodeAtrributeNameValue As String
Dim strUnderUserNodeThisNodesAtrributeNameValue As String
Dim bSuccess As Boolean = False
' The XmlDocument class represents the XML document and has a Load method to load the document from a file, stream, or an XmlReader.
' So load in the XML file.
Dim myXmlDocument As XmlDocument = New XmlDocument()
' Write an log entry.
strInputLogMessage = "In FindAndUpdateXMLEntries method."
LogAnEntry(strInputLogMessage)
Try
' Load in the XML file.
myXmlDocument.Load(strFileZillaFilePathAndName)
' Use the XmlNode object that the DocumentElement property of the XmlDocument returns to manipulate an XML node.
xmlNode1 = myXmlDocument.DocumentElement
' Field to match to under the "Users" node. Building the "#-Private" or "#-Private" User root node.
strUserNodeAtrributeNameValue = iBackupSpaceId.ToString() & "-" & strAccountType.Trim()
' The next field to match to under the "User" node that I find.
strUnderUserNodeThisNodesAtrributeNameValue = "Pass"
' Iterate thru to find the node to update.
For Each xmlNode1 In xmlNode1.ChildNodes
If xmlNode1.Name = "Users" Then
' Find the child nodes in "Users" only.
For Each xmlNode2 In xmlNode1.ChildNodes
' Find the "User" node that I want.
If xmlNode2.Attributes("Name").Value = strUserNodeAtrributeNameValue Then
For Each xmlNode3 In xmlNode2.ChildNodes
' Find the node that I want that is under the "User" node. Looking for: <Option Name="Pass">some value</Option>
If xmlNode3.Attributes("Name").Value = strUnderUserNodeThisNodesAtrributeNameValue Then
' Update the XML to the new password value.
xmlNode3.InnerText = strFtpAccountPassword
bSuccess = True
Exit For
End If
If bSuccess = True Then
Exit For
End If
Next
End If
Next
End If
If bSuccess = True Then
Exit For
End If
Next
If bSuccess = True Then
Try
' Use the Save method of the XmlDocument class to save the altered XML back to the input XML file.
myXmlDocument.Save(strFileZillaFilePathAndName)
Catch ex As Exception
strErrorMessage = "During entry update - save of FileZilla file failed. " & ex.Message
End Try
Else
strErrorMessage = "During entry update - No User node to update"
End If
Catch ex As Exception
strErrorMessage = "During entry update - load of FileZilla file failed. " & ex.Message
End Try
If strErrorMessage <> "" Then
Throw New System.Exception(strErrorMessage)
End If
End Sub
I have tried a diverse amount of methods this is my latest method which I have tried to not fire the error but to no avail I still get the FileIOPermission error
The Full error is
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
The code I am using is the below
Dim permissions As New Security.PermissionSet(Security.Permissions.PermissionState.None)
permissions.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Execution))
permissions.AddPermission(New Security.Permissions.SecurityPermission(Security.Permissions.SecurityPermissionFlag.Assertion))
permissions.Assert()
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)
Dim asm As Reflection.Assembly = Reflection.Assembly.Load("ReportingServiceUtils, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cca1b177d76f2036")
Dim asm_name As Reflection.AssemblyName = asm.GetName()
ReportViewer1.LocalReport.AddFullTrustModuleInSandboxAppDomain(New Security.Policy.StrongName(New Security.Permissions.StrongNamePublicKeyBlob(asm_name.GetPublicKeyToken()), asm_name.Name, asm_name.Version))
The Code being used in the dll is the below
Public Sub Add(ByVal group As String, ByVal groupCurrentPageNumber As String)
Try
If _GroupWithRunningMaxPageNumber.ContainsKey(group) Then
_GroupWithRunningMaxPageNumber(group) = groupCurrentPageNumber
Else
If _GroupWithRunningMaxPageNumber.Count = 0 Then
Dim fileName = "C:\Working Folder\ms-dot-net-report-viewer-group-pagenation\ReportingServiceUtils\test.xml"
sw = New System.IO.StreamWriter(fileName, False)
sw.WriteLine("<root>")
sw.WriteLine("</root>")
sw.Close()
sw.Dispose()
End If
_GroupWithRunningMaxPageNumber.Add(group, groupCurrentPageNumber)
sw.WriteLine("<Group current='" & group & "' lastPage='" & CStr(groupCurrentPageNumber) & "'/>", 1, 1)
sw.Close()
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Does anyone see anything wrong with the below code
I have found the solution and it was quite funny when I did.
The below 1 liner solves the problem of not being able to have file access from report.
Dim auth As New System.Security.Permissions.FileIOPermission( System.Security.Permissions.PermissionState.Unrestricted)
Using PermissionSet
var sec = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(sec);
You can convert from C# to VB.net easyly
I am trying to build an error handler for my desktop application. The code Is in the class ZipCM.ErrorManager listed below.
What I am finding is that the outputted file is not giving me the correct info for the StackTrace.
Here is how I am trying to use it:
Try
'... Some stuff here!
Catch ex As Exception
Dim objErr As New ZipCM.ErrorManager
objErr.Except = ex
objErr.Stack = New System.Diagnostics.StackTrace(True)
objErr.Location = "Form: SelectSite (btn_SelectSite_Click)"
objErr.ParseError()
objErr = Nothing
End Try
Here is the class:
Imports System.IO
Namespace ZipCM
Public Class ErrorManager
Public Except As Exception
Public Location As String
Public Stack As System.Diagnostics.StackTrace
Public Sub ParseError()
Dim objFile As New StreamWriter(Common.BasePath & "error_" & FormatDateTime(DateTime.Today, DateFormat.ShortDate).ToString().Replace("\", "").Replace("/", "") & ".log", True)
With objFile
.WriteLine("-------------------------------------------------")
.WriteLine("-------------------------------------------------")
.WriteLine("An Error Occured At: " & DateTime.Now)
.WriteLine("-------------------------------------------------")
.WriteLine("LOCATION:")
.WriteLine(Location)
.WriteLine("-------------------------------------------------")
.WriteLine("FILENAME:")
.WriteLine(Stack.GetFrame(0).GetFileName())
.WriteLine("-------------------------------------------------")
.WriteLine("LINE NUMBER:")
.WriteLine(Stack.GetFrame(0).GetFileLineNumber())
.WriteLine("-------------------------------------------------")
.WriteLine("SOURCE:")
.WriteLine(Except.Source)
.WriteLine("-------------------------------------------------")
.WriteLine("MESSAGE:")
.WriteLine(Except.Message)
.WriteLine("-------------------------------------------------")
.WriteLine("DATA:")
.WriteLine(Except.Data.ToString())
End With
objFile.Close()
objFile = Nothing
End Sub
End Class
End Namespace
What is happenning is the .GetFileLineNumber() is getting the line number from objErr.Stack = New System.Diagnostics.StackTrace(True) inside my Try..Catch block. In fact, it's the exact line number that is on.
Any thoughts of what is going on here, and how I can catch the real line number the error is occuring on?
Edit: Changed the code to account for the Exception.StackTrace being a string rather than a real StackTrace
You're creating a new StackTrace, so then it will be for the line you're declaring it on, if you want the line number of the original exception, use the stack trace in Exception.StackTrace.
I think you're being a little confused, I can't see why you create the new StackTrace at all?
Edit: Added more bits to the answer here since easier to see the syntax than in a comment
Currently you have the line
objErr.Stack = New System.Diagnostics.StackTrace(True)
Which means that you're creating a whole new stacktrace, starting when you're creating it.
Instead change that line to:
objErr.Stack = New System.Diagnostics.StackTrace(ex, True)
Which will have the stacktrace from when the error actually happened.
Edit: Added complete sample:
Private Sub a1()
Try
a2()
Catch ex As Exception
Dim st As New StackTrace(True)
Debug.WriteLine(String.Format("ST after exception, will give line number for where st was created. Line No: {0}", st.GetFrame(0).GetFileLineNumber()))
st = New StackTrace(ex, True)
Debug.WriteLine(String.Format("ST after exception using exception info, will give line number for where exception was created. Line No: {0}", st.GetFrame(0).GetFileLineNumber()))
End Try
End Sub
Private Sub a2()
Dim st As New StackTrace(True)
Debug.WriteLine(String.Format("ST before exception, will give line number for where st was created. Line No: {0}", st.GetFrame(0).GetFileLineNumber()))
Dim b As Integer = 0
Dim a As Integer = 1 / b
End Sub
SOLVED: You should change the wrong instruction, of the original code:
.WriteLine(Stack.GetFrame(0).GetFileLineNumber())
with this new one:
.WriteLine(Stack.GetFrame(Stack.FrameCount - 1).GetFileLineNumber)
and you will see, it will return the exact Line_Number of code
where the run time error occurs!!
You do not need to include a Stack property for your ErrorManager, because you have access to the stack trace through the exception.
From experience, I would create a Shared Sub Write(ex As Exception, location As String) method on the ErrorManager, and call in your Catch statement as:
ZipCM.ErrorManager.Write(ex, "Form: SelectSite (btn_SelectSite_Click)")
This change results in cleaner code, reduces the need to write lots of code in each Catch statement, and allows you to change the implementation of Write without having to revisit/rework/refactor each Catch statement.
For instance, you can change the Write method to also call Debug.WriteLine(ex) so you can see which exceptions you are handling during debugging without having to open the file. Moreover, you may want to include WriteNotify method that displays a message box of the exception then calls the Write method to log the exception.