December 31, 2012

Count number of current users / sessions - Asp.Net

There are a few ways you can approach this. One is to track users using global.asax and an application variable.

Add Global.asax file to your website / web application.

------------
C# Code :
------------

        protected void Application_Start(object sender, EventArgs e)
        {
            Application["SessionCount"] = 0;
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            Application["SessionCount"] = Convert.ToInt32(Application["SessionCount"]) + 1;
            Application.UnLock();
        }

        protected void Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            Application["SessionCount"] = Convert.ToInt32(Application["SessionCount"]) - 1;
            Application.UnLock();
        }

----------------
VB.Net Code : 
----------------

        Protected Sub Application_Start(sender As Object, e As EventArgs)
     Application("SessionCount") = 0
        End Sub

        Protected Sub Session_Start(sender As Object, e As EventArgs)
    Application.Lock()
           Application("SessionCount") = Convert.ToInt32(Application("SessionCount")) + 1
    Application.UnLock()
       End Sub

       Protected Sub Session_End(sender As Object, e As EventArgs)
    Application.Lock()
    Application("SessionCount") = Convert.ToInt32(Application("SessionCount")) - 1
    Application.UnLock()
      End Sub


Then, in any page you can get current count of number of users:


<asp:Label ID="CounterLabel" runat="server" 
    Text='<% Response.Write("Current session count: " + Application["SessionCount"]) %>' />

November 8, 2012

Create a New Android Project

After you’ve created an AVD, the next step is to start a new Android project in Eclipse.
  • From Eclipse, select Select File -> New -> Other…

  • Click on Android Project and click Next.
  • Fill in the project details with the following values:
    1. Project name: HelloAndroid
    2. Application name: Hello, Android
    3. Package name: com.test.helloandroid (or your own private namespace)
  • Create Activity: HelloAndroid
  • Min SDK version : 8 (as per API level)
  • Click Finish.
  • Run the Application
    The Eclipse  plug-in makes it easy to run your applications:
    1. Select Run > Run.
    Or Right click on project from project explorer and go
    Run as ->Android Application
    Yeah, you will see a black screen at your AVD with Your application name and a “Hello …..” text.
    Enjoy android.



Getting Started With Android Development


This article shows you how to download and install Android SDK to get you started developing Android Application.

Now get started to accomplish these objectives. Follow these points.

1. Install Java (If it is not on your machine)

  • Select Platform and Language for your download and accept the license Agreement



  • Now save file and install the JDK.

2. Install Eclipse

  • Click on download icon.
  • After downloading, Unzip this file.
  • Now you open eclipse.exe file from your unzip folder directory. You will see this.
  • Set your workspace directory. Then click ok

3. Install ADT Plugin

  • Start Eclipse, then select Help > Software Updates or Help > Install New Software. In the dialog that appears, click the Available Software/Install New Software tab.

  • Back in the Available Software view, you should see the plugin. “Android Developer Tools”, and “Android Editors” should both be checked. The Android Editors feature is optional, but recommended. Then click on the button “Install
  • Click on the button Next
  • Accept the license agreements” and click Finish.
  • Eclipse will ask to restart, click on the button Yes.
  • After restart, update your Eclipse preferences to point to the SDK directory.

4. Download Android SDK

  • Download the Android SDK from the Android homepage under Android SDK download . The download contains a zip file which you can extract to any place in your file system, e.g. I placed it under “C:\android”.

5. Configuration

  • In Eclipse open the Preferences dialog via Windows -> Preferences. Select Android and maintain the installation path of the Android SDK. Click Apply, then OK.
  • Now, set your PATH environment variable by right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables. Add the full path to the tools/ directory to the path, in this case, it is: ;C:\android\android-sdk-windows\tools. Then click OK , OK , OK.

6. Create an AVD

  • You will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
  • To create an AVD, In Eclipse, choose Window > Android SDK and AVD Manager.
  • Select Virtual Devices in the left panel.
  • Click New.
  • The Create New AVD dialog appears.
  • Type the name of the AVD, such as “testAVD”.
  • Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.2) you want to run on the emulator.
  • Click Create AVD.  Your new AVD is created now!
Hope so you well understand, in next article I'll show you to create first application like Hello World  in Android application. Stay tuned.

October 19, 2012

Declare var Globally

On different forums, many peoples are asking about the same thing like:

string a; (This is valid no issue)
var a; (This is error why??)

So my answer to them are that the following restrictions apply to implicitly-typed variable declarations like var
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.
If you want to use var, then the compiler MUST know at compile time what the type will be. Let me give you an another example

string myString; (At compile time, compiler knows what type myString is)
var myString;  (At compile time, compiler does not know what the type myString is)

Let me fix it using explicit type as like this :

var myString = "default value";  (Valid, because the value on the right hand side of the '=' is a string)

September 24, 2012

Button onClick and onClientClick

