Thursday, November 24, 2011

Anonymous types



The Basics


Anonymous types are those types which are not declared before they are used. Say while you are doing your program, you want a temporary storage of your data, what you need to do, you need either declare a concrete class for the storage of the same, or you can use any collection like ArrayList, HashTable etc to store the key value collection. C# 3.5 and onwards allows you to dynamically create a type and use it directly in your program. You can use ‘var’ or implicit type declaration to ensure you could use the properties just like normal types.
var myruntimeObject = new { FirstProperty = 10, SecondProperty = new DateTime(), ThirdProperty = "string type" };

Console.WriteLine("Type of myruntimeObject is {0}", myruntimeObject.GetType().Name);
Console.WriteLine("Type of FirstProperty is {0}",       myruntimeObject.FirstProperty.GetType().Name);
Console.WriteLine("Type of SecondProperty is {0}", myruntimeObject.SecondProperty.GetType().Name);
Console.WriteLine("Type of ThirdProperty is {0}",        myruntimeObject.ThirdProperty.GetType().Name);

Console.Read();

In the above example I have created one anonymous type using var. The var will give you a chance to get intellesense in your code. You can see the variable holds an object of an anonymous type generated runtime. The power of var in code can also be tested. Just hover over the var keyword and you will see that the type is defined as anonymous.


https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi5yRgZkchYPQKIrmZjZ7WM2WO-firKVIbOrsbH47HsUEqsY9otsXAAwqt1o2AibrZT25DGgtSAdx2EVVAPwR9b5HSJqAQUcWVnvdCcXgjyrylrbadOOYz7iclnp4MwOf78P5IplWhXQGo/s640/1.JPG
In the previous code after the declaration of anonymous object, I have tried to see what exactly the type of the object and the members look like that I have declared. Lets see the output below :
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEifwVRBfuU4rXaX8IbFJB3w3gNercTQ7xjqD7kHmbXlt7PQjwHqOaThluLje6eGqiwNZCZwlwj9Ql8Zg0VDNyiD2uLVSvMs1_xG8xOKcezhPBZlkGXAOxAsWzRNrZOFRUYCyiMNpOUzvlk/s1600/2.JPG

