March 30, 2008
@ 11:00 PM

http://www.csharphelp.com/archives3/archive532.html

Error Logging in ASP.NET
By Robert Pohl

All coders are quite familiar with error messages. They are quite handy when developing stuff but you don't want them around after the release of your system and the users don't really think they are too funny.

So, how can we get rid of these ugly messages and still get nice information when your functions break down? I have written some code (with some inspiration from other error logging examples) that provide your system with some nice features:

- On error, it redirects the user to a page that in English explains that an error has occurred.
- You can set the object to either send an email or write in the EventLog, or both
- All the browser information is included in the email for support help.
- It can also present an "Alert" message to the user.

Code explanation:

// The constructor is overloaded and gets the important variables from either the object creation or web.config  
public KillahErrHandler()
{
  this.MailServer = ConfigurationSettings.AppSettings["MailServer"];
  this.EmailReciever  = ConfigurationSettings.AppSettings["MailReciever"];
  this.LogName                          = ConfigurationSettings.AppSettings["LogName"];
}  
web.config  

<appSettings>
                <add key="MailServer" value="mail.yourserver.com" />
                <add key="MailReciever" value="you@yourcompany.com" />
                <add key="LogName" value="MyWeb Log Alert" />
</appSettings> 

or..

...


 
Categories: log4net

http://dotnetslackers.com/community/blogs/bmains/archive/2006/09/06/Trace-Listening-in-ASP.NET-Applications.aspx

Trace Listening in ASP.NET Applications

If you are interested in writing your own trace listener (say to write to a database), you can do so from inheriting the System.Diagnostics.TraceListener class, which you can find examples on the web.  However, if you want to use it in your web application, there are several steps you need to take, which you can find documented here:  http://msdn2.microsoft.com/en-us/library/b0ectfxd.aspx

Using this example, you can register custom listeners through:

<system.diagnostics>   
  <trace autoflush="true">
    <listeners>
      <add name="DatabaseTraceListener"
        type="Mains.DatabaseTraceListener, App_Code"/>
    </listeners>
  </trace>
</system.diagnostics> 

Autoflush means messages will be written automatically to the listener; if false, then a manual Flush() method call must be peformed before trace information is written.  You add your custom class using the <add> element, like many other sections in the code.  I left out the initializeData property, which may or may not be allowed with trace listeners.

Once defined, you can use tracing in two ways.  First, you can use it manually:

System.Diagnostics.Trace.Write()

Or you can use the tracing that comes with the Page class (System.Web.TraceContext), defining this in the web.config:

<system.web>
    <trace enabled="true" writeToDiagnosticsTrace="true"/>
</system.web>

writeToDiagnosticsTrace means that all tracing will run through the trace listeners you setup in the <system.diagnostics> section.  The last step is to setup the compilers to output the switch /d:Trace, as defined below:

<system.codedom>
  <compilers>
    <compiler language="c#;cs;csharp"
              extension=".cs"
              compilerOptions="/d:TRACE"
              type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="1" />
    <compiler language="VB"
              extension=".vb"
              compilerOptions="/d:Trace=true"
              type="Microsoft.VisualBasic.VBCodeProvider, System,                                        Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </compilers>
</system.codedom>

For windows projects, you can set up the /d:Trace switch in the property settings for the project.  However, with web applications, you must specify the information here.  If you don't specify the compiler options, tracing information through the diagnostics trace listener is ignored completely, which I found out the hard way when debugging.

 

Other example

<system.diagnostics>    
  <trace autoflush="true">
    <listeners>
      <add name="WebPageTraceListener" 
        type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      <add name="TestTracer" 
        type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
        initializeData="<app root directory>\Asptesttrace.log" />
    </listeners>
  </trace>
</system.diagnostics>
This walkthrough illustrated how to work with ASP.NET and System.Diagnostics tracing features to route all trace messages a single output. 
You might want to experiment more with trace listeners and output and ASP.NET instrumentation features. For example, you might want to do 
the following:
  • Add an EventLogTraceListener object to your application.

    To do this, you would add an EventLogTraceListener object either programmatically or by using the configuration file that uses the same
    procedure as for the WebPageTraceListener.
    You can open the Event Log to review the trace messages that your application writes to the Event Log.

    • Change the business component to work with database data instead of with an XML file. You do not need to make any change to the controls on the page.

    public static void Main(string[] args) {
    
        // Create a trace listener for the event log.
        EventLogTraceListener myTraceListener = new EventLogTraceListener("myEventLogSource");
    
        // Add the event log trace listener to the collection.
        Trace.Listeners.Add(myTraceListener);
    
        // Write output to the event log.
        Trace.WriteLine("Test output");
     }
     

 
