Visual Studio 2010 and ASP.NET 4.0 beta 1 Released

August 12, 2009 at 2:24 pm | Posted in ASP.NET | Leave a comment
Tags: , , , ,

Microsoft has released Visual Studio 2010 and ASP.NET 4.0 beta 1recently, I felt there are some amazing features which can help developer improve productivity.

Visual Studio 2010 and .NET Framework 4 focuses on the core pillars of developer experience, support for the latest platforms, targeted experiences for specific application types, and core architecture improvements.

Check out the following links:

What’s New in Visual Studio 2010

What’s New in the .NET Framework 4

Download Visual Studio 2010 and .NET Framework 4 Beta 1

State Management in ASP.NET

August 3, 2009 at 1:46 pm | Posted in ASP.NET | Leave a comment
Tags: , , , , ,

Web form pages are HTTP-Based, they are stateless, which means theydon’t know whether the requests are all from the same client, and pagesare destroyed and recreated with each round trip to the server,therefore information will be lost, therefore state management isreally an issue in developing web applications

We could easilysolve these problems in ASP with cookie, query string, application,session and so on. Now in ASP.NET, we still can use these functions,but they are richer and more powerful, so let’s dive into it.

Mainly there are two different ways to manage web page’s state: Client-side and Server-side.

Client-side state management :

There is no information maintained on the server between round trips.Information will be stored in the page or on the client’s computer.

A. Cookies.