This is a simple example to show the difference between OnClick and OnClientClick event of asp:Button.
HTML Code

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
        function ConfirmThis() {            
            if (confirm('Do you want to server-side click?')) {
                return true;
            }
            else {
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtResult" runat="server" />
        <asp:Button ID="btnClick" runat="server" Text="Click Here" OnClick="btnClick_Click" 
            OnClientClick="return ConfirmThis();" />
    </div>
    </form>
</body>
</html>

Code-Behind

protected void btnClick_Click(object sender, EventArgs e) 
        {
            txtResult.Text = "Server side clicked";
        }

Now run your project. just Click on the button “Click Here”. It will ask to “Do you want a server-side click?”. If you select YES then you will do a server trip and when you select NO you will not redirect to server. So here for validation purpose we are using onClientClick and for doing process on server side, we are using onClick.

September 20, 2012

ASP.NET Configuration

Using the features of the ASP.NET configuration system, you can configure all of the ASP.NET applications on an entire server, a single ASP.NET application, or individual pages or application subdirectories. You can configure features, such as authentication modes, page caching, compiler options, custom errors, debug and trace options, and much more.

The ASP.NET configuration system features an extensible infrastructure that enables you to define configuration settings at the time your ASP.NET applications are first deployed so that you can add or revise configuration settings at any time with minimal impact on operational Web applications and servers.

ASP.NET configuration data is stored in XML text files that are each named Web.config. Web.config files can appear in multiple directories in ASP.NET applications. These files allow you to easily edit configuration data before, during, or after applications are deployed on the server. You can create and edit ASP.NET configuration files by using standard text editors, the ASP.NET MMC snap-in, the Web Site Administration Tool, or the ASP.NET configuration API.

ASP.NET configuration files keep application configuration settings separate from application code. Keeping configuration data separate from code makes it easy for you to associate settings with applications, change settings as needed after deploying an application, and extend the configuration schema.

The ASP.NET configuration system provides the following benefits:
  • Configuration information is stored in XML-based text files. You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.
  • Multiple configuration files, all named Web.config, can appear in multiple directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. Configuration files in child directories can supply configuration information in addition to that inherited from parent directories, and the child directory configuration settings can override or modify settings defined in parent directories. The root configuration file named systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Machine.config provides ASP.NET configuration settings for the entire Web server.
  • At run time, ASP.NET uses the configuration information provided by the Web.config files in a hierarchical virtual directory structure to compute a collection of configuration settings for each unique URL resource. The resulting configuration settings are then cached for all subsequent requests to a resource. Note that inheritance is defined by the incoming request path (the URL), not the file system paths to the resources on disk (the physical paths).
  • ASP.NET detects changes to configuration files and automatically applies new configuration settings to Web resources affected by the changes. The server does not have to be rebooted for the changes to take effect. Hierarchical configuration settings are automatically recalculated and recached whenever a configuration file in the hierarchy is changed. The <processModel> section is an exception.
  • The ASP.NET configuration system is extensible. You can define new configuration parameters and write configuration section handlers to process them.
  • ASP.NET help protect configuration files from outside access by configuring Internet Information Services (IIS) to prevent direct browser access to configuration files. HTTP access error 403 (forbidden) is returned to any browser attempting to request a configuration file directly.

File Types

Here is a list of file extensions which are configured by default to be handled by ASP.NET 2.0.
  • asax used for application level logic (global.asax)
  • ascx used for creating a web user control.
  • ashx used to create a custom httphandler
  • asmx used to create web services
  • aspx used for web application pages
  • axd is used for a special webresource axd handler which allows the developer to package components and controls along with javascript, images etc.. in a single assembly. The extension is also used for trace output.
  • browser are the browser capabilities files stored in XML format. These files are used to define the capabilities of the browser.
  • config used to store the configuration of the web application. web.config and machine.config are the common examples
  • cs used as the code behind when the language chosen is C# (CSharp)
  • vb used as the code behind when the language chosen is Visual Basic.Net
  • master used as the extension for the master page.
  • resx used as an extension for the resource file of the page for internationalization and localization purpose.
  • sitemap is used as the configuration file for a sitemap
  • skin used as the skin file for themes
  • svc used to define a Windows Communication Foundation (WCF) based service

Export data to Excel Using DataTable

----------------
C# Code :
----------------

        public void ExportToExcel(DataTable dt)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();

            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.Write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
            Response.AddHeader("content-disposition", "attachment;filename=PolicyClaimDetail.xls");
            Response.ContentEncoding = Encoding.UTF8;
            Response.Charset = "";
            EnableViewState = false;

            //Set Fonts
            Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
            Response.Write("<BR><BR><BR>");

            //Sets the table border, cell spacing, border color, font of the text, background,
            //foreground, font height
            Response.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");

            // Check not to increase number of records more than 65k according to excel,03
            if (dt.Rows.Count.ToString() <= 65536)
            {
                // Get DataTable Column's Header
                foreach (DataColumn column in dt.Columns)
                {
                    //Write in new column
                    Response.Write("<Td>");

                    //Get column headers  and make it as bold in excel columns
                    Response.Write("<B>");
                    Response.Write(column);
                    Response.Write("</B>");
                    Response.Write("</Td>");
                }

                Response.Write("</TR>");

                // Get DataTable Column's Row
                foreach (DataRow row in dt.Rows)
                {
                    //Write in new row
                    Response.Write("<TR>");

                    for (int i = 0; i <= dt.Columns.Count - 1; i++)
                    {
                        Response.Write("<Td>");
                        Response.Write(row(i).ToString());
                        Response.Write("</Td>");
                    }

                    Response.Write("</TR>");
                }
            }

            Response.Write("</Table>");
            Response.Write("</font>");

            Response.Flush();
            Response.End();
        }

----------------------
VB.Net Code :

    Sub ExportToExcel(ByVal dt As DataTable)

        Response.Clear()
        Response.ClearContent()
        Response.ClearHeaders()

        Response.Buffer = True
        Response.ContentType = "application/vnd.ms-excel"
        Response.Write("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">")
        Response.AddHeader("content-disposition", "attachment;filename=PolicyClaimDetail.xls")
        Response.ContentEncoding = Encoding.UTF8
        Response.Charset = ""
        EnableViewState = False

        'Set Fonts
        Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>")
        Response.Write("<BR><BR><BR>")

        'Sets the table border, cell spacing, border color, font of the text, background,
        'foreground, font height
        Response.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>")

        ' Check not to increase number of records more than 65k according to excel,03
        If dt.Rows.Count.ToString() <= 65536 Then

            ' Get DataTable Column's Header
            For Each column As DataColumn In dt.Columns
                'Write in new column
                Response.Write("<Td>")

                'Get column headers  and make it as bold in excel columns
                Response.Write("<B>")
                Response.Write(column)
                Response.Write("</B>")
                Response.Write("</Td>")
            Next

            Response.Write("</TR>")

            ' Get DataTable Column's Row
            For Each row As DataRow In dt.Rows
                'Write in new row
                Response.Write("<TR>")

                For i As Integer = 0 To dt.Columns.Count - 1
                    Response.Write("<Td>")
                    Response.Write(row(i).ToString())
                    Response.Write("</Td>")
                Next

                Response.Write("</TR>")
            Next
        End If

        Response.Write("</Table>")
        Response.Write("</font>")

        Response.Flush()
        Response.End()
    End Sub

LINQ Features

There are two types of codes present but here we talk about declarative. First I describe both of them.

Imperative:

You describe how to accomplish the task by indicating each step in code.

Declarative:

You describe the final result needed, leaving the steps up to the query language.

LINQ is a declarative syntax which makes some computational tasks easier. We call this language the query language, because it is very useful for retrieving information from data bases by formulating queries, or questions, expressed in the language.

Let's explore query expressions. Query expressions are built with declarative clauses that specify the results you want, not how you want to achieve them. Let's check out this program that uses a query expression on an in-memory array of integers.

int[] array = { 1, 2, 3, 6, 7, 8 };

// Query expression.
var elements = from element in array
       orderby element descending
       where element > 2
       select element;

// Enumerate.
foreach (var element in elements)
{
    Console.Write(element);
    Console.Write(' ');
}

Now I discuss each phase of LINQ briefly here.

1) Conversion :

These extension methods perform a conversion from an IEnumerable collection into a certain collection: an array, Dictionary, List or Lookup data structure. We describe the methods, which are some of the most useful in the System.Linq namespace.

a) ToArray:

           int[] array1 = { 5, 4, 1, 2, 3 };
           var query = from element in array1
                 orderby element
                 select element;

           int[] array2 = query.ToArray();
           foreach (int value in array2)
          {
                 Console.WriteLine(value);
          }

         Output        
         1
         2
         3
         4
         5
