Wednesday, March 14, 2012

Understanding XML Schema - XSD

XML Schema - An XML schema describes the structure of an XML document.
XML schema language also referred as XML schema definition(XSD).
XSD is XML based alternative of DTD(Data Type Definition).

Basics
1. Defines elements of document.
2. Defines attributes of document.
3. Defines which elements are child elements.
4. Defines no. of child elements and order of child elements.
5. Defines an element is empty or can have text.
6. Defines data types for elements and attributes.
7. Defines Default and fixed values for elements and attributes.
8. W3C recommendation.

XSDs are successor of DTDs because
1. XSDs are richer, more powerful and extensible in future.
2. Written in XML.
3. Support data types.
4. Support namespaces.

Why XSDs are recommended
1. XML format - Platform independent.
2. Extensible - Own data types can be created based on standard data types, other schemas can be referenced in a schema, a document can have references of multiple schemas.
3. Support data types - Can be define allowable contents, makes data type conversion easy.
4. Secure data communication - Both ends having data structure.

Example

Simple XML document

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Friday, March 2, 2012

Understanding XPath

XPath is a language to find information in an XML document.



* XPath is a syntax for defining parts of an XML document
* XPath uses path expressions to navigate in XML documents
* XPath contains a library of standard functions
* XPath is a major element in XSLT
* XPath is a W3C recommendation

Understanding XSLT

XSLT(eXtensible style sheet language transformations) is a language to transform a XML document into XHTML document or other XML document.

CSS = Style sheet for HTML document
XSL = Style sheet for XML document

When we open XML document in any browser it opens as it is in text form. Because XML has user defined tags (not predefined) and browser don't know how to display that.
We can create XSLT for any XML document so with the help of XSLT browser understand how to display given XML.

* XSLT stands for XSL Transformations
* XSLT is the most important part of XSL
* XSLT transforms an XML document into another XML document
* XSLT uses XPath to navigate in XML documents
* XSLT is a W3C Recommendation

Thursday, March 1, 2012

Understanding XML

XML is hardware and software independent tool to store and transport data.
XML stands for eXtensible markup language.
XML is a W3c consortium recommendation.
XML is a markup language much like HTML.
XML designed to store and carry data not to display data.
XML designed to be self-descriptive.
XML tags are not predefined, you must define your own tags.

Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Lucky</to>
<from>Mukesh</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

FACTS about XML

1. XML is designed to store and transport data and HTML designed for displaying data.
2. XML doesn't do anything its just designed for structure, store and transport data.

Sunday, February 26, 2012

Override and New keywords

Abstract or virtual members(method/events/indexer) of base class can be redefined in derived class, this is called overriding. An Abstract member is implicitly Virtual.

The method you are overriding must have same signature with overridden method. An overridden method of base class also can be overridden in derived class, because override shows that method exist in some upper class in inheritance hierarchy.

You can't use static, new or virtual to modify method with override.

Reasons
-
With Static - Static makes a method common for all instances, static method is not an instance method so it can't take part in inheritance.

With New - You can have same signature method in derived class compare to base class method with keyword Override or New. Override makes sense that you are redefining a base class method in derived class. New makes sense that it is a fresh new method not having any connection with base class method, it hides existence of base class method in derive class it called Hiding (or Shadowing in VB.Net), Use of New is not recommended because it breaks rules of OOP.

With Virtual - Because we can override a method that is already Virtual.
Some examples to understand it -

Below examples showing Runtime/Dynamic polymorphism.

How runtime calls methods in these scenarios?

First CLR checks runtime type of object, then starts searching last derived form of called method from variable type(compile time type) class to the runtime type class, and calls the last derived form of the called method in between this path.  

Thursday, February 16, 2012

New Features in Sql Server 2008

New In Sql Server for SSIS
1. Introduced VSTA - Introduced Visual Studio Tools for Applications(VSTA) for writing 'Script tasks' and 'Script components'. Earlier VSA(Visual Studio for Applications) was used in Sql 2005 for writing Script tasks and components, by using VB Script as language. In Sql 2008 now its become more functional and secure, now C# and Vb.net can also be used as scripting language. All main features of visual studio added in VSTA like intellisence, build, debug, .net assemblies references, COM components, adding web services etc..  You can create Script task by Open a new or existing Integration Services package in Business Intelligence Development Studio (BIDS). Read article with details on http://www.sql-server-performance.com/2009/ssis-new-features-in-sql-server-2008-part5/ and http://msdn.microsoft.com/en-us/library/ms135952.aspx



