Accessing session variables within classes in App_Code

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext. If you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

In this case, you can always use a wrapper class around the ASP.NET session to simplify access to session variables.

Sample Code:

public class YourSession
{
private YourSession()
{
Property1 = “default value for property 1”;
Property2 = “default value for property 2”;
Property3 = “default value for property 3”;
}

public static YourSession Current
{
get
{
YourSession session =
(YourSession)HttpContext.Current.Session[“__YourSession__”];
if (session == null)
{
session = new YourSession();
HttpContext.Current.Session[“__YourSession__”] = session;
}
return session;
}
}

public string Property1 { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}

This above class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class. The session properties can be assessed in the following manner:

string property1 = YourSession.Current.Property1;
YourSession.Current.Property1 = new value for property 1″;

string property2 = YourSession.Current.Property2;
YourSession.Current.Property2 = new value for property 2″;

string property3 = YourSession.Current.Property3;
YourSession.Current.Property3 = new value for property 3″;

Advertisements

XSLT Transformations with the XslTransform Class (C#)

You can use the XslTransform class to transform XML data using an Extensible Stylesheet Language for Transformations (XSLT) style sheet. XslTransform supports the XSLT 1.0 syntax. The XSLT style sheet must use the namespace http://www.w3.org/1999/XSL/Transform.
 
The following code example loads an XSLT style sheet, reads a file called mydata.xml into an XPathDocument, and performs a transformation on the data on a fictitious file called myStyleSheet.xsl, sending the formatted output to the console.
 
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
public class Sample
{
    private const String filename = "mydata.xml";
    private const String stylesheet = "myStyleSheet.xsl";
    public static void Main()
    {
    XslTransform xslt = new XslTransform();
    xslt.Load(stylesheet);
    XPathDocument xpathdocument = new
    XPathDocument(filename);
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting=Formatting.Indented;
    xslt.Transform(xpathdocument, null, writer, null);   
    }
}

Using Application Domains (C#)

Application domains, which are represented by AppDomain objects, help provide isolation, unloading, and security boundaries for executing managed code. You use application domains to isolate tasks that might bring down a process. If the state of the AppDomain that’s executing a task becomes unstable, the AppDomain can be unloaded without affecting the process. This is important when a process must run for long periods without restarting. You can also use application domains to isolate tasks that should not share data. If an assembly is loaded into the default application domain, it cannot be unloaded from memory while the process is running. However, if you open a second application domain to load and execute the assembly, the assembly is unloaded when that application domain is unloaded. Use this technique to minimize the working set of long-running processes that occasionally use large DLLs.
 
using System;
using System.Reflection;
using System.Threading;
 
class Module1
{
    public static void Main()
    {
        // Get and display the friendly name of the default AppDomain.
        string callingDomainName = Thread.GetDomain().FriendlyName;
        Console.WriteLine(callingDomainName);
        // Get and display the full name of the EXE assembly.
        string exeAssembly = Assembly.GetEntryAssembly().FullName;
        Console.WriteLine(exeAssembly);
        // Construct and initialize settings for a second AppDomain.
        AppDomainSetup ads = new AppDomainSetup();
        ads.ApplicationBase =
            System.Environment.CurrentDirectory;
        ads.DisallowBindingRedirects = false;
        ads.DisallowCodeDownload = true;
        ads.ConfigurationFile =
            AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
        // Create the second AppDomain.
        AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads);
        // Create an instance of MarshalbyRefType in the second AppDomain.
        // A proxy to the object is returned.
        MarshalByRefType mbrt =
            (MarshalByRefType) ad2.CreateInstanceAndUnwrap(
                exeAssembly,
                typeof(MarshalByRefType).FullName
            );
        // Call a method on the object via the proxy, passing the
        // default AppDomain’s friendly name in as a parameter.
        mbrt.SomeMethod(callingDomainName);
        // Unload the second AppDomain. This deletes its object and
        // invalidates the proxy object.
        AppDomain.Unload(ad2);
        try
        {
            // Call the method again. Note that this time it fails
            // because the second AppDomain was unloaded.
            mbrt.SomeMethod(callingDomainName);
            Console.WriteLine("Sucessful call.");
        }
        catch(AppDomainUnloadedException)
        {
            Console.WriteLine("Failed call; this is expected.");
        }
    }
}
 
// Because this class is derived from MarshalByRefObject, a proxy
// to a MarshalByRefType object can be returned across an AppDomain
// boundary.
public class MarshalByRefType : MarshalByRefObject
{
    //  Call this method via a proxy.
    public void SomeMethod(string callingDomainName)
    {
        // Get this AppDomain’s settings and display some of them.
        AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation;
        Console.WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}",
            ads.ApplicationName,
            ads.ApplicationBase,
            ads.ConfigurationFile
        );
        // Display the name of the calling AppDomain and the name
        // of the second domain.
        // NOTE: The application’s thread has transitioned between
        // AppDomains.
        Console.WriteLine("Calling from ‘{0}’ to ‘{1}’.",
            callingDomainName,
            Thread.GetDomain().FriendlyName
        );
    }
}
 
