Wednesday, 30 June 2010

18486 Login failed for user ’sa’ because the account is currently locked out

The error Msg: 18486 Login failed for user ’sa’ because the account is currently locked out will throw only when the account is locked.

When the account is getting locked?

When the number of unsuccessful login attempts exceeds certain time, the login account will be disabled by the System.

WorkAround:

1. Disable the locking policy of the system. But it may affect the security level of the system as it will allow unlimited number of unsuccessful login attempts.

2. ALTER LOGIN "sa" With Password = 'YourPassword' UNLOCK;

-it will unlock the Account.

3. The best practice would be create a new system account with the same rights as "sa" and disable "Sa" login.

Not enough storage is available to process this command

I recently faced an issue in the development server, the error message "Not enough storage is available to process this command" popped up when try to ran the longer query in the sql server.



The reason for the error was due to the IPRStackSize registry entry was missing or setting too low.

In my case the IPRStackSize registry entry was missing .

To resolve these errors I did the following:

1) Start -> Run ->Type regedit
2) Locate and click the following entry
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters

3)If the IRPStackSize entry is not present in this subkey, follow these steps:


Click Edit, point to New, and then click DWORD Value.

Type IRPStackSize, and then press ENTER.

Note: Type IRPStackSize exactly as it appears. The value name is case sensitive.

4) Right Click IRPStackSize and then click Modify.



5) Select the Base as decimal. In the Data Value box, type a larger value and then click OK.


Display line numbers in .NET Code Editor




.NET Tips,Display line numbers in code editor, display line numbers in VS .NET IDE
We can display the line numbers in the Visual studio .NET code editor.

In the VS.NET IDE ,

Click TOOLS > OPTIONS

Expand TEXT EDITOR (in left window)

Select Basic > Editor

You will find the Line Numbers Option Under Interaction Group box.

Check Line Numbers option

Downloading Files C#

A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported.

C# Code

// Get the physical Path of the file(test.doc)
string filepath = Server.MapPath("test.doc");

// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);

// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
Response.ClearContent();

// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());

// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());

// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(file.FullName);

// End the response
Response.End();
}

private string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
default:
return "application/octet-stream";
}

N.B: If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below code

Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);

Response.TransmitFile VS Response.WriteFile:
1- TransmitFile: This method sends the file to the client without loading it to the Application memory on the server. It is the ideal way to use it if the file size being download is large.
2- WriteFile: This method loads the file being download to the server's memory before sending it to the client. If the file size is large, you might the ASPNET worker process might get restarted.

Hope this helps,

Conversion Tools

While working on forums, i have seen a lot of questions about converting C# code to VB.NET
and vice versa. So i thought to share tools which will help you throughout your process

Convert To VB.NET

Convert To C#


Telerik Code Converter

Compress/Decompress Files using System.IO.Compression.GZipStream Class [2.0]

I was in need to compress and decompress files in one of the projects im currently working on. At the start i only knew about GZipStream existance in 2.0 but never used it before. So today i used it and i was able to compress and decompress the files back when i need to. Below are two functions

///
/// To Compress A File
///

/// The Complete file path to the file you want to compress
protected void Compress(string filePath)
{
FileStream sourceFile = File.OpenRead(filePath);
FileStream destinationFile = File.Create(Server.MapPath("~") + "/tv.gzip");
byte[] buffer = new byte[sourceFile.Length];
GZipStream zip = null;
try
{
sourceFile.Read(buffer, 0, buffer.Length);
zip = new GZipStream(destinationFile, CompressionMode.Compress);
zip.Write(buffer, 0, buffer.Length);
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
zip.Close();
sourceFile.Close();
destinationFile.Close();
}
}

///
/// To Decompress an already compressed file
///

/// The complete file path of the already compressed file
protected void Decompress(string filePath)
{
FileStream sourceFile = File.OpenRead(filePath);
FileStream destinationFile = File.Create(Server.MapPath("~") + "/tv1.xml");
GZipStream unzip = null;
byte[] buffer = new byte[sourceFile.Length];
try
{
unzip = new GZipStream(sourceFile, CompressionMode.Decompress, false);
int numberOfBytes = unzip.Read(buffer, 0, buffer.Length);

destinationFile.Write(buffer, 0, numberOfBytes);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
sourceFile.Close();
destinationFile.Close();
unzip.Close();
}
}

