Pages

Tuesday, July 6, 2010

Huge File Uploads in ASP.NET

After a month and half, bosome time to keep this going.

There was an issue happening repeatedly, when we were trying to upload an image file with size 5MB through an File Upload Control in ASP.NET application.

Uploading a large file with File Upload Control gets tricky. The maximum default size is limited to 4MB by .NET framework, since some attackers may find this easier to upload large files which inturn consume huge server resources.

Increasing the Maximum Upload Size

The 4MB default is set in machine.config.

<system.web>
<httpRuntime executionTimeout="110" maxRequestLength="20000" />
</system.web>

But you can override it in you web.config. For example, to expand the upload limit to 20MB, you'd do this:

<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>

Hope this solution might help to solve your problems. Please pass in your valuable feedbacks or doubts here.

Monday, May 3, 2010

Select Multiple Table Columns with JOINS

In one of our project(a kind of ETL project), there was a requirement to map the a single table columns with multiple table column. I searched in many forums and finally from MSDN learned a new implementation using Joins.

Here we go:

These are the three tables and their columns.

MasterTable:
ID
Name
Value
Area
State
County
CreatedDate
ModifiedDate

State:
ID
StateCode
State
CreatedDate
ModifiedDate

Area:
ID
AreaCode
Area
CreatedDate
ModifiedDate

The Area and State tables are like KeyValue pair tables, in which the AreaCode and StateCode represents the integer value for corresponding string values. The requirement is to create a View for MasterTable, in which the Area should be matched with AreaCode, and State to be matched with StateCode.

Code Snippet:

CREATE VIEW [dbo].[vMaster]
AS
SELECT m.ID,
m.Name,
m.Value,
a.AreaCode,
s.StateCode,
m.County,
m.CreatedDate,
m.ModifiedDate

FROM MasterTable m LEFT JOIN Area a
ON a.Area = m.Area LEFT JOIN State s
ON s.State = m.State

I think this might be useful. Don't feel shy to drop in your comments.

Happy coding. Have a good day.

Thursday, March 25, 2010

Copy Generic Collection List in DotNet

After a very long time I am learning something new. It doesn't mean that I was not experimenting new things, but I haven't learned something new in DotNet Programming for past 2 months. Quite a big time!!!!

Anyway Coming to the Collection List Addition,

I would like to explain you with the following collection object.

EG:
Product - Object which has properties (ProductID, ProductName, ProductDescription, DateSold, DaysOnMarket and e.t.c)

SoldProductList - Generic collection object of type Product
PendingProductList - Generic collection object of type Product
ActiveProductList - Generic collection object of type Product
TotalProductList - Generic collection object of type Product

The business logic is to add all the three SOLD, PENDING and ACTIVE list collections to a single collection TOTALPRODUCT list object.

Initially I had my code to loop through each items of the 3 Collection List and add it to the TotalProductList. I was very much sure there should be some other efficient way to make it. As I googled, I found a solution for it. I implemented the following and this helped me in drastically reducing my code and increased the performance of the application flow.

Code:
TotalProductList.getRange(ActiveProductList.ToArray());
TotalProductList.getRange(PendingProductList.ToArray());
TotalProductList.getRange(SoldProductList.ToArray());

Interesting Right!!! Well to fundamentally explain this, DotNet framework has as inbuilt method (getRange) for each collection to copy Array of elements of SAME TYPE. Here we are converting the ActiveProductList generic collection to an Array ( here the Array will be created of same type Product ) and then appending to TotalProductList collection which is also of same Product type.

I hope this helps you do better coding. Please let me know your thoughts and comments on this post.

Happy coding. Have a great time.

Tuesday, January 12, 2010

Importing data to SQL Server from Excel file

After a very long gap of a month and half, I had some space for me to write some technical blog.

This is all about exporting the Excel sheet to SQL Data source. You will need this in many instances to manipulate datas present in the sheet. These were the steps to be followed.

Step 1:

You have to check some basic configurations in your Surface Area Configuration of the SQL Server.

Please refer the following link to do these configurations:
http://www.kodyaz.com/articles/enable-Ad-Hoc-Distributed-Queries.aspx

Step 2:

Install Microsoft.ACE.OLEDB.12.0 component from this following link:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en


Step 3:


The DB script for importing datas from .xlsx(Excel) file to SQL Server 2005 is mentioned below.


Simple Importing:

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\TestExcel.xlsx', 'SELECT * FROM [Sheet1$]');


Importing Data to Table:

SELECT * INTO [dbo].[ExcelTempTable] FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\TestExcel.xlsx', 'SELECT * FROM [Sheet1$]');


