Monday, January 30, 2012

WPF : Starting a WPF application in a new domain

Here is the code snippet for creating a new app domain and hosting your wpf allication in that domain


1           var domain1 = AppDomain.CreateDomain(
2:          "new domain");
3:
4:        CrossAppDomainDelegate action = () =>
5:        {
6:          Thread thread = new Thread(() =>
7:          {
8:            App app = new App();
9:            app.MainWindow = new Window1();
10:            app.MainWindow.Show();
11:            app.Run();
12:          });
13:          thread.SetApartmentState(
14:            ApartmentState.STA);
15:          thread.Start();
16:        };
17:
18:        domain1.DoCallBack(action);

WPF : Creating a custom UI Thread

Here is a code snippet for creating a custom UI Thread and showing a new window through that thread


Thread thread = new Thread(() =>
    {
     Window1 w = new Window1();
     w.Show();

     w.Closed += (sender2, e2) =>
      w.Dispatcher.InvokeShutdown();

     System.Windows.Threading.Dispatcher.Run();
    });

   thread.SetApartmentState(ApartmentState.STA);
   thread.Start();

Wednesday, January 11, 2012

Lazy Types (.Net 4)


Let’s look at definition of Lazy types as defined
[SerializableAttribute]
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true,
        ExternalThreading = true)]
public class Lazy<T>

A variable which is declared to be of Lazy type is initialized when its accessed first time.
Lazy type exposes following 2 properties
1)  IsValueCreated : It’s a Boolean property and indicates whether a value has been created for concerned type.
2)  Value : It returns actual instance for concerned type.


Lazy type has following constructors:

1)<T>() : It’s a default constructor and here it used default constructor defined for type “T”.
2)Lazy<T>(bool isThreadSafe): Here framework uses default constructor for initialization. isThreadSafe indicates whether this instance is usable by multiple threads. If isThradSafe is set as True then then  ThreadSafetyMode for the instance variable  is set as “LazyThreadSafetyMode.ExecutionAndPublication” else it sets ThreadSafetyMode as “LazyThreadSafetyMode.None”.
3) Lazy<T>(Func<T>) : Here framework uses Func method to initialize concerned variable.
4) Lazy<T>(LazyThreadSafeMode mode) : It uses Default constructor for type to initialize concerned instance. LazyThreadSafeMode enum has 3 values (None, PublicationOnly, ExecutionAndPublication).
“LazyThreadSafeMode.None” indicates instance is not thread safe.
“LazyThreadSafeMode.PublicationOnly” indicates when multiple threads try to initialize , all of them are allowed but whichever thread completes first, sets the value for instance.
“LazyThreadSafeMode.ExecutionAndPublication” indicates that only one thread is allowed to initialize instance.
Refer to here, to get more information about exception and their behavior wrt to LazyThreadSafeMode.
5) Lazy<t>(Func<t> valueFactory, bool isThreadSafe): It uses specified function for initialization and specifies ThreadSafe while creation.
6) Lazy<T>(Func<T>,LazyThreadSafeMode mode) : It uses specified function for inilitalization and specifies ThereadSafeMode for instance.


Now I am going to show how we can implement Singleton using Lazy types.
I have defined “LazySingleton” class which has a public static property Instance which returns a Lazy type variable.


using System;
 
namespace LazyTypes
{
 
   //Setting class as sealed to avoid any inheritance for this class.
   public sealed class LazySingleton
   {
        //Lazy type variable 
        private static readonly Lazy<LazySingleton> _instance = new Lazy<LazySingleton>(() => new LazySingleton());
 
        // Setting constructor as private to prevent direct instantiation.
        private LazySingleton()
        {
 
        }
 
        // public property to expose instance
        public static LazySingleton Instance
        {
            get
            {
                    return _instance.Value;
            }
        }
    }
}

Tuesday, January 10, 2012

Key Architecture Principles