Thursday, February 9, 2012

New features in Visual Studio 2008

1.  Multi targeting support - We can develope, build and debug 2.0, 3.0 and 3.5 applications.
2.  Linq support - Efficient way to work with queries. Benefits compile time error checking and step by step query debugging.


Monday, January 30, 2012

Anonymous Functions

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. These two features are known collectively as anonymous functions. In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions.
The following example demonstrates the evolution of delegate creation from C# 1.0 to C# 3.0:

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

Monday, January 23, 2012

Structure

A Struct is a value type typically used to encapsulate small group of related variables.
A structure can have fields, properties, constants, operators, events, methods, constructors, indexers, nested types etc.
A struct can't have parameter less constructor, because CLR initializes all types of struct to their default values by own, so having explicit parameter less constructor will be overhead on performance, and CLR also not guarantees that the constructor will be called.         
Ex.
public struct Book
{
public string author;
public string name;
public string publisher;
public decimal price;
}
Structure Vs Class
A struct is like a class but having some differences -
A. Class is reference type and struct is value type.
B. Class created on heap while struct created on stack.
C. Class can be inherited but struct can't be inherited, A struct can't be a base of any class or struct, because they are sealed by default.
D. Using struct is recommended if having small group of members, because any where we
pass struct a copy of struct passes, so it will be performance overhead if having big size. While class with big group of members is efficient because it's reference passes.
public struct strEx
{
public int x;
}
public class clsEx
{
public int x;
}
public class clsMain
{
public static void main()
{
strEx ObjStr = new strEx();
clsEx ObjCls = new clsEx();

ObjStr.x = 225;
ObjCls.x = 225;

AssignStr(ObjStr); //A copy of object is passing to method
AssignCls(ObjCls); //Refrence of object is passing to method

Console.WriteLine("Value of x of struct is :{0}", ObjStr.x);
Console.WriteLine("Value of x of class is :{0}", ObjCls.x);
}

public static void AssignCls(clsEx cls)
{
cls.x = 500;
}
public static void AssignStr(strEx str)
{
str.x = 500;
}
}
Output -
Value of x of struct is  225
Value of x of class is 500

Sunday, January 22, 2012

Indexers

Indexers allows client code to access a collection item of a class (or interface or structure) by
using object of class as an array.
Syntax -
public int this[int x]  
{
       //  get and set accessors
}

Terminology -
A. Indexers defined by using this keyword, denotes current instance.
B. Indexer must have a parameter of any data type, else compiler will through the error.
C. Object of class behave like an array for indexer.
D. Indexer can't be static it always be the instance member.
E. Indexer can be overloaded, you can have multiple indexers with different signatures.
F. Provides syntactical benefit.
G. Indexers can be used with structures same as used with classes.
H. Indexers declared in an interface enforces to implement same signature(parameter and return type, not access modifier) indexers in Classes those implement that interface.
I. Syntax of indexer in an interface, its not have access modifier because they are public by default and do not have body of accessors because interface only declares members not defines.
int this[int index]
    {
        get;
        set;
    }