b) ToDictionary:

          int[] values = new int[ ]  { 1, 3, 5, 7 };
          Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true);

          foreach (KeyValuePair<int, bool> pair in dictionary)
         {
                 Console.WriteLine(pair);
         }

         Output

         [1, True]
         [3, True]
         [5, True]
         [7, True]
c) ToList:

         string[] array = new string[ ] { "A", "B", "C", "D" };
         List<string> list = array.ToList();
         Console.WriteLine(list.Count);
         foreach (string value in list)
         {
               Console.WriteLine(value);
         }

         Output

        4
       A
       B
       C
       D
d) ToLookup:

          string[] array = { "cat", "dog", "horse" };
          var lookup = array.ToLookup(item => item.Length);
  
          foreach (string item in lookup[3])
         {
                Console.WriteLine("3 = " + item);
         }

         foreach (string item in lookup[5])
        {
              Console.WriteLine("5 = " + item);
        }

        foreach (var grouping in lookup)
       {
            Console.WriteLine("Grouping:");
    
           foreach (string item in grouping)
          {
                     Console.WriteLine(item);
          }
      }

       Output

         3 = cat
         3 = dog
         5 = horse
        Grouping:
        cat
        dog
        Grouping:
         horse

2) Mutation :

 These methods filter or mutate one or more collections by change the elements in your query in some way: by removing unneeded elements, by adding new elements, or by changing other aspects of the elements themselves.  
  • AsEnumerable
  • AsParallel
  • Cast
  • Concat
  • DefaultIfEmpty
  • Distinct
  • ElementAt
  • ElementAtOrDefault
  • Except
  • First
  • FirstOrDefault
  • GroupBy
  • GroupJoin
  • Intersect
  • Join
  • Last
  • LastOrDefault
  • OfType
  • OrderBy
  • OrderByDescending
  • Reverse
  • Select
  • SelectMany
  • Single
  • SingleOrDefault
  • Union
  • Where
  • Zip

3) Skip and Take :


These extension methods are particularly useful. They eliminate the need for you to compose custom code to check ranges. They are recommended in a variety of contexts in your programs.

a) Skip:

          int[] array = { 1, 3, 5, 7, 9, 11 };
          var items1 = array.Skip(2);
         foreach (var value in items1)
        {
              Console.WriteLine(value);
        }

       var items2 = array.Skip(4);
       foreach (var value in items2)
      {
            Console.WriteLine(value);
      }

       Output

        5      The first two numbers in the array are missing.
        7
        9
       11

        9      The first four numbers are skipped.
       11
