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