Sunday, August 28, 2011

Textual description of firstImageUrl

FileUpload Control File Type and File Size Validations

Normally we need validation to restrict the user for uploading any kind of files on a Web Server due to security or application requirement also we need to limit the file size to upload on web server.There are many ways to implement validation on file upload control its depend upon application requirement which method you can used .Here I will explain only three validation method you can implement on file upload controls.
 

Upload Control

Validation using Custom Validator on Client Side

You can used custom validator to implement fileupload validation on client side.This validation is faster and easy to implement.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">

<script language="javascript" type="text/javascript">
function ValidateAttachment(Source, args)
{
var UploadControl = document.getElementById('<%= UploadControl.ClientID %>');

var FilePath = UploadControl.value;

if(FilePath =='')
{
args.IsValid = false;//No file found
}
else
{
var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();

if (Extension == "doc" || Extension == "txt")
{
args.IsValid = true; // Valid file type
}
else
{
args.IsValid = false; // Not valid file type
}
}
}


</script>

<div>
<asp:FileUpload ID="UploadControl" runat="server" />
&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" style="height: 26px" />
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateAttachment"
ErrorMessage="Please select valid .doc or .txt file"
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:Label runat="server" ID="StatusLabel" Text="Upload status: " />

</div>
</form>
</body>
</html>

Validation using Custom Validator on Server Side


You can also apply validation on server using custom validator its slower than client side but its more secure than client side.

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{

string UploadFileName = UploadControl.PostedFile.FileName;

if (string.IsNullOrEmpty(UploadFileName))
{
args.IsValid = false;
}
else
{
string Extension = UploadFileName.Substring(UploadFileName.LastIndexOf('.') + 1).ToLower();

if (Extension == "doc" || Extension == "txt")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
args.IsValid = true;

}
else
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "File size should be less than 100 kb";
}
}
else
{
args.IsValid = false; // Not valid file type
CustomValidator1.ErrorMessage = "File Type should be .doc or .txt";
}
}



}

By default, the maximum size of a file to be uploaded to the server using the FileUpload control is around 4MB. You cannot upload anything that is larger than this limit.




Change File Upload Limit


In the web.config file, find a node called <httpRuntime> that looks like the following:

<httpRuntime 
executionTimeout="110"
maxRequestLength="4096"
requestLengthDiskThreshold="80"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="5000"
enableKernelOutputCache="true"
enableVersionHeader="true"
requireRootedSaveAsPath="true"
enable="true"
shutdownTimeout="90"
delayNotificationTimeout="5"
waitChangeNotification="0"
maxWaitChangeNotification="0"
enableHeaderChecking="true"
sendCacheControlHeader="true"
apartmentThreading="false" />



lot is going on in this single node, but the setting that takes care of the size of the files to be uploaded is the maxRequestLength attribute. By default, this is set to 4096 kilobytes (KB). Simply change this value to increase the size of the files that you can upload to the server. If you want to allow 10 megabyte (MB) files to be uploaded to the server, set the maxRequestLength value to 11264, meaning that the application allows files that are up to 11000 KB to be uploaded to the server.


for futher detail check this Working Around File Size Limitations.


Direct Validation on Upload Button