Consider the following key principles when designing your architecture:

  • Build to change instead of building to last. Consider how the application may need to change over time to address new requirements and challenges, and build in the flexibility to support this.
  • Model to analyze and reduce risk. Use design tools, modeling systems such as Unified Modeling Language (UML), and visualizations where appropriate to help you capture requirements and architectural and design decisions, and to analyze their impact. However, do not formalize the model to the extent that it suppresses the capability to iterate and adapt the design easily.
  • Use models and visualizations as a communication and collaboration tool. Efficient communication of the design, the decisions you make, and ongoing changes to the design, is critical to good architecture. Use models, views, and other visualizations of the architecture to communicate and share your design efficiently with all the stakeholders, and to enable rapid communication of changes to the design.
  • Identify key engineering decisions. Use the information in this guide to understand the key engineering decisions and the areas where mistakes are most often made. Invest in getting these key decisions right the first time so that the design is more flexible and less likely to be broken by changes.

Refer to (.Net Application Architecture Guide V2.0)

Sunday, January 8, 2012

WPF : Implementation of DoEvents feature

When we are doing heavy operations on UI thread, it doesn't update UI changes untill its freed to do that. To overcome that we had DoEvents in VB6 which used to let UI thread updates UI and then come back to do heavy operation.
Here I am going to show an implementation of that feature.

I have an application class, where I start with a frame which is created when application begins, and whenever you call DoEvents it creates 1 more frame and forces Dispatcher to complete all pending frames between application started frame and end frame.

public class Application
    {
        private static readonly DispatcherOperationCallback exitFrameCallback = ExitFrame;
 
 
        private static Object ExitFrame(Object state)
        {
            var frame = state as DispatcherFrame;
 
            // Exit the nested message loop.
            frame.Continue = false;
            return null;
        }
 
        public static void DoEvents()
        {
            // Create new nested message pump.
            var nestedFrame = new DispatcherFrame();
 
            // Dispatch a callback to the current message queue, when getting called,
            // this callback will end the nested message loop.
            // note that the priority of this callback should be lower than the that of UI event messages.
            DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
                DispatcherPriority.Background, exitFrameCallback, nestedFrame);
 
            // pump the nested message loop, the nested message loop will
            // immediately process the messages left inside the message queue.
            Dispatcher.PushFrame(nestedFrame);
 
            // If the "exitFrame" callback doesn't get finished, Abort it.
            if (exitOperation.Status != DispatcherOperationStatus.Completed)
            {
                exitOperation.Abort();
            }
        }
 
    }


Now from any part of your application you can simply put following code and it will make sure that UI thread updates the UI.

Application.DoEvents();

Thursday, January 5, 2012

IIS Authentications


IIS 6 & 7 supports following types of authentications
1)      Anonymous Authentication :  Anonymous authentication allows any user to access any public content without providing a user name and password challenge to the client browser. By default, Anonymous authentication is enabled in IIS 7.
2)      Basic Authentication :  The Basic authentication method is a widely used, industry-standard method for collecting user name and password information. Basic authentication transmits user names and passwords across the network in an unencrypted form. You can use your Web server's encryption features, in combination with Basic authentication, to secure user account information transmitted across the network. To use Basic authentication, grant each user the right to log on locally. For easier administration, add each user to a group that has access to the necessary files.
3)      Digest Authentication :  Digest authentication offers the same functionality as Basic authentication; however, Digest authentication provides a security improvement in the way that a user's credentials are sent across the network. Digest authentication transmits credentials across the network as an MD5 hash, or message digest, where the original user name and password cannot be deciphered from the hash
4)      Windows Authentication : With Integrated Windows authentication (formerly called NTLM, and also known as Windows NT Challenge/Response authentication), the user name and password (credentials) are hashed before being sent across the network. When you enable Integrated Windows authentication, the client browser proves its knowledge of the password through a cryptographic exchange with your Web server, involving hashing.


