Friday, April 15, 2011

State Mangement in ASP.net

very useful link for State Mangement on MSDN

http://msdn.microsoft.com/en-us/library/75x4ha6s(v=VS.100).aspx

Anonymous Types and Anonymous Method in C#.

Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.
var v = new { Amount = 108, Message = "Hello" };
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
The most common scenario is to initialize an anonymous type with some properties from another type. In the following example, assume a class that is named Product that includes Color and Price properties together with several other properties that you are not interested in. Products is a collection of Product objects. The anonymous type declaration starts with the new keyword. It initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.

If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name to a property that is being initialized with an expression.
var productQuery =
from prod in products
select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}


Anonymous Method

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.
By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
The scope of the parameters of an anonymous method is the anonymous-method-block.
Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection.
A reference to n is captured at the time the delegate is created.
An anonymous method cannot access the ref or out parameters of an outer scope.
No unsafe code can be accessed within the anonymous-method-block.
It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.
The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method.

Animated bar chart in Jquery

How can data retrive from Excel file using C#?

using System;
using System.Collections;
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.OleDb;
using System.IO;
public partial class export : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Always use single xls file in xlsfilepath  
       
        string ExcelPath = " D:\\xlfile";
        if (Directory.Exists(ExcelPath))
        {
            DirectoryInfo GetExeclFiles = new DirectoryInfo(ExcelPath);
            FileInfo[] Files = GetExeclFiles.GetFiles("*.xls");
            if (Files.Length > 0)
            {
                DataTable dtnewtable = new DataTable();
                DataTable dttable = new DataTable();
                string FilePath, excelConnectionString, sqlConnectionString;
                for (int k = 0; k < Files.Length; k++)
                {
                    FilePath = Files[k].FullName.ToString();
                    excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0;";
                    // Create Connection to Excel Workbook
                    using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
                    {
                        if (connection.State == ConnectionState.Open)
                            connection.Close();
                        if (connection.State == ConnectionState.Closed)
                            connection.Open();

                        //  here in query you should pass sheet name here relatedproducts is sheet name
                        OleDbCommand command = new OleDbCommand("Select * FROM [RelatedProducts$]", connection);
                        // Create DbDataReader to Data Worksheet
                        using (System.Data.Common.DbDataReader dr = command.ExecuteReader())
                        {
                            dttable.Load(dr);
                           
                            DataTable ProductsTable = new DataTable();
                            DataColumn Dtcolumn = new DataColumn("Product", typeof(string));
                            DataColumn Dtcolumn2 = new DataColumn("RelatedProduct", typeof(string));
                            ProductsTable.Columns.Add(Dtcolumn);
                            ProductsTable.Columns.Add(Dtcolumn2);
                 // code for one-to-many relation 
                            DataTable dt = dttable;
                            int colCount = dt.Columns.Count;
                            for (int r = 0; r < dt.Rows.Count; r++)
                            {
                                for (int i = 0; i < colCount; i++)
                                {
                                    for (int j = 0; j < colCount; j++)
                                    {
                                        if (string.IsNullOrEmpty(dt.Rows[r][i].ToString())) { i++; if (i >= colCount) break; }
                                        if (string.IsNullOrEmpty(dt.Rows[r][j].ToString())) { j++; if (j >= colCount) continue; }
                                        if (j != i)
                                        {
                                            if (string.IsNullOrEmpty(dt.Rows[r][i].ToString()) || string.IsNullOrEmpty(dt.Rows[r][j].ToString())) continue;
                                            ProductsTable.Rows.Add(dt.Rows[r][i].ToString(), dt.Rows[r][j].ToString());
                                        }
                                    }
                                }
                            }
                          

                            ////
                            connection.Close();
                            connection.Dispose();
                            GridView1.DataSource = ProductsTable;
                            GridView1.DataBind();
                         //
                        }//end of USING dataReader
                    }//end of USING sql connection
                }//end of for loop
              
            }//end of if(Files.Length > 0)
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ExportGridView();
    }
    private void ExportGridView()
    {
        string attachment = "attachment; filename=RelatedProducts.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        // Create a form to contain the grid
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);

        frm.RenderControl(htw);
        //GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

DWR like .NET Comet Ajax in ASP.NET

C# String Theory—String intern pool

The string intern pool is a table that contains a single reference to each unique literal string declared or created programmatically in your application. The Common Language Runtime (CLR) uses the intern pool to minimize string storage requirements. As a result, an instance of a literal string with a particular value only exists once in the system. For example, if you assign the same literal string to several different variables, at runtime, the CLR retrieves the unique reference to that literal string from the intern pool and assigns it to each variable.
The String.Intern (string) method searches the intern pool for a string equal to the specified value. If such a string exists, its reference in the intern pool is returned. Otherwise, a reference to the specified string is added to the intern pool and that reference is returned.
In the following example, the string, declared with a value of "Intern pool" is interned; because, it is a string literal. The string built is a new string object with the same value as declared but generated by the System.Text.StringBuilder class. The Intern method searches for a string with the same value as built. Since the string already exists in the intern pool, the method returns the same reference that is assigned to declared and assigns that reference to interned.
References declared and built compare unequal because they refer to different objects, while references declared and interned compare equal because they refer to the same string.

String declared = "Intern pool"; 
String built    = new StringBuilder().Append("Intern ")
   .Append("pool").ToString(); 
String interned = String.Intern(built); 
Console.WriteLine ((Object)built==(Object)declared);    // different references
Console.WriteLine ((Object)interned==(Object)declared); // same reference 

Performance considerations

When trying to reduce the total memory allocated by your application, remember that interning has two unfortunate side effects. Firstly, the memory allocated for interned String objects is unlikely to be released until the CLR terminates: the CLR's references to interned String objects may persist after your application or application domain terminates. Secondly, to intern a string, a string must first be created. Thus, despite the fact that the memory will eventually be garbage collected, the memory used by the String object will still be allocated.

For more Details:- http://en.csharp-online.net/CSharp_String_Theory%E2%80%94String_intern_pool