N.B: Do not forget to import two namespaces

1.
System.IO
2.
System.IO.Compression

Best Regards,

Single Sign On in Forms Authentication

If you have for example two ASP.NET applications and you want to share the authentication cookie between those application, you can do that using the SSO.

To configure your applications to share the authentication cookie, each application has to have same configurations in the web.config file. One important notice in here that the name, protection and path attributes should be the same also in the two web.config files





validation="SHA1" />

Copy the above configurations into the web.config.


Best Regards,

.NET Framework 2.0 SP1!

Microsoft
Released a service pack for .NET Framework 2.0. This release provides security improvements, and prerequisite feature support for .NET Framework 3.0 Service Pack 1, and .NET Framework 3.5

Download it from

.NET Framework 2.0 SP1

Regards,

Timer to Redirect Users To Another Webform!

In this blog post, we will discuss how to create a decremental timer which will redirect the user to another page after 60 seconds. You might have seen this feature in almost every site providing content to be downloaded.

Below is Javascript code to be inserted inside the tag of the HTML.



For Making this sample work, insert a label with id Label1 and text equals to 60.



Hope this Helps,

Authenticate Users Via POST request

In this blog post, I will explain how to submit user credentials to another application to authenticate users.

Suppose in your application, you wanted to retrieve data from another application (for instance RSS feeds), this rss feed isn't for public use, and you don't control the login authentication on that application.

Solution
You can submit user credentials from your Application to the other application and process the login click event using the HttpWebRequest class. In this way, if the user is authenticated the authentication cookie will be saved in the response header. After this stage, Each time you want to retrieve information for Application B, you could set the authentication cookie already retrieved to the request header so Application B will deal with the request as an authenticated one.

Let's drill down to the code

string loginURL = "http://www.example.com/default.aspx";
// Create a webrequest to the above url
HttpWebRequest webRequest = WebRequest.Create(loginURL) as HttpWebRequest;
// Set the request method to post
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = false;
// Set the content type to urlencoded
webRequest.ContentType = "application/x-www-form-urlencoded";
// Set the data which needs to be posted. Note here os_username, os_password is the textbox ID for the //username, password on Application B. login is the ID of the login button control, LogIn is its value.
string postData = "os_username=haissam&os_password=password&login=LogIn";
// Set the content length of the request
webRequest.ContentLength = postData.Length;
// set the webrequest stream to the requestWriter
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
// Write the data which need to be posted to the streamwriter
requestWriter.Write(postData);
// Close the stream
requestWriter.Close();
// you don't need to get the response only the authentication cookie so directly we close it
webRequest.GetResponse().Close();

Hope this helps,

Restart ASP.NET Application Programatically

A lot of developers are asking how to restart the ASP.NET application or recycle the ASP.NET process without the need to modify the content of web.config file or changing its name.

You can use the HttpRuntime.UnloadAppDomain() which will terminate the application and of course remove all the session objects for all users the next time a request is being received.

Demonstration:

Create a dummy web application, drag and drop two buttons. and use some like below

private void Page_Load(object sender, System.EventArgs e)

{

// Put user code to initialize the page here

if(!IsPostBack)

Session.Add("ASP","hello");

}

private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
HttpRuntime.UnloadAppDomain();
}

private void Button2_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
}


When you click Button2, you will have object reference not set to an instance of an object error which indicates that Session["ASP"] is equal to null.

Hope this helps

Exchange data between ASP.NET and Adobe Flex

As i'm an ASP.NET developer and knowing that this technology is powerfull, I needed to find a way to exchange data between Adobe Flex application used as front end and my ASP.NET application used as a backend. After spending some time googling, i found an open source library "The FluorineFx open source library provides an implementation of Flex/Flash Remoting, Flex Data Services and real-time messaging functionality for the .NET framework."

To start using this open source library go to http://www.fluorinefx.com/download.html and click on "Download FluorineFx v1.0.0.13".

Once the installation process is completed, A folder on your desktop will be created "DotNet", Navigate to "FlexToNet.AMFService\Bin" to get the dlls

required. Paste these 2 dlls into the bin folder of your ASP.NET application.

