Monday, February 27, 2012


Factory design pattern


Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses." Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input.

Goal:
Only creating objects
A C# example of the Factory Pattern
// A Simple Interface
public interface IVehicle
{
    void Drive(int miles);
}

// The Vehicle Factory
public class VehicleFactory
{
    public static IVehicle getVehicle(string Vehicle)
    {
        switch (Vehicle) {
            case "Car":
                return new Car();
            case "Lorry":
                return new Lorry();
            default:
                throw new ApplicationException(string.Format("Vehicle '{0}' cannot be created", Vehicle));
                break;
        }
    }
}

// A Car Class that Implements the IVehicle Interface
public class Car : IVehicle
{
    public void IVehicle.Drive(int miles)
    {
        // Drive the Car
    }
}

// A Lorry Class that Implements the IVehicle Interface
public class Lorry : IVehicle
{
    public void IVehicle.Drive(int miles)
    {
        // Drive the Lorry
    }
}

Example code Download here :FactoryExa

Design Patterns


Design patterns are recognized solutions to common problems defined originally by the Gang of Four programmers. Design patterns are used throughout the ASP.NET Framework.  The various patterns are commonly divided into several different groups depending on the nature of the design problem they intend to solve.

Creational Patterns

  • Factory - This pattern is used to create concrete class instances without specifying the exact class type.  
  • Abstract Factory - This pattern is used to create concrete class instances without specifying the exact class type. The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme.
  • Flyweight - A pattern used to maximize the sharing of objects resulting in reduced memory consumption.
  • Singleton - This pattern insures that only a single instance of a given object can exist.
  • Builder - This pattern separate the construction of a complex object from its representation so that the same construction process can create different representations..

Structural Patterns

  • Adapter - Convert the interface of a class into another interface clients expect. Adapter lets the classes work together that couldn't otherwise because of incompatible interfaces
  • Bridge - Decouples an abstraction from its implementation so that the two can vary independantly.
  • Composite - Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • Decorator - Allows an objects behavior to be altered at runtime.
  • Facade - Used to provide a simpler interface into a more complicated portion of code. 
  • Proxy - Provides a Placeholder for another object to control access to it.

Behavioral Patterns

  • Chain of Responsibility - The chain of responsibility pattern is a way of communicating between objects.
  • Command - Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.   
  • Iterator - Provides a way to sequentially access aggregate objects without exposing the structure of the aggregate.
  • Mediator - The mediator pattern encapsulate the interaction between a set of objects.
  • Memento - Allows you to save the state of an object externally from that object.
  • Observer - Allows a single object to notify many dependent objects that its state has changed.
  • State - Allows an object to change its behaviour when its internal state changes.
  • Strategy - Allows multiple algorithms to be used interchangeably at runtime.
  • Visitor - The visitor design pattern enables us to create new operations to be performed on an existing structure.
  • Template Method -  Defines the skeleton of an algorithm then lets subclasses implement the behaviour that can vary.

Antipatterns

Antipatterns are misapplied design patterns. Common Antipatterns include:
  • The Blob/God Object - When one class contains all of the methods, operations and logic of your application
  • Re-coupling - building an unnecessary dependency between objects
  • Poltergeists - object whose main purpose in life is to pass messages to another object
  • Sequential Coupling - a class that imposes a particular order on its method calls. 

Other patterns

Videos

Articles

Books

refer from some wiki articles

Friday, February 24, 2012

Enums Csharp


Enums

An enum is a special value type that lets you specify a group of named numeric

Constants. For example:


  public enum BorderSide { Left, Right, Top, Bottom }

We can use this enum type as follows: 

  
  BorderSide topSide = BorderSide.Top;
  bool isTop = (topSide == BorderSide.Top);
  

Each enum member has an underlying integral value. By default: 

• Underlying values are of type int.

• The constants 0, 1, 2... are automatically assigned, in the declaration order of

the enum members.

You may specify an alternative integral type, as follows: 

  public enum BorderSide : byte { Left, Right, Top, Bottom }

You may also specify an explicit underlying value for each enum member:

  public enum BorderSide : byte { Left = 1, Right = 2, Top = 10, Bottom = 11 }

Thanks…
Ref C# nutshell and Google


Thursday, February 23, 2012

Abstract Classes and Abstract Members