Categories: log4net

March 30, 2008
@ 10:36 PM
 
Connecting to Diagnostic Listeners
 
Tracing in ASP.NET is somewhat orthogonal to tracing in the .NET Framework. The Systems.Diagnostics namespace defines two classes, Trace and Debug, whose methods are used to trace the code. The Trace and Debug classes are essentially identical and work on top of more specialized modules known as listeners. A listener collects and stores messages in the Windows event log, a text file, or some other similar file. Each application can have its own set of listeners; all registered listeners receive all emitted messages. The tracing subsystem of ASP.NET 2.0 has been enhanced to include support for forwarding ASP.NET tracing information to any registered .NET trace listeners. You enable this feature by turning on the writeToDiagnosticsTrace attribute in the <trace> section of the web.config file, like so:
 
<trace enabled="true" pageOutput="false" 
       writeToDiagnosticsTrace="true" />
Setting the writeToDiagnosticsTrace attribute is not enough, though. You also need to register one or more listeners for the Web application. Use the <trace> section under the <system.diagnostics> section to do that, as shown here:
 
<system.diagnostics>
  <trace autoflush="true">
    <listeners>
      <add name="myListener" 
           type="System.Diagnostics.TextWriterTraceListener" 
           initializeData="c:\myListener.log" />
    </listeners>
  </trace>
</system.diagnostics>
There are two important things to note here. First, only text written through either Write or Warn is forwarded to the listeners. That is, the listener won't store a copy of the standard ASP.NET trace information; the information tracked is limited to the contents of the Trace Information section. The second thing is that you can write custom listeners to send trace information to the medium of your choice—for example, a SQL Server database. All you have to do is inherit a class from System.Diagnostics.TraceListener and override a few methods. Next, you register the new class with the web.config file of the Web application you plan to trace. (For more information on writing custom TraceListener types, see msdn.microsoft.com/msdnmag/issues/06/04/CLRInsideOut.) One interesting thing to note is that System.Web.dll now includes a TraceListener-derived type, WebPageTraceListener, whose job is to serve as the counterpart to writeToDiagnosticsTrace. When an instance of WebPageTraceListener is added to the trace listeners collection, messages written to the .NET diagnostics trace will also be written to the ASP.NET trace.
Finally, you should be aware that in ASP.NET 2.0 a new <deployment> section has been added to the Web configuration section related to tracing.

 
Categories: Asp.net | log4net

http://www.c-sharpcorner.com/UploadFile/Santhi.M/ASP.NETLifeCycle11282005043446AM/ASP.NETLifeCycle.aspx

In this article, we will see the stages of execution of the ASP .NET Page.

Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application. In web.config and also in machine.config you will find these lines in <httpHandlers> section.

If you run through the following program, it will be much easier to follow

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

This extension can be associated with HandlerClass or HandlerFactory class. HttpApplication object gets the page object that implements the IHttpHandler Interface. The process of generating the output to the browser is started when the object calls ProcessRequest method.

Page Life Cycle

Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives.

Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served.

Stages and corresponding events in the life cycle of the ASP.NET page cycle:
 
Stage Events/Method
Page Initialization Page_Init
View State Loading LoadViewState
Postback data processing LoadPostData
Page Loading Page_Load
PostBack Change Notification RaisePostDataChangedEvent
PostBack Event Handling RaisePostBackEvent
Page Pre Rendering Phase Page_PreRender
View State Saving SaveViewState
Page Rendering Page_Render
Page Unloading Page_UnLoad

Some of the events listed above are not visible at the page level. It will be visible if you happen to write server controls and write a class that is derived from page.

Page Execution Stages

The first stage in the page life cycle is initialization. This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage.

After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored.

Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.

After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field.

Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method.

The final stage of the life cycle is unload event. This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page.



 
Categories: Asp.net

March 30, 2008
@ 02:59 PM
ASP.NET2.0 Interview Questions

