Tuesday, January 6, 2009

Error Handling in asp.net


The Error handling model in asp.net lets you handle errors at 3 different levels

Method Level
Page Level
Application Level


Method Level:

We use Method level error handling for all the recoverable errors.
For non recoverable errors it goes to next level.

For the all the errors which can be handled we use

Try…Catch blocks

For throwing any message if an error occurred or any exception we use .

Throw… block

To clean up the error we use

Finally… block


Syntax:

Try

‘’..code for execution

Catch ex as Exception

‘’..handle the error

Finally

‘clear the error

End try



Try block contains the code need to be implemented ,
Catch block is used to handle the error
Finally block used to clear the error.


Let us suppose we are using database connection in the code and if the error occurs in the query .net framework doesn’t close the database connections. I this case we need to write the code in the FINALLY block to close he connection.


Page Level:

We use Page Level event handling when we want to trap the errors occurred in the page and redirect the user to another page which the displays the error details.

Implementation:

Write required code in the Page_Error event handler of the page.

The Page_Error event of the ASP.NET Page object is raised any time an unhandled error occurs in a page


Use GetLastError method to get reference to the latest error occurred


Set the ErrorPage property of the page object to the URL of the page which need to display the error details

The page will be redirected to the url mentioned when any unhandled error occurs.


Add error number,message to the query string in the URL.
Dim lastError As Exception

'get the last error that occurred

lastError = Server.GetLastError( )
Page.ErrorPage = "Errorpage.aspx"?errMessage=" & lastError.Message &errnumber=" & lastError.number

  • When any Unhandled error occurred in the page level ,Page_Error event is triggered and the page will be redirected to the error page mentioned with all the details of the error in the query string.
  • If we don’t add any Query string parameters,.NET will assign one for usi.e aspxerrorpath which gives relative path of the error message.

Application Level: If we want to Log all the errors raised in an application in Single location we use application level error handling. Add Page_Error event handler to the page to throw the error to next level i.e application level Add Application_error event handler in global.asax file to perform logging and redirection
To process errors at the application level, each page must include the Page_Error event handler with a single line of code to rethrow the last exception that occurred.

Private Sub Page_Error(ByVal sender As ObjectByVal e As System.EventArgs) Handles MyBase.Error 'Rethrow the last error that occurred

Throw Server.GetLastError( )

End Sub

***********Error handling in Application_error

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Const EVENT_LOG_NAME As String = "Application"

Dim lastException As Exception

Dim Log As EventLog

Dim message As String

'get the last error that occurred

lastException = Server.GetLastError( )