A class declared as abstract can never be instantiated. Instead, only its concrete
subclasses can be instantiated.
Abstract classes are able to define abstract members. Abstract members are like virtual
members, except they don’t provide a default implementation. That implementation
must be provided by the subclass, unless that subclass is also declared
abstract:



public abstract class Asset
{
    // Note empty implementation
    public abstract decimal NetValue { get; }
}
public class Stock : Asset
{
    public long SharesOwned;
    public decimal CurrentPrice;
    // Override like a virtual method.
    public override decimal NetValue
    {
        get { return CurrentPrice * SharesOwned; }

    }
}

 Thanks........



Tuesday, February 21, 2012

How to send email in asp.net


 

To send mail you can use ‘System.Net.Mail’.

Code-Behind:

  Using System.Net.Mail;
public void SendEmail(string from, string to, string bcc, string cc, string subject,
string body)
{
    try
    {  
        MailMessage NewEmail = new MailMessage();
        NewEmail.From = new MailAddress(from);
        NewEmail.To.Add(new MailAddress(to));
        if (!String.IsNullOrEmpty(bcc))
        {
            NewEmail.Bcc.Add(new MailAddress(bcc));
        }
        if (!String.IsNullOrEmpty(cc))
        {
            NewEmail.CC.Add(new MailAddress(cc));
        }
        NewEmail.Subject = subject;
        NewEmail.Body = body;
        NewEmail.IsBodyHtml = true;
        SmtpClient mSmtpClient = new SmtpClient();
        // Send the mail message
        mSmtpClient.Send(NewEmail);
        this.Label1.Text = "Email sent successful.";
    }
    catch
    {
        this.Label1.Text = "Email sent failed";
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    string from = "sender address";// like username@server.com
    string to = TextBox1.Text; //Recipient address.
    string bcc = "";
    string cc = "";
    string subject = "text";
    string body = "text";
    SendEmail(from, to, bcc, cc, subject, body); }
Web.Config:
<system.net>
  <mailSettings>
    <smtp>
      <network host="your stmp server" port="25" userName="your from email" password="your password"/>
    </smtp>
  </mailSettings>
</system.net>

 

Related thread:

http://forums.asp.net/t/1207868.aspx

Transfer data between pages asp.net


Here are several approaches to transfer data between pages:

Query Strings: You can transfer data between pages with query strings. The data will be displayed in the URL as parameters. Sometimes you want to encode the parameters, which can be done with HttpServerUtility.UrlEncode or HttpUtility.UrlEncode.

For example:

In page1, you can transfer the data to another page by redirecting.

Response.Redirect("Page2.aspx?parameter=" + TextBox1.Text);
 In page2, you can use

QueryString["parameter"] to get the data from page1.

Cookies: Cookies can be stored on client side machines. If you do not set the cookie's expiration, the cookie will be created but will not be stored on the user's hard disk. Instead, the cookie will be maintained as part of the user's session information. When the user closes the browser or if the session times out, the cookie is discarded.

You can add cookies to the Response.Cookies collection in a couple of ways, the following example shows two methods:

Response.Cookies["userName"].Value = "mike";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);


You can get more details from this link: http://msdn.microsoft.com/en-us/library/aa289495.aspx .

Session Variables: A session is stored in the server memory and it is unique to a particular client.

For example:

Store the data into a session in Page1:
Session["userName"] = "mike";
Retrieve the data in Page2:
Session["userName"].ToString();

Server.Transfer:

Server.Transfer sends all of the information that has been assembled for processing by one page to another page. The URL on IE won’t be changed.
For example:

In page1, you can use ‘transfer’ to send all of the information in page1 to page2.
Server.Transfer("Page2.aspx", true);
Then you can use the below codes in Page_Load to retrieve the value of TextBox1 from page 1.
Response.Write(Request.Form["TextBox1"]);
You can get more information from this link: http://msdn.microsoft.com/en-us/library/ms525800.aspx and ASP.NET State Management Overview.

Related thread: http://forums.asp.net/t/1208146.aspx

How to check if the users are online or offline