Configuration

Once you have placed the two dlls inside the bin folder of your application, in Visual Studio 2005 right click on References and click Add Reference.
Browse to the application bin folder and select the two dlls.
For the communication between ASP.NET and Adobe flex to work, you need to create a dummy page called "Gateway.aspx" and add the below code to the web.config file inside System.Web tags






As you may have noticed, the dll being added to the application bin folder serves as http module which will serialize the objects and allow the communication between these two technologies


Adobe Flex
In Adobe Flex builder, create a new project of type mxml application and add the below code




import mx.controls.Alert;
import flash.net.NetConnection;
private function CallDotNetMethod(event:Event):void
{
// Create a new instance of NetConnection class
var net:NetConnection = new NetConnection();
// Connect to your ASP.NET application
net.connect("http://localhost/webApplication5/Gateway.aspx");
// Call a function in your application called RetrieveMsg inside a class called "Test"
net.call("WebApplication2.Test.RetrieveMsg", new Responder(Result,null));
// Close the connection
net.close();
}
public function Result(data:Object):void
{
// this method will be called once the result from the .NET class is received which will just display the message returned
Alert.show(data.toString());
}
public function HandleClick():void
{
// This method will be called on creation complete event of the mxml application
btnTest.addEventListener(MouseEvent.CLICK,CallDotNetMethod);
}
]]>




ASP.NET Application
Create a new web application, create a new class called "Test" inside it add the below code

public string RetrieveMsg()
{
return "Hello World";
}

Finally you need to create a dummy page called "Gateway,aspx"

For demonstration only, this method will only return Hello world to adobe flex application.


Run the application
Once you run the application inside Adobe flex, or you added the swf file being compiled in Adobe flex builder to an aspx page, you can test the application by clicking on the button to see the alert message returning the data from the .net class

Of course you can use web services to enable this communication, but keep in mind that using webservices is slower than directly calling a .NET class. I have added the project as an attachment so you can download it and take a deeper look into it.

Hope this helps,

Crystal Report and ASP.NET

In this blog post, Haissam Abdul Malak will explain how to dynamically load a crystal report file into a webform by using the CrystalReportViewer class and how to successfully deploy the application
. For instance, suppose you have ".rpt" file in your web application folder and you dynamically want to show it in the page. Below is the code to use

// Get the filePath
string filePath = Server.MapPath("~/Reports/report1.rpt");
// Create new instance of the CrystalReportViewerClass
CrystalReportViewer rptViewer = new CrystalDecisions.Web.CrystalReportViewer();
// Create new instance of the Report Document
ReportDocument rptDoc = new ReportDocument();
// Load the rpt file into the ReportDocument Class
rptDoc.Load(filepath);
// Set the already loaded rpt file into the CrystalReportViewer class
rptViewer.ReportSource = rptDoc;
// Add the control to the page
Page.Form.Controls.Add(rptViewer);

P.S: You should add CrystalDecisions.CrystalReports.Engine and CrystalDecisions.Web and import them.

Now locally it should work because when installing VS 2005, it will install to your local pc all the dlls needed for the crystal report rendering in the GAC . However, you might encounter problems when deploying the application on a web server where the dlls are not installed. One of the solutions is to install the dlls on the web server. You can locate the installer on your local pc at "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports". The file name is "CRRedist2005_x86.msi". Run this installer on your webserver
and re-run the application.

Hope this helps,

ASP.NET RSS Toolkit With Proxy Server

Lots of ASP.NET developers took advantage of the free ASP.NET RSS toolkit to consume and provide RSS feeds. Thanks to dmitry in a matter of minutes, we will have a nice and robust toolkit which can be intergrated easily in our web application. However, After i finished my application and deploy it on one of our web servers
, Consuming RSS stopped working. The error message was "unable to connect to remote server". After investigating and contacting dmitry, i realized our proxy server was rejecting the request. I looked into the open source code provided and knew that the RSS was being loaded directly into an XmlDocument. All we needed is to send an HttpWebRequest, set the proxy configuration, read the response, and finally load the XmlDocument.

In DownloadManager Class, replace DownloadFeedDom by the below

//// look for disk cache first
CacheInfo dom = TryLoadFromDisk(url);

if (CacheReadable(dom))
{
return dom;
}

