Thursday, January 8, 2009

Enable Tracing in Shared components Using Listeners (Web and Non Web Application):

Enable Tracing in Shared components (Web and Non Web Application):

To enable tracing in business components which are used by both web and non web application,we need to implement trace without using the HTTPContext.(Components which are outside the application as well)

This can be done using Listeners which are inherited from Trace.Listener class.

A listener is an object that receives the trace output and outputs it somewhere; that somewhere could be a window in your development environment, a file on your hard drive, a Windows Event log, a SQL Server or Oracle database, or any other customized data store


.Net Framework uses the concept of Trace Listener in handling the Trace messages.In this context we need to create a Listener that inherited from trace.Listener class and add this to the Listener collection in the Web.Config File.
When we enable tracing in the application by default Single Listener is added to the Listeners Collection.If we want add more listeners we need to add to the listener collection as well Programatically in web.config file.


  <system.diagnostics>

<trace autoflush="true" indentsize="0">

<listeners>

<add name="ComponentListener"

type="Myproject.Examples.compListener, esamples" />

</listeners>

</trace>

</system.diagnostics>

The custom TraceListener in our example overrides the Write and WriteLine methods to write the passed message to the current HTTP context.

Both the Trace and Debug classes share the same TraceListenerCollection object; therefore, if you add a listener to Trace object, it will also be available to Debug object, and vice versa.

Some of the methods of Trace Listeners:
Fail : Outputs the specified text with the Call Stack.

Write :Outputs the specified text.
WriteLine :Outputs the specified text and a carriage return.
Flush :Flushes the output buffer to the target media.
Close :Closes the output stream in order to not receive the tracing/debugging output.


Once the Listeners are added to the web.config file.

In the component created.

Import System.diagnostics and use trace.write methods to write trace to output.


There ENDS Tracing in the components implementing Listeners

Tracing in WebComponents Of Application

Tracing with in Web Application components

To identify the problems within the components of the application we need to refer to the current context of the Http request. This can be accomplished by the System. Web Name space.

Import System.Web Namespace in the component
Refer to the current context of the http request while using trace.write to output the trace information to the page or to the log file.


Trace.Write, as in

HTTPContext.Current.Trace.Write.



HTTPContext provides access to the trace object to write the output information.

Disadvantege of using the HTTPContext is it doenot allow not web applications to use the companent it is referring to.
It is impossible to share the component between Web and Non Web Applications.

To share the Component we need to implement Listener class instead of HTTP context.


Suppose we are using add method in the component.

Imports System.Web
----
----
----
public sub addnumbers(Byval a as integer, Byval b as integer)
int total;
// output trace message indicating the start of the Method execution

HttpContext.Current.Trace.Write("In Component", "Before performing addition");
Total=a+b
// output trace message indicating the end of the concatenations
HttpContext.Current.Trace.Write("In Component", "After performing Addition");
End Sub


In the aspx page in which we are using the component,just create instance and use it


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim webComponent As Testcomponet
webComponent = New Testcomponet
'add a string to the string in the component 1000 times
webComponent.addToString(2000, 1000)
End Sub 'Page_Load

Tuesday, January 6, 2009

Tracing in .Net

Tracing

We use tracing to pinpoint the problems in the code.Tracing allows to get whole host information about the currently executing request and write it in the trace of the page or in the Trace log.

Tracing can be achieved in two different methods.

-Page Level Tracing
-Application Level tracing

We can also dynamically turn Page level tracing on.
To enable page level tracing for the page we need to set the trace attribute to true in the
@page directive and then use trace.write () or Trace.warn() statements to write trace information to trace output.

Trace Context : Trace context is the class where .net stores information about all http requests and trace information. We can access Trace context class by using Page.trace attribute of the page .

Trace context class has 2 methods to write trace output to the page .They are

Trace.Write( )
Trace.Warn( )


The only difference between them is for Trace.Warn the output is ddisplayed in red in color such that it can be easily notified in the Trace log.

Both methods we have 3 versions .

1. If we pass single argument .Net writes it to Message column of the log file
2. If we use two string arguments, the first string appears in the Category column and the second in the Message column
3. If you use a third argument, it must be of type Exception and contain information about an error, which ASP.NET then writes to the trace log.

Trace.Write(“Page Loaded”)



The Trace Information section of 4 sections.

Category :
A custom trace category that you
specified as the first argument in a Trace.Write (or Trace.Warn) method call. Message :

A custom trace message that you specified as the second argument in a Trace.Write (or Trace.Warn) method call.
From First (s) :
The time, in seconds, since the request processing was started (a running total).
From Last (s) :
The time, in seconds,
since the last message was displayed. This column is especially helpful for seeing how long individual operations are taking.


Application Level Tracing:
If we don’t want to change paging in each and every page and we need to write the trace to entire application we opt for application level tracing.
To accomplish this we need to enable application-level tracing in the web.config file of the application and view the AXD application trace log for trace information.

