Saturday, 27 August 2011

Upload file using ajax file uploader

/*In this article you will learn how to upload file using ajax file uploader javascript library in json.This is very simple and easy to use this script file. You only need to add reference script libray into your aspx page.*/
//below is the aspx code for uploading files.





//Add reference for ajax file upload library. 



//Create Handler to save file  and write below code inside Process Request
public void ProcessRequest (HttpContext context) {
        try
        {
            string Attachment = "";
            string attachmentPath = "";            
            context.Response.ContentType = "text/plain";
            context.Response.Expires = -1;
            string pathToSave = context.Server.MapPath(@"~\FolderPath\");
            string fileName = string.Empty;
            string fextention = string.Empty;

                foreach (string f in context.Request.Files.AllKeys)
                {
                    HttpPostedFile file = context.Request.Files[f];
                    if (!String.IsNullOrEmpty(file.FileName))
                    {

                        Attachment = file.FileName;
                        Attachment = Attachment.Replace(" ", "");
                        Attachment = Attachment.Replace("'", "");
                        
                        Attachment = pathToSave + Attachment;
                          
                        
                        file.SaveAs(Attachment);

                    }

                }
            

        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }

Sending class object in json request

below article describes that how to send an object in json request Instead of list of parameters.

below is the aspx page code for input fields.
Emp ID
Emp Name



below is the java script function to get form values.
Function baigFunc() {                    
            var _X = {};

Note: below "EmpId" and "EmpName" are class Properties. 
Get all values you required and add them in array.
send array object in json request.

            _X["EmpId"] = $("input[id$='txtEmpID']").val(); 
            _X["EmpName"] = $("input[id$='txtEmpName']").val();
            var request = "{'obj':" + JSON.stringify(_X) + "}";

            $.ajax({
                type: "POST",
                url: "pageName.aspx/TestFunc",
                data: request,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: callSucess
            });
        }
        function callSucess() {
            alert('Sucessfull');
        }
below is the code for serverside.

[WebMethod]
    public static void TestFunc(BaigClass obj)
    {     
        var empId = obj.EmpId; 
        var empName = obj.EmpName;
    }
Below is the class for getting values
public class BaigClass
{
    public string EmpId { get; set; }
    public string EmpName { get; set; }
} 


this is the best solution for sending values on server side when you have many input fields on form because this will take so much time to define variables and sending them in jSon request.

Converting Datatable into List

attend.getData(); //function call to get record in dataset

var l = (from x in _attend.AttendanceDS.Tables["EmpAttendanceSummary"].AsEnumerable()
  select new AttendanceSummary
  {
      EmpId = x.Field("EMPLOYEE_ID"),
      TotalHours = String.IsNullOrEmpty(x.Field("TotalWorkingHours")) 
      ? 0 :Convert.ToInt64(x.Field("TotalWorkingHours")),
      Department = x.Field("department_id"),
      Designation = x.Field("designation_id"),
      }).ToList();

//now you can get values from list by class object

AttendanceSummary _o = new AttendanceSummary();

       _o. HighestHours = l.Max(p => p.TotalHours);
       _o. DepartmentHighestHours = l.Where(p => p.TotalHours > 0 && 
       p.Department == int.Parse(5001)).Max(p => p.TotalHours);
      
       return _o;

public class AttendanceSummary
{
  public Int64 EmpId { get; set; }
  public Int64 TotalHours { get; set; }
  public int Department { get; set; }
  public int Designation { get; set; }
  public long HighestHours { get; set; }
  public long DepartmentHighestHours { get; set; }
 }

Regular expression for validating numbers

Only Digits:

unsigned (positive) whole number.

1): Any size or pattern using a set
function testExp(str) {
 var exp=/^ *[0-9]+ *$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }

2): 3 to 5 digits.

function testExp(str) {
 var exp=/^\d{3,5}$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }


The first regular expression allows one or more characters in the set [0-9] preceded or followed by any number of spaces within the length of the string. A number with leading and trailing spaces can be considered valid because conversion to numeric data will ignore the spaces.

if you dont want to allow spaces then use this
/^[0-9]*$/;

The second regular expression with the addition of {3,5} that restricts the data to only 3 to 5 digits.

signed integer:
 
1): Any size or pattern using a set
function testExp(str) {
 var exp=/^[-+]?[0-9]+$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }

2): An optional sign and 3 to 5 digits
function testExp(str) {
 var exp=/^[-+]?\d{3,5}$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }

Decimal or Float:
 
1): Any size or pattern using a set

function testExp(str) {
 var exp=/^[-+]?[0-9]+(\.[0-9]+)?$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }

2): Limited number of whole digits and decimals

function testExp(str) {
 var exp=/^[-+]?\d{3,5}(\.\d{1,3})?$/;
    if (exp.test(str)) {
                alert('valid');
            }
   }

Friday, 26 August 2011

Regular expression for phone number

this article show that how to validate phone number using regular expression.

Exp 1:

/^\d{3,4}-\d{7}$/;