Note: This doesn't mean that the [ExcelTempTable] should be predefined. Its a table created dynamic with the columns from Excel sheet.


This would suffice for exporting data from .xlsx file to SQL Server. Happy coding.









Tuesday, December 8, 2009

Application Level Error Handling in .NET

There were many chances for the occurrence of error in a .NET web application. We can easily fetch those errors and handle the users in a friendly way with the Global.asax file.

The event Application_Error in the Global.asax file deals with this. You can add this Global.asax file in the root of your web application. Inside that place the following code.

void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/CustomErrors/ErrorHandlingPage.aspx?error=" + Server.GetLastError().Message);
}

This code will fetch the last error occurred in the application and redirects to the ErrorHandlingPage.aspx. Here you can get the error message from the query string 'error'. This is how it works.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String ErrorMsg;
ErrorMsg = Request.QueryString["error"].ToString();
LitError.Text = "Sorry for the inconvenience caused. We regret the situation. Please try after some time. The following exception occured - " + ErrorMsg;
//The below line is for publishing the error to the Exception Log - Specific to the application
ExceptionManager.Publish(ErrorMsg);
}
}

Its upto you to decide, whether to show the message to the user or make in entry in the exception log and notify user with custom error message. Thats it.
Happy coding. Have a good day.

Monday, October 19, 2009

AJAX implementation using POST method in .NET

Here is where the real Ajax is implementation happens. In fact the .Net framework itself supports the partial page posting using Update Panel and etc. But what actually happens here is, the whole contents of the page goes to the server and comes back. Which is again a similar to a page postback. The only difference is the page events doesn't gets loaded again since its not a post back, but all the contents of the page goes to the server and then returns back.

The real implementation of the AJAX happens only with the JavaScript functions. Here you can really send the partial contents to the server and get back the desired results. There were two ways for the AJAX form posting.
1. GET method and
2. POST method.

Most people tend to go for the GET method since its easier to implement.(Particularly beginners). As you grow you have to be able to identify the instance where you are going to use(GET or POST method). In a simple way,

GET - should be used when a minimum amount of data is going to be passed to the server and collect all the information in a single AJAX call.

POST - when the request is going to be updated frequently and also the server data is going to be changed with the AJAX call then you have to go for POST. Also POST is secured compared to GET method since it doesn't expose the parameters(Query String values).

Here is the example where the POST implementation for simple Login.
EG:

Java script Function


function ajaxPOSTFunction(email,password)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
if(xmlhttp.responseText.match("success"))
{
window.location = '<%= ResolveClientUrl("../profile.aspx") %>';
}
else
{
document.getElementById("validateTips").innerHTML = xmlhttp.responseText;
}
}
}
}

//GET METHOD IMPLEMENTATION - Same implementation using GET - commented
//xmlhttp.open("GET","login.aspx?email=" + email + "&password=" + password,true);
//xmlhttp.send(null);


//POST METHOD IMPLEMENTATION
var params = "email="+email+"&password="+password;
xmlhttp.open("POST",'<%= ResolveClientUrl("../login.aspx") %>',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}

And here is the code for the login.aspx page - PageLoad() and Private method

Login.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim email As String = Request.Form("email")
Dim password As String = Request.Form("password")
AuthenticateUser(email, password)
Catch ex As Exception
Response.Write(ex.ToString())
End Try

End Sub

Public Sub AuthenticateUser(ByVal userName As String, ByVal password As String)
Dim ErrorBuilder As New StringBuilder
Dim responseStatus As Integer
Dim responseText As String = String.Empty

responseStatus = Me.Controller.AuthenticateUser(userName, password)
If responseStatus = Constants.ServiceResponseStatus.Success Then
responseText = "success"
End If

Select Case responseStatus

Case Constants.ServiceResponseStatus.Success

Response.Write(responseText)
Response.End()

Case Constants.ServiceResponseStatus.Failure
Response.Write("failure")
Response.End()

Case Constants.ServiceResponseStatus.Exception
Response.Write("There has been an internal error. Please try to login again!")
Response.End()

Case Else
Response.Write("The username or the password you provided was not a valid. Please login with valid username and password.")
Response.End()

End Select

End Sub

Wednesday, October 14, 2009

Printer Friendly Button in JS

I was so pleased with Javascript. In an printer friendly version page if you wanna a Print button which will direct you for printing, then this is the simplest way.

Here we go.

EG: In the anchor tag just call the javascript function window.print().

javascript:window.print();

Click on the Print this page link to check out.

Print this Page

Really small piece of code right..