/* This code produces output similar to the following:
AppDomainX.exe
AppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
AppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.config
Calling from ‘AppDomainX.exe’ to ‘AD #2’.
Failed call; this is expected.
 */
 
 

AppDomain (C#)

Usually each process runs in its own space and if first process making a call to second process, and if second process crashes, so first will also crash. In .NET, we attempt to solve this problem through Application Domains. An Application Domain is a virtual location in memory where a process runs. The main process is created by the .NET CLR and then, each assembly runs in its own Application Domain. And many Application Domains can exist in a single process space. So, if one Application Domain crashes, only its space is released and the process remains as is.

If an Application Domain does crash, the CLR throws back an exception which can be handled in the caller. The AppDomain class is the programmatic interface to application domains. This class includes methods to create and unload domains, to create instances of types in domains, and to register for various notifications such as application domain unloading.

Let’s start with a simple example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AppDomain1
{
    class Program
    {
        static void Main(string[] args)
        {
            Worker localWorker = new Worker();
            Console.WriteLine("localWorker is running in: {0}", localWorker.DomainName);
            AppDomain myDomain = null;
            try
            {
                myDomain = AppDomain.CreateDomain("Remote Domain");
                Worker remoteWorker = (Worker)myDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "MyAppDomain.Worker");
                Console.WriteLine("remoteWorker is running in: {0}", remoteWorker.DomainName);
            }
            finally
            {
                if (myDomain != null)
                    AppDomain.Unload(myDomain);
            }
        }
    }
 
    public class Worker : MarshalByRefObject
    {
        public Worker()
        {
        }

        public string DomainName
        {
            get
            {
                return AppDomain.CurrentDomain.FriendlyName;
            }
        }
    }
}

Now, let’s try to crash… Unhandled exceptions can cause code to crash or leave your application in an unstable state. Application Domains are isolated and can help you to catch unhandled exceptions and unload the application domain when needed. So when we expand our example to include this, we get something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AppDomain2
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain myDomain = null;
            try
            {
                myDomain = AppDomain.CreateDomain("Remote Domain");
                myDomain.UnhandledException += new UnhandledExceptionEventHandler(myDomain_UnhandledException);
                Worker remoteWorker = (Worker)myDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Worker).FullName);
                remoteWorker.VeryBadMethod();
            }
            catch(Exception ex)
            {
                myDomain_UnhandledException(myDomain, new UnhandledExceptionEventArgs(ex, false));
            }
            finally
            {
                if (myDomain != null)
                    AppDomain.Unload(myDomain);
            }
 
            Console.ReadLine();
        }
 
        static void myDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            if (ex != null)
                Console.WriteLine(ex.Message);
            else
                Console.WriteLine("A unknown exception was thrown");
        }
    }
 
    public class Worker : MarshalByRefObject
    {
        public Worker()
        {
        }
 
        public string DomainName
        {
            get
            {
                return AppDomain.CurrentDomain.FriendlyName;
            }
        }
 
        public void VeryBadMethod()
        {
            // Outch!
            throw new InvalidOperationException();
        }
    }
}