b) SkipWhile:

         int[] array = { 1, 3, 5, 10, 20 };
        var result = array.SkipWhile(element => element < 10);
        foreach (int value in result)
       {
                Console.WriteLine(value);
       } 

       Output

      10
      20
c) Take:

           List<string> list = new List<string>();
  list.Add("cat");
                list.Add("dog");
  list.Add("programmer");

           var first = list.Take(2);
           foreach (string s in first)
          {
                    Console.WriteLine(s);
          }
          Console.WriteLine();

         var last = list.Reverse<string>().Take(2);
         foreach (string s in last)
        {
                Console.WriteLine(s);
        }
        Console.WriteLine();

        Output

         cat
        dog

        programmer
        dog
d) TakeWhile:

          int[] values = { 1, 3, 5, 8, 10 };
         
          var result = values.TakeWhile(item => item % 2 != 0);
          foreach (int value in result)
          {
                 Console.WriteLine(value);
         }

           Output
           1
           3
           5

4) Computation :

They are also called computational methods. These act upon a certain query and then return a number or other value. These can also simplify your code, by eliminating the requirement of computing values such as averages yourself.

a) Aggregate:

int[] array = { 1, 2, 3, 4, 5 };
int result = array.Aggregate((a, b) => b + a);
// 1 + 2 = 3
// 3 + 3 = 6
// 6 + 4 = 10
// 10 + 5 = 15
Console.WriteLine(result);

result = array.Aggregate((a, b) => b * a);
// 1 * 2 = 2 // 2 * 3 = 6 // 6 * 4 = 24 // 24 * 5 = 120
Console.WriteLine(result);

Output

15
120
b) All:

int[] array = { 10, 20, 30 };

// Are all elements >= 10? YES
bool a = array.All(element => element >= 10);

// Are all elements >= 20? NO
bool b = array.All(element => element >= 20);

// Are all elements < 40? YES
bool c = array.All(element => element < 40);

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);

Output

True
False
True
c) Any:

int[] array = { 1, 2, 3 };
// See if any elements are divisible by two.
bool b1 = array.Any(item => item % 2 == 0);
// See if any elements are greater than three.
bool b2 = array.Any(item => item > 3);
// See if any elements are 2.
bool b3 = array.Any(item => item == 2);
// Write results.
Console.WriteLine(b1);
Console.WriteLine(b2);
Console.WriteLine(b3);
Output

True
False
True
d) Average:

double[] array1 = { 1, 2, 3, 5, 0 };
double average1 = array1.Average();
Console.WriteLine(average1);
//
// Use Average to compute average string length.
//
string[] array2 = { "dog", "cat", "perls" };
double average2 = array2.Average(x => x.Length);
Console.WriteLine(average2);

Output

2.2
3.66666666666667
e) Count:

int[] array = { 1, 2, 3 };

// Don't use Count() like this! Use Length.
Console.WriteLine(array.Count());

List<int> list = new List<int>() { 1, 2, 3 };

// Don't use Count() like this! Use Count property.
Console.WriteLine(list.Count());

var result = from element in array
     orderby element descending
     select element;

// Good.
Console.WriteLine(result.Count());
Output
3
3
3
f) SequenceEqual:

string[] array1 = { "dot", "net", "perls" };
string[] array2 = { "a", "different", "array" };
string[] array3 = { "dot", "net", "perls" };
string[] array4 = { "DOT", "NET", "PERLS" };

bool a = array1.SequenceEqual(array2);
bool b = array1.SequenceEqual(array3);
bool c = array1.SequenceEqual(array4, StringComparer.OrdinalIgnoreCase);

Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Output

False
True
True
i) Sum:

int[] array1 = { 1, 3, 5, 7 };
List<int> list1 = new List<int>() { 1, 3, 5, 7 };

//
// Use Sum extension on their elements.
//
int sum1 = array1.Sum();
int sum2 = list1.Sum();

//
// Write results to screen.
//
Console.WriteLine(sum1);
Console.WriteLine(sum2);
Output
    (All element values were added together to get the result.)

16
16

5) Max and Min :

You can search a collection for its largest or smallest value. This is effective for many value types, such as strings and
numbers.

Max/Min

         int[] array1 = { 1, -1, -2, 0 };

        Console.WriteLine(array1.Max());
        Console.WriteLine(array1.Max(element => Math.Abs(element)));

       Console.WriteLine(array1.Min());
       Console.WriteLine(array1.Min(element => -element));

       Output

       1
       2
     -1
     -2

6) Enumerable :

The Enumerable type presents some static methods that can be useful in certain situations.

a) Empty:

         var empty = Enumerable.Empty<int>();
         Console.WriteLine(empty.Count());
         int[] array = empty.ToArray();
         Console.WriteLine(array.Length);
         Output

         0
         0
b) Repeat :

          var integers = Enumerable.Repeat(1, 10);
          foreach (int value in integers)
          Console.WriteLine(value);

         Output

          1
          1
          1
          1
          1

7) Query keywords :

Query expressions use a whole new set of keywords. These are contextual keywords. This means they only have meaning in query expressions. These query clauses are described in more detail.
  • ascending
  • descending
  • group
  • join
  • let
  • orderby
  • select new
They typically reduce performance. But LINQ methods and query expressions often improve the readability of C# programs. LINQ sometimes leads to new algorithmic approaches.

September 18, 2012

Asp.Net State Management

Asp.Net State Management can be done using various ways and in this post I'll discuss a comparative analysis of all the state management techniques. ASP.NET offers a number of places to store state, both on the client and server. However, sometimes it's difficult to decide where you should put things and how to make that decision.

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

