August 12, 2013

JSON (JavaScript Object Notation)

JSON is a syntax for storing and exchanging data.
JSON is an easier to use alternative to XML.
  • JSON is lightweight data interchange format
  • JSON is language independent because JSON uses JavaScript syntax, but the JSON format is text only, just like XML. Text can be read and used as a data format by any programming language.
  • JSON is "self-describing" and easy to understand
JSON Example
{  :[ ]}
A collection of name/value pairs.
XML

<?xml version="1.0" encoding="UTF-8" ?>
                <name>John</name>
                <age>30</age>
                <cars>Ford</cars>
                <cars>BMW</cars>
                <cars>Fiat</cars>

<?xml version="1.0" encoding="UTF-8" ?>
                <cars>Ford</cars>
                <cars>BMW</cars>
                <cars>Fiat</cars>
               
JSON Array
{
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
}


{"cars":[ "Ford", "BMW", "Fiat" ]}

<?xml version="1.0" encoding="UTF-8" ?>
                <employees>
                                <firstName>John</firstName>
                                <lastName>Doe</lastName>
                </employees>
                <employees>
                                <firstName>Anna</firstName>
                                <lastName>Smith</lastName>
                </employees>


<?xml version="1.0" encoding="UTF-8" ?>
                <type>Fiat</type>
                <model>500</model>
                <color>white</color>
JSON Object

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}
]}






{type:"Fiat", model:"500", color:"white"}

JavaScript Arrays
var cars = ["Ford", "BMW", "Fiat"];

 JavaScript Object

var car = {type:"Fiat", model:"500", color:"white"};


JSON is an easier to use alternative to XML.Similarity, instead of using a parser (like XML does), a JavaScript program can use standard

JavaScript functions to convert JSON data into native JavaScript objects.

<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

For AJAX applications, JSON is faster and easier than XML:


<head runat="server">
    <title></title>

    <script src="jquery-1.7.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        function ShowCurrentTime() {
            $.ajax({
                type: "POST",
                url: "Default3.aspx/GetCurrentTime",
                data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function(response) {
                    alert(response.d);
                }
            });
        }
        function OnSuccess(response) {
            alert(response.d);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        Your Name :
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
    </div>
    </form>
</body>

codebehind

[System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
    }

-------------------------------------------------------------------------------------------------------
Insert Data using JSON, ASP.NET Web services and jQuery
[WebMethod]
public string ReceiveUpdatesWebservice(string name,string email, string phone, string address) {
using (SqlConnection conn=new SqlConnection(conStr))
{
// Creating insert statement
string sql = string.Format(@"INSERT INTO [SampleTestDB].[dbo].[SampleInfoTable]
([Name]
,[Email]
,[Phone]
,[Address])
VALUES
('{0}'
,'{1}'
,'{2}'
,'{3}')",name,email,phone,address);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
conn.Open();
rowsInserted=cmd.ExecuteNonQuery();
conn.Close();
cmd = null;
}

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function CallService() {
// Creating variables to hold data from textboxes
var name = $('#_txtname').val();
var email = $('#_email').val();
var phone = $('#_phone').val();
var addr = $('#_addr').val();

$.ajax({
type: "POST",
url: "MultipleUpdateWebService.asmx/ReceiveUpdatesWebservice",
data: "{ 'name': '" + name + "','email': '" + email + "', 'phone': '" + phone + "','address':'" + addr + "'}",
contentType: "application/json",
async: false,
success: function(data) {
$('#message').text(data.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Name: <asp:TextBox ID="_txtname" runat="server"></asp:TextBox><br />
Email: <asp:TextBox ID="_email" runat="server"></asp:TextBox><br />
Phone: <asp:TextBox ID="_phone" runat="server"></asp:TextBox><br />
Address: <asp:TextBox ID="_addr" runat="server"></asp:TextBox><br />
<input id="_btnSubmit" type="button" value="Submit" onclick="CallService();" />
<span id="message">

</span>

</div>
</form>

August 8, 2013

pro and Cons of Loosely couple architecture

In our company,My manager always trying to make application loosely coupled architecture.
Let see the Pro and cons of this
Loose Coupling allows you to make changes in one area of the application without affecting the others. 
It definitely makes your applications more flexible, more adept at change, and easier to maintain (since you don't have to worry about a change in one area of the application breaking another).
  • Scalability - allow you to expand out a database access layer
  • Maintainability - just change the code in one place
  • more developer can work.Each one can take bunch of code.
Service Oriented Architecture (SOA) is loosely coupled architecture.

Cons
  • It's more work at the beginning, and if you don't do it well, you may never see the benefits of it.
  • Defining API is quite difficult and requires very experienced developers. It's easy to do initially, but its hard on the long run.
  • Generalization of loose coupling can in fact lead to loose typing everywhere. Instead of using clearly defined meaningful objects, you may observe an increase in the usage of 'object' parameters or return type, of generic types added to every class or interface. The bad effect of this is the average developer will probably add wild cast operations everywhere, assuming types on both sides of the so-called loosely coupled systems.
  • Some loose coupling techniques are based on the generalization of interfaces definition, with an intent to avoid direct dependency. 
  • Loose coupling somehow bypasses one of the most powerful tool ever created: the compiler (C# or others). And that's the whole purpose of it actually, but it definitely has some drawbacks because all the ground work the compiler was doing (type checking, etc...) will need to be done elsewhere (tests), and that will have a cost.
  • Many out-of-the-box tools will probably not work any more. You will not be able to use things such as Visual Studio "Go To Definition" or "Find All References".Documentation is too important in this type of architecture.