string ttlString = null;
HttpWebRequest webRequest = null;
string strResult = null;
try
{
// Create a new web request
webRequest = WebRequest.Create(url) as HttpWebRequest;
// Check if ProxyServerUrl in the appSettings is not empty
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString()))
{
// instantiate a new WebProxy class and send the ProxyServerUrl to the contructor parameter
System.Net.WebProxy proxy = new System.Net.WebProxy(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString(), true);
// Set the proxy credentials
proxy.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["PassThroughUser"].ToString(), WebConfigurationManager.AppSettings["PassThroughPwd"].ToString());
// Set the WebRequest proxy property by the WebProxy class already configured
webRequest.Proxy = proxy;
}
// Read the response
using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// Set strResult to the response
strResult = sr.ReadToEnd();
}
}
catch
{
}
// Load xml From the string
XmlDocument doc = new XmlDocument();
doc.LoadXml(strResult);

if (doc.SelectSingleNode("/rss/channel/ttl") != null)
{
ttlString = doc.SelectSingleNode("/rss/channel/ttl").Value;
}

//// compute expiry
int ttlMinutes = GetTtlFromString(ttlString, _defaultTtlMinutes);
DateTime utcExpiry = DateTime.UtcNow.AddMinutes(ttlMinutes);

//// save to disk
return TrySaveToDisk(doc, url, utcExpiry);

P.S: I would like to thank dmitry for his quick response eventhough i know that he would be busy.

Hope this helps,

Execute same code on every WebForm

Have you ever encountered the need to execute lines of code on each page_load event for each page you have in your project! I have seen a lot of developers from the official ASP.NET forums writting the same code on each page which works fine but in case you need to change something you have to reflect it on all the pages.

Below i will describe a way you can implement to overcome this issue.

1- Create a class "MyPage" which inherits from Page class.

public partial class MyPage: Page

2- Override the onLoad event of the Page class by adding the below code

protected override void OnLoad(EventArgs e)
{
Response.Write("hello World");
base.OnLoad(e);
}


3- In your webform replace System.Web.UI.Page by MyPage



Hope this helps,

Convert ASPX Pages to Word Document

We will discuss how to convert an ASPX page to word document and send it to the client. We will create an HttpModule which use the Application_BeginRequest event to check if a specific query string parameter exists to render the page into a word file.
First of all, Create a new class library project "WordConverter", Rename the class into "Converter" and let it implement IhttpModule interface which exists in System.Web namespace (you need to add it to your references before being able to add it to your namespace collection)

public class Converter : IHttpModule

After this stage, use the Init() to register for the Application_BeginRequest event.

public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
}
// Dispose should be added
public void Dispose()
{
}

In the app_BeginRequest event you will need to write the below code

HttpContext.Current.Response.Clear();
// Check if ToWord exists in the query string parameters
if(HttpContext.Current.Request.QueryString["ToWord"]!=null)
{
// Set the buffer to true
HttpContext.Current.Response.Buffer = true;
// Create a new HttpWebRequest to the same url
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(HttpContext.Current.Request.Url.ToString().Split('?')[0]);
// Set the credentials to default credentials: used if you are under proxy server
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Get the response as stream
Stream stream = webRequest.GetResponse().GetResponseStream();
// Set the content type of the response on msword
HttpContext.Current.Response.ContentType = "application/msword";
// Read the response as string
string pageHTML = new StreamReader(stream).ReadToEnd();
// Write it to the response
HttpContext.Current.Response.Write(pageHTML.ToString());
// Complete the Request
((HttpApplication)sender).CompleteRequest();
// End the response.
HttpContext.Current.Response.End();
}
P.S: Make sure you added the below namespaces
using System.Net;
using System.Web;
using System.IO;

After finishing implementing the code, compile your project. Now you need to add this module to your web application by adding it to your references and add the below code into the web.config to register the module.





You can find the Module solution attached to this blog post.

Hope this helps,

Upload Large Files in ASP.NET Using HttpModule

AS you may know, ASP.NET by default only allows the maximum request length to be 4MB. The developer needs to modify the web.config file to allow the upload process to handle large files.
If you use Reflactor and you dissamble the HttpRequest under System.Web, you will find a method called GetEntireRawContent which will check if the request is larger than the value in the web.config and throws an error