HTTP is a stateless protocol. Once the server serves any request from the user, it cleans up all the resources used to serve that request. These resources include the objects created during that request, the memory allocated during that request, etc. If anyone whom comming from a background of Windows application development, this could come as a big surprise because there is no way he could rely on objects and member variables alone to keep track of the current state of the application.

You choices for state management include:

Application      - Stored on the server and shared for all users. Does not expire(Deprecated by Cache)
Cache              - Stored on the server and shared for all users. Can expire.
Session            - Stored on the server.  Unique for each user.  Can expire.
ViewState        - Stored in a hidden page input (by default).  Does not expire.
Cookies           - Stored at the client. Can expire.
QueryString    - Passed in the URL.  Must be maintained with each request.
Context.Items - Only lasts for one request's lifetime.  More.
Profile             - Stores the data in the database. Can be used to retain user data over multiple request and session.

If we have to track the users' information between page visits and even on multiple visits of the same page, then we need to use the State management techniques provided by ASP.NET. State management is the process by which ASP.NET let the developers maintain state and page information over multiple request for the same or different pages.

There are mainly two types of state management that ASP.NET provides:

1.Client side state management
2.Server side state management

Client side state management techniques :

• View State
• Control State
• Hidden fields
• Cookies
• Query Strings

Server side state management techniques :
• Application State
• Session State
• Profile Properties

The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.

View State :

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.

Control State :

The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property.

Hidden Fields :

ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.

Cookies :

A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary or persistent.

Query Strings :

Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL.

ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client. With server-based state management, you can decrease the amount of information sent to the client in order to preserve state, however it can use costly resources on the server.

Application State :

ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.

Session State :

Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session will have a different session state. In addition, if a user leaves your application and then returns later, the second user session will have a different session state from the first.

Profile Properties :

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user.

The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database. In addition, the profile makes the user information available using a strongly typed API that you can access from anywhere in your application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic storage system that allows you to define and maintain almost any kind of data while still making the data available in a type-safe manner.

September 14, 2012

IEnumerable & IQueryable

To query from database using LINQ, We use IEnumerable and IQueryable for manipulation of data. 

IENUMERABLE :

IEnumerable exposes the enumerator, which supports a simple iteration over a non-generic collection.

IQUERYABLE :

IQueryable provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

COMPARISION :

1. IEnumerable exists in System.Collections Namespace.
    IQueryable exists in System.Linq Namespace.

2. IEnumerable is a forward only collection, it can’t move backward and between the items.
    IQueryable is a forward only collection, it can’t move backward and between the items.

3. IEnumerable is best to query data from in-memory collections like List, Array etc.
    IQueryable is best to query data from out-memory (like remote database, service) collections.

4. While query data from database, IEnumerable execute select query on server side, load data in-memory
    on client side and then filter data.
    While query data from database, IQueryable execute select query on server side with all filters.

5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
    IQueryable is suitable for LINQ to SQL queries.

6. IEnumerable supports deferred execution.
    IQueryable supports deferred execution.  

7. IEnumerable doesn’t supports custom query.
    IQueryable supports custom query using CreateQuery and Execute methods.

8. IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
    IQueryable support lazy loading. Hence it is suitable for paging like scenarios.

9. Extension methods supports by IEnumerable takes functional objects.
    Extension methods supports by IQueryable takes expression objects means expression tree.

September 13, 2012

How to Win Friends and Influence People

How to Win Friends and Influence People is one of the first best-selling self-help books ever published. Written by Dale Carnegie and first published in 1936, it has sold 15 million copies world-wide. In 1981, a new revised edition with updated language and anecdotes was released. The revised edition reduced the number of sections from 6 to 4, eliminating sections on effective business letters and improving marital satisfaction.

For online reading this book visit here

Major Section & Points

I. Twelve Things This Book Will Do For You


  1. Get you out of a mental rut, give you new thoughts, new visions, new ambitions.
  2. Enable you to make friends quickly and easily.
  3. Increase your popularity.
  4. Help you to win people to your way of thinking.
  5. Increase your influence, your prestige, your ability to get things done.
  6. Enable you to win new clients, new customers.
  7. Increase your earning power.
  8. Make you a better salesman, a better executive.
  9. Help you to handle complaints, avoid arguments, keep your human contacts smooth and pleasant.
  10. Make you a better speaker, a more entertaining conversationalist.
  11. Make the principles of psychology easy for you to apply in your daily contacts.
  12. Help you to arouse enthusiasm among your associates.

II. Fundamental Techniques in Handling People

  1. Don't criticize, condemn, or complain.
  2. Give honest and sincere appreciation.
  3. Arouse in the other person an eager want.

III. Six Ways to Make People Like You

  1. Become genuinely interested in other people.
  2. Smile.
  3. Remember that a person's name is, to that person, the sweetest and most important sound in any language.
  4. Be a good listener. Encourage others to talk about themselves.
  5. Talk in terms of the other person's interest.
  6. Make the other person feel important – and do it sincerely.

IV. Twelve Ways to Win People to Your Way of Thinking

  1. The only way to get the best of an argument is to avoid it.
  2. Show respect for the other person's opinions. Never say "You're Wrong."
  3. If you're wrong, admit it quickly and emphatically.
  4. Begin in a friendly way.
  5. Start with questions to which the other person will answer yes.
  6. Let the other person do a great deal of the talking.
  7. Let the other person feel the idea is his or hers.
  8. Try honestly to see things from the other person's point of view.
  9. Be sympathetic with the other person's ideas and desires.
  10. Appeal to the nobler motives.
  11. Dramatize your ideas.
  12. Throw down a challenge.