In this method you don’t need to used custom validator you can directly write the code on button click and manually show message using label control.



 protected void btnUpload_Click(object sender, EventArgs e)
{

if (UploadControl.HasFile)
{
try
{
if (UploadControl.PostedFile.ContentType == "image/jpeg")
{
if (UploadControl.PostedFile.ContentLength < 102400)
{
string filename = Path.GetFileName(UploadControl.FileName);
UploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
else
StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
}
else
StatusLabel.Text = "Upload status: Only .doc or .txt files are accepted!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}

}

Wednesday, August 17, 2011

Dynamic Load or Add User Control and Maintain the View State

In this post I will explain you how to add or load user control in a page or any other user control and maintain the view state.Normally we are facing problem when we load user control on button click or any business condition in this case when page will post back control will lost its view state or in other words losing form field values on post back.This is happen because we are adding user control after page Load View State Stage for further detail you should learn asp.net page lifecycle.That means, if we want our dynamic controls to persist view state itself we must add them to the control hierarchy in the page's Init event.

Here, I will explain the example when we want to add user control on any event.I have two user controls one is Grid view and second I will take login control and load on it into two submit buttons.
 
Adding Reference or Directive on a Webpage
 
The first thing we have to do, is declare our UserControls. It can be done either in each page where it's used, or globally in the web.config file. There is no performance difference, but when declaring UserControls in the web.config file, the controls have to reside in a different directory than the page(s) using it for further detail check my pervious post Register Custom User Control in Web.Config File

So in the webform, add the following directive:

<%@ Register src="Controls/GridView.ascx" tagname="GridView" tagprefix="uc1" %>

<%@ Register src="Controls/LoginControl.ascx" tagname="LoginControl" tagprefix="uc2" %>

Loading dynamically

For loading user control on a page you should need to drag and drop the place holder where you want to show user control.

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Also add the two buttons to add user control on button click .
<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
your aspx page look like this,

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="Controls/GridView.ascx" TagName="GridView" TagPrefix="uc1" %>
<%@ Register Src="Controls/LoginControl.ascx" TagName="LoginControl" TagPrefix="uc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

<asp:Button ID="btnGrindControl" runat="server" Text="Button" />
<asp:Button ID="btnLoginControl" runat="server" Text="Button" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

</asp:Content>



Code Behind

In the Code Behind of the page, we add the control like this:
PlaceHolder1.Controls.Add(LoadControl("~/UserControl.ascx"));


In order to maintain the Viewstate of user control you should maintain the UserControl complete path and used this path every time on postback and load the control.

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

public partial class _Default : System.Web.UI.Page
{
public string ControlPath
{
get
{
if (ViewState["controlPath"] != null)
return Convert.ToString(ViewState["controlPath"]);
else
return null;
}

set
{
ViewState["controlPath"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();

}
private void LoadUserControl()
{
if (!string.IsNullOrEmpty(ControlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(ControlPath);
PlaceHolder1.Controls.Add(uc);
}
}



protected void btnGrindControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/GridView.ascx";
LoadUserControl();
}
protected void btnLoginControl_Click(object sender, EventArgs e)
{
ControlPath = "Controls/LoginControl.ascx";
LoadUserControl();
}
}


In above example I create one property name “ControlPath” for maintaining the Url of user control on button click .In LoadUserContol() I am just clearing the placeholder and adding the user control.In postback user control is adding everytime beacuse  user control was added after the page load and view state stage .There are few good articles written by Scott Mitchell on dynamically loading Controls which you will find in the following links:


Conclusion

In this article we saw how to work with dynamic controls so that their values and view state can be correctly persisted across postbacks.

Wednesday, August 3, 2011

Debugging Asp.net application using XML Serialization

 

Debugging on Test or Production server is very difficult task for developers.First of all developers do not have any rights to touch the Test or Production environment and he received the list of bugs mainly due to data problem on production or Test Server.When developers try to reproduce the bugs on development environment is not possible because data development environment is accurate.So I have found out the solution of this problem through XML Serialization techniques which describe as below:-

In this article I am taking a example of simple Employee Detail.I will explain how we can debug using XML Serialize data.

Example

First I have declare a Employee class and create one method for creating employee details.

public class Employee
{
public string EmployeeName { get; set; }
public string Address { get; set; }
public int MobilNo { get; set; }


public List<Employee> GetEmployees()
{
List<Employee> Emplst = new List<Employee>();

for (int i = 0; i < 5; i++)
{
Employee emp = new Employee();
emp.EmployeeName = "Employee" + "-" + i.ToString();
emp.Address = "Address" + "-" + i.ToString();
emp.MobilNo = 9899 + (i + 2);
Emplst.Add(emp);
}
return Emplst;
}

}



 



Now create one page and call the GetEmployee() Method and fill the grid.



 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp= new Employee();

GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
}





Scenario 1



It is very simple code to populate grid from GetEmployees() method but you assume that data is coming from the database and populating the grid and at this time you are facing problem .Now you can track or debug the application with XML Serialization.



protected void Page_Load(object sender, EventArgs e)
{
Employee objEmp = new Employee();

SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
GridView1.DataSource = ReadXMLData<Employee>("Employee.XML");
GridView1.DataBind();
}


#region For Serialization Code

public void SaveXMLData<T>(List<T> list, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<T>));
{
TextWriter writer = new StreamWriter(Server.MapPath("~\\XMLFiles") + "\\" + fileName);
serializer.Serialize(writer, list);
writer.Close();

}
}

public List<T> ReadXMLData<T>(string filename)
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<T>));
TextReader textReader = new StreamReader(Server.MapPath("~\\XMLFiles") + "\\" + filename);
List<T> list;
list = (List<T>)deserializer.Deserialize(textReader);
textReader.Close();

return list;
}

#endregion
}


If you see the code on page load I have save the data first into XML and then retrieve and display into the grid due to this every time save data into XML So if  you find any problem in module you will get the XML file from Production or Test Server and Load into development environment through ReadXMLData() method and debug it.



Here is the XML Generate file from the above SaveXMLData() method.



<?xml version="1.0" encoding="utf-8" ?> 
- <ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <Employee>
<EmployeeName>Employee-0</EmployeeName>
<Address>Address-0</Address>
<MobilNo>9901</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-1</EmployeeName>
<Address>Address-1</Address>
<MobilNo>9902</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-2</EmployeeName>
<Address>Address-2</Address>
<MobilNo>9903</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-3</EmployeeName>
<Address>Address-3</Address>
<MobilNo>9904</MobilNo>
</Employee>
- <Employee>
<EmployeeName>Employee-4</EmployeeName>
<Address>Address-4</Address>
<MobilNo>9905</MobilNo>
</Employee>
</ArrayOfEmployee>




Scenario 2



If you are thinking for every time save and read data from XML then application performance will affected so you can change the code like this only when exception will raise it will save the data into xml and then if you want to debug write ReadXMLData() method in a code where you want.



protected void Page_Load(object sender, EventArgs e)
{
try
{
Employee objEmp = new Employee();
GridView1.DataSource = objEmp.GetEmployees();
GridView1.DataBind();
}
catch (Exception ex)
{
SaveXMLData(objEmp.GetEmployees(), "Employee.XML");
throw;
}

}



Conclusion






We have seen in above samples that how we can take advantage of serialization mechanism provided by .Net. In this tutorial I have tried to keep things as simple as possible so you can understand and using the basic concepts of XML serialization for debugging the application. Feel free to share your comments.

PDF Arabic watermark using MVC and iTextSharp

PDF full page Arabic watermark using MVC and iTextSharp Download :  Source Code Most of the time we have requirement to  gen...