Example -
class Indexers
{
        public Indexers()
        { }

//Temprature taken at different time
float[] Temp = new float[]{56.2F, 56.7F, 56.5F, 56.9F, 58.8F,
61.3F, 65.9F, 62.1F, 59.2F, 57.5F};
public float this[int index]
{
get
{
        return Temp[index];
}
set
{
        Temp[index] = value;
}
}

//Weekdays
string[] days = new string[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
private string Getday(string gday)
{
    foreach (string tDay in days)
    {
        if (tDay == gday) return tDay;
    }
    return "Invalid day";
}
public string this[string day] //Overloading of indexers
{
    get
    {
        return Getday(day);
    }
}
}
public class CallIndexers
{
    public static void Main()
    {
        Indexers ObjIndexers = new Indexers();
        Console.WriteLine(ObjIndexers["Wed"]); //Output : Wed

        Console.WriteLine(ObjIndexers[2]); //Output : 56.5F
        ObjIndexers[5] = 60.02F;
        Console.WriteLine(ObjIndexers[5]); //Output : 60.02F
    }
}

Tuesday, January 10, 2012

Boxing and Unboxing

Boxing and Unboxing is act like a bridge between value types and reference type.


Boxing - Storing value type to System.Object type or any interface type that implimented by this value type is called Boxing.
Boxing is implicit, Explicit Boxing also possible but its never required.
Compiler copies value of value type variable to object type and stores it in managed heap by GC.

Unboxing - Copying object type value or an interface type value that this value type implements to a value type variable is called UnBoxing. Unboxing is explicit.

Unboxing consists two steps -
I Checking that object containing value is boxed value of given variable type.
II Copying Object containg value to value type variable.



int i = 123;
object o = i; //Boxing
int j = (int)o; //Unboxing


Wednesday, November 16, 2011

Object oriented programming (OOP)

Namespace
A name space is a logical grouping of classes and other data structures.
Ex. Animals
namespace animals
{
}

Class
A class is definition of a real life object.
Ex. Dogs
class dogs
{
public int AgeOfDog = 30;

public virtual void bark()
{
Console.WriteLine("Dogs bark.");
}
}

Object
An object is an instance of a class.
Ex. Jimmy
dogs jimmy = new dogs();

Access modifiers
Private A member that can be accessible only in the class where it declared.
Protected A member that can be accessible in same class and derived class.
Public A member that can be accessible any where, normally by using object of the class.
Internal A member that can be accessible inside the assembly, also called friend or Assembly member.

Inheritance
Inheritance is a technique that allows a class to acquire attributes of its base type.
Its an ability to create new classes based on existing classes. Inheritance referred as second pillar of OOPs.   

A derived type can access all the protected, internal(if derive type in same assembly) and public members of base type.
It can overload a method of base type, can redefine (override) a virtual method of base type

class dabaurman : dogs //dabaurman inheriting dogs
{
AgeOfDog = 12;
public override void bark() //Overriding bark function of dogs class
{
Console.WriteLine("Daburmans looks ready to bark always, max age of them is " + AgeOfDog.Tostring());
}
}

Abstraction (Data hiding)
Abstraction means to show only the necessary details to the client of the object. Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT.
Let’s say you have a method "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member, Right?
We use thousands of methods provided by .net library without having knowledge of internal process of methods, like Math.Round(decimal d), how this function rounds the number we don't know but we can use it, this is an example of Abstraction.

Encapsulation (Data binding)
Encapsulation is process of binding data with code in a single entity. This keeps the data safe from outside interface and misuse.
Encapsulation is a protective wrapper that prevent data from being arbitrary accessed by other code.
Encapsulation referred as first pillar of OOPs.  
Variables of a class can hold data, we can give access to outside code over this type of members according us, like read only, write only or read write.

Accidental modification can happen to the public variables.
public int AgeOfDog = 30;
Putting data with related functions inside class is called Encapsulation.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. one way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Now question is that How Encapsulation hide data? 

Class Customer
{
    private int _age; //private member

    public int getAge(){return _age;}
    //OR 
    //public int Age
    // {
    //    get{return _age;}
    //    set{_age = value;}         
    // }
}
1. We can have read-only, write-only or read-write access to a member(_age) by having get, set or get and set both respectively .
2. We can validate data before setting value(in property or method).
3. We can audit or log data before setting value(in property or method).

Polymorphism
Its a technique in that a object can take multiple forms.
A base type variable can hold object of any of its drive type. Polymorphism referred as third pillar of OOPs.    

Types of Polymorphism -
1. Static Polymorphism(Compile time Polymorphism)
Ex. Function overloading, operator overloading

2. Dynamic Polymorphism(Run time Polymorphism)
Ex. Function overriding

How runtime calls methods in these scenarios? 
First CLR checks runtime type of object, then starts searching last derived form of called method from variable type(compile time type) class to the runtime type class, and calls the last derived form of the called method in between this path. 


namespace Animals
{
    class Humans
    {
        public virtual void walk()
        {
           Console.writeline("Human can walk.");
        }

    class Indians : Humans
    {
        public override void walk()
        {
            Console.writeline("Indians can walk fast.");
        }
    }
}

class mainclass
{
    void main()
    {
        Humans ObjHumans;
     
        ObjHumans = new Indians();
        ObjHumans.Walk(); // will call Indians' walk function

        ObjHumans = new Humans();
        ObjHumans.Walk(); // will call Human's walk function
    }
}

Refer http://gstomar.blogspot.in/2012/02/overriding-and-new-keywords.html

If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The newkeyword is put before the return type of a class member that is being replaced. The following code provides an example:
public class BaseClass
{
public void DoWork() { WorkField++; }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { WorkField++; }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
Hidden base class members can still be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.

Function overloading
It’s a technique that enables a function name to accept different nos. and types of parameters. In other word we can create a no. of functions in a class of same name with different no. and different type of parameters.
Function overloading can be performed by
1. Different no. of parameters
2. Different type of parameters
3. Different sequence of parameters
Benefits \ Requirement
1. Makes consistency of interface.
2. No need to remember a no. of functions.
Return type can be changed of different overloaded methods.
Only change of return type can not overload a method, compiler will fire an error “you cannot overload a method by changing only return type
Ex.
Public class Words
{
Private string Getword()
{
// Will return first word of entered string
}
Private string Getword(int index)
{
// Will return word, searching by index from entered string
}
Private string Getword(string word)
{
// Will return word, by searching passed word from entered string
}
}

Function overriding 
A good article on overriding given on Code project
http://www.codeproject.com/KB/cs/cs_methodoverride.aspx

A method of base class can be re-defined in derived class this technique is called function overriding.
In other words if you want a method of base class behave something different for drive class then you can re-define it in derived class.

Method should be marked virtual (overridable in VB) in base class.
When you override it in derived class it will mark override (overrides in VB).

Signature (return type and parameters) of base and overridden methods must be same.
Access modifier of base and overridden methods must be same.
Static or non virtual method can’t be overridden.
An overridden method can’t be marked virtual, abstract or static.
It can be marked sealed so that you can stop it to overriden in further drived calsses.

Class Shapes
{
Public class Square
{
Public double x;
Public square(double x) //constructor
{
this.x = x;
}
Public virtual double area()
{
Return x * x;
}
}

Class Cube : Square
{
Public double x;

public cube(double x) //constructor
{
this.x = x;
}

public override double area()
{
return 6 * x* x;
}

}
Public static void main()
{
Double x = 2.6;
Square S = new Square(x);
Square C = new Cube(x);
Response.write(“Area of Square:” + S.area().tostring());
Response.write(“Area of Cube:” + C.area().tostring());
}
}

Monday, November 29, 2010

Reflection

Reflection is a technique that enables you to fetch and manipulate assembly information at runtime.
Assembly information that can be accessed or manipulated includes type, properties, methods, events of object, constructors etc.
Reflection allows to access information at runtime of assembly that is not available at compile time.
Reflection uses PE file of assembly to access assembly information.

Name spaces those provide required classes
1. System.Reflection
2. System.Type

objAssembly=System.Reflection.Assembly.LoadFrom(str path);
After loading assembly you can get all types from assembly, Function GetTypes() returns array of objects of System.Type
arOfTypes=objAssembly.GetTypes();

Some functions to get information of an object of System.Type
ConstructorInfo[] ctrInfo=t.GetConstructors(); //Returns array of objects of ConstructorInfo type
PropertyInfo[] pInfo = t.GetProperties(); //Returns array of objects of PropertyInfo type
MethodInfo[] mInfo=t.GetMethods(); //Returns array of objects of MethodInfo type
EventInfo[] eInfo=t.GetEvents(); //Returns array of objects of EventInfo type

Type t= Type.GetType("MyReflection.MyClass1"); //Returns object of type MyClass1.

=============
Reflection is the ability of the .NET framework to gather information (metadata) about assemblies, modules and types at runtime. It allows you also to dynamically create instances of types, invoke methods and access fields, properties and attributes.

Getting all types information that assembly have

Code block 1
using System;
using System.Reflection;
class Class1
{
public static void Main()
{ // You must supply a valid fully qualified assembly name.
Assembly SampleAssembly = Assembly.Load
("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken = 8744b20f8da049e3");
// Display all the types contained in the specified assembly.
foreach (Type oType in SampleAssembly.GetTypes())
{
Console.WriteLine(oType.Name);
}
}
}

Getting complete information of a method using loadfrom method
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
// Obtain a reference to a method known to exist in assembly.
MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Method1");
// Obtain a reference to the parameters collection of the MethodInfo instance.
ParameterInfo[] Params = Method.GetParameters();
// Display information about method parameters.
// Param = sParam1
// Type = System.String
// Position = 0
// Optional=False
foreach (ParameterInfo Param in Params)
{
Console.WriteLine("Param=" + Param.Name.ToString());
Console.WriteLine(" Type=" + Param.ParameterType.ToString());
Console.WriteLine(" Position=" + Param.Position.ToString());
Console.WriteLine(" Optional=" + Param.IsOptional.ToString());
}

Code block 2
            Assembly objAsmbl = Assembly.LoadFrom("path");
            Type[] objType = objAsmbl.GetTypes();
            foreach (Type type in objType)
            {
                MethodInfo[] lstMethods = type.GetMethods();
                EventInfo[] lstEvents = type.GetEvents();
                ConstructorInfo[] lstConstructor = type.GetConstructors();
                FieldInfo[] lstFields = type.GetFields();

                foreach (MethodInfo mthd in lstMethods)
                {
                    Console.WriteLine(mthd.Name + mthd.ReturnType.ToString() + mthd.IsStatic.ToString());
                    ParameterInfo[] lstParameter =  mthd.GetParameters();
                    foreach (ParameterInfo pi in lstParameter)
                    {
                        Console.WriteLine(pi.Name + pi.ParameterType.ToString() + pi.Position.ToString() + pi.IsOptional.ToString());
                    }
                }
           
            }

Friday, November 26, 2010

Faqs

Q.1 How to access Master page's controls on content page?

We will have to put a tag to content page then we can access master page's content place holder control and other content controls.

<%@ MasterType VirtualPath="~/MasterCAT.master" %>

Accessing control of master page
AdRotator adr = Master.FindControl("MyAdRotator");
===================

Q. 2 How to install an assembly to GAC?

gacutil -i assemblyname
===================

Q. 3 How can you attach master page dynamically?

this.MasterPageFile = "~/NewMaster.Master";
===================

Q.4 What is 'AutoEventWireup' ?
Its an attribute of 'Page' tag, that has true default value. This means events of page are bind with the event handlers written in code behind.
If we give it value false, then we need to specify code that connect page events to event handlers written in code behind file.
Ex. Connecting Page_load event to its handler
 override protected void OnInit(EventArgs e)
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }

Thursday, November 25, 2010

Caching

An application can increase performance by storing data that is accessed
frequently and require significant time to create.
Instead of recreating same data, satisfying request with stored data in sub
sequent requests, this technique is called Caching.
Application cache
Provides a way to store application data in pair of key \ value. This stored
data is volatile, it removes as it expire or become invalidate. Application can
be configure to notify when an item remove from caching.
Pattern is that any time you access an item from cache you checks whether
it exist or not, if not you can recreate it and place it to cache, this pattern
ensures that cache contained latest data.
Adding value to cache
Cache.Insert("Name", strName,
new CacheDependency(Server.MapPath("name.txt"),
DateTime.Now.AddMinutes(2), TimeSpan.Zero);

Accessing cached value
if (Cache["name"] != null)  Label1.Text= Cache["name"].ToString();

Page output cache
It stores processed page / user control in cache. This allows asp.net to send
response to client without processing page again.
This technique can increase performance of page dramatically. You can use
it for a page that has high traffic and not updated frequently.
Full page can be cached by putting below tag to the page

By specifying on page this will cache the page for 60 seconds.
<%@ OutputCache Duration="60" VaryByParam="none" %>

There are two divisions types of page output cache
1. Control caching(Fragment caching)
2. Post-cache substitution

1. Control caching(Fragment caching)
- You can mark a particular section as
cacheable like user control, so whole page recreated dynamically every time
accept marked cacheable area.

Specifying this will cache the complete user control in wich you define it
<%@ OutputCache Duration="60" VaryByControl="ControlID" %>

Ex. Share stock display page, displays weekly summary also then make user
control for weekly summary and mark that cacheable.

2. Post-cache substitution - You can mark a particular section as non cacheable,
so whole page cached but marked section recreated dynamically each time page
requested.
we can achieve this by using substitution control, this control is used for this
purpose generally. we assign 'MethodName' attribute of this tag by a method that
returns a string.
<asp:Substitution ID="Substitution1" runat="server" MethodName="getScore" />
Ex.
1. Live cricket score page, area / user control that displaying score can be marked
as non cacheble, so every time it will recreated and whole page come from cache.
2. If you have a static page that has a label that displays name of page requester
then you can mark that label non cacheable, so whole page will cached and label
recreated dynamically each time.

ASP.NET can remove data from the cache for one of these reasons:
1. Because memory on the server is low, a process known as scavenging.
2. Because the item in the cache has expired.
3. Because the item's dependency changes.
Read page on below link http://msdn.microsoft.com/en-us/library/aa478965.aspx

Wednesday, November 24, 2010

User control Vs Custom control

User Control
The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the html, form and body elements since a Web Forms page hosts the user control.
Creating and adding user control to form at runtime
you can add an user control to application by right click on solution and click on 'add new item' option.
You can add an user control to page by adding a register tag to page at compile time.
'<%@ Register TagPrefix="tp" Src="~/WebUserControl.ascx" TagName="MyUC" %>'
Now you can use control on page like '<tp:MyUC ID ="myFirstUc" runat="server" />' 

Add user control to page at run time.
// Load the control by calling LoadControl on the page class. Control c1 = LoadControl("test.ascx"); // Add the loaded control in the page controls collection. Page.Controls.Add(c1);

Custom control
Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does. In new project window select in web select ASP.net server control and then write code in control's class. Now you can override render method of control to display as you want on rendering of control.
namespace FirstCustomControl {
 [DefaultProperty("Text")]
    [ToolboxData("<{0}:CustomEmailLink runat=server></{0}:CustomEmailLink>")]
    public class CustomEmailLink : WebControl {
        [Bindable(true)]
        [Category("Appearance")]
        
        [Localizable(true)]
        public string DisplayName {
            get {
                String s = (String)ViewState["DisplayName"];
                return ((s == null) ? "[DisplayName]" : s);
            }

            set {
                ViewState["DisplayName"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Email {
            get {
                String s = (String)ViewState["Email"];
                return ((s == null) ? "[Email]" : s);
            }

            set {
                ViewState["Email"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Subject {
            get {
                String s = (String)ViewState["Subject"];
                return ((s == null) ? string.Empty : s);
            }

            set {
                ViewState["Subject"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Body {
            get {
                String s = (String)ViewState["Body"];
                return ((s == null) ?string.Empty : s);
            }

            set {
                ViewState["Body"] = value;
            }
        }
        protected override void RenderContents(HtmlTextWriter output) {
            if (this.DesignMode) { RenderDesign(output); } else {
                if (this.Visible) {
                    RenderRuntime(output);
                }
                else {
                    return;
                }
            }
        }

        private void RenderRuntime(HtmlTextWriter output) {
            HyperLink link = new HyperLink();
            link.ID = this.ID;
            link.Text = this.DisplayName;
            link.NavigateUrl=string.Format("mailto:{0}",this.Email);
            if (!string.IsNullOrEmpty(Subject)) {
                link.NavigateUrl = link.NavigateUrl + "?subject=" + this.Subject;
                link.NavigateUrl = link.NavigateUrl + "&body=" + this.Body;
            }
            link.RenderControl(output);
        }

        private void RenderDesign(HtmlTextWriter output) {
            output.Write("Display Name:{0}<br/>Email:{1}<br/>Subject:{2}<br/>Body:{3}", this.DisplayName, this.Email,this.Subject,this.Body);
        }
}        
    }


You can add control to tool box
Right click on tool box select 'choose items', then select .net components, then browse custom control's dll. Now you can use this custom control on pages like other controls.

User control Vs Custom Control 
1. You can use custom control in your application by adding assembly reference to application while you need separate copy of user control in each application. 
2. You can add custom control in tool box while user control can’t be added. 
3. Custom control can be used in multiple applications by adding assembly to the GAC for same machine. 
4. Custom controls are difficult to create but easy to use in multiple applications. 
5. User controls are easy to create but difficult to use in multiple application.

Friday, October 29, 2010

Threading

Threading enables concurrent processing, you can perform multiple tasks simultaneously.

Multithreading is the ability of operating system to concurrently run programs or tasks in separate threads.
Multithreading requires OS those can perform it, and we written programs in such manner that uses this ability of OS.
It’s a fast computation because it runs multiple tasks simultaneously in different threads.
Basically it’s a game of operating system, tasks not run simultaneously os allots time slots to each thread and runs threads for those allotted time slots, user response is very slow compare to system so user feels like processes running concurrently.
How threading works
Application domains run in processes, and each application domain starts with a single thread and then a thread can call other threads. Operating system divided processor time among threads, it allotted time slots to threads to be executed slots depends on priority, os and thread size.
When a thread switches from running state to suspended os saves context (information) for it, and loaded context of thread to be executed.
Thread pool class – To manage group of threads.
Timer - Enable calling to delegates after a certain amount of time.
Mutex - Mutex class is used to protect simultaneous access of a shared resource. State of Mutex object is set to 'signaled' when it is not owned by any thread or 'nonsignaled' when owned by any thread, so treads can own it one by one.

Pausing and resuming threads
Method Thread.Sleep(miliseconds) immediately suspend a thread for given milliseconds and other thread uses this time slice.
Thread.Sleep(Timeout.Infinite) - Sends to sleep for infinite time.
Thread.Abort() - Aborted the thread.
Thread.Interrupt() - Interrupt the thread.

Overview
1. Threads enables concurrent processing.
2. System.Threading provides classes and interfaces for it, ex to create, start, abort, suspend, synchronization of multiple threads etc.
3. Threads share application resources.

Using System.Threading;

Thread thrd = new Thread(new ThreadStart(obj.Method));
thrd.start();


Friday, October 22, 2010

Asynchronous Calling to a method

We can call a method asynchronously by using beginInvoke and endInvoke methods of delegate,
we pass method's parameters to beginInvoke method then we have got to pass return value of beginInvoke method to endInvoke method, endInvoke method returns actual result(return type of method).
Asynchronous call to a method runs method in a separate thread.
Once you ask the framework to call something asynchronously, it needs a thread to do the work. It can not be the current thread, because that would make the invocation synchronous (blocking). Instead, the runtime queues a request to execute the function on a thread from the .NET Thread Pool. You don’t really need to code anything for it, all of it happens in the background. But, just because it is all transparent doesn’t mean you should care about it. There are a few things to remember:
  • FlushToDisk is executed on a separate thread, a thread that belongs to the .NET Thread Pool.
  • A .NET Thread Pool normally has 25 threads in it (you can change that limit), and each time  FlushToDisk is called, it is going to be executed on one of these threads. You can't control which one.
  • The Thread Pool has its limits! Once all the threads are used, an async method invocation is queued until one of the threads from the pool is freed. This is called Thread Pool Starvation, and normally when it comes to that, performance is compromised.

class DataCache {
public int FlushToDisk(string fileName) {
// simulate a long operation
Thread.Sleep(4000);
return 0;
}
}

class Program {
// define a delegate for the long operation
delegate int CacheFlusher(string fileName);
static void Main(string[] args) {
// create the object and then the delegate
DataCache cache = new DataCache();
CacheFlusher flusher = new CacheFlusher(cache.FlushToDisk);
// invoke the method asynchronously
IAsyncResult result = flusher.BeginInvoke("data.dat", null, null);
// get the result of that asynchronous operation
int retValue = flusher.EndInvoke(result);
Console.WriteLine(retValue);
}
}


Method # 01
// begin execution asynchronously
IAsyncResult result = flusher.BeginInvoke("data.dat", null, null);
// wait for it to complete
while (result.IsCompleted == false) {
// do some work
Thread.Sleep(10);
}
// get the return value
int returnValue = flusher.EndInvoke(result);


Method # 02
// call the delegate asynchronously
IAsyncResult result =
flusher.BeginInvoke("data.dat", null, null);
// wait for the call to finish
result.AsyncWaitHandle.WaitOne();
// get the return value
int returnValue = flusher.EndInvoke(result);


Method # 03
static void Main(string[] args) {
// create the object
DataCache cache = new DataCache();
// create the delegate
CacheFlusher flusher = new CacheFlusher(cache.FlushToDisk);
// call the delegate asynchronously
flusher.BeginInvoke("data.dat", new AsyncCallback(CallbackMethod), flusher);
// wait to exit
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
static void CallbackMethod(IAsyncResult result) {
// get the delegate that was used to call that
// method
CacheFlusher flusher =
(CacheFlusher) result.AsyncState;
// get the return value from that method call
int returnValue = flusher.EndInvoke(result);
Console.WriteLine("The result was " + returnValue);
}

Thursday, October 14, 2010

Sql - Function Vs Stored Procedure

Functions

1. Can be used with Select statement.
2. Not returns output parameter but returns table variables.
3. You can join UDFs.
4. Can not be used to change server configuration.
5. Can not be used with XML FOR clause.
6. Can not have transaction within function.


Stored Procedures

1. Used with EXEC or EXECUTE.
2. Returns output parameter.
3. You can not join SPs.
4. Can be used to change server configuration.
5. Can be used with XML FOR Clause.
6. Can have transaction within SP.

Sunday, October 10, 2010

Using Scenario - Abstract Class Vs Interface

Abstract class

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated.

The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

Interface

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the declaration of methods.

As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.


Using Scenario - Abstract Class Vs Interface

1. If you want to create multiple versions of your component, means need to create some new version in future then use abstract class because you can update abstract class and all classes derived from it updated automatically. While If you need to update interface it's not allowed, you will have to create whole new interface.

2.
If your base functionality will be useful for a wide disparate or unrelated range of classes then create interface, because abstract classes should be created for something closely related classes.

3.
If you have requirement of common, implemented base functionality then create abstract class because abstract class allow implementation also of members while in interface you can not implement any member.
If you need to have some code, data, access modifiers in functionality then use abstract class, in interface all members are public by default.

4.
If you are designing small base functionality then create interface for large base functionality use abstract class.

Thursday, September 30, 2010

Abstract and Sealed concepts

Abstract classes and members

Abstract keyword used to define class and class members for the purpose of inheritance.
An abstract class can't be instantiated and an abstract method doesn't have definition in base class, declaration followed by semicolon.

public abstract classA
{
public abstract void dowork(int i); //Abstract method has only declaration in base class
}

A non abstract derived class of an abstract base class must define all the abstract methods of base class and inherited abstract members from upper hierarchy of base class.
public classB : classA
{
public override void dowork(int i)
{
//Implementation of abstract method of base class
}
}

A. Should not define public or protected internal constructor.
B. Can be define Protected or internal constructor.
C. Abstract members are implicitly Virtual.
D. Declaring an abstract member as Virtual or Static is an error.
E. Abstract class may contain non abstract members, non abstract members can have definition in abstract class, meant common method for all derived classes without overriding the method.
F. An abstract derived class can define or not define abstract members of base class.
G. An abstract class can't be declared as Sealed, because having opposite meaning.
H. Non abstract class can't contain abstract members, abstract method can be declared in Abstract class.
I.  An abstract method declaration don't have braces {}, declaration followed by semicolon only.
    Ex.  public abstract void dowork(int i);
J. An Abstract class must implement all members of inherited Interface but not required to override all abstract members of inherited base class.
k. Abstract method declaration is allowed to override a virtual method of base class.

class A
{
   public virtual void F() {
      Console.WriteLine("A.F");
   }
}
abstract class B: A
{
   public abstract override void F();
}
class C: B
{
   public override void F() {
      Console.WriteLine("C.F");
   }
}

Purpose of abstract class to make common definition of a base class that multiple derived classes can share.
A class library has a abstract class than programmers can use the library and have their own implementation of derived class using base abstract class.

Ex.
     public abstract class Animals
    {
        public void Move()  //Non Abstract function
        {
            string s = "All animals can move";
        }
        public abstract void Breath();   
    }
    public class Dogs : Animals
    {
        public Dogs() { }
        public override void Breath()
        {  //Breath in open air
        }
    }
    public class Fish : Animals
    {
        public Fish() { }
        public override void Breath()
        {  //Breath in water
        }
    }
Dogs DaburMan = new Dogs();
            DaburMan.Breath();   //Abstract function of base abstract class
            DaburMan.Move();     //Non Abstract function of base abstract class
       Fish Shark = new Fish(); 
            Shark.Breath();  //Abstract function of base abstract class
            Shark.Move();    //Non Abstract function of base abstract class

***********************

Sealed classes and members


A sealed class can't be inherited, Sealed keyword is used to protect from derivation a class.
A sealed class can't be abstract, because of opposite meaning.
A sealed method also can't be override in derived class.
When applied to method or property sealed keyword always used with override keyword.

If you override an base class virtual method in derived class, you can declare that sealed there(on override) to protect override of that method in further derived classes. This negates the virtual aspect of the member for any further derived class.

public class D : C
{
public sealed override void DoWork()
{
// Implementation
}
}

Scenario - Creating Sealed class
1. To take away inheritance feature from users so they can't inherit that class.
2. If we have some internal operation/s in class or function, because access of class or function in this case can be harmful. ex. .net's string class is sealed.
3. If we have static members in class(Static members are sealed by default). ex pen, brush classes are sealed.

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...