Acookie is a small amount of data stored either in a text file on theclient’s file system or in-memory in the client browser session.Cookies are mainly used for tracking data settings. Let’s take anexample: say we want to customize a welcome web page, when the userrequest the default web page, the application first to detect if theuser has logined before, we can retrieve the user informatin fromcookies:
[c#]
if (Request.Cookies[“username”]!=null)
lbMessage.text=”Dear “+Request.Cookies[“username”].Value+”, Welcome shopping here!”;
else
lbMessage.text=”Welcome shopping here!”;

If you want to store client’s information, you can use the following code:
[c#]
Response.Cookies[“username’].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.

B. Hidden Field

Ahidden field does not render visibly in the browser, but you can setits properties just as you can with a standard control. When a page issubmitted to the server, the content of a hidden field is sent in theHTTP Form collection along with the values of other controls. A hiddenfield acts as a repository for any page-specific information that youwould like to store directly in the page. Hidden field stores a singlevariable in its value property and must be explicitly added it to thepage.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.
[c#]
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value=”this is a test”;
//to retrieve a value
string str=Hidden1.Value;

Note:Keep in mind, in order to use hidden field, you have to use HTTP-Postmethod to post web page. Although its name is ‘Hidden’, its value isnot hidden, you can see its value through ‘view source’ function.

C. View State

Eachcontrol on a Web Forms page, including the page itself, has a ViewStateproperty, it is a built-in struture for automatic retention of page andcontrol state, which means you don’t need to do anything about gettingback the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.
[c#]
//to save information
ViewState.Add(“shape”,”circle”);
//to retrieve information
string shapes=ViewState[“shape”];

Note: Unlike Hidden Field, the values in ViewState are invisible when ‘view source’, they are compressed and encoded.

D. Query Strings

Querystrings provide a simple but limited way of maintaining some stateinformation.You can easily pass information from one page to another,But most browsers and client devices impose a 255-character limit onthe length of the URL. In addition, the query values are exposed to theInternet via the URL so in some cases security may be an issue.
A URL with query strings may look like this:

http://www.examples.com/list.aspx?categoryid=1&productid=101

When list.aspx is being requested, the category and product information can be obtained by using the following codes:
[c#]
string categoryid, productid;
categoryid=Request.Params[“categoryid”];
productid=Request.Params[“productid”];

Note: you can only use HTTP-Get method to post the web page, or you will never get the value from query strings.

Server-side state management :

Information will be stored on the server, it has higher security but it can use more web server resources.

A. Aplication object

TheApplication object provides a mechanism for storing data that isaccessible to all code running within the Web application, The idealdata to insert into application state variables is data that is sharedby multiple sessions and does not change often.. And just because it isvisible to the entire application, you need to used Lock and UnLockpair to avoid having conflit value.
[c#]
Application.Lock();
Application[“mydata”]=”mydata”;
Application.UnLock();

B. Session object

Sessionobject can be used for storing session-specific information that needsto be maintained between server round trips and between requests forpages. Session object is per-client basis, which means differentclients generate different session object.The ideal data to store insession-state variables is short-lived, sensitive data that is specificto an individual session.

Each active ASP.NET session isidentified and tracked using a 120-bit SessionID string containingURL-legal ASCII characters. SessionID values are generated using analgorithm that guarantees uniqueness so that sessions do not collide,and SessionID’s randomness makes it harder to guess the session ID ofan existing session.
SessionIDs are communicated acrossclient-server requests either by an HTTP cookie or a modified URL,depending on how you set the application’s configuration settings. Sohow to set the session setting in application configuration? Ok, let’sgo further to look at it.

Every web application must have aconfiguration file named web.config, it is a XML-Based file, there is asection name ‘sessionState’, the following is an example:

<sessionStatemode=”InProc” stateConnectionString=”tcpip=127.0.0.1:42424″sqlConnectionString=”data source=127.0.0.1;user id=sa;password=”cookieless=”false” timeout=”20″ />

‘cookieless’ option can be‘true’ or ‘false’. When it is ‘false’(default value), ASP.NET will useHTTP cookie to identify users. When it is ‘true’, ASP.NET will randomlygenerate a unique number and put it just right ahead of the requestedfile, this number is used to identify users, you can see it on theaddress bar of IE:

http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, it is further enough, let is go back to session object.
[c#]
//to store information
Session[“myname”]=”Mike”;
//to retrieve information
myname=Session[“myname”];

C. Database

Databaseenables you to store large amount of information pertaining to state inyour Web application. Sometimes users continually query the database byusing the unique ID, you can save it in the database for use acrossmultiple request for the pages in your site.

.Net KeyBoard Shortcuts

November 24, 2008 at 5:53 pm | Posted in ASP.NET | Leave a comment
Tags: , ,

# For Uppar Case/Lower Case: Ctrl+SHFT+U/Ctrl+U

# To Specify regions and etc: CTRL+K, CTRL+S

# Word Wrap: CTRL+E, W

# Transpose Line: SHFT+ALT+T

# Delete white space: CTRL+K, \

# Move to Nav Bar: Ctrl + F2

# For Full Screen: Alt + Shift + Enter

# For Intellisense: Ctrl + J Or Ctrl + Space

# To close the current tab: Ctrl+F4

# Expand/collapse definitions : Ctrl+M+M

# Used to move pervious position: Ctrl +-

# Go to declaration/Find usages: F12

# To focus on Solution Explorer: Ctrl + Alt + L

# To focus on Properties Window: F4

# To focus on Object Browser: Ctrl + Alt + J

# To focus on ToolBox: Ctrl + Alt + X

# To focus Immediate WIndow: Ctrl + Alt + I

# Debug Start: F5

# Debug Restart: Ctrl + Shift + F5

# StopDebugging: Cntl +F5

# Start WIthout debugging: Cntl + F5

# Build.BuildSolution: Ctrl +  Shift+ B

# Build.Cancel: Ctrl+Break

# Build.Compile: Ctrl + F7

# Debug.Breakpoints: Ctrl + Alt + B

# Debug.StepInto: F11

# Debug.StepOver: F10

# Debug.StepOut: SHift + F11

# Exceptions Window: Ctrl+Alt+E

# TO View Output: Ctrl + Alt + O

# To View CommandWindow: Ctrl + Alt + A

# To view Code: F7

# To View Designer: Shift + F7

# To copy any line in your .Net Editor don’t select complete line, just place the cursor on the line and
press ctrl-c and press ctrl-v where ever you want to paste the line.

# For Comments: Ctrl – K + C

# For Un Comments: Ctrl – K + U

# To Format the document: Ctrl-K + D

# To Add new items: Ctrl-N or Ctrl-Shift+A

# To cut a line you also use: Ctrl-L

# To shift between .net editor Pages: Ctrl + Tab

# To Format the selection: Ctrl – K + F

# To cycle through clipboard “ring”: Ctrl+Shift+V

# To Add a Book Mark use: Ctrl K + K

# To Navigate to new Book Mark: Ctrl K + N

# To Clear all book marks : CTRL+B, C

CTYPE, DIRECTCAST AND TRYCAST

November 21, 2008 at 5:07 pm | Posted in ASP.NET | 5 Comments
Tags: , , , ,

CTYPE is most commonly used one. But if you are converting types other than the underlying type of an object
CType can convert the underlying object to a new instance of an object of a different type.

Ctype requires 2 parameter , the object and also the type.

Code Example :
varObject =1;
varString = CType(varObject, String)

varObject =1;
varString = CType(varObject, String)

Directcast can only convert a type tp another type that has inheritance or implementation relationship. It can be used  to convert objects to their actual type, can’t convert into some other type.

For example :
varObject = “1”; //varObject is of type “Object” Actual type is String
varString = DirectCast(varObject, String); //This will work

The above code will work as the object’s actual type is string. Now check the below code where the object’s actual type is integer.

varObject = 1; //varObject is of type “Object” Actual type is integer
varString = DirectCast(varObject, String); //This will not work. Throws an exception

Another Example : Casting System.windows.Forms.form to System.Windows.Forms.Control.

Which one is better:
1)use Directcast when possible to convert objects to their  nderlying types instead of Ctype because it is faster than CTYPE.
2)Readability : DirectCast is not vb.net specific, portal to other language. Other language programmers can easily read and understand the code written by you. It is a much more “intentional” way of coding than CType.
3)DirectCast is twice faster than CTYPE for value type. But same performance for refernce type.

TryCast
If an attempted conversion fails, CType and DirectCast both throw an InvalidCastException error. This can adversely affect the performance of your application. TryCast returns Nothing (Visual Basic)
You need’t to write codes for handle exception when TryCast can handle it for you. But there are some limitations
1)TryCast operates only on reference types, such as classes and interface.

Code Sample:
varObject = “1”; //varObject is of type “Object” Actual type is String
varString = TryCast(varObject, String);

C# equivalent to trycast[VB.Net] is “as”

Code Sample:
varObject = “1”; //varObject is of type “Object” Actual type is String

varString = varObject as String;

Advantages and disadvantages of Viewstate

November 19, 2008 at 7:10 pm | Posted in ASP.NET | 6 Comments
Tags: , , ,

The primary advantages of the ViewState feature in ASP.NET are:

1. Simplicity. There is no need to write possibly complex code to store form data between page submissions.
2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to persist the values of  some fields but not others.

There are, however a few disadvantages that are worth pointing out:

1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the session approach, values can be stored in the session and accessed from other pages. This is not possible with ViewState, so storing data into the session must be done explicitly.

2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to the back end using some form of data object.

What does the EnableViewState property do?

November 19, 2008 at 6:52 pm | Posted in ASP.NET | Leave a comment

Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip, then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.

Difference between webconfig and machineconfig files

November 19, 2008 at 6:45 pm | Posted in ASP.NET | Leave a comment

Web.config and machine.config both are configuration files.Web.config contains settings specific to an application
where as machine.config contains settings to a system. The Configuration system first searches settings in machine.config
file & then looks in application configuration  files.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. There is only Machine.config file on a web server.

ASP.Net Session

November 16, 2008 at 12:11 pm | Posted in ASP.NET | Leave a comment

You can store values that need to be persisted for the duration of a
user’s session in session variables. These variables are unique to each
user session and can be accessed in any ASP.NET page within an
application. You can set and access session information from within an
ASP.NET application.

Note that session variables are now
objects. Thus, to avoid a run-time error, you should check whether the
variable is set before you try to access it.

C#Code:
Session[“UserName”]=”Srinath”;

string User;
 if (Session[“UserName”] != null)
 User= (string)Session[“UserName”];

Session variables are automatically discarded after they are not used
for the time-out setting that is specified in the Web.config file. On
each request, the time out is reset. The variables are lost when the
session is
explicitly abandoned in the code.

When a session is
initiated on first request, the server issues a unique session ID to
the user. To persist the session ID, store it in an in-memory cookie
(which is the default), or embed it within the request URL after the
application name. To switch between cookie and cookieless session
state, set the value of the cookieless parameter in the Web.config file
to true or false.

In cookieless mode, the server automatically
inserts the session ID in the relative URLs only. An absolute URLis
not modified, even if it points to the same ASP.NET application, which
can cause the loss of session variables.

ASP.NET supports three modes of session state:
InProc:
In-Proc mode stores values in the memory of the ASP.NET worker process.
Thus, this mode offers the fastest access to these values. However,
when the ASP.NET worker process recycles, the state data is lost.

StateServer:
Alternately, StateServer mode uses a stand-alone Microsoft Windows
service to store session variables. Because this service is independent
of Microsoft Internet Information Server (IIS), it can run on a
separate server. You can use this mode for a load-balancing solution
because multiple Web servers can share session variables. Although
session variables are not lost if you restart IIS, performance is
impacted when you cross process boundaries.

SqlServer: If
you are greatly concerned about the persistence of session information,
you can use SqlServer mode to leverage Microsoft SQL Server to ensure
the highest level of reliability. SqlServer mode is similar to out-of-process mode, except that the session data is maintained in a
SQL Server. SqlServer mode also enables you to utilize a state store
that is located out of the IIS process and that can be located on the
local computer or a remote server.

Note You can use all three modes with in-memory cookie or cookieless session ID persistence.

ASP.NET Page Life Cycle

November 15, 2008 at 2:27 pm | Posted in ASP.NET | 109 Comments
Stage Description
Page request The page request occurs before the page life cycle begins. When the
page is requested by a user, ASP.NET determines whether the page needs
to be parsed and compiled (therefore beginning the life of a page), or
whether a cached version of the page can be sent in response without
running the page.
Start In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page’s UICulture property is set.
Page initialization During page initialization, controls on the page are available and each control’s UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
Page Load During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
Validation During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
Postback event handling If the request is a postback, any event handlers are called.
Rendering Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page’s Response property.
Page Unload Unload is called after the page has been fully rendered, sent to the client,
and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Difference between System.String and string in C#.

November 15, 2008 at 7:58 am | Posted in ASP.NET | Leave a comment

Confusing about which one to use? Don’t be, they are the same!
“string” is C# alias of type System.String. Both string and String are
compiled down to System.String in IL, very much like int for
System.Int32. There’s no performance implication in any way. In some
forums, i found threads related to System.String and string, it says
that String is kept on heap and string is on stack, but thats not true.
Some developers will use “string” and some uses “String”, which one of
these to use is only a matter of style.

Next Page »


Entries and comments feeds.