if (length > maxRequestLengthBytes)
{
throw new HttpException(SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}


In this article, Haissam Abdul Malak will demonstrate how to upload large files in ASP.NET without the need to modify the value of maxRequestLength attribute of the httpRuntime tag in the web.config.

We will create an HttpModule which will read the file in chunks (500KB per chunk).
We will handle the BeginRequest event and use the HttpWorkerRequest which provides more low level control for the request.
Below is the full implementation of the HttpModule. I included comments to enable you to fully understand each line of code.

I recommend connecting to msdn and read about HttpWorkerRequest class. Personally i didnt know about the existence of such class except lately.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);

}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;

if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
FileStream fs = null;
// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;

if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
string[] fileName = context.Request.QueryString["fileName"].Split(new char[] { '\\' });
fs = new FileStream(context.Server.MapPath("~/Uploads/" + fileName[fileName.Length-1]), FileMode.CreateNew);
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Write the chunks to the physical file
fs.Write(buffer, 0, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);

}
}
fs.Flush();
fs.Close();
context.Response.Redirect("UploadFinished.aspx");
}

}
public void Dispose()
{
}
}
}


To know the file name selected by the user, I had to use javascript function on the page containing the fileupload control to change the action property of the form tag to post to the same page with a query

string parameter containing the selected file name. Users will be redirected to a page called "UploadFinished.aspx" to display a successful upload process message.

Below is the javascript function


And call it using

You need to register the module in the application web.config file by placing the below inside the tag.





Hope this helps,

Upload Large Files in ASP.NET Using HttpModule

AS you may know, ASP.NET by default only allows the maximum request length to be 4MB. The developer needs to modify the web.config file to allow the upload process to handle large files.
If you use Reflactor and you dissamble the HttpRequest under System.Web, you will find a method called GetEntireRawContent which will check if the request is larger than the value in the web.config and throws an error

if (length > maxRequestLengthBytes)
{
throw new HttpException(SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}


In this article, Haissam Abdul Malak will demonstrate how to upload large files in ASP.NET without the need to modify the value of maxRequestLength attribute of the httpRuntime tag in the web.config.

We will create an HttpModule which will read the file in chunks (500KB per chunk).
We will handle the BeginRequest event and use the HttpWorkerRequest which provides more low level control for the request.
Below is the full implementation of the HttpModule. I included comments to enable you to fully understand each line of code.

I recommend connecting to msdn and read about HttpWorkerRequest class. Personally i didnt know about the existence of such class except lately.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);

}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;

if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
FileStream fs = null;
// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;

if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
string[] fileName = context.Request.QueryString["fileName"].Split(new char[] { '\\' });
fs = new FileStream(context.Server.MapPath("~/Uploads/" + fileName[fileName.Length-1]), FileMode.CreateNew);
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Write the chunks to the physical file
fs.Write(buffer, 0, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);

}
}
fs.Flush();
fs.Close();
context.Response.Redirect("UploadFinished.aspx");
}

}
public void Dispose()
{
}
}
}


To know the file name selected by the user, I had to use javascript function on the page containing the fileupload control to change the action property of the form tag to post to the same page with a query

string parameter containing the selected file name. Users will be redirected to a page called "UploadFinished.aspx" to display a successful upload process message.

Below is the javascript function


And call it using

You need to register the module in the application web.config file by placing the below inside the tag.





Hope this helps,

Chunking Viewstate

One interresting feature a developer should know is the ability to chunk the viewstate field into multiple fields. Why you

need such feature? Some proxy servers and firewalls won't allow a request to be processed if a hidden fields' length is

large. To overcome this, You can set up in the web.config file for all the pages to have a maximum viewstate field.





The value of maxPageStateFieldLength is in Bytes.

In this way, if the hidden viewstate field is larger than 1 kb, ASP.NET will create multiple hidden viewstate field to hold

the data entered by the user before the postback. For example if the size of the data entered by the user is 2KB, the below

fields in the page once being rendered to HTML will be created





Keep in mind that this won't improve the application performance. It will add more steps to serialize the data back before

being sent to the client.

Hope this helps,

Redirect to Error Page When Maximum Request Length is Exceeded [FileUpload]