In this expression "d" means only numeric values and "{3,4}" means 3 or 4 digits allowed at start of string before dash(-) and after dash(-) 7 digits required.

Exp 2:

/^\d{4}-\d{7}$/;

In this expression "d{4}" means 4 digits allowed at start of string before dash(-) and after dash(-) 7 digits required.

you can match these expressions with your input string like this.

function testContactNo(regExp,str)
{
     if ((str.search(regExp))) {
     alert('invalied number');
     }
}



Monday, 15 August 2011

Bind Dropdown using Jquery

In this article you will learn how to bind dropdown list using jquery. Suppose you want to show all employees name with their employee Id in dropdown list, then use this code.



//Function to call web method for getting Names

function GetName() {
$.ajax({
type: "POST",
url: "Emp_Name.aspx/GetEmpName",
data:"" ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onGetData_Received,
error: onGetDataError
});

}

function onGetDataError(xmlHttpObj) {

var error = eval("(" + xmlHttpObj.responseText + ")");
alert(error.Message);
}

function onGetData_Received(data) {
data = data.d;
$("#EmployeeName").append($("").val("0").html("----Select----"));

for (var i = 0; i < data.length; i++) {
$("#EmployeeName").append($("").val(data[i].employeeID).html(data[i].employeeName));

 }
}


//Web method to get list of employees names 
[WebMethod]

public static List GetEmpName()
{

BussName obj = new BussName ();
return obj.GetNames();
}

Export into Excel from gridview

In this article you will learn how to export data from gridview into excel in asp.net c#.

on of my friend told me that he facing problem to export data from gridview into excel when he is using updatepanel, then i feel to write this code.

// write this code in our export button click event 

protected void export_click(object sender, EventArgs e){

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
this.ClearControls(GridViewName);
GridViewName.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

}


//Also add this function to clear the controls 
private void ClearControls(Control ctrl)
{
for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
{
ClearControls(ctrl.Controls[i]);
}

if (!(ctrl is TableCell))
{
if (ctrl.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
ctrl.Parent.Controls.Add(literal);
try
{
literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
}

catch
{
}
ctrl.Parent.Controls.Remove(ctrl);
}

else if (ctrl.GetType().GetProperty("Text") != null)
{
if (ctrl.Visible == true)
{
LiteralControl literal = new LiteralControl();
ctrl.Parent.Controls.Add(literal);
literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
ctrl.Parent.Controls.Remove(ctrl);

}
}
}
return;

}

public override void VerifyRenderingInServerForm(Control control)
{

}

Redirect page from Iframe

In this article you will learn how to redirect page from iframe in asp.net. If you want to redirect page out side of iframe then just copy this code.
ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://PageName.aspx';}", true);

Import Data From Excel Into Gridview

In this tutorial you will learn how to import data from excel into gridview in asp.net. you can easily use this code in your page and can get desired functionality.

/*Here is the aspx code in which you have asp.net file uploader and a button to perform import functionality.*/


























/* If your code is placed on server then first you need to save file in a folder and then get record from that file.*/

protected void btnImport_Click(object sender, EventArgs e)
{
string path = uploadExel.FileName;
uploadExel.SaveAs(Server.MapPath("~/Folder Name/" + path));// Save file on server

//if using office 2003 or lower then use below connection string

string connString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0";

//if using office 2007 or later then use below connection string
string connString=@" Provider=Microsoft.ACE.OLEDB.12.0;
Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(connString);  

oconn.Open();                        
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", conn);
/* Here sheet1 is the name of sheet in from where you have data.*/
DataSet ds = new DataSet();
OleDbDataAdapter dapt = new OleDbDataAdapter(cmd);
dapt.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
oconn.Close();            
}

How to import data from excel into Sql server

In this tutorial you will learn how to import data from excel into database (Sql server).
//Here is aspx code




//Here is aspx.cs code
string path = uploadExel.FileName;//Here you will get file from asp uploader
uploadExel.SaveAs(Server.MapPath("~/Folder Name/" + path));//
//Here you nee to establish a connection with excel file
//if your code is running locally then use only file name instead of 'server.mapPaht' 

OleDbConnection conn = newOleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Server.MapPath(path)+";Extended Properties=Excel 8.0");                
oconn.Open();                        

//Here sheet1 is the sheet name in your excel file from which you will get data
OleDbCommand cmd = newOleDbCommand("select * from [Sheet1$]", conn);
OleDbDataReader dr = cmd.ExecuteReader();
string id = "";
string service = "";
string name= "";
while (dr.Read())
{
id = valid(dr, 0);//valid is function created for checking empty values.
service = valid(dr, 1);
name = valid(dr, 2);
//Now save your data into sql server.
_obj.saveData(id, service, name);

}

oconn.Close();            

//Valid Function to check empty values
protectedstring valid(OleDbDataReader reader, int val)//if any columns are      
{       

//if found null then they are replaced by zero
object val = reader[val];
if (val != DBNull.Value)
return val.ToString();
else
returnConvert.ToString(0);

}