Monday, August 20, 2012

SQL to LINQ, LINQ to Lambda so (SQL to Lambda)

Converting SQL to LINQ then LINQ to Lambda
So we can also convert SQL to Lambda expressions.....

Everyone knows sql very well, it's easy to think your app logic in SQL queries. But in the c# codes, you want to query using linq or lambda  expressions, its very difficult to construct such queries sometimes. So follow the steps below, you will easily convert your SQL queries to linq/lambda expressions.

2 steps you need to follow,
1. Write you app logic query in SQL then convert it to LINQ through SQLtoLINQ tool.
2. Copy the result LINQ query from linker to LINQPad & execute, press 'lambda' symbol to show Lambda
Expression.

Happy Coding....

Monday, July 2, 2012

Tracking Online Users in your application...

There are many ways to count number of active visitors on your ASP.NET website.
They differ in technique and accuracy.

here is the simplest approach that delivers acceptable accuracy when configured optimally:

Step 1:
    - first we need to add these lines to our global.asax file 
      (if your website do not have it, create it by right-clicking on website in solution explorer, 
       and choosing Add New Item > Global Application Clasoption)

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["OnlineUsers"] = 0;
    }
 
    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
        Application.UnLock();
    }
 
    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
        Application.UnLock();
    }

This will allow us that whenever some distant web visitor opens our website in his browser, 
and new session is created for him, our  "OnlineUsers" variable in the global HttpApplicationState class instance
is increased.

Also when user closes his browser or does not click on any links in our website, session expires, 
and our "OnlineUsers" global variable is decreased.

To know more about ApplicationState and HttpApplicationState class visit this MSDN link:
msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx

NOTE:
 we are using Application.Lock and Application.Unlock methods to prevent multiple threads 
from changing this variable at the same time. 

By calling Application.Lock we are receiving exclusive right to change the values in Application state.
But we must not forget to call Application.Unlock() afterwards.

Step 2:
    In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):

        <system.web>
        <sessionState mode="InProc" cookieless="false" timeout="20" />
        </system.web>

