Monday, January 13, 2014

Return Json Data to Ajax Success call in asp.net

In asp.net, there are many ways to return Json data to your Ajax Success Method. One of them is as follows:

Create a static class as ExtensionClass:

using System.Web.Script.Serialization;
namespace Extensions
{
        public static string ToJson(this object obj)
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJson(this object obj, int recursionDepth)
        {
            var serializer = new JavaScriptSerializer {RecursionLimit = recursionDepth};
            return serializer.Serialize(obj);
        }
}

Make sure you use the namespace System.Web.Script.Serialization to use the JavaScriptSerializer() as above.

Now, to make use of the above statement in return web method. Use the following:

Class having properties:

public class JsonData
{
       public string Id{get;set;}
       public string Name{get;set;}
       public string Status{get;set;}
}

Test.aspx.cs Web Page:
[System.Web.Services.WebMethod]
public static string ShowInfo()
{
     //Your Set of Statements
    var jsonData = new JsonData
                                               {
                                                   Id = "1",
                                                   Name = "Amit Jain",
                                                   Status = "Ok"
                                               };
    return jsonData.ToJson();
}


Jquery Ajax Call:
<script type='text/javascript'>
function testMethod()
{
     $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "Test.aspx/ShowInfo",
                    dataType: "json",
                    data: "",
                    success:
                    function (Result) {                              //Success Method
                        if (Result != '') {
                            var jSonData = JSON.parse(Result.d);
                             alert(jSonData.Name);
                        }
                    },
                    error:
                    function (XMLHttpRequest, textStatus, errorThrown) {
                    }
                });
}
</script>


I hope this helps.

Thanks
Amit Jain

Thursday, January 2, 2014

Set the First Day of the week in Sql

By Default, the first day of the week is set as Sunday. Now to change it to Monday. Enter the following command before your Sql Query:

Set DateFirst 1

Now It sets the first day of the week as Monday.

Cheers !

Friday, December 27, 2013

Jquery Ajax Call in Asp.Net

 <div id="Result">Click here</div>
<script type="text/javascript">
    $('#Result').click(function() {
      $.ajax({
        type: "POST",
        url: "Default.aspx/HelloWorld",
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function(msg) {
          // Replace the div's content with the page method's return.
          $("#Result").text(msg.d);
        }
      });
    });
  </script>

Phone Number Validation Class using IDictionary

Class:
public class PhoneValidator {
static IDictionary<string, Regex> countryRegex = new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")},
{ "UK", new Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")},
};
public static bool IsValidNumber(string phoneNumber, string country) {
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}
public static IEnumerable<string> Countries {
get {
return countryRegex.Keys;
}
}
}
Calling:
if (!PhoneValidator.IsValidNumber("+1-1234-232-232", "USA"))
      Console.Writeline('Enter Valid Phone Number');

 

Tuesday, December 24, 2013

C#: Get Hours, Minutes, seconds from total Minutes using TimeSpan

var ts = TimeSpan.FromMinutes(intMinutes);
var message = string.Format("Hours: {0}, Minutes: {1}, Seconds: {2}", ts.Hours, ts.Minutes, ts.Seconds);

Console.WriteLine(message);

Copy a table into new table with/without data conditionally / unconditionally - SQL Server

1. Copy only the structure of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable WHERE 1=2

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable).


2. Copy the structure plus all the data of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable) as well as data.


3.  Copy only the data of an existing table into an existing table in other DB:
INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable

The above query will copy all the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable).

4.  Copy only the data of an existing table into an existing table in other DB on the basis of some condition:
 INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable Where id > 50

The above query will copy the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable) having id of source table(tblSourceExistingTable) greater than 50. So, Lets say, there are 100 records in source table from id 1 to 100, then it will copy only 50 records to destination table.




Tuesday, December 3, 2013

Calculate the dates of previous, current and next month

--SQL Server 2005/2008/2012
DECLARE @DATE DATETIME
 
Select @DATE = GetDate()
 
--First date of the Previous Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE)-1,0),120) AS [Previous Month]
 
--First date of the Current Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE),0),120) AS [Current Month]
 
--First date of the Next Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE)+1,0),120) AS [Next Month]
 
Previous Month
--------------
2013-11-01
 
(1 row(s) affected)
 
Current Month
-------------
2013-12-01
 
(1 row(s) affected)
 
Next Month
----------
2014-01-01
 
(1 row(s) affected)