V. Be a Leader: How to Change People Without Giving Offense or Arousing Resentment

  1. Begin with praise and honest appreciation.
  2. Call attention to people's mistakes indirectly.
  3. Talk about your own mistakes before criticizing the other person.
  4. Ask questions instead of giving direct orders.
  5. Let the other person save face.
  6. Praise every improvement.
  7. Give the other person a fine reputation to live up to.
  8. Use encouragement. Make the fault seem easy to correct.
  9. Make the other person happy about doing what you suggest.

VI. Six Rules For Making Your Home Life Happier

  1. Don't nag.
  2. Don't try to make your partner over.
  3. Don't criticize.
  4. Give honest appreciation.
  5. Pay little attentions.
  6. Be courteous.

Nine Suggestions on How to Get the Most Out of This Book

1. If you wish to get the most out of this book, there is one indispensable requirement, one essential infinitely more important than any rule or technique. Unless you have this one fundamental requisite, a thousand rules on how to study will avail little, And if you do have this cardinal endowment, then you can achieve wonders
without reading any suggestions for getting the most out of a book. What is this magic requirement? Just this: a deep, driving desire to learn, a vigorous determination to increase your ability to deal with people.

How can you develop such an urge? By constantly reminding yourself how important these principles are to you. Picture to yourself how their mastery will aid you in leading a richer, fuller, happier and more fulfilling life. Say to yourself over and over: "My popularity, my happiness and sense of worth depend to no small extent upon my skill in dealing with people."

2. Read each chapter rapidly at first to get a bird's-eye view of it. You will probably be tempted then to rush on to the next one. But don't - unless you are reading merely for entertainment. But if you are reading because you want to increase your skill in human relations, then go back and reread each chapter thoroughly. In the long run, this will mean saving time and getting results.

3. Stop frequently in your reading to think over what you are reading. Ask yourself just how and when you can apply each suggestion.

4. Read with a crayon, pencil, pen, magic marker or highlighter in your hand. When you come across a suggestion that you feel you can use, draw a line beside it. If it is a four-star suggestion, then underscore every sentence or highlight it, or mark it with "****." Marking and underscoring a book makes it more interesting, and far easier to review rapidly.

5. I knew a woman who had been office manager for a large insurance concern for fifteen years. Every month, she read all the insurance contracts her company had issued that month. Yes, she read many of the same contracts over month after month, year after year. Why? Because experience had taught her that that was the only way she could keep their provisions clearly in mind. I once spent almost two years writing a book on public speaking and yet I found I had to keep going back over it from time to time in order to remember what I had written in my own book.

The rapidity with which we forget is astonishing. So, if you want to get a real, lasting benefit out of this book, don't imagine that skimming through it once will suffice. After reading it thoroughly, you ought to spend a few hours reviewing it every month, Keep it on your desk in front of you every day. Glance through it often. Keep constantly impressing yourself with the rich possibilities for improvement that still lie in the offing. Remember that the use of these principles can be made habitual only by a constant and vigorous campaign of review and application. There is no other way.

6. Bernard Shaw once remarked: "If you teach a man anything, he will never learn." Shaw was right. Learning is an active process. We learn by doing. So, if you desire to master the principles you are studying in this book, do something about them. Apply these rules at every opportunity. If you don't you will forget them quickly.

Only knowledge that is used sticks in your mind. You will probably find it difficult to apply these suggestions all the time. I know because I wrote the book, and yet frequently I found it difficult to apply everything I advocated. For example, when you are displeased, it is much easier to criticize and condemn than it is to try to understand the other person's viewpoint. It is frequently easier to find fault than to find praise. It is more natural to talk about what vou want than to talk about what the other person wants. And so on, So, as you read this book, remember that you are not merely trying to acquire information. You are attempting to form new habits. Ah yes, you are attempting a new way of life. That will require time and persistence and daily application. So refer to these pages often.

Regard this as a working handbook on human relations; and whenever you are confronted with some specific problem - such as handling a child, winning your spouse to your way of thinking, or satisfying an irritated customer - hesitate about doing the natural thing, the impulsive thing. This is usually wrong. Instead, turn to these pages and review the paragraphs you have underscored. Then try these new ways and watch them achieve magic for you.

7. Offer your spouse, your child or some business associate a dime or a dollar every time he or she catches you violating a certain principle. Make a lively game out of mastering these rules.

8. The president of an important Wall Street bank once described, in a talk before one of my classes, a highly efficient system he used for self-improvement. This man had little formal schooling; yet he had become one of the most important financiers in America, and he confessed that he owed most of his success to the constant application of his homemade system. This is what he does, I'll put it in his own words as accurately as I can remember.

"For years I have kept an engagement book showing all the appointments I had during the day. My family never made any plans for me on Saturday night, for the family knew that I devoted a part of each Saturday evening to the illuminating process of self-examination and review and appraisal. After dinner I went off by myself, opened my engagement book, and thought over all the interviews, discussions and meetings that had taken place during the week. I asked myself:

'What mistakes did I make that time?'
'What did I do that was right-and in what way could I have improved my performance?'
'What lessons can I learn from that experience?'
"I often found that this weekly review made me very unhappy.