What is an assembly ?
Name some of the Microsoft Application Blocks. Have you used any? Which ones?
What is the difference between Dataset and Datareader?
What r the ASP.NET list controls and difference between them?
If we remove web.config or machine.config from the application
How do we Sort the data from a Dataset ?
What is the difference between Web User Control and Web Custom Control.
Which namespace is used by ADO.NET?
How do you create a permanent cookie ?
What is difference between OR and OR ELSE ?
What is event bubbling?
How do we get only edited/deleted/inserted records from a Dataset?
What are ASP.NET Web Forms?
What order do the events of an ASPX page execute
What is the difference between Dataset and Recordset.
What is IPostBack? How to use it?
What is the difference between Server.Transfer and Response.Redirect ?
What is delay signing?
Which DLL handles the request of .aspx page?
How can we implement a Identity (SQL Server) call in an asp.net page?
What is Preprocessor in .NET and type , where it use
What types of data validation events are commonly
Can you give an example of when it would be appropriate to
Difference between Friend and Protected Friend.
What is the difference between a defect and an enhancement?
What are the differences between client-side and server-side
What is an abstract class?
List of Words of Preprocessor in .NET ?
Which control would you use if you needed to make sure
What is DLL hell ?
What is difference between ASP State Management
Which method do you use to redirect the user to another
How would you get ASP.NET running in Apache web servers ?
Can a .NET web application consume Java web service ?
What is the transport protocol you use to call a Web service SOAP
What might be best suited to place in the Application
What is the root namespace for all types?
How does u call and execute asp in .NET ?
What does the "EnableViewState" property do? Why would I want it on or off?
What is CLR ?
How do u declare static variable and how it is declared and what is its lifetime ?
Which method do you invoke on the Data Adapter control
What is the difference between an ADO.NET Dataset
How Dataadapter.fill works?
Which namespace is used to get assembly details?
What is difference between abstract class and an interface?
Why Data reader is useful?
What is shadowing?
What base class do all Web Forms inherit from?
How can we pass information between 2 asp.net pages?
What is Viewstate?
How to enter same record twice in target table?
What is smoke testing ?
Which two properties are on every validation control?
What is the difference between inline and code behind ?
Microsoft Technologies, ASP.NET2.0 Interview Questions,
Which template must you provide, in order to display data in a Repeater control ?
What is versioning in .NET?
How do you turn off cookies for one page in your site ?
What are delegates ?
Describe session handling in a webfarm ?
How does VB.NET/C# achieve polymorphism?
Should validation occur server-side or client-side ?
What tag do you use to add a hyperlink column to the Data Grid?
How is a property designated as read-only?
What method do you use to explicitly kill a user s session ?
What is the life cycle of an asp.net page?
What are the disadvantages of viewstate /what are the benefits
Explain the differences between Server-side and Client-side code ?
What is difference between singleton and single call?
How to reduce the width of textbox in EditCommandColumn of DataGrid?
How can you provide an alternating color scheme in a Repeater control ?
Difference between Overriding and overloading ?
What is the standard you use to wrap up a call to a Web service
What are client activated objects and server activated objects ?
What is server infrastructure & Server components?
How to get particular record from the table in informatica?
Can you explain what inheritance is and an example of when you might use it ?
What type of code is found in a Code-Behind class ?
What are webservices ?
How do you call procedures in data stage?
How to create dynamic Grid view ?
How many classes can a single .NET DLL contain?
What is CLR?
What is .NET remoting ?
How to create primary key only on odd numbers?
How would you implement inheritance using VB.NET/C#?
How does session handling work ?
What does WSDL stand for ?
What is the difference between CLR & CTS
What are the limits of session handling ?
Where would you use an iHTTPModule, and what are the limitations of any
How to get the records starting with particular letter like A in informatica?


 
Categories: Interview Question

Truly understanding Dynamic Controls

Truly understanding ViewState

Must read if you are an ASP.NET developer. Read them letter by letter every month, memorize them.

This is the third time I am linking to these articles. Every time I (re)read them I understand something new.