How many times you tried to catch the maximum request length error thrown by the FileUplad control if the web.config HttpRuntime entry is not modified?
In this blog post, Haissam Abdul Malak will create an HttpModule which check if the file is larger than 4 MB to redirect the user to a webform "Error.aspx".
The module will register to the BeginRequest event to execute the needed code


Below is the implementation

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;


namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);

}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;

if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;

if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);

}
}
// Redirect the user to an error page.
context.Response.Redirect("Error.aspx");
}

}
public void Dispose()
{
}
}
}

Now all you need to do is to add the module in the web.config file by adding the below entry under system.Web





Hope this helps,

Paging Records Using SQL Server 2005 Database - ROW_NUMBER Function

SQL Server 2005 has a ROW_NUMBER Function that can help with paging records for you database applications. ROW_NUMBER returns a sequential number, starting at 1, for each row returned in a resultset.

If I want the first page of 10 records from my log file sorted by Date DESC, I can use the ROW_NUMBER FUNCTION as follows:



SELECT Description, Date
FROM (SELECT ROW_NUMBER() OVER (ORDER BY Date DESC)
AS Row, Description, Date FROM LOG)
AS LogWithRowNumbers
WHERE Row >= 1 AND Row <= 10



The second page of 10 records would then be as follows:



SELECT Description, Date
FROM (SELECT ROW_NUMBER() OVER (ORDER BY Date DESC)
AS Row, Description, Date FROM LOG)
AS LogWithRowNumbers
WHERE Row >= 11 AND Row <= 20



If you have a lot of records, using TOP X in the inner SELECT clause may speed up things a bit as there is no use returning 1000 records if you are only going to grab records 11 through 20:



SELECT Description, Date
FROM (SELECT TOP 20 ROW_NUMBER() OVER (ORDER BY Date DESC)
AS Row, Description, Date FROM LOG)
AS LogWithRowNumbers
WHERE Row >= 11 AND Row <= 20



We can rap this up in a Stored Procedure as follows:



CREATE PROCEDURE dbo.ShowLog
@PageIndex INT,
@PageSize INT
AS

BEGIN

WITH LogEntries AS (
SELECT ROW_NUMBER() OVER (ORDER BY Date DESC)
AS Row, Date, Description
FROM LOG)

SELECT Date, Description
FROM LogEntries
WHERE Row between

(@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize


END



It is only available in SQL Server 2005, but it is a heck of a lot easier and more intuitive than creating temp tables and using other stored procedures that I have used in the past. However, if you want to target your application for SQL Server 2000 use, I would stick with a record paging solution that works for both SQL Server 2005 and SQL Server 2000 Databases.

Disable Session Expiration when using Directory.Delete()

As you may already know, one of the reasons why the asp.net worker process recycles which kills all the session variables in memory is due to dynamically deleting a folder under the root application folder. You have two options to follow in this case

1- To use out-of-process mode session
2- To use the below code which uses reflection to disable monitoring for the folders inside the application. In this way, once you delete a folder, the Application domain won't restart thus you won't be losing any session variable

PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
object o = p.GetValue(null, null);
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
object monitor = f.GetValue(o);
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
m.Invoke(monitor, new object[] { });

Do not forget to import System.Reflection Namespace

Hope this helps,

How to Identify the browser using java script (for IE/Safari/Firefox)

/**
* @returns A string which specifies which is the current
* browser in which we are running.
*
* Currently-supported browser detection and codes:
* * 'opera' -- Opera
* * 'msie' -- Internet Explorer
* * 'safari' -- Safari
* * 'firefox' -- FireFox
* * 'mozilla' -- Mozilla
*
* If we are unable to property identify the browser, we
* return an empty string.
*
* @type String
*/
OpenLayers.Util.getBrowserName = function() {
var browserName = "";

var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf( "opera" ) != -1 ) {
browserName = "opera";
} else if ( ua.indexOf( "msie" ) != -1 ) {
browserName = "msie";
} else if ( ua.indexOf( "safari" ) != -1 ) {
browserName = "safari";
} else if ( ua.indexOf( "mozilla" ) != -1 ) {
if ( ua.indexOf( "firefox" ) != -1 ) {
browserName = "firefox";
} else {
browserName = "mozilla";
}
}

return browserName;
};