In-process mode stores session state values and variables in memory on the local Web server. 
It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once
in a 20 minutes, they are considered online. 
If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session 
is destroyed, so our online visitor counter is decreased by 1.
(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

Ok, so now we are done with configuration steps, let us see how to use this:

To show number of online visitors/users on your ASPX page you can use this code:
        Visitors online: <%Application["OnlineUsers"].ToString() %>
Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and
use Timer to refresh it in regular intervals without refreshing the whole page, but that is another story

Monday, June 25, 2012

State Management in ASP.Net


State Management in ASP.Net : 

As we know Web pages are based on the HTTP Protocol which is a stateless protocol, means that there is no information about the request, such as where they are coming from i.e. whether the request is from the same client or from a new client. Since the page is created each time, the page is requested then destroyed. So we can say that the state is not maintained between client requests by default.

ASP.NET developers use various available technologies for State Management. We can classify them as client side state management or server side state management.

                     statemgmt1.gif
CLIENT SIDE STATE MANAGEMENT:

View State:

ViewState is an approach to saving data for the user. Because of the stateless nature of web pages, regular page member variables will not maintain their values across postbacks. ViewState is the mechanism that allows state values to be preserved across page postbacks and by default, EnableViewState property will be set to true. In a nutsheell, ViewState:
  • Stores values per control by key name, like a Hashtable.
  • Tracks changes to a View State value's initial state.
  • Serializes and Deserializes saved data into a hidden form field on the client.
  • Automatically restores View State data on postbacks.

    statemgmt2.gif

Sample:
//To Save Information in View State 
ViewState.Add ("NickName", "Dolly");
//Retrieving View state
String strNickName = ViewState ["NickName"];

Here is a simple example of using the "ViewState" property to carry values between postbacks.
Code Example:

public int SomeInteger {
    get {
        object o = ViewState["SomeInteger"];
        if (o != nullreturn (int)o; 
        return 0;
        //a default    }
    set { ViewState["SomeInteger"] = value; }
}


Control State:

The purpose of the control state repository is to cache data necessary for a control to properly function. ControlState is essentially a private ViewState for your control only, and it is not affected when ViewState is turned off. ControlState is used to store small amounts of critical information. Heavy usage of ControlState can impact the performance of application because it involves serialization and deserialization for its functioning.

There are two methods you have to implement in your custom control.
  • Load Control State
  • Save Control State

    statemgmt3.gif
Code Example:
public class ControlStateWebControl : Control{    #region Members
    private string _strStateToSave;
    #endregion
    #region
 Methods
    protected override void OnInit(EventArgs e)
    {
        Page.RegisterRequiresControlState(this);
        base.OnInit(e);
    }
    protected override object SaveControlState()
    {
        return _strStateToSave;
    }
    protected override void LoadControlState(object state)
    {
        if (state != null)
        {
            _strStateToSave = state.ToString();
        }
    }
 
    #endregion}Hidden Fields:
A Hidden control is the control which does not render anything on the web page at client browser but can be used to store some information on the web page which can be used on the page. Hidden fields are used to store data at the page level. These fields are not rendered by the browser, rather it's just like a standard control for which you can set its properties. If you use hidden fields, it is best to store only small amounts of frequently changed data on the client.

statemgmt4.gif
Sample:
//Declaring a hidden variableprotected HtmlInputHidden hidNickName;
//Populating hidden variablehidNickName.Value = "Page No 1";
//Retrieving value stored in hidden field.string str = hidNickName.Value; 
Code Example:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)|
        Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}
protected void Button1_Click(object sender, EventArgs e)
{
    HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();
 
    Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}


Cookies: 
A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. Every time a user visits a website, cookies are retrieved from the user machine and help identify the user.

Cookies are useful for storing small amounts of frequently changed information on the client. The information is sent with the request to the server.

statemgmt5.gif
Sample:
 // Creating a cookiemyCookie.Values.Add("muffin""chocolate");
myCookie.Values.Add("babka""cinnamon");
// Adding Cookie to CollectionResponse.Cookies.Add(myCookie);
// Getting Values stored in a cookieResponse.Write(myCookie["babka"].ToString());
// Setting cookie pathmyCookie.Path = "/forums";
// Setting domain for a cookiemyCookie.Domain = "forums.geekpedia.com";
// Deleting a cookiemyCookie.Expires = DateTime.Now.AddDays(-1);
Code Example:
//Storing value in cookieHttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "David";
Request.Cookies.Add(cookie);
//Retrieving value in cookieif (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)
         lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();
else         lblNickName.Text = "Welcome Guest"

Query String:
A Query string is used to pass the values or information form one page to another page. They are passed along with URL in clear text. Query strings provide a simple but limited way of maintaining some state information. When surfing the internet you should have seen weird internet addresses such as:

http://www.localhost.com/Webform2.aspx?name=ABC&lastName=XYZ

This HTML address uses a QueryString property to pass values between pages.

statemgmt6.gif
Syntax:
Request.QueryString(variable)[(index)|.Count] 
Code Example:
using System;using System.Web.UI;
public partial class _Default : Page{
    protected void Page_Load(object sender, EventArgs e)
    {
        string v = Request.QueryString["param"];
        if (v != null)
        {
            Response.Write("param is ");
            Response.Write(v);
        }
        string x = Request.QueryString["id"];
        if (x != null)
        {
            Response.Write("   id detected");
        }
    }
}

SERVER SIDE STATE MANAGEMENT:

Application State: 
Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing a small amount of often-used data. If application state is used for such data instead of frequent trips to the database, then it increases the response time/performance of the web application.

In classic ASP, an application object is used to store connection strings. It's a great place to store data that changes infrequently.

statemgmt7.gif
Code Example 1:
//Stroing information in application statelock (this)

       Application["NickName"] = "Nipun";
}
//Retrieving value from application statelock (this)
{
      string str = Application["NickName"].ToString();

Code Example 2:
 protected void Page_Load(object sender, EventArgs e)
    {
// Code that runs on page load
        Application["LoginID"] = "Nipun";
        Application["DomainName"] = "www.nipun.com"
    }


Session State:
ASP.NET Session state provides a place to store values that will persist across page requests. Values stored in Session are stored on the server and will remain in memory until they are explicitly removed or until the Session expires. It is defined as the period of time that a unique user interacts with a Web application. Session state is a collection of objects, tied to a session stored on a server.

statemgmt8.gif
Sample:
//Storing informaton in session stateSession["NickName"] = "ABC";
//Retrieving information from session statestring str = Session["NickName"]; 

 
Code Example:
 object sessionObject = Session["someObject"];if (sessionObject != null)
{
 myLabel.Text = sessionObject.ToString();
}


Profile Properties:
ASP.NET provides a feature called profile properties, which allows you to store user-specific data. It is similar to session state, except that unlike session state, 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. In this each user has its own profile object.

statemgmt9.gif
 
Sample:
<profile>
  <properties>
    <add item="item name" />
  </properties>
</profile>
 
Code Example:
 <authentication mode="Windows" /> 
      <profile>  
      <properties>  
     <add name="FirstName"/>  
     <add name="LastName"/>  
     <add name="Age"/>  
     <add name="City"/>  
      </properties>  
   </profile> 
Thanks to nagaraju for this post.

Pros & Cons of Using LINQ

Pros
  • Quick turn around for development 
  • Queries can be dynamically 
  • Tables are automatically created into class 
  • Columns are automatically created into properties 
  • Relationship are automatically appended to classes
  • Lambda expressions are awesome Data is easy to setup and use 
Cons
  • No clear outline for Tiers
  •  No good way of view permissions 
  • Small data sets will take longer to build the query than execute 
  • There is an overhead for creating queries 
  • When queries are moved from sql to application side, joins are very slow DBML concurrency issues 
  • Hard to understand advance queries using Expressions

Friday, June 22, 2012

.Net Framework

The .NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows. It includes a large library and provides language interoperability (each language can use code written in other languages) across severalprogramming languages. Programs written for the .NET Framework execute in a software environment (as contrasted to hardwareenvironment), known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security, memory management, and exception handling. The class library and the CLR together constitute the .NET Framework.
The .NET Framework's Base Class Library provides user interface, data access, database connectivity, cryptography, web applicationdevelopment, numeric algorithms, and network communications. Programmers produce software by combining their own source code with the .NET Framework and other libraries. The .NET Framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces a popular integrated development environment largely for .NET software called Visual Studio.
.Net Framework Stack and versions...
                                           

CLR, CLS, CTS, JIT, CIL

The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as just-in-time (JIT) compilation, the CLR compiles the intermediate language code known as Common Intermediate Language (CIL) into the machine instructions that in turn are executed by the computer's CPU. The CLR provides additional services including memory management,type safety and exception handling. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. It provides exception handling, Garbage collection and thread management.



The Common Type System (CTS) A set of data types and operations that are shared by all CTS-compliant programming languages. Metadata Information about program structure is language-agnostic, so that it can be referenced between languages and tools, making it easy to work with code written in a language you are not using.
This is a Guideline that to communicate smoothly with other .Net Languages. CLS is set of language rules that defines the language standards for dotnet.

Common Language Specification (CLS) A set of base rules to which any language targeting the CLI should conform in order to interoperate with other CLS-compliant languages. The CLS rules define a subset of the Common Type System.
This is used to communicate with other language. That means to match the data types, library methods, classes..., CTS make us feel it as a common environment without considering the language. Example in vb we have int and in c++ we have long so that in one case they are not compatiable with each other so that CTS palys important role with using System.int32

Basics....

Thursday, June 21, 2012

Reduce the size of Log(.ldf) File in SQL Server

Today i had a problem. When i checked my database LDF file (log) file it’s some where around 200GB and growing. I was trying to shrink the file, but it's upto few MB's. So that was not helpful. Found a solution, First make the database to SIMPLE Recovery mode and do it.

-– Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE [databasename]
SET RECOVERY SIMPLE;
GO
–- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE ([log file name], 1);
GO
– Reset the database
ALTER DATABASE [databasename]
SET RECOVERY FULL;
GO
Also you can do the above steps in UI,
  1. Right click the database you want to delete the log, go to Properties, select Options, then select Simple in Recovery Model and click Ok. 
  2. Then again go to properties -> Files -> change _log file size by changing the size in "Initial Size (MB)" column to 1 -> then click ok 
  3. Then Again change the recovery model to full. This will free some log space. If you want the earlier log files, you should've kept the Full Backup of database before deleting log file.