I was frequently astonished at my own blunders. Of course, as the years passed, these blunders became less frequent. Sometimes I was inclined to pat myself on the back a little after one of these sessions. This system of self-analysis, self-education, continued year after year, did more for me than any other one thing I have ever attempted.

"It helped me improve my ability to make decisions - and it aided me enormously in all my contacts with people. I cannot recommend it too highly."

Why not use a similar system to check up on your application of the principles discussed in this book? If you do, two things will result.

First, you will find yourself engaged in an educational process that is both intriguing and priceless.
Second, you will find that your ability to meet and deal with people will grow enormously.

9. You will find at the end of this book several blank pages on which you should record your triumphs in the application of these principles. Be specific. Give names, dates, results. Keeping such a record will inspire you to greater efforts; and how fascinating these entries will be when you chance upon them some evening years from now!

The 8 Habits of Highly Effected People

Stephen Covey defined the 8 habits of highly effected peoples that Your life doesn't just "happen." Whether you know it or not, it is carefully designed by you. The choices, after all, are yours. You choose happiness. You choose sadness. You choose decisiveness. You choose ambivalence. You choose success. You choose failure. You choose courage. You choose fear. Just remember that every moment, every situation, provides a new choice. And in doing so, it gives you a perfect opportunity to do things differently to produce more positive results.

HABIT 1 : (BE PROACTIVE)

Be Proactive is about taking responsibility for your life. You can't keep blaming everything on your parents or grandparents. Proactive people recognize that they are "response-able." They don't blame genetics, circumstances, conditions, or conditioning for their behavior. They know they choose their behavior.

Reactive people, on the other hand, are often affected by their physical environment. They find external sources to blame for their behavior. If the weather is good, they feel good. If it isn't, it affects their attitude and performance, and they blame the weather. All of these external forces act as stimuli that we respond to. Between the stimulus and the response is your greatest power--you have the freedom to choose your response. One of the most important things you choose is what you say. Your language is a good indicator of how you see yourself.

A proactive person uses proactive language--I can, I will, I prefer, etc. A reactive person uses reactive language--I can't, I have to, if only. Reactive people believe they are not responsible for what they say and do--they have no choice. Instead of reacting to or worrying about conditions over which they have little or no control, proactive people focus their time and energy on things they can control. The problems, challenges, and opportunities we face fall into two areas--Circle of Concern and Circle of Influence.

Proactive people focus their efforts on their Circle of Influence. They work on the things they can do something about: health, children, problems at work. Reactive people focus their efforts in the Circle of Concern--things over which they have little or no control: the national debt, terrorism, the weather. Gaining an awareness of the areas in which we expend our energies in is a giant step in becoming proactive.

HABIT 2 : (BEGIN WITH THE END IN MIND)

So, what do you want to be when you grow up? That question may appear a little trite, but think about it for a moment. Are you--right now--who you want to be, what you dreamed you'd be, doing what you always wanted to do? Be honest. Sometimes people find themselves achieving victories that are empty--successes that have come at the expense of things that were far more valuable to them. If your ladder is not leaning against the right wall, every step you take gets you to the wrong place faster.

It is based on imagination--the ability to envision in your mind what you cannot at present see with your eyes. It is based on the principle that all things are created twice. There is a mental (first) creation, and a physical (second) creation. The physical creation follows the mental, just as a building follows a blueprint. If you don't make a conscious effort to visualize who you are and what you want in life, then you empower other people and circumstances to shape you and your life by default. It's about connecting again with your own uniqueness and then defining the personal, moral, and ethical guidelines within which you can most happily express and fulfill yourself. Begin with the End in Mind means to begin each day, task, or project with a clear vision of your desired direction and destination, and then continue by flexing your proactive muscles to make things happen.

One of the best ways to incorporate Habit 2 into your life is to develop a Personal Mission Statement. It focuses on what you want to be and do. It is your plan for success. It reaffirms who you are, puts your goals in focus, and moves your ideas into the real world. Your mission statement makes you the leader of your own life. You create your own destiny and secure the future you envision.

HABIT 3 : (PUT FIRST THINGS FIRST)

To live a more balanced existence, you have to recognize that not doing everything that comes along is okay. There's no need to overextend yourself. All it takes is realizing that it's all right to say no when necessary and then focus on your highest priorities.

Habit 1 says, "You're in charge. You're the creator." Being proactive is about choice. Habit 2 is the first, or mental, creation. Beginning with the End in Mind is about vision. Habit 3 is the second creation, the physical creation. This habit is where Habits 1 and 2 come together. It happens day in and day out, moment-by-moment. It deals with many of the questions addressed in the field of time management. But that's not all it's about. Habit 3 is about life management as well--your purpose, values, roles, and priorities. What are "first things?" First things are those things you, personally, find of most worth. If you put first things first, you are organizing and managing time and events according to the personal priorities you established in Habit 2.

HABIT 4 : (THINK WIN-WIN)

Think Win-Win isn't about being nice, nor is it a quick-fix technique. It is a character-based code for human interaction and collaboration.

Most of us learn to base our self-worth on comparisons and competition. We think about succeeding in terms of someone else failing--that is, if I win, you lose; or if you win, I lose. Life becomes a zero-sum game. There is only so much pie to go around, and if you get a big piece, there is less for me; it's not fair, and I'm going to make sure you don't get anymore. We all play the game, but how much fun is it really?

