Monday, January 31, 2011

What is difference between Server.Transfer and Response.Redirect ?

Transfer and Response.Redirect in ASP.NET applications. Redirect and Transfer both cause a new page to be processed, but the interaction between the client (web browser) and server (ASP.NET) is different in each situation.



Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.



Roundtrip means in case of Response.Redirect it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes But in case of Server.Transfer it directly communicate with the server to change the page hence it saves a roundtrip in the whole process.



If you are using Server.Transfer then you can directly access the values, controls and properties of the previous page which you can't do with Response.Redirect.



Response.Redirect changes the URL in the browser's address bar. So they can be bookmarked. Whereas Server.Transfer retains the original URL in the browser's address bar. It just replaces the contents of the previous page with the new one.



Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages and is specific to ASP and ASP.NET.



Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.

File Upload Control in Asp.Net

Introduction

ASP.Net 2.0 comes up with a completely new File Upload Control. This is how you can declare the file upload control.
< asp:FileUpload id="FileUpload1? runat="server" />

Some useful properties
FileUpload1.FileName :- Will give File Name with the full Path.
FileUpload1.PostedFile.FileName :- Will give only the file name.
FileUpload1.PostedFile.ContentLength :- will give size of the file in Bytes.
FileUpload1.PostedFile.ContentType :- will give MIME type of uploaded file, i.e. "image/gif".

Web.Config Settings
By Default, maximum allowed size for file is 4MB. To allow files larger than the default of 4MB, one need to change the web.config.There is a parameter called maxRequestLength which takes value in the KB.
< system.web>
< httpRuntime executionTimeout="1000? maxRequestLength="1048576?/>
< /system.web>


The maxRequestLength property dictates the size of the request made to the Web server.When you upload files, the file is included in the request.

This example changes the maxRequestLength property's value to 1048576KB (around 1GB). With this setting in place, end users can upload 1Gb file to the server.

There is a one more property named "executionTimeout".This property sets the time (in seconds) for a request to attempt to execute to the server before ASP.NET shuts down the request (whether or not it is finished). The default setting is 90 seconds.
The end user receives a timeout error notification in the browser if the time limit is exceeded. If you are going to permit larger requests, remember that they take longer to execute than smaller ones. If you increase the size of the maxRequestLength property, you should examine whether to increase the executionTimeout property as well.


Role of IIS
Uploading files in ASP.NET is very inefficient.When you pick a file and submit your form, IIS needs to suck it all in and only then you have access to the properties of uploaded file(s).You can not do about the fact that you have to sit through a long upload and wait. Neither can you display a meaningful progress bar because there's no way to know how much is transmitted at any given time. Once IIS buffers your upload, ASP.NET takes it from there.

You might receive errors when your end users upload files to your Web server through the FileUpload control in your application. These might occur because the destination folder on the server is not writable for the account used by ASP.NET. If ASP.NET is not enabled to write to the folder you want, you can enable it using the folder's properties.

Different States in ASP.NET

An ASP.NET application ends after generating a web page. The current status of date maintained by the application is lost. In other words, HTTP does not maintain the state of the application. This is described in the below figure.

You can see that a browser on the client side requests a page from the web server. After processing the request and returning the page, the server drops the connection. Then. if the browser makes another request the server has no way to associate the browser with the previous request. So HTTP is called as a stateless protocol. But ASP.NET provides several ways to maintain the state.

View State
View state is used to maintain the values of server control properties. AS ASP.NET implements view state by default you need not to write any special code to use it.

Session State
Session state is used to maintain data between execution of an application. For this, ASP.NET creates a session state object that is kept on the server whenever a user starts a new session. The session state object contain unique session ID, and this ID is sent back and forth between the server and browser each time the user request a page. Then when the server receives a new request from the user, it can retrive the right session state object for that user. You can add data items to the session object in your code, so there previous values are available each time a web form is executed.

Application State

ASP.NET provides an application state object to save application state data, which applies to all the users of an application. You can use application state object to manage global counters to maintain a list of users who are currently logged on to an application.

Profile
ASP.NET also provides profile feature to keep track of user data. Although a profile is similar to session state object, it persists between user session as it is stored in a database. For example we can use profiles we can keep track of the products ordered by an user in an shopping application and when the user starts a new session, you can display those products in a "ordered items" listbox.

Saturday, January 29, 2011

Embed a media player in a web page in ASP.Net

We can embed the media player in a web page in many ways. But the easiest and the most straight forward way is to place a literal control on the web page. Then just set the text of the same as mentioned below:



Step 1:

'---Place the Literal control on the web page as mentioned below:



< asp:literal id="ltrlMediaPlayer" runat="server">< /asp:literal>

Step 2:

'--- Set the text of the literal control as mentioned below:



ltrlMediaPlayer.Text = "< OBJECT ID='MediaPlayer' WIDTH='320' HEIGHT='240'" & _

"CLASSID='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' " & _

"STANDBY='Loading Windows Media Player components...' " & _

"TYPE='application/x-oleobject' VIEWASTEXT>" & _

"< PARAM name='FileName' VALUE='ACTUAL FILE PATH' > " & _

"< PARAM name='autostart' VALUE='false'> " & _

"< PARAM name='ShowControls' VALUE='true'> " & _

"< param name='ShowStatusBar' value='true'> " & _