So the actual type created by CLR at runtime looks like <>f_AnnonymousType0`3. We will discuss about it later in this post, but the thing that you might wonder, is the compiler is smart enough to declare the type of the members exactly. The FirstProperty is declared as Int32, second as DateTime and third as String. The type is self evaluated in the code and declared accordingly.

Now if I change the value just a bit like :
var myruntimeObject = new
{
   FirstProperty = 10d,
   SecondProperty = new DateTime(),
   ThirdProperty = "string type"
};

The code says the FirstProperty is double. The 10d is evaluated as double value.

You are also free to declare anonymous type for its members.
var myruntimeObject = new { FirstProperty = 10, SecondProperty = new DateTime(), ThirdProperty = "string type", MoreProperty = new { N1 = "" } };

Here the MoreProperty declares another anonymous type implicitly. But there is restriction the usage of anonymous types. You cannot declare a method inside any object declaration, even there is no way to give accessibility specifier to its members. All the members inside an anonymous type are readonly properties, hence if you try to do :
myruntimeObject.FirstProperty = 20;

It will prompt you an error.

Another important thing about anonymous type is that the compiler is smart enough to use anonymous type gracefully. It does not create a new anonymous type if the next instruction is exactly tries to create the same class. Hence if you use :
var myruntimeObject = new { FirstProperty = 10, SecondProperty = new DateTime(), ThirdProperty = "string type", MoreProperty = new { N1 = "" } };

var myruntimeObject2 = new { FirstProperty = 30, SecondProperty = new DateTime(), ThirdProperty = "string type2", MoreProperty = new { N1 = "blah blah" } };

Both internally represent the same type.

The Internals

Now as you know the basics of anonymous Types, lets look deep into its internal structure. In terms of IL, both var and anonymous type is nothing. Var is actually represented as actual type while anonymous type is mapped to an actual type.

The object creation looks similar to
<>f__AnonymousType0<<N1>j__TPar> moreproperty = new <>f__AnonymousType0<<N1>j__TPar>("");

<>f__AnonymousType1<<FirstProperty>j__TPar, <SecondProperty>j__TPar, <ThirdProperty>j__TPar, <MoreProperty>j__TPar>
                myruntimeObject = new
                <>f__AnonymousType1<<FirstProperty>j__TPar, <SecondProperty>j__TPar, <ThirdProperty>j__TPar, <MoreProperty>j__TPar>(10, new DateTime(), "string type", moreproperty);

Hence it seems to be quite big name for the type and also includes a generic argument named <N1>j__TPar. This lets the object to refer the same type when argument differs. As Reflection API is not good enough to show the actual generic types, it shows a numeric representation for the same.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjW51iE36T0FRSSTVs4r6WMz22iyXO4f5KnxHplVQrVA2OUZurdMWjadKeHgNn2Bc9UzM8AGev_vejlhVk04WYlM4JkPQeF8ddoQpMmpXXFMAFlonKl1XAg31msbxg8-IlSDsOH8HSE2AQ/s1600/3.JPG


Now as you can see, the Compiler generated type for MoreProperty looks like one above. The first thing that you should notice is the DebuggerDisplayAttribute just above class. With this attribute, Visual Studio debugger shows only <anonymous type> rather than the whole type name.

The Type takes a Generic type argument <N1>j__TPar in its constructor and builds the class. You should notice the parameter is marked as Readonly, so it is not writable. Also the type overrides ToString, GetHashCode and Equals by using the generic EqualityComparer. This looks a nice implementation.

Conclusion

Finally, to conclude, I must say anonymous types is an interesting feature which is widely used and eventually changed the way of coding. It is very much useful while working with LINQ. We will discuss internals of LINQ in later part of the series. But there should be a provision to define methods inside an anonymous type, which I think will be added sooner than later.


------------------------------------------------------------------------------------------------------------------------------

LINQ means Language Integrated Query is one of the major step forward to .NET framework to support queries to work on objects. LINQ allows you to write custom query statements on .NET objects or more specifically any IEnumerables to filter or fetch data from it.



Simple Projection

To start with Internals, let me create a List of strings on a Type. You should already know, that you can easily replace .NET initializer to allow initialize array into any IEnumerable.
public static List<string> myList = new List<string>
{
"Abhishek",
"Amit",
"Abhijit",
"Kunal",
"Krishna",
"Dhananjay"
};

Yes it will compile, and by your previous knowledge, you think it is initialized the same way if you use an array. But it isnt.

C# compiler automatically replaces the code with proper List.Add statements to add each individual statements. If you see the same code in reflector, you will see a new backup list variable is added to eventually add each strings internally.
var simpleprojection = from i in Program.myList
                                   select i;

Now starting what we call the most basic LINQ query represents to project each individual elements in the list directly into another IEnumerable. Now how does the IL looks like :
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSwSOGvRsRoM1GR_MO9S5WTv4sn86nWQGQs1s-ZCbkiUkEqhEz8rNnUCVU3D1J3FXxFUCreB5c6YKl0oi-wZINGmwPIFGAewVZlMhLxo8VNCNoNXK8raL42-WU0PJ-LTW_G9me-CxvWhA/s1600/l1.JPG


Now here you wonder how both the sections as I have discussed looks like. Yes, the initializer introduces a Static constructor internally (created by compiler itself) which adds up each of the strings into the List.  On the other hand, simpleprojection gets an Enumerable from Enumerable.Select which takes an IEnumerable and a delegate.

Internally the Enumerable puts each element from an enumerator and process it using the delegate we pass. Just as our delegate actually returns i. So nothing will be changed. Now let me change the code slightly.
var simpleprojection = from i in Program.myList
                       select new { x = i.StartsWith("A"), y = i.Reverse() };

Hmm, the code looks similar, but here we have yield a new object. Now if you see the IL, it produces a concrete implementation of the class to hold X and Y and eventually creates object of each.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmCwaAbVkmnPaxDbvKatza_YRWnBISZ4t5ZX3GfkuhH2YkOwStraompZ9BXknxVvYSCmYlIFylM94KaMqsgvOrRAWWXuzAXTf1h1Enr-eKBzwmvw-y9pdxrEee3hGCAQ3wtf5mZlLENy0/s640/l2.JPG
Click to see the Image
Well, yes,  as you can see, the IEnumerable returns an object of Concrete Type. Know more about anonymous types from "Internals of Anonymous Type".

Now coming to our scenarios, the code is same as the other one, just replacing the select statement inside the delegate.

Lets add up a bit more with Let :
var simpleprojection = from i in Program.myList
                        let isStartWithA = i.StartsWith("A")
                        let reverseString = i.Reverse()
                        select new { x = isStartWithA , y = reverseString };

Well, the code works the same with two let statements which assigns the value of each on separate variable isStartWithA and reverseString. But internally everything is now changed.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgaup8DF4yKssDVs34GqPFaOT3SlPy_NzgJTucaUGE11v6rOE2B_BWMPJRDjQmX9Gg54dohBDczgXdBsvxibab7RNGqqhdI-5vIy0WTe31zed4Bb_ayL6oNbmpA01MR8vvZyQdcZcQDtLM/s1600/l3.JPG

Hmm, the statement is now replaced with three Enumeration.Select calls nested one within another. Lets break these lines manually to understand what is happening.
var  firstEnumerable = Enumerable.Select(myList, delegate (string i) {
                                                    return new { i = i, isStartWithA = i.StartsWith("A") };
          });
          //Replacing <>f__AnonymousType0<string, bool> fType<string, bool>
          var secondEnumerable = Enumerable.Select(
                                            firstEnumerable,
                                            delegate (fType<string, bool> obj) {
                                                return new { Fobj = obj,
                                                                reverseString = obj.i.Reverse<char>() };
                                            });

        //Replacing <>f__AnonymousType1<<>f__AnonymousType0<string, bool> to fType2<fType<string,bool>, IEnumerable<char>>
         var simpleprojection = Enumerable.Select(
                                   secondEnumerable,
                                    delegate (fType2<fType<string,bool>, IEnumerable<char>> obj) {
                                    return new { x = obj.Fobj.isStartWithA,
                                                y = obj.reverseString };
                                });

I have intentionally replaced few compiler generated typenames to some other to make you understand code better.

In the first call we pass the list to a delegate which creates a object with variable isStartWith which is the boolean representation of our first let statement.

In the second call, we pass the result of first call. The second delegate generates the reverseString wrapping around the first call object.

Finally, in the outermost call, it will generate the end product.

Now why should you need three nested calls ? Yes there is a reason. Actually when you define the first let statement, you would internally think that from the next statement we should make the variable x available. So the scope of the First let, isStartWith lies on both of the next two lines reverseString and select. Hence we pass on the value in a anonymous type. Thus we can easily use isStartWith on both of these lines.

Similarly on the next successive calls we need to wrap around all the let statements internally into its respective anonymous types until finally we reach out the select. The compiler is smart enough to go on create anonymous types with first property being the parent object and second being the actual let statement.

Hence you can infer, for every let statement in LINQ query, compiler will generate 1 anonymous type at least.

Now lets alter our query to introduce Order By.
var simpleprojection = from i in Program.myList
                        orderby i
                        select i;

If we look into the Reflector for the code we see the code writes the same thing as the first code, the only difference is it is using Enumerable.OrderBy instead of Select and returns back IOrderedEnumerable. The OrderBy actually processes each element using the delegate that we pass, and puts it into a call to OrderedEnumerable, which internally uses EnumerableSorter to get each object from the List.

If you ask me does it internally stores the elements in sorted order after it is being processed, then I think you need to read more about IEnumerable may be from C# iterators. Actually when you enumerate from IOrderedEnumerable, it will internally get the next element from the list which represents the ordering. As IEnumerable internally maintains a state machine, it will save its state until further yield.

Next, lets put a GroupBy.
var simpleGroup = from i in Program.myList
                        group i by i.Count() into g
                        select new { Count = g.Count(), Elements = g };

Well, here we grouped the list based on character count. You should note each Group statement gives you an object (g) which represents the group and you can use g in your select statement.

Now lets see it into reflector:
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgarOa0YKHS_4LEOUOTyUells6MxesE4ipyPkDSeM3GkmSfXnR5gToBIo2Pgb98hIU3Mhk2hkI-MvYHxHdS_GJjBzs9u8v1AMkmur-dxtgmYLy4yCHcaTEtg1GR2Eh-xa8Ep4OcyBiesW8/s1600/l4.JPG

So you can see here in to code, the C# compiler wraps around a Enumerable.GroupBy inside the Enumerable.Select where the former returns an IEnumerable of IGrouping members. The select statement then uses this IGrouping object to generate its result.

Similar to OrderBy the GroupBy uses GroupedEnumerable object to generate each Group object on each yield. You should note, the object g is internally managed IGrouping object, hence groups does not generate additional Types.

Finally lets see how Join statement looks like. For simplicity I used inner join statement.
var customers = new List<Customer>{ new Customer { Id = 1, Name="Abhishek"},
                                new Customer { Id = 2, Name = "Amit"},
                                new Customer { Id = 3, Name = "Abhijit"},
                                new Customer { Id= 4, Name="Kunal"},
                                new Customer { Id = 5, Name= "Krishna"},
                                new Customer { Id = 6, Name = "Dhananjay"}
};

var orders = new List<Orders>
{
    new Orders { Id = 1, CustomerId = 4, NosOrder=20},
    new Orders { Id = 2, CustomerId = 1, NosOrder=30},
    new Orders { Id = 3, CustomerId = 2, NosOrder=50},
    new Orders { Id = 4, CustomerId = 1, NosOrder=10},
    new Orders { Id = 5, CustomerId = 3, NosOrder=60},
    new Orders { Id = 6, CustomerId = 4, NosOrder=10},
};

var simpleJoin = from c in customers
                join o in orders on c.Id equals o.CustomerId
                select new { c.Name, o.NosOrder };

Well, here I have put one of the most simplest customer and order Join which puts only the equal elements on the result. If you see this on reflector
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJC7myOES3VhAb8FfYQP8Wju_zrCpIhlmM_FKFjvTpwyYDS5OgqqAOSLzYWZmXm1RkO6e7zpJl5qh1qqLA0AmWwFe_6-taVHbfRcoBn3DVZilsxkWo8xyfmhZP7JHHOA89I0P32DkSDZE/s1600/l5.JPG


Hmm, it eventually calls upon the Enumerable.Join statement with delegates which filters the first argument, the  second argument and the result. In case of Joins, for each yield, the first and second delegate is fetched once, and 3rd delegate is called upon for each successful match in the lists. The framework uses JoinIterator internally to iterate between two lists.

For OuterJoins :
var simpleJoin = from c in customers
                join o in orders on c.Id equals o.CustomerId into outer
                from l in outer.DefaultIfEmpty()
                select new { c.Name, l.NosOrder };

It introduces Enumerable.GroupJoin nested inside Enumerable.SelectMany.

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqqwliT9xqJ2lbWR5cA-iYrfUB3v9h4Q7FMd33yvEoi8XQ_lydAEE7SZ-JdvQSBCr-qRJmxWC8POGJyyawixXzmRYsYpJ47JWCQhyNI8YDTOcj1-NRYnZ-YPd-uqebsaXoMJ6yKQLQXgg/s1600/l6.JPG

The GroupJoin uses GroupJoinIterator to group each individual first delegate with second delegate and each group is selected.



by abhishek sur

gridview stuff

   <div>
    <asp:GridView ID="GridView1" runat="server"
              AutoGenerateColumns="False"
              CellPadding="2" ForeColor="#333333"
              DataKeyNames="EMPID"
           OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server"
              AutoPostBack="true"
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
                                       
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server"
              AutoPostBack="true"
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="EMPID" HeaderText="ID"
                SortExpression="ID"/>
<asp:TemplateField HeaderText="EMPName" SortExpression="EMPName">
<ItemTemplate>
<asp:TextBox ID="txtEName" runat="server"
             Text='<%# Bind("EMPNAME") %>' ForeColor="Blue"
             BorderStyle="none" BorderWidth="0px"
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server"
             Text='<%# Bind("ADDRESS") %>'
             ForeColor="Blue" BorderStyle="none"
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SALARY" SortExpression
="SALARY">
<ItemTemplate>
<asp:TextBox ID="txtSAL" runat="server"
             Text='<%# Bind("SALARY") %>'
             ForeColor="Blue" BorderStyle="none"
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
-----------------------
.cs file
-------------------------
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DEMO"].ConnectionString;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Show();

        }

    }
    private void Show()
    {
        SqlConnection con = new SqlConnection(GetConnectionString());
        con.Open();
        DataTable dt = new DataTable();

        SqlCommand command = new SqlCommand("SELECT * from [EMPLOYEE]", con);
        SqlDataAdapter ada = new SqlDataAdapter(command);
        ada.Fill(dt);
       GridView1. DataSource = dt;
       GridView1.DataBind();
        con.Close();

    }
    protected void chkSelectAll_CheckedChanged(object sender, EventArgs e)
    {


        CheckBox chkAll =

           (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");

        if (chkAll.Checked == true)
        {

            foreach (GridViewRow gvRow in GridView1.Rows)
            {

                CheckBox chkSel =

                     (CheckBox)gvRow.FindControl("chkSelect");

                chkSel.Checked = true;

                TextBox txtEName = (TextBox)gvRow.FindControl("txtEName");

                TextBox txtAdd = (TextBox)gvRow.FindControl("txtAdd");
                TextBox txtSal = (TextBox)gvRow.FindControl("txtSal");


                //txtEName.ReadOnly = false;

                //txtAdd.ReadOnly = false;
                ////txtSal.ReadOnly = false;

                //txtEName.ForeColor = System.Drawing.Color.Black;

                //txtAdd.ForeColor = System.Drawing.Color.Black;
                //txtSal.ForeColor = System.Drawing.Color.Black;

            }

        }

        else
        {

            foreach (GridViewRow gvRow in GridView1.Rows)
            {

                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");

                chkSel.Checked = false;

                TextBox txtEName = (TextBox)gvRow.FindControl("txtEName");

                TextBox txtAdd = (TextBox)gvRow.FindControl("txtAdd");
                TextBox txtSal = (TextBox)gvRow.FindControl("txtSal");

                //txtEName.ReadOnly = true;

                //txtAdd.ReadOnly = true;
                //txtSal.ReadOnly = true;

                //txtEName.ForeColor = System.Drawing.Color.Blue;

                //txtAdd.ForeColor = System.Drawing.Color.Blue;
                //txtSal.ForeColor = System.Drawing.Color.Blue;
                //Show();
            }

        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox status = ((CheckBox)(row.Cells[0].Controls[1]));

            if (status.Checked == true)
            {

                row.BackColor = System.Drawing.Color.Red;

            }
            else if (status.Checked == false)
            {
                row.BackColor = System.Drawing.Color.White;
            }

        }


    }
    //protected void rowedit(object sender, EventArgs e)
    //{
       
    //}
   

    protected void chkSelect_CheckedChanged(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox status = ((CheckBox)(row.Cells[0].Controls[1]));

            if (status.Checked == true)
            {

                row.BackColor = System.Drawing.Color.Red;

            }
            else if (status.Checked == false)
            {
                row.BackColor = System.Drawing.Color.White;
            }

        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      // Checking if row type
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        // find the textbox control
       TextBox txtSAL = e.Row.FindControl("txtSAL") as TextBox;
        // read the value from the datasoure
        Double Salary= Convert.ToDouble(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Salary")));
  
        if (Salary > 15000.00)
        {
          // get the cell where that textbox contains
             DataControlFieldCell d = txtSAL.Parent as DataControlFieldCell;
  
          // to change the backcolor
          d.BackColor = System.Drawing.Color.Green;
  
          // to change the row color by setting
           
          //e.Row.BackColor = System.Drawing.Color.Blue;
  
          // to change the text color like this
         
            txtSAL.ForeColor = System.Drawing.Color.Chocolate;
         }
      }
     }

}





Wednesday, November 23, 2011

how to increase web application performance.....

1) Set debug=false under compilation as follows:
<compilation default Language="c#" debug="false">
2) Use Server.Transfer instead of Response.Redirect.
3) Always check Page.IsValid when using Validator Controls
4) Use Foreach loop instead of For loop for String Iteration.
5) Use Client-Side Validation. (but not all the time you have to validate even on the server side)
6) Check “Page.IsPostBack”. To avoid repetition code execution.
7) GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)
8) Use the AppOffline.htm when updating binaries
9) Turn off Tracing unless until required. (by default it's off, use on the pages where it's required)
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file. 11) Turn off Session State, if not required.
<sessionstate timeout="20" cookieless="false" mode="Off" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no">
12) Select the Release mode before making the final Build for your application.
This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug
13) Disable ViewState when not required.
EnableViewState="false"
14) Avoid frequent round trips to the Database.
15) Use Caching to improve the performance of your application.
16) Validate all Input received from the Users.
17) Use Finally Method to kill resources. (But not in the case of using)
18) The String and Stringbuilder Magic.
It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location
19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.
20) Avoid Exceptions: Use If condition (if it is check proper condition)
21) Code optimization:  Avoid using code like x = x +1; it is always better to use x+=1.
22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned
23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.
24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.
25) Enabling buffering will improve the performance, like
<% response.buffer=true %>
Then use:
<% response.flush=true %> 
26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.
27) Data listing is more time consume when large data are retrieve from database.
Paging will display only particular data but take load of all data.
Fetch only data that is needed for current page.
28) Avoid Inline JavaScript and CSS
29) Use single css file instead of multiple css file.
Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.
.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.
Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.
30) Reduce cookie size
31) Compress CSS, JavaScript and Images
Online compressors are available; to compress file please refers following web and Replace your file content with optimize code.
http://iceyboard.no-ip.org/projects/css_compressor for CSS compression
www.xtreeme.com/javascript-optimizer/ . For JS Compression
32 .Use Cache appropriately
i. Page output caching:
<%@ OutputCache Duration="3600" VaryByParam="none" %>
ii. Page fragment caching:
Write a Page output caching code into each User Control
iii. Data caching:
<script language="C#" runat="server">
Protected void Page_Load (Object src, EventArgs e) {
DataView dv = (DataView) Cache. Get ("EmployeesDataView");
If (dv == null) { // wasn't thereSqlConnection conn =
new SqlConnection ("server=localhost;uid=sa;pwd=;database=Test");
SqlDataAdapter da =new SqlDataAdapter ("select * from Employees", conn);
Dataset ds = new DataSet();da.Fill(ds, "Employees");
dv = ds.Tables["Employees"].DefaultView;
Cache.Insert ("EmployeesDataView", dv);conn.Close();}
Else
Response.Write ("<h2>Loaded employees from data cache! </h2>");
lb1.DataSource = dv;
lb1.DataTextField = "Name";
lb1.DataValueField = "Age";
DataBind () ;}
</script>
33) Use server side compression software such as Port80s http://www.port80software.com/products/httpzip/ 
34) Usage of "using" and I don't know why it's not yet published.
35) Don't make the member variables public or proteted, try to keep private and use public/protected as properties.
36) Use strString=string.Empty instead of strString="" . [And perhaps instead of strString=null also (?)]
37) Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.
38) Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.
39) Retrieve data from database at once, if possible. Don't add up to database trip as far as possible. For this, combine the datafields from different tables and select them.
40) Use short ID name for WebControl.

MS SQL SERVER Stuff

TBL_Demo1

id  name       salary
1   Avik       23000
2   jitesh     32000
3   Neeru      25000
4   anurag     50000
5   paras      21010
6   avik       23000
7   Neeru      25000



Q.1 write a query for following output

id  name       repetedno
1   Avik       2
4   anurag     1
2   jitesh     1
3   Neeru      2
5   paras      1


Query :
SELECT id,name,count(name) as repetedno from TBL_Demo1 group by name

2.


Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego


SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';

Result:
'EastBoston'.



Sunday, November 20, 2011

javaScript Stuff

  
Step 1.
 <script type="text/javascript">
  function SwitchMenu(obj){
    if(document.getElementById)
{
    var el = document.getElementById(obj);
    var ar = document.getElementById("masterdiv").getElementsByTagName("span");
        if(el.style.display != "block"){
            for (var i=0; i<ar.length; i++){
                if (ar[i].className=="submenu")
                ar[i].style.display = "none";
            }
            el.style.display = "block";
        }else{
            el.style.display = "none";
        }
    }
}
</script>

------------------------------------
Step2.
   <div class="Demo" onclick="SwitchMenu('sub1')">
                              <img src="tidf.gif" width="12" height="19" border="1" />
                              </div>

--------------------------------
Step3.
<div id="masterdiv">
    <span class="submenu" id="sub1">

                          <table width="775" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                  

                                </tr>
                              </table>
                              </span>
                          </div>

Monday, November 14, 2011

SMTP mail via ASP.net

  private bool SendMail(string mailto, string username, string pasword)
    {
        bool chkstatus = false;
        try
        {
            string verifyurl;
            verifyurl = "http://www.demo.com/demos1/SignIn.aspx";
            string boardurl = "http://Shera.com";

            MailMessage mailmsg = new MailMessage();
            mailmsg.From =  new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["FromAdminAddress"].ToString());
            mailmsg.To.Add(mailto);

            mailmsg.Subject = "Account activation mail: " + ' ' + " " + '"' + "Demo....." + '"' + "";

            string msgBody = "Hi,<BR><BR>";
            msgBody += "Welcome to my Demo..... <BR><BR>";
            msgBody += "Please keep this e-mail for your records. Your account information is as follows:<BR><BR>";
            msgBody += "--------------------------------------------------------";
            msgBody += "<table  border='0'>      " +
                          "  <tr>                           " +
                          "  <td>                           " +
                          "      Username:</td>             " +
                          "  <td align='left'>      " +
                          "     " + username + "                " +
                          "  </td>                          " +
                          " </tr>                           " +
                          "<tr>                             " +
                          " <td>                            " +
                          "      Board URL:</td>         " +
                          "   <td  align='left'>     " +
                          "  <A HREF=" + pasword + " >" + pasword + "</A>  " +
                          "        </td>                    " +
                          " </tr>                           " +
                          "<tr>                             " +
                          " <td>                            " +
                          "      Board URL:</td>         " +
                          "   <td  align='left'>     " +
                          "  <A HREF=" + boardurl + " >" + boardurl + "</A>  " +
                          "        </td>                    " +
                          " </tr>                           " +
                          "</table>                         ";
            msgBody += "--------------------------------------------------------<BR>";
            msgBody += "Please visit the following link in order to activate your account:<BR><BR>";
            msgBody += "<p><a href=" + verifyurl + " >" + verifyurl + "</a></p>";
            msgBody += "<BR>Thank you for registering.";
            msgBody += "<BR><BR>The Demo..... Team";
            msgBody += "<BR>-------------------------------";
            mailmsg.Body = msgBody;
            mailmsg.IsBodyHtml = true;


            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = ConfigurationManager.AppSettings["SmtpHost"].ToString();
            smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"].ToString());
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserName"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
            smtpClient.EnableSsl = false;

            smtpClient.Send(mailmsg);

            mailmsg.Dispose();
            chkstatus = true;

        }

        catch (Exception ex)
        {
           
            chkstatus = false;
        }

        return chkstatus;
    }

---------------------------
web.config
<add key="FromAdminAddress" value="shera@vedangsoftware.com"/>
    <add key="SmtpHost" value="60.5.523.212"/>
    <add key="SmtpPort" value="15"/>
    <add key="UserName" value="Shera@demos.com"/>
    <add key="Password" value="123456"/>