Win-win sees life as a cooperative arena, not a competitive one. Win-win is a frame of mind and heart that constantly seeks mutual benefit in all human interactions. Win-win means agreements or solutions are mutually beneficial and satisfying. We both get to eat the pie, and it tastes pretty darn good!

A person or organization that approaches conflicts with a win-win attitude possesses three vital character traits:
  1. Integrity: sticking with your true feelings, values, and commitments
  2. Maturity: expressing your ideas and feelings with courage and consideration for the ideas and feelings of others
  3. Abundance Mentality: believing there is plenty for everyone
Many people think in terms of either/or: either you're nice or you're tough. Win-win requires that you be both. It is a balancing act between courage and consideration. To go for win-win, you not only have to be empathic, but you also have to be confident. You not only have to be considerate and sensitive, you also have to be brave. To do that--to achieve that balance between courage and consideration--is the essence of real maturity and is fundamental to win-win.

HABIT 5 : (SEEK FIRST TO UNDERSTAND, THEN TO BE UNDERSTOOD)

Communication is the most important skill in life. You spend years learning how to read and write, and years learning how to speak. But what about listening? What training have you had that enables you to listen so you really, deeply understand another human being? Probably none, right?

If you're like most people, you probably seek first to be understood; you want to get your point across. And in doing so, you may ignore the other person completely, pretend that you're listening, selectively hear only certain parts of the conversation or attentively focus on only the words being said, but miss the meaning entirely. So why does this happen? Because most people listen with the intent to reply, not to understand. You listen to yourself as you prepare in your mind what you are going to say, the questions you are going to ask, etc. You filter everything you hear through your life experiences, your frame of reference. You check what you hear against your autobiography and see how it measures up. And consequently, you decide prematurely what the other person means before he/she finishes communicating. Do any of the following sound familiar?

"Oh, I know just how you feel. I felt the same way." "I had that same thing happen to me." "Let me tell you what I did in a similar situation."

Because you so often listen autobiographically, you tend to respond in one of four ways:

Evaluating:You judge and then either agree or disagree.
Probing:You ask questions from your own frame of reference.
Advising:You give counsel, advice, and solutions to problems.
Interpreting:You analyze others' motives and behaviors based on your own experiences.

You might be saying, "Hey, now wait a minute. I'm just trying to relate to the person by drawing on my own experiences. Is that so bad?" In some situations, autobiographical responses may be appropriate, such as when another person specifically asks for help from your point of view or when there is already a very high level of trust in the relationship.

HABIT 6 : (SYNERGIZE)

To put it simply, synergy means "two heads are better than one." Synergize is the habit of creative cooperation. It is teamwork, open-mindedness, and the adventure of finding new solutions to old problems. But it doesn't just happen on its own. It's a process, and through that process, people bring all their personal experience and expertise to the table. Together, they can produce far better results that they could individually. Synergy lets us discover jointly things we are much less likely to discover by ourselves. It is the idea that the whole is greater than the sum of the parts. One plus one equals three, or six, or sixty--you name it.

When people begin to interact together genuinely, and they're open to each other's influence, they begin to gain new insight. The capability of inventing new approaches is increased exponentially because of differences.

Valuing differences is what really drives synergy. Do you truly value the mental, emotional, and psychological differences among people? Or do you wish everyone would just agree with you so you could all get along? Many people mistake uniformity for unity; sameness for oneness. One word--boring! Differences should be seen as strengths, not weaknesses. They add zest to life.

HABIT 7 : (SHARPEN THE SAW)

Sharpen the Saw means preserving and enhancing the greatest asset you have--you. It means having a balanced program for self-renewal in the four areas of your life: physical, social/emotional, mental, and spiritual. Here are some examples of activities:

Physical:                  Beneficial eating, exercising, and resting
Social/Emotional:    Making social and meaningful connections with others
Mental:                   Learning, reading, writing, and teaching
Spiritual:                 Spending time in nature, expanding spiritual self through meditation, music, art,
                                prayer or service

As you renew yourself in each of the four areas, you create growth and change in your life. Sharpen the Saw keeps you fresh so you can continue to practice the other six habits. You increase your capacity to produce and handle the challenges around you. Without this renewal, the body becomes weak, the mind mechanical, the emotions raw, the spirit insensitive, and the person selfish. Not a pretty picture, is it?

Feeling good doesn't just happen. Living a life in balance means taking the necessary time to renew yourself. It's all up to you. You can renew yourself through relaxation. Or you can totally burn yourself out by overdoing everything. You can pamper yourself mentally and spiritually. Or you can go through life oblivious to your well-being. You can experience vibrant energy. Or you can procrastinate and miss out on the benefits of good health and exercise. You can revitalize yourself and face a new day in peace and harmony. Or you can wake up in the morning full of apathy because your get-up-and-go has got-up-and-gone. Just remember that every day provides a new opportunity for renewal--a new opportunity to recharge yourself instead of hitting the wall. All it takes is the desire, knowledge, and skill.

HABIT 8 : (FROM EFFECTIVENESS TO GREATNESS)

In today's challenging and complex world, being highly effective is the price of entry to the playing field. To thrive, innovate, excel, and lead in this new reality, we must reach beyond effectiveness toward fulfillment, contribution, and greatness. Research is showing, however, that the majority of people are not thriving. They are neither fulfilled nor excited. Tapping into the higher reaches of human motivation requires a new mindset, a new skill-set --a new habit.