Full Source Code Download: http://cid-d1df34a904545dc5.skydrive.live.com/self.aspx/Public/AppDomain.zip

Writing XML with the XmlWriter Class (C#)

The XmlWriter class is an abstract base class that provides a forward-only, write-only, non-cached way of generating XML streams. It can be used to build XML documents that conform to the W3C Extensible Markup Language (XML) 1.0 (Second Edition) (www.w3.org/TR/2000/REC-xml-20001006.html) recommendation and the Namespaces in XML recommendation (www.w3.org/TR/REC-xml-names/). You can use the XmlWriter class to read and write XML.
 
The following example creates an XmlWriter that outputs to an XML file in C#.
 
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = ("    ");
using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
{
    // Write XML data.
    writer.WriteStartElement("book");
    writer.WriteElementString("price", "19.95");
    writer.WriteEndElement();
    writer.Flush();
}

Automatically Implemented Properties (C#)

C# 3.0 was released as a part of the Microsoft .NET 3.5 Framework. In this blog post, I’ll cover the automatically implemented properties feature of C# 3.0. Automatically implemented properties offer a concise syntax for implementing property accessors that get and set a private field. They create a field backed property without requiring you to actually create a field. The compiler automatically generates it for you at compile time. They can be used only for simple get and set of properties because there is no body and no field. No property body means no breakpoints or validation logic can be used. No field means no default value. Typing "prop [tab][tab]" is the Visual Studio code snippet for producing an automatically implemented property. This can make your code much more concise. A classic example of a field back property is shown below:
 
private int myProperty = 0;
 
public int MyProperty
{
   get { return this.myProperty; }
   set { this.myProperty = value; }
}
 
The above code snippet can be refactored to use automatically implemented properties as shown below:
 
public int MyProperty
{
   get; set;
}
 
The above code snippet can be refactored to include a private set and use a constructor to control the value as shown below:
 
class Customer
{
   public Customer(string customerKey)
   {
      CustomerKey = customerKey;
   }
 
   public string CustomerKey { get; private set; }
   public string ContactName { get; set; }
   public string City { get; set; }
}
 
Although this does protect the field from the outside, it could still be altered internally to the class. In reality, an automatically implemented property probably isn’t appropriate for the CustomerKey property and the above code snippet can be further refactored to:
 
class Customer
{
   public Customer(string customerKey)
   {
      this.CustomerKey = customerKey;
   }
   private readonly string customerKey;
 
   public string CustomerKey
   {
      get return this.customerKey;
   }
 
   public string ContactName { get; set; }
   public string City { get; set; }
}
 
The above code snippet illustrates the point that the automatically implemented properties should be applied liberally, but with caution.

C# 4.0 Dynamic Lookup

One of the core features introduced in C# 4.0 is called Dynamic Lookup which allows a unified approach to invoking things dynamically. Currently, when you call object methods or properties, the compiler checks that they exist and raises an error if they do not. With dynamic lookup, you can call any method or property, and they are not checked until runtime. C# 4.0 is extending towards the dynamic languages.

 
C# 4.0 will support dynamic typing through a new static type called “dynamic”. As already described, when you have an object of type dynamic you can do whatever you like with it, those operations are resolved only at runtime. Lets first see a method declaration:
 
public dynamic GetService()
{
    // Getting some service…
}
 
and how to use it:
 
dynamic service = GetService();
service.Do("YourJob");
 
The C# compiler allows you to call a method with any name and any arguments because service is declared as dynamic. SOnly at runtime will you get an error if the returned object doesn’t have such a method.