Enable Application level tracing.
-To enable application tracing ,locate the web.config file in the application
-Add the trace element to System.web section of Web.config file and set the enabled attribute to true

‘<>

‘ <>


web.config:





<configuration>

<system.web>

<httpHandlers>

<remove verb="*" path="trace.axd" />

</httpHandlers>

</system.web>

</configuration>









-View the application trace log by browsing to the trace.axd page from the application root, like this:
http://localhost//trace.axd
trace.axd is not an page but rather it is a special URL that is intercepted by ASP.NET.
It is an http handler.

Some of the trace Elements are
RequestLimit: Defualt number of Http requests stored in the trace information are 10, if limit is reached tracing will be disabled,requests count can be set using this attribute.
pageOutput :If, in addition to viewing the trace.axd file,
you also want to see trace information displayed at the bottom of the page that it is associated with, add pageOutput="true" to the element:

The trace information you will see is identical to what would appear had you placed Trace="true" in the @ Page directive for the page
localOnly :To show trace information
to the local user (i.e., the browser making the request is on the machine serving the request) but not to remote users, make sure the element includes localOnly="true":


If we want to identify problems only
when an exception occurs.we can enable trace dynamically in the catch block.
· Set Page.Trace.IsEnabled = true in the Catch block of your exception handler.
· Write to the trace log by using a Trace.Write of the form Trace.Write("Exception", "Message", exc).












Error Handing in .Net FAQ

1. How to prevent errors at design time?

VB.Net offers the Option Strict and Option Explicit statements to prevent errors at design time.

• Option Explicit :

Prevent errors at design time. It forces explicit declaration of all variables at the module level

Syntax Option

Option Explicit On.

By default it is off.

We can set option explicit in .aspx page in the page directive




• Option strict :

Enabling Option Strict causes errors to be raised if you attempt a data type conversion that leads to a loss in data.


2.What Precisely is an Exception?

The Exception Class is a member of System NameSpace and base class for all the exceptions.

2 subclasses of Exception class are System Exception Class and Application Exception class.

Exception Class
System Exception Application Exception

The SystemException class defines the base class for all .NET predefined exceptions

3.What are the properties of Exception Object ?

Source : Gets the naem of the application or the object that causes the error
Message :Gets a message that describes the current exception.
StackTrace : Gets a string representation of the frames on the call stack at the time the current exception was thrown.
InnerException : Gets the Exception instance that caused the current exception
TargetSite : Gets the method that throws the current exception.
HelpLink :Gets or sets a link to the help file associated with this exception.

4.What is Structured and UnStructured Error Handling?

Unstructured Error Handling:


Unstructured error handling is implemented with the On Error statement, which is placed at the beginning of a code block to handle all possible exceptions that occur during the execution of the code. All Visual Basic 6.0 error handlers in .NET are objects that can be accessed by using the Microsoft.VisualBasic.Information.Err namespace. The handler is set to Nothing each time the procedure is called. You should place only one On Error statement in each procedure, because additional statements disable all previous handlers that are defined in that procedure.

On Error { GoTo [ line 0 -1 ] Resume Next }

Structured Error Handling :

With structured error handling, Visual Basic now has an effective way to prevent unexpected errors from terminating the execution of the application. Structured error handling also provides the programmers with a simpler way to create robust applications that are easier to maintain. Structured error handling is implemented in Visual Basic. NET or Visual Basic 2005 with a Try...Catch...Finally block of statements. The Try...Catch...Finally block provides, for the first time to Visual Basic, the capability of nested error handling.

5. Mention Predefined exceptions provided by .net run time?


Exception --Object--Base class for all exceptions.
SystemException--Exception--Base class for all runtime-generated errors.
IndexOutOfRangeException--SystemException--Thrown by the runtime only when an array indexed improperly.
NullReferenceException--SystemException--Thrown by the runtime only when a null object
referenced.

InvalidOperationException--SystemException--Thrown by methods when in an invalid state.

ArgumentException --SystemException--Base class for all argument exceptions.

ArgumentNullException --ArgumentException--Thrown by methods that do not allow
an argument to be null.
ArgumentOutOfRangeException --ArgumentException --Thrown by methods that verify
that arguments are in a given range.

ExternalException--SystemException--Base class for exceptions that occur or are targeted
at environments outside the runtime.

ComException--ExternalException--Exception encapsulating COM HRESULT information.

SEHException --ExternalException--Exception encapsulating Win32 structured exception handling information

6.What class we need to inherit to create custom Excepton class.
To create a custom exception we must inherit from the ApplicationException class

7.How to redirect the user to the friendly error-handler page when an Application error occurs?

Modify web.config as


customErrors mode="On" defaultRedirect="errorpage.aspx"

The configuration section supports an inner tag that associates HTTP status codes with custom error pages. For example:

--< mode="On" defaultredirect="genericerror.htm">
-- < statuscode="404" redirect="pagenotfound.aspx">
--< statuscode="403" redirect="noaccess.aspx">
--< /customerrors>







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/