'create the error message from the message in the last exception along 'with a complete dump of all of the inner exceptions (all exception 'data in the linked list of exceptions)

message = lastException.Message & lastException.ToString( )

'Insert error information into the event log

Log = New EventLog

Log.Source = EVENT_LOG_NAME

Log.WriteEntry(message,EventLogEntryType.Error)

'perform other notifications, etc. here

'clear the error and redirect to the page used to display the 'error information

Server.ClearError( )

Response.Redirect("Errorpage.aspx?errMessage=" & lastException.Message _)

End Sub

















Tuesday, December 30, 2008

Remote Shut down-Script

******Shutdown, power off or restart the machine remotely ******

Dim x, y
Set objWShell = CreateObject("WScript.Shell")
Set x =CreateObject("WScript.Shell")

'wait for 10 Sec for confirmation,if not confirm it as "Yes"

y=x.Popup("System about to shutdown in 10 seconds",10,"Answer This Question:",4 + 32)

if y=7 then


Set objCmd = objWShell.Exec("shutdown /l /a /y")
else

Set objCmd = objWShell.Exec("shutdown -s -t 01")

end if

*******Other Arguments ********





Argument detials


-s shutdown the computer

-f Forces the applications to close ,close the hung/busy application instantly without prompting you to end the application manually(end now)

-a Aborts system Shut down instantly (if confirmation is no,"shutdown /l /a /y" in above example)

-t Interval for shutdown.

-r Restarts

-l Local Machine

-m \\computer_name_or_IP_Address Remote Machine

shutdown -s -f -t 10 -m \\10 indicates seconds to wait before shutdown




Friday, December 12, 2008

Sending mails from sql server

Configure datqabase email in the server...


USE MyDB
GO
Declare @tableHTML NVARCHAR(MAX)
-- @query='select * from Employee where Id=78';
SET @tableHTML =
N '<>Employee Entry Details Report' +
N '< border="1">' +
N '<><>Id< /th><>Date< /th><>EmployeeName' +
N '<>Intime< /tr>' +
CAST ( ( SELECT td =H_Id, '',
td =convert(varchar,getdate(),106), '',
td = (H_Firstname + ' ' + rtrim(H_LAstname)),'',
td = (mydb.acsuser.getFirstInTime(H_Id,convert(varchar,getdate(),106))), ''
FROM mydb.dbo.employee where H_Manager_Id=2034
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'< /table>' ;


EXEC msdb.dbo.sp_send_dbmail @profile_name='Pname',

mailto:recipients=,
--@query='select rtrim(H_Id),cast((H_Firstname + '' '' + rtrim(H_LAstname)) as varchar(100)) as Employeename,cast(mydb.acsuser.getFirstInTime(H_Id,convert(varchar,getdate(),106)) as varchar(20)) as FirstIntime from mydb.Employeed where H_Manager_Id=2034',
@subject='Employee Entry Timings',
@body= @tableHTML,
@body_format = 'HTML',
--Attach output inside the body
-- @attach_query_result_as_file = 0 ,
--seperator
@query_result_separator = '',
--@query_result_separator ='char(10)',
--@query_result_width =880,
@query_result_header =0,
--exclude output message
@exclude_query_output = 1,
@query_no_truncate =1;


''''''''''Usefull links for the concept''''''''''''''''''''''''''''
http://msdn.microsoft.com/en-us/library/ms190307.aspx
http://msdn.microsoft.com/en-us/library/bb510680.aspx
http://blog.sqlauthority.com/2008/08/23/sql-server-2008-configure-database-mail-send-email-from-sql-database/

Thursday, April 24, 2008

google one more add on

Hi,
Here is another interesting service from Google.
Want to know, which movie is being showed in which theater at what time?
Just enter your city name. It lists everything. Really

http://www.google.co.in/movies

Hope its helpful to you all..

Monday, March 31, 2008

Strip Single Quotes While Export To Excel

Genrally to export data form Sql server to Excel.We generally do via IMPORT/Export Wizard.
The steps we generally follow are.




-Select the Source Server and the database.









-Select Destination as Microsoft Excel-Locate the file to Export Data



-Specify Whether it is direct export from table or View or any Query



-If it is from table select the table

-Execute the package




-Complete the wizard-Export the data








After export the first character in every single cell of the excel spreadsheet is
the quotation mark ' evn thoygh this is not present in the table values.

That is how Excel ISAM driver was designed to work. It adds the apostrophe to discriminate
between text and numeric values.

The Work around for this problem is

While exporting the data instead of Selecting the destination as Microsoft Excel choose it as Flat file Destination , dont forget to check check Unicode checkbox




-Specify Whether it is direct export from table or View or any Query

-If it is from table select the table

-Configure Flat file destination
set Row delimiter as - {CR}{LF}
set Column Delimtier as - Tab {t}




-Save and Execute the Package

Export the data .

Once the data is exported sucessfully,you can see the single quotes got stripped of.



--Happy Programming
**Harika**

Wednesday, March 26, 2008

Downloading File from Web server

Hi
In my previous BLog,we have seen uploading file to the Webserver,
Let us discuss today on Download.

To Download a file the steps we need to do are
1.Create a listbox and name it as "Lstfiles"
2.Create a Button control and name it as "btndownload"

In the Code behind Page.
1.Imports System.data.IO (to do file operations)
2.Imports System.Data Namespaces
3.In the page load event bind the list of files in the folder to the Listbox.

We can bind the data using GetFiles Method of Directory Class





Here I am getting the list of files from the "UploadDocs" folder from the server




Dim i As Int16
'files is an array that stores list of files in the dirctory mentioned
Dim files() As String
'Server.MapPath("UploadDocs") get address of the folder on the server machine
files = Directory.GetFiles(Server.MapPath("UploadDocs"))
For i = 0 To files.Length - 1
files(i) = New FileInfo(files(i)).Name
Next
'Bind the array to Listbox
If Not Page.IsPostBack Then
lstfiles.DataSource = files
lstfiles.DataBind()
End If








4.In btndownload Click event stream the selected file from the listbox to Response Object.






The code behind code would be as follows..


Imports System.IO
Imports System.Data


Partial Class FileDownload
Inherits System.Web.UI.Page


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


Dim i As Int16
'files is an array that stores list of files in the dirctory mentioned
Dim files() As String
'Server.MapPath("UploadDocs") get address of the folder on the server machine
files = Directory.GetFiles(Server.MapPath("UploadDocs"))
For i = 0 To files.Length - 1
files(i) = New FileInfo(files(i)).Name
Next
'Bind the array to Listbox
If Not Page.IsPostBack Then
lstfiles.DataSource = files
lstfiles.DataBind()
End If


End Sub


Protected Sub btndownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btndownload.Click
Dim f1 As FileInfo
Dim Selfile As String
Selfile = Server.MapPath("UploadDocs") & "\" & lstfiles.SelectedItem.Text
f1 = New FileInfo(Selfile)
'Clear the buffer,if it not cleared there is a chance of OverWriting the file and file gets Corrupted
Response.Clear()
'Add ContentDisposition and Content Length,Content type to header file
Response.AddHeader("Content-Disposition", "attachment;filename=" & lstfiles.SelectedItem.Text)
Response.AddHeader("Contetn-Length", f1.Length)
Response.ContentType = "application/octet-stream"
Response.Write(Selfile)
Response.End()
End Sub
End Class






To stream a file to a browser, you must write it to the Response object. The first step in writing a file to the Response object is to call its Clear method to remove any data currently in the buffer stream. If the Response object already contains data, when you attempt to write a file to it, you will receive a corrupt file error.



Before writing the file, use the AddHeader method of the Response object to add the name of the file being downloaded and its length to the output stream. You must also use the ContentType method to specify the content type of the file. In this example, the type is set to application/octet-stream so that the browser will treat the output stream as a binary stream and prompt the user to select a location to which to save the file. In your own application you may want to set the content type to an explicit file type, such as application/PDF or application/msword. Setting the content type to the explicit file type allows the browser to open it with the application defined to handle the specified file type on the client machine.

Now, at last, you are ready to write the file to the Response object using Response.WriteFile. When the operation is complete, call Response.End to send the file to the browser.





Any code that appears after the Response.End statement will not be executed. The Response.End statement sends all buffered data in the Response object to the client, stops the execution of the page, and raises the Application_EndRequest event

Thursday, March 13, 2008

File upload in ASP.Net




Upload File to the Server
To upload a file to the server we need to do the foolowing steps.
1. Set the form encoding type to multipart/form-data.
<

.Drag Fileupload control from toolbox to designer window
3.Add a button called Upload to upload the File
4.Create folder in the server where the uploded files to be saved.In the example "UploadDocs" is the folder where all the uploded files will be saved.

By default, the ASPNET account under which ASP.NET runs does not have permission to write files to the filesystem of the server. You will need to modify the security settings on the folder used for uploads to allow the ASPNET user to write to the folder. The steps for doing so vary somewhat for the different flavors of Windows, but the basic steps are these:Using Windows Explorer, browse to the folder where the uploaded files will be saved.Access the security settings by right-clicking on the folder, select Properties, and then select the Security tab.Add the ASPNET user and allow write access.

Create a page called fileupload.aspx.

1.Create a File upload control name it as fileupload1

2.Create upload button

3. Change enctype to enctype="multipart/form-data" in Form tag


In onclick event of upload button,write the following code

Fileupload.aspx.vb code



****Imports the Name Space ***********


Imports System.IO




Protected Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Upload.Click
Dim serverpath As StringDim filename As String
Dim f As FileInfofilename = FileUpload1.PostedFile.FileNamef = New FileInfo(filename)
If f.Name <> "" Then
serverpath = Server.MapPath("Uploaddocs")
FileUpload1.PostedFile.SaveAs(Server.MapPath("Uploaddocs") & "\" & f.Name)
End If
End Sub





Here ends your code...

Note : By default, file uploads are limited to 4M. Any attempt to upload a file largerthat 4M will result in an error message.
You can change the maximum file size that can be uploaded bychanging the maxRequestLength attribute of the httpRuntime element in the web.config file,