Many developers tend to use ‘Session_End’ event to mark a user as ‘Offline’, but this may not be a good idea, because there are no one-to-one mappings between an ASP.Net session and a user. For example if a user opens 2 separate instances of Internet Explorer (e.g. 2 separate IE processes) on his workstation, he can have 2 ASP.Net sessions open. The ‘Session_End’ event of one of the session does not necessarily mean that the user is offline, they can still be using the website.
In addition, ‘Session_End’ event is only available in the ‘InProc’ session mode. If you are trying to store session states in the State Server or SQL Server, ‘Session_End’ event, it will never fire.
I would suggest using the last visiting time as the ideal approach.
Membership helps build the user database and there is a convenient approach to get it via Membership.GetUser(stringuserName).IsOnline.
If you don’t use Membership, you can use the method below which uses the same principle in Membership:
In the application, you can define a global dictionary membershipDictionary to store the information about users online and offline.
Use an AJAX Timer (or simply XmlHttpRequest in client side JavaScript) in the pages to update theLastVisitTime of the user and store it into membershipDictionary at intervals.
From time to time, visit the dictionary membershipDictionary to filter out the idle users (who have not visited the page for a long time) and also retrieve information on how many users are still online.  Regular maintenance can be done in a separate thread or a server-based timer. Please also be aware of thread synchronization issues.

Friday, February 17, 2012

c# Type Safety

c sharp is type safety language 
simple definition
"well typed program-never go wrong"   

C# is primarily a type-safe language, meaning that types can interact only through
protocols they define, thereby ensuring each type’s internal consistency. For instance,
C# prevents you from interacting with a string type as though it were an
integer type.
More specifically, C# supports static typing, meaning that the language enforces
type safety at compile time. This is in addition to dynamic type safety, which the .NET
CLR enforces at run time.


Type safe code access only the memory location ,It is authorized to access.
It cannot read value from another private fields. Its access types only in well defined, allowable ways


Reference book c# 4.0 in a nutshell

composite key in sql

A primary key can consist of one or more columns of a table. When two or more columns are used as a primary key, they are called a composite key. Each single column's data can be duplicated but the combination values of these columns cannot be duplicated.
for example

In SQL Server Management Studio, you can highlight more than one column in the table designer, and choose "Set Primary Key" from the context menu:
alt text
That makes those selected columns a composite primary key.

Thursday, February 16, 2012

When to use abstract class and interface

f you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.

If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
Use an abstract class to define a common base class for a family of types.
Use an abstract class to provide default behavior.
Subclass only a base class in a hierarchy to which the class logically belongs.

Use an interface

When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
Use an interface to design a polymorphic hierarchy for value types.
Use an interface when an immutable contract is really intended.
A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality.

Monday, February 13, 2012

Jquery Web page method




<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript" src="https://github.com/malsup/blockui/raw/master/jquery.blockUI.js?v2.34"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            data: "{}",
            url: "JQuery AJAX call to page method not working.aspx/GetCountry",
            dataType: "json",
            success: function(data) {
                $(data.d).each(function(index, item) {
                    $("#country").append($("<option>").val(item.CountryID).html(item.CountryName));
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                debugger;
            }
        });
        $("#country").change(function() {
            $.blockUI({ message: '<img src="http://www.clickbd.com/global/img/loading.gif" alt="loading..."/> <br /> Just a moment......' });
            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: "{CountryID:" + $(this).val() + "}",
                url: "JQuery AJAX call to page method not working.aspx/GetState",
                dataType: "json",
                success: function(data) {
                    $("#State").empty();
                    $(data.d).each(function(index, item) {
                        $("#State").append($("<option>").val(item.StateID).html(item.StateName));
                    });
                    $.unblockUI();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                }
            });
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
  <select id="country" >
  </select>
  <select id="State" ></select>
    </form>
</body>
</html>
public partial class JQuery_AJAX_call_to_page_method_not_working : System.Web.UI.Page
{
    [System.Web.Services.WebMethod]
    public static object GetCountry()
    {
        var obj = new { CountryID = 0, CountryName = "Country Name 0" };
        var objList = (new[] { obj }).ToList();
        for (int i = 1; i < 10; i++)
            objList.Add(new { CountryID = i, CountryName = "Country Name "+i.ToString() });
        return objList;
    }
    [System.Web.Services.WebMethod]
    public static object GetState(string CountryID)
    {
        var obj = new { StateID = 0, StateName = "Country "+CountryID+ " state Name 0" };
        var objList = (new[] { obj }).ToList();
        for (int i = 1; i < 10; i++)
            objList.Add(new { StateID = i, StateName = "Country " + CountryID + " state Name "+i.ToString() });
        System.Threading.Thread.Sleep(4000);//Delete this line
        return objList;
    }
}