(http://sendhil.spaces.live.com/blog/cns!30862CF919BD131A!1117.entry)




 
Categories: Asp.net

http://sendhil.spaces.live.com/Blog/cns!30862CF919BD131A!583.entry

Scott Hanselman's interview questions - Senior Developers/Architects

Answers to Senior Developers/Architects
  1. What’s wrong with a line like this? DateTime.Parse(myString);

    Parse converts date at any cost. What if user passes date in format MM/dd/yyyy whereas you are expecting in dd/MM/yyyy.Assume the user is passing 12/09/2006 meaning Dec 12, 2006, whereas Parse (based on the current locale) picked it up as Sep 12, 2006. The result is not something which you would like. Also Parse takes more time compared to other as it has to check for a gazillion formats. Instead if you know the format its better to go with ParseExact. Then why the hell do we have Parse? May be for the old VB customers it was an easier transition. Chec out more here or here
  2. What are PDBs? Where must they be located for debugging to work?

    A Program DataBase file (extension .pdb) is a binary file that contains type and symbolic debugging information gathered over the course of compiling and linking the project. A PDB file is created when you compile a C/C++ program with /ZI or /Zi or a Visual Basic, Visual C#, or JScript program with the /debug option. The Visual Studio debugger uses the path to the PDB in the EXE or DLL file to find the project.pdb file. If the debugger cannot find the PDB file at that location, or if the path is invalid, for example, if the project was moved to another computer, the debugger searches the path containing the EXE followed by the symbol paths specified in the Options dialog box (Solution Properties-->Debug Symbol Files node in VS.NET 2003). The debugger will not load a PDB that does not match the binary being debugged.
  3. What is cyclomatic complexity and why is it important?

    This calls for a separate entry in itself. http://sendhil.spaces.live.com/blog/cns!30862CF919BD131A!581.entry
  4. Write a standard lock() plus “double check” to create a critical section around a variable access.

    This calls for a separate entry in itself. http://sendhil.spaces.live.com/blog/cns!30862CF919BD131A!582.entry
  5. What is FullTrust? Do GAC’ed assemblies have FullTrust?

    Full Trust Permission Set Grants unrestricted permissions to system resources. My_Computer_Zone code group by default has has FullTrust permission. This can be changed using CASPOL.exe though.
  6. What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

    Allows administrators to see exactly which permissions your application needs to run, using PermView
    Prevents your code from being exploited beyond what permissions it absolutely needs
    Allows your application to forcibly fail instead of having to manually handle situations where it might be denied permissions it requires.
    More info can be found here / here
  7. What does this do? gacutil /l | find /i "Corillian"

    gacutil /l lists the assemblies in GAC. Find /i lists all the assemblies which have Corillian in their identity. (/i ignores case I suppose).
  8. What does this do? sn -t foo.dll

    Extracts the publick key token from the strongly named assembly foo.dll
  9. What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

    135 is used by Windows RPC. HKEY_LOCAL_MACHINE\Software\Microsoft\Rpc\Internet (Key) Ports (Multi Line String Value) specifies what other ports will be open.
  10. Contrast OOP and SOA. What are tenets of each?

    OOP Tenets - Abstraction, Encapsulation, Inhertiance, Polymorphism. SOA Tenats - (PEACE) - Policy based negotiation, Explicitness of boundaries, Autonomy, Contract Exchange Differences: Read this nice analogy. This is as best as it can get http://blogs.msdn.com/smguest/archive/2004/01/29/64871.aspx
  11. How does the XmlSerializer work? What ACL permissions does a process using it require?

    The XmlSerializer creates a temporary assembly with two types named XmlSerializationReader1, XmlSerializationWriter1 which derive from XmlSerializationReader and XmlSerializationWriter classes. These types are responsible for DeSerializing and Serializing respectively. The XMlSerializer constructors caches the assemblies emitted if you use one of these constructors
    System.Xml.Serialization.XmlSerializer(Type) 
    System.Xml.Serialization.XmlSerializer(Type,String) 
    
    Its recommended to use these. So the account under which host process is running must have Write, Delete permissions on the temporary directory. This the user profile temp directory for windows applications and the app specific folder under Temporary ASP.NET Files (in the framework directory) for ASP.NET applications
  12. Why is catch(Exception) almost always a bad idea?

    When you catch an exception, you’re stating that you expected this exception, you understand why it occurred, and you know how to deal with it. In other words, you’re defining a policy for the application. However, you shouldn’t catch Exception because a StackOverflowException or OutOfMemoryException exception could be thrown at any time. Hiding these fatal problems and allowing the application to continue running will cause unpredictable results.
  13. What is the difference between Debug.Write and Trace.Write? When should each be used? Debug.Write is compiled into a release build. Trace.Write gets compiled irrespective of the build configuration chosen. Trace is useful for production debugging (can be turned on off based on config at various levels / severity). Debug is useful for development environment debugging.
  14. What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

    • A debug build generates a file containing debug symbols (.pdb); a release build does not.
    • A debug build generates extra instructions to accomodate the debugger (e.g. NOP instructions to assist your setting breakpoints); a release build does not include these.
    • A release build uses full optimizations when compiling which might include rearranging your code or inlining it for efficiency, a debug build doesn't do this.
    • A debug build allocates extra memory on the heap for objects to facilitate detecting memory overwrite errors; a release build doesn't do this.
    • A release build will thus be smaller, faster, and more efficient than a debug build.
    More Info
    http://p2p.wrox.com/topic.asp?TOPIC_ID=16066
    http://www.hanselman.com/blog/PermaLink.aspx?guid=a40c0d4f-66d0 -4704-94f6-0efda4a44465
  15. Does JITting occur per-assembly or per-method? How does this affect the working set?

    Per-method. Since methods which are not called are not compiled at all, this reduces the working set.
  16. Contrast the use of an abstract base class against an interface?

    http://sendhil.spaces.live.com/blog/cns!30862CF919BD131A!576.entry
  17. What is the difference between a.Equals(b) and a == b?

    Cannot be answered unless you have the variable declarations for a and b.
    The default implemenation for Equals on object checks for references or identity.
    There is no default implementation for '==' on value types.
    The default implementation for '==' on reference types checks for idenity or memory references
    More here

  18. In the context of a comparison, what is object identity versus object equivalence?

    identity comparison: check if both the instances point to the same memory address.
    equivalence: two instances are considered equal if their values represented by them are equal, they can point to different memory locations. For example:
    Person p1 = new Person();
    p1.age = 25;
    Person p2 = new Person();
    p2.age = 25;
    

    identity comparison of p1 and p2 should return false whereas equivalence should return true.
  19. How would one do a deep copy in .NET?

    Serialize / DeSerialize is an option, but it has a performance impact and required all the objects to be serializable.
    ICloneable is another.
  20. Explain current thinking around IClonable.

    Because the interface contract does not specify the type of clone performed, different classes have different implementations. A consumer cannot rely on ICloneable to let them know whether an object is deep-cloned or not. May be I would use something like ICloneableEx with ShallowCopy and DeepCopy as members. Read more here
  21. What is boxing?

    http://sendhil.spaces.live.com/blog/cns!30862CF919BD131A!349.entry

  22. Is string a value type or a reference type?

    String is a reference type. But being immutable it gives the illusion of a value type.
  23. What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?

    Nillable value types. condiitonal serialization of fields using the Property specified pattern.
    http://msdn.microso ft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemXmlSerializationXmlSerializerClassTopic.asp

  24. Why are out parameters a bad idea in .NET? Are they?

    Out parameters can be abused however. As a matter of good programming style if you find yourself writing a method with many out parameters then you should think about refactoring your code. One possible solution is to package all the return values into a single struct.
    http://msdn.microsoft.com/vcsharp/programming/language/ask/refandout /default.aspx
    .Net doesn't verify that an out parameter is set inside a method that uses an out parameter before an exception is called. This mean that you may use an uninitialized parameter without the compiler catching on to this. Use ref parameters instead.
  25. Can attributes be placed on specific parameters to a method? Why is this useful?

    Yes. Best example is MarshalAs attribute used for PInvoke.

 

Other C# interview question

http://rileyperry.blogspot.com/2005/05/c-interview-questions.html


 
Categories: Interview Question

March 29, 2008
@ 10:14 AM

VB.NET and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between VB.NET (version 2) and C#. Hope you find this useful!
Thank you to Tom Shelton, Fergus Cooney, Steven Swafford, Gjuro Kladaric, and others for your contributions.
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

[ Download Word Version or PDF Version ]

 

 Top 10 reasons C# is better than VB.NET
http://www.vbrad.com/article.aspx?id=63

 

 

 


 
Categories: