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.

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...