6 June 2011

Singleton Class in C# with Example

Singleton class in C#

What is Singleton class?
A class that has only one instance, and you need to provide a global point of access to the instance.

How to achieve Singleton class?
Singleton provides a global, single instance by:
1. Making the class create a single instance of itself.
2. Allowing other objects to access this instance through a class method that returns a reference to the instance.A class method is globally accessible.

3. Declaring the class constructor as private so that no other object can create a new instance.

Uses of Singleton Class
1. The static initialization approach is possible because the .NET Framework explicitly defines how and when static variable initialization occurs.
2. The Double-Check Locking idiom described earlier in "Multithreaded Singleton" is implemented correctly in the common language runtime.

Demerits of Singleton Class
If your multithreaded application requires explicit initialization, you have to take precautions to avoid threading issues.

Singleton class vs. Static methods

1.Static classes don’t promote inheritance. If your class has some interface to derive from, static classes makes it impossible.
2.You cannot specify any creation logic with static methods.

When to User Singleton Class?
The below activities is common through out the application, Singleton increase the performance of the application

1. Logging
2. Database Access
3. Reading Configuration information.

Singleton provides a global, single instance by:

1. Making the class create a single instance of itself.
2. Allowing other objects to access this instance through a class method that returns a reference to the instance.
3. A class method is globally accessible.
4. Declaring the class constructor as private so that no other object can create a new instance.

The following implementation of the Singleton design pattern follows the solution presented in Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95] but modifies it to take advantage of language features available in C#, such as properties:

The class is marked sealed to prevent derivation, which could add instances.

The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

Example :

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}


Static Initialization of Singleton Class
One of the reasons Design Patterns [Gamma95] avoided static initialization is because the C++ specification left some ambiguity around the initialization order of static variables. Fortunately, the .NET Framework resolves this ambiguity through its handling of variable initialization:

Example:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
 
   private Singleton(){}

   public static Singleton Instance
   {
      get
      {
         return instance;
      }
   }
}

The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created.

Multithreaded Singleton in C#

Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution. Cases do exist, however, in which you cannot rely on the common language runtime to ensure thread safety, as in the Static Initialization example. In such cases, you must use specific language capabilities to ensure that only one instance of the object is created in the presence of multiple threads.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

using System;
public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed. In practice, an application rarely requires this type of implementation. In most cases, the static initialization approach is sufficient.

1 June 2011

Move next line in Multiline textbox in C#

Move next line in Multiline textbox

In C#

mtxtAlertMessage.Text += message+"\r\n" ;

Problem:Combobox Editable in C# Windows application and Asp.net

Problem:Combobox Editable in C# Windows application and Asp.net

Change the property of combobox from Dropdownstyle to DropDownList

or change in code at run time

this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDown;

24 May 2011

LINQ to XML: XML Integration

LINQ to XML: XML Integration


-.NET Language-Integrated Query for XML (LINQ to XML) allows XML data to be queried by using the standard query operators as well
as tree-specific operators that provide
XPath-like navigation through descendants, ancestors, and siblings.

-It provides an efficient in-memory representation for XML that integrates with the existing System.Xml reader/writer
infrastructure and is easier to use than W3C DOM.
There are three types that do most of the work of integrating XML with queries: XName, XElement and XAttribute.

XName provides an easy-to-use way to deal with the namespace-qualified identifiers (QNames) used as both element and attribute names.
XName handles the efficient atomization of identifiers transparently and allows either symbols or plain strings to be used wherever
a QName is needed.

XML elements and attributes are represented using XElement and XAttribute respectively.
XElement and XAttribute support normal construction syntax, allowing developers to write XML expressions using a natural syntax:

var e = new XElement("Person",
new XAttribute("CanCode", true),
new XElement("Name", "Loren David"),
new XElement("Age", 31));

var s = e.ToString();

This corresponds to the following XML:


Loren David
31


XML elements can also be constructed from an existing XmlReader or from a string literal:

var e2 = XElement.Load(xmlReader);
var e1 = XElement.Parse(
@"
Loren David
31
");


XElement dovetails with the query operators, allowing developers to write queries against non-XML information and produce XML results by constructing XElements in the body of a select clause:

var query = from p in people
where p.CanCode
select new XElement("Person",
new XAttribute("Age", p.Age),
p.Name);

SQL GROUP BY Statement

SQL GROUP BY Statement:

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer


GROUP BY More Than One Column

SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders
GROUP BY Customer,OrderDate

LINQ - Language-Integrated Query - Basics in C# 3.0

LINQ - Language-Integrated Query - Basics in C# 3.0


-To indicate that query is an integrated feature of the developer's primary programming languages.
-Language-integrated query allows query expressions to benefit from the rich metadata, compile-time syntax checking,
static typing and IntelliSense that was previously available only to imperative code .
-The standard query operators allow queries to be applied to any IEnumerable-based information source.
-The extensibility of the query architecture is used in the LINQ project itself to provide implementations
that work over both XML and SQL data.
-The query operators over XML (LINQ to XML) use an efficient, easy-to-use, in-memory XML facility to provide XPath/XQuery
functionality in the host programming language.

simple C# 3.0 program

using System;
using System.Linq;
using System.Collections.Generic;

class app {
static void Main() {
string[] names = { "Burke", "Connor", "Frank",
"Everett", "Albert", "George",
"Harris", "David" };

IEnumerable query = from s in names
where s.Length == 5
orderby s
select s.ToUpper();

foreach (string item in query)
Console.WriteLine(item);
}
}

Output:

BURKE
DAVID
FRANK

-The local variable query is initialized with a query expression. A query expression operates on one or more information
sources by applying one or more query operators from either the standard query operators or domain-specific operators.
This expression uses three of the standard query operators: Where, OrderBy, and Select.

Enumerable query = names
.Where(s => s.Length == 5)
.OrderBy(s => s)
.Select(s => s.ToUpper());

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...