Besides these IIS 7 supports following authentications
1)      IIS Client Certificate Mapping Authentication
A certificate is a digitally signed statement that contains information about an entity and the entity's public key, thus binding these two pieces of information together. A trusted organization (or entity) called a Certification Authority (CA) issues a certificate after the CA verifies that the entity is who it says it is. Certificates can contain different types of data. For example, an X.509 certificate includes the format of the certificate, the serial number of the certificate, the algorithm used to sign the certificate, the name of the CA that issued the certificate, the name and public key of the entity requesting the certificate, and the CA's signature. X.509 client certificates simplify authentication for larger user bases because they do not rely on a centralized account database. You can verify a certificate simply by examining the certificate.

Monday, January 2, 2012

LINQ : Joins


Here we are going to write Linq queries which will perform Left Join, Left Outer Join, and Cross Join. We have 2 tables Employess and Department. Employees has 5 rows and Department has 4 rows as shown below.

  1. Join : Here is a query which will join Employees and Department and show the result.

Query :
var joins = from em in Employees
join d in Departments on em.DeptId equals d.DeptId
select new {Name = em.EmpName, Department = d.DeptName};

 Output :

2. Left Outer Join : Here is a query which will Left outer join Employess with Department and show the result.
Query :
var leftouterjoins = from em in Employees
                     join d in Departments on em.DeptId equals d.DeptId
                      into empd
                     from ed in empd.DefaultIfEmpty()
                     select new {Name = em.EmpName, 
                          Department = ed == null ? string.Empty:  ed.DeptName};
Output:


3.
 Cross Join : Here is a query which will cross join Employee table with Department and show the result.
Query:
  var crossjoins = from em in Employees
                   from d in Departments
                   select new {Name = em.EmpName, Department = d.DeptName};

Output:



Sunday, January 1, 2012

IEnuemrable & IQueryable


Let’s look at Definition for IEnumerable first
 public interface IEnumerable
  {
    IEnumerator GetEnumerator();
  }

And when you drill further for IEnumerator definition, it looks like this
  public interface IEnumerator
  {
    bool MoveNext();
    object Current { get; }
    void Reset();
  }


And Now let’s looks at definition for IQueryable
public interface IQueryable : IEnumerable
{

// Summary:
//     Gets the type of the element(s) that are returned when the expression tree
//     associated with this instance of System.Linq.IQueryable is executed.
//
// Returns:
//     A System.Type that represents the type of the element(s) that are returned
//     when the expression tree associated with this object is executed.
Type ElementType { get; }

//
// Summary:
//     Gets the expression tree that is associated with the instance of System.Linq.IQueryable.
//
// Returns:
//     The System.Linq.Expressions.Expression that is associated with this instance
//     of System.Linq.IQueryable.
Expression Expression { get; }


//
// Summary:
//     Gets the query provider that is associated with this data source.
//
// Returns:
//     The System.Linq.IQueryProvider that is associated with this data source.
IQueryProvider Provider { get; }

}

So IQuryable interface is derived from IEnumerable interface and has 3 extra properties which are ElementType, Expression and Provider, which indicates that it should be used with expression trees. An expression tree represents code in a tree like data structure , where each node is an expression , for example a method call or binary operations such as x < y.

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries.
You can have the C# or Visual Basic compiler create an expression tree for you based on an anonymous lambda expression, or you can create expression trees manually by using the System.Linq.Expressions namespace.

Regular Expressions


Here are the most commonly used regular expressions\
1.       Validating Dates : (0[1-9]|1[012])/ ([1-9]|0[1-9]|[12][0-9]|3[01])/\d{4}
2.       Zip Codes: ^\d{5}(-?\d{4})?$
3.       Phone Number : ^((\d{3}[\-\.]?\d{3}[\-\.]?\d{4})|(\d{2}[\-\.]?\d{2}[\-\.]?\d{3}[\-\.]?\d{3}))$
4.       SSN : ^\d{3}\-?\d{2}\-?\d{4}$