nidhi

Date:: Jun 14, 2007

Time:: 17:42


For info only, this is old skool, useful really only if you wanted to check for IE

Before it was possible to use appName, but both Mozilla and Safari both return Netscape which is why you cant really use it now.

the navigator object is a throwback from Netscape Navigator days I believe hence the use of that keyword.

simple test I used. This is for information only, it is not something you should be using. As I said before, only handy if you want to check for MSIE only.







Yo

Tuesday, 29 June 2010

Ways to Pass Data Between Webforms!

In this blog post, i will be showing different ways to pass data between webforms. Different techniques could be implemented, it all depends on what serves you most! We all know that Http is stateless, so data should be stored somewhere in order to be able to retrieve it.

1- Query String
2- Cookies
3- Session variables
4- Cross Page Posting
5- Submit form
6- Server.Transfer or Server.Execute

We will talk in details about each one and which kind of data it could store.

1- Querystrings: Using Query string variables, you can pass data between webforms. below is an example

Ex: Suppose you want to pass the TextBox1.Text variable from WebForm1 to WebForm2 on button click event.

protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm2.aspx?id=" + TextBox1.Text);
}

To Read the value of "id" in WebForm2, you should use the below code
string queryStringID = Request.QueryString["id"];

Now queryStringID will hold the data from the querystring.


2- Cookies: AS you might already know, cookies are small text files stored in the client machine. Cookies can only store up to approximately 4 kbs.
Once the cookie is stored into the client machine, each request from the client to your application, the web browser will look for the cookie and send it via the Request Object.

Ex: To store a value of TextBox1.Text inside the cookie use the below code

protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = TextBox1.Text;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Response.Redirect("WebForm2.aspx");
}
Now in webform2 page_load event, you should write the below code to get the value

if(Request.Cookies["UserName"] != null)
Response.Write(Request.Cookies["UserName"].Value);

3- Session Variables: By default, session variables are stored in the webserver's memory. Session variables are unique per each user.

Ex: To store a value inside a session variable use the below code

protected void Button1_Click(object sender, EventArgs e)
{
Session["UserName"] = TextBox1.Text;
Response.Redirect("WebForm2.aspx");
}

To retrieve the value from WebForm2 use the below code

Response.Write(Session["UserName"]);

4- Cross Page Posting (ASP.NET 2.0): Cross page posting was introduced in ASP.NET 2.0. I already have a blog post about it.

Ex: The same example is taken from my previous blog post

Set the Button1 PostBackUrl property to WebForm2.aspx

Now in WebForm2.aspx, Write the below code to get the value of textbox1

TextBox txtFirstPage = (TextBox)(PreviousPage.FindControl("TextBox1"));
Response.Write(String.Format("You wrote {0} in Page1",txtFirstPage.Text));

5- Submit Form: You can submit the form in Webform1.aspx to webform2.aspx. In that case, you can retrieve all the WebForm1's form element from webform2. What we will do in the below example is to add another form ( not a server side one) which will have two HTML controls; the first is an
submit control the second is a hidden field which will have the value of TextBox1 web server control to be posted to webform2

Ex: now the HTML code of webform1 will look like below




name="SubmittedForm" action="WebForm2.aspx" method="post">
onclick="CopyTextToHiddenField()" />



Of course you realized the we handled the onclick event of the submit button which will call a javascript function to copy the value of TextBox1 into the hidden field (Hidden1) in order to post it to webform2. Also you so in the second form tag the action attribute in which we specified to which page the second form (SubmittedForm) will be posted.

Add the below javascript code inside the tag of WebForm1



Now you retrieve the value of "Hidden1" hidden field in webform 2 using the below code

Response.Write(Request.Form["Hidden1"]);

6- Server.Transfer & Server.Execute: These two functions take 2 parameters; the first is the webform name to which you want to redirec the user the second is a bool parameter to specify if you want the form to be reserved.

Ex:
protected void Button1_Click1(object sender, EventArgs e)
{
Server.Transfer("WebForm2.aspx", true);
}


Now in webform2 page_load event use the below code to get the value of TextBox1

Response.Write(Request.Form["TextBox1"]);
Same Code for Server.Execute..

Hope this Helps