"< PARAM name='ShowDisplay' VALUE='false'> " & _

"< EMBED TYPE='application/x-mplayer2' NAME='MediaPlayer'> " & _

"< /EMBED>" & _

"< /OBJECT>"


Note: 'ACTUAL FILE PATH' should be the complete path of the file to be played in the media player.

Event Life cycle of ASP.NET 2.0

The events occur in the following sequence. Its best to turn on tracing() and track the flow of events :

PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.

Init – Each control in the control collection is initialized.

Init Complete* - Page is initialized and the process is completed.

PreLoad* - This event is called before the loading of the page is completed.

Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.

LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.

PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.

PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.

SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.

Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.

The events marked with * have been introduced in ASP.NET 2.0.

Difference between int.parse and Convert.ToInt32

Consider the following example…

string strCount="32";
int count1 = Convert.ToInt32(strCount);
int count2 = int.Parse(strCount);

If you print the result it will be same i.e. 32

If suppose the string is the null,
Convert.ToInt32 will return zero.
but the int.Parse will throw ArgumentNullException error.

string strCount=null;
int count1 = Convert.ToInt32(strCount); // Returns 0
int count2 = int.Parse(strCount); // Error

Search/Replace in Files in C#

Sometimes you need a quick & easy way to search and replace text in a file. The following code shows how it can be done using the static methods on the Regex regular expression class. Because this sample loads the entire file contents in memory, is not appropriate for very large files.

using System;
using System.IO;
using System.Text.RegularExpressions;

///
/// Replaces text in a file.
///

/// Path of the text file.
/// Text to search for.
/// Text to replace the search text.
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();

content = Regex.Replace( content, searchText, replaceText );

StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}

Read Text File Line-by-Line in C#

Here is the code to read a text file from disk one line at a time into a string. This code ensures the file exists and properly closes the file if an exception occurs.

using System;
using System.IO;

namespace CSharp
{
class Program
{
static void Main( string[] args )
{
string filePath = @"c:\temp\test.txt";
string line;

if (File.Exists( filePath ))
{
StreamReader file = null;
try
{
file = new StreamReader( filePath );
while ((line = file.ReadLine()) != null)
{
Console.WriteLine( line );
}
}
finally
{
if (file != null)
file.Close();
}
}

Console.ReadLine();
}
}
}

How To Add JavaScript Delete Confirmation in GridView "Delete" Command Button dynamically?

if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].HasControls())
{
LinkButton lnkbtnDelete = ((LinkButton)e.Row.Cells[1].Controls[0]);
lnkbtnDelete.Attributes.Add("onclick", "return confirm('Do you want to Delete?');");
}
}

Note:
1. The Cell starts with 0 Index.
2. The line "if (e.Row.Cells[1].HasControls())" is to check, if the control is exists or not. This will be useful, when Edit Command Button is used along with Delete Command Button.

How to Validate FileUpload control to allow only Image Files using RegularExpressionValidator?

To upload images to the server from Asp.Net web application, we will use the FileUpload server control. This control can be validated to upload only Image files using the RegularExpressionValidator control.

To achieve this drag and drop a FileUpload and RegularExpressionValidator control into your aspx page. Then set the ControlToValidate property as “FileUpload1” and the ValidationExpression property as specified below.



ErrorMessage="Invalid Image File"
ValidationExpression=
"^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$">


So the above RegularExpressionValidator will only allow jpg, jpeg, bmp, gif, png formats image files. You can add more file formats separated by “|” symbol. Also you can specify more special characters after the string “_\-~” to allow the files you want to upload to the server.

Setting Session time-out

We can do the setting in in the Session_Start event in Global.ASAX file, web.config file or IIS.The default time-out is 20 min.

**In Web.Config**
Here the timeout "20" is in
minutes if u want u can change in to fit your requirement.

mode="InProc"
cookieless="false"
timeout="20"
/>

InProc --> Indicates that session state is stored within the same process as that the application is running.
cokieless = "false" --> Indicates that sessions without cookies should not be used. The default is false.

**Session_Start of Global.ASAX**

protected void Session_Start(Object sender, EventArgs e)
{
Session.Timeout = 20;
}

**In IIS**

Go to Inetmgr -> Default Web Site -> Properties -> Home Directory -> Configuration -> Options


Priority is as follows : 1. Code
2. Web.Config
3. IIS

Disabling SessionState

Disable Session State at the Application Level: - In Web.Config, locate the section, and set the mode value to Off.

Disable Session State at the Page Level :- At the top of the page, add EnableSessionState="false" in the @ Page directive

Where is the ViewState value stored?

When we write something to a ViewState object a hidden field is created in the HTML whose value is encrypted. During a PostBack this value travels along with the page to the server and comes back. Because of this reason we should not store large values in Viewstates as they become heavy.

Ex: < input name="__VIEWSTATE" value="dDwtMTY3MTY4OTI3NDs7Pr AYZq+d1r V++f3rE2ngBQMU9l5h" type="hidden">

Load all colors in a ComboBox using C#

In Windows Forms, the Color structure has a public property for each color. We can use System.Reflection to read all colors of a Color structure and load its properties.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
foreach (System.Reflection.PropertyInfo prop in typeof(Color).GetProperties())
{
if (prop.PropertyType.FullName == "System.Drawing.Color")
comboBox1.Items.Add(prop.Name);
}
}
}
}

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...