File.Create not working in asp.net - asp.net

It might be a little funny but I am facing some stupid issue.
I am using
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
and
Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
when I using this the error is given to me is "Could not find a part of the path "
If am storing the path in a string then its working fine else producing error.
For your reference I am copying my function code snippet.
Please help
Thanks
Public Shared Function LogErrorToLogFile(ByVal ee As Exception, ByVal userFriendlyError As String) As String
Try
Dim path As String = context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))
' check if directory exists
If Not Directory.Exists(path) Then
'Directory.CreateDirectory(path)
Directory.CreateDirectory(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
End If
path = path & DateTime.Today.ToString("dd-MMM-yy") & ".log"
' check if file exist
If Not File.Exists(path) Then
File.Create(path).Dispose()
'File.Create(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1"))).Dispose()
File.Create(ConfigurationManager.AppSettings("LogFilePath1")).Dispose()
End If
' log the error now
Using writer As StreamWriter = File.AppendText(path)
'Using writer As StreamWriter = File.AppendText(context.Current.Server.MapPath(ConfigurationManager.AppSettings("LogFilePath1")))
writer.WriteLine(HttpUtility.HtmlEncode(vbCr & vbLf & "Log written at : " & DateTime.Now.ToString() & vbCr & vbLf & "Error occured on page : " & context.Current.Request.Url.ToString() & vbCr & vbLf & vbCr & vbLf & "Here is the actual error :" & vbLf & ee.ToString()))
writer.WriteLine("==========================================")
writer.Flush()
writer.Close()
End Using
Return userFriendlyError
Catch
Throw
End Try
End Function

If you change the current lines with the comment-outed lines in your function code snippet, you're logic is changed because when you use Path, there is added a filename [dd-MMM-yy].log to the path-string. but you don't use that addition when you use the ConfigurationManager.AppSettings("LogFilePath1") directly!

I assume that you have not used the folder path with slash (ex: #"C:\FolderName\") and that is the reason you are getting the error.

Related

Copy and rename folder into another folder based on field value name

I have this code, my objective is to copy and paste a folder (with all its content) from a current template folder to paste onto a destination file path that is based on the field values as a condition to the new file destination name.
I am receiving an error:
FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
Not sure why, can you please help. Thank you.
Private Sub Command83_Click()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "C:\Database Test Center\Master" '<< Change
ToPath = "C:\Database Test Center\Projects\" & Me.ProjectName.Value & "-" &
Me.Lead.Value & "\MasterTemplate"
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFile Source:=FromPath & FileExt, Destination:=ToPath
MsgBox "You can find the files from " & FromPath & " in " & ToPath
End Sub

How to ensure I get current date in vb?

I have the following code:
Public Function UltimoIngreso() As Date
Try
UltimoIngreso = Now.Date 'I am not ALWAYS getting the current date and time
' --other lines of code
Catch ex As Exception
' An error has occured so display an error message.
ReportBDLog.ReportErrorBD(ex, Me.GetType.ToString & "." & "UltimoIngreso" & vbCrLf & "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf, System.Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Function
Sometimes, but not always, I get "Object reference not set to an instance of an object."
How do I ensure that Function UltimoIngreso always returns current date and time?
What am I missing?
This Function is used in an asp.net App.

vb.net string concat adds vbCrlf literal to the string

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

How to ignore logging errors for images in global asax

I have an error handler in my global.asax as follows;
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim ex = Server.GetLastError.GetBaseException
Dim lastErrorWrapper As HttpException = Server.GetLastError()
Dim lastError As Exception = lastErrorWrapper
If lastErrorWrapper.InnerException IsNot Nothing Then
lastError = lastErrorWrapper.InnerException
End If
My.ErrorHandler.LogError( _
"<BR/><BR/>URL: " & Request.RawUrl & _
"<BR/><BR/>STACK: " & ex.StackTrace & _
"<BR/><BR/>SOURCE: " & ex.Source & _
"<BR/><BR/>MESSAGE: " & ex.Message & _
"<BR/><BR/>TYPENAME: " & ex.GetType.ToString & _
"<BR/><BR/>INNER EXCEPTION: " & lastError.ToString & _
"<BR/><BR/>REFERRER: " & HttpContext.Current.Request.Url.AbsoluteUri & _
"<BR/><BR/>USER IP: " & Request.ServerVariables("REMOTE_ADDR") & " -- " & Request.ServerVariables("HTTP_USER_AGENT"))
End Sub
Obviously, this works great and sends me an email whenever there is an error. But, this is also true for any images that are not found in the file system. It gives me a "File does not exist." error. Is there a way to ignore logging errors for images that are not located on disk?
Cant you resolve the FileNotFoundException instead? If the exception should not occur then rather resolve the issue than suppressing it. To handle a known exception you can use the following code.
if(Server.GetLastError().GetBaseException() is System.Web.HttpException)
{
//You could check whether the
//Server.GetLastError().GetBaseException().Message contains the appropriate message
Debug.WriteLine("Suppressed FileNotFoundException");
}else
//Log an unhandled exception
var ex = Context.Error;
if (ex is HttpException)
{
var httpException = (HttpException)ex;
if (httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
return; // Do nothing 404
}
I know that this sounds very easy, or very simple, or you may search for the error code, but this is what I do - simple check if the error contains the message of dose not exist:
lastErrorWrapper.ToString().Contains("does not exist.")

add client script to asp.net page dynamically

I want to add javascript to asp.net page dynamically.
can anybody point me towards working example?
i know it can be done by using Page.ClientScript.RegisterClientScriptBlock
but i have no idea to use it.
MSDN
This is the MSDN link
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "Utils"))
{
string UtilsScript = ResourceHelper.GetEmbeddedAssemblyResource("Utils.js");
this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Utils", UtilsScript, true);
}
I added the above example to help,
Here we test if the script is already registered (using the type an dkey we register against) get the script as a string from an embedded resource, then register (the last parameter of true tells the code to render Script tags).
hope this helps
P
An example to move the value of a Drop Down List to text field. The ID parameters are the Object.ClientID properties for the drop down list and text box.
Private Sub RegisterClientDropDownToTextBox(ByVal functionName As String, ByVal dropDownId As String, ByVal textBoxId As String)
Dim javascriptFunction As String = "function " & functionName & "() {" & _
"document.getElementById('" & textBoxId & "').value = document.getElementById('" & dropDownId & "').value;" & _
"}"
Dim javascriptWireEvent As String = "document.getElementById('" & dropDownId & "').onclick = " & functionName & ";"
Me.ClientScript.RegisterClientScriptBlock(Me.GetType(), functionName & "_ScriptBlock", javascriptFunction, True)
Me.ClientScript.RegisterStartupScript(Me.GetType(), functionName & "_Startup", javascriptWireEvent, True)
End Sub

Resources