Sunday, 18 December 2011

Get Query String from Javascript

In this tutorial you will se how to get query string values using javascript.
function getQueryString()  
{  
    var vars = [], hash;  
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');  
    for(var i = 0; i < hashes.length; i++)  
    {  
        hash = hashes[i].split('=');  
        vars.push(hash[0]);  
        vars[hash[0]] = hash[1];  
    }  
    return vars;  
}  
Let's suppose we have the following URL
http://www.mysite/home.aspx?id=1&name=test
Calling getQueryString() function would return you the following array:
{  
    "id"    : "1",  
    "name" : "test"  
}
To get the value of parameters you will do this.
var id= getQueryString()["id"];  
var name= getQueryString()["name"];  

Hope this tutorial will help you.

Convert in Uppercae and Lowercase using JavaScript

you can use builtIn javascript .toUpper() and .toLower() functions to convert string into upper or lower case.

var test="This is Test";

var test=test.toUpperCase();   

OutPut:

THIS IS TEST.


var test="This is Test";

var test=test.toLowerCase();   

OutPut:

this is test.

This is very simple and easy.

Different Date Time Conversion in SQL

In this tutorial i will explain different date time conversions avail in SQL.

Below are the list of the different date formats using CONVERT function. As you can that the output of these date formats are of VARCHAR data types, so if you have to compare any dates that are in varchar data type then again you have to convert them in datetime data type.

SELECT convert(varchar, getdate(), 100)  -- mon dd yyyy hh:mm 

Output:-
Sep 16 2011 5:55 PM 

SELECT convert(varchar, getdate(), 101)  --mm/dd/yyyy   

Output:-
09/16/2011 


SELECT convert(varchar, getdate(), 102)  --yyyy.mm.dd 


Output:-
2011.09.16


SELECT convert(varchar, getdate(), 106)  --dd mon yyyy 

Output:-
16 Sep 2011

SELECT convert(varchar, getdate(), 105)  --dd-mm-yyyy

Output:-
16-09-2011

SELECT convert(varchar, getdate(), 107)  --mon dd, yyyy 

Output:-
Sep 16, 2011


SELECT convert(varchar, getdate(), 103)  --dd/mm/yyyy  

Output:-
16/09/2011

SELECT convert(varchar, getdate(), 108)  --hh:mm:ss 

Output:-
17:57:08

Convert.ToString() and .ToString() Functions

The purpose of both Convert.ToString() and .ToString() is same but with a small difference.
The basic difference between them is .ToString() does not handle null value and will throw a NULL reference exception error while Convert.ToString() function handles null value. So always use Convert.ToString().

Thursday, 27 October 2011

Saturday, 15 October 2011

Regular expression for validating numbers

Only Digits:

below expression is for unsigned (positive) whole number.

1): Any size or pattern

function testExp(str) {
                    return /^ *[0-9]+ *$/.test(str);
                }

2): 3 to 5 digits.
function test3(str) {
                    return /^\d{3,5}$/.test(str);
                }
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. The metacharacters ^ and $ meaning beginning and end of string respectively excludes any characters other than specified in the pattern. A number with leading and trailing spaces can be considered valid because conversion to numeric data will ignore the spaces. However, it is a good idea to trim data before validating using alltrim covered previously.
The second pattern disallows leading and trailing spaces and is shorter because in uses the metacharacter \d for digits. If the data is trimmed before validating with an alltrim covered previously, data otherwise valid will pass this test.
The third regular expression is the same as the second with the addition of {3,5} that restricts the data to having 3 to 5 of the preceding character(s) in this case digits.
A signed integer: 
1): Any size; pattern using a set
function test1(str) {
                str = alltrim(str);
                return /^[-+]?[0-9]+$/.test(str);
            }

2): An optional sign and 3 to 5 digits
function test3(str) {
                str = alltrim(str);
                return /^[-+]?\d{3,5}$/.test(str);
            }

Decimal or Float 
1): Any size; pattern using a set
function test1(str) {
    str = alltrim(str);
    return /^[-+]?[0-9]+(\.[0-9]+)?$/.test(str);
}

2): Limited number of whole digits and decimals
function test3(str) {
    str = alltrim(str);
    return /^[-+]?\d{3,5}(\.\d{1,3})?$/.test(str);
}
The expressions again follow the pattern set forth in the previous examples. These differ only in the addition of test, (\.\d+) for a decimal point and decimals.

Thursday, 22 September 2011

Access both Old and New Task Managers on Windows 8

In this article i will tell you how to access both old and new Task Manager in Microsoft window 8.
Windows 8 Task Manager looks very good, but it’s too much for us to start using it right away after installing Windows 8 Developer Preview, do you know you can still access Windows 7 style task manager on Windows 8 by creating a shortcut, below are the steps to do that.





Shortcut for Old Task Manager on Windows 8
1. Right-click on the desktop and browse for New>Shortcut
2. Type “taskMGR” and click “Next” give it the name whatever you want like “old task manager” and click “Finish” button.
3. Now you can open old task manager by clicking the shortcut on the desktop.




Now without disabling New Task Manager, we can now use both Task Managers at the same time by using this shortcut.

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);

}