Tuesday, October 30, 2012

ASP.NET web method call using AJAX (jQuery)

This article is about how to call a server side function (web method) from client side (aspx page) using AJAX(provided by Jquery).

Its interesting and easy to implement. As always- lets go directly to an example and see
 how to implement it...




In this example we will create a webmethod which will return a message to client side

1) Create an ASP.NET Application.

2) Add a new page 'WebForm1.aspx' and make it the start up page.

3) In WebForm1.aspx include jQuery file as given below. If you do not have jQuery file, you can
 download the latest files from http://jquery.com/


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

4) In code behind page (WebForm1.aspx.cs) create a webmethod to return some data as given below.
 Make sure to add the attribute [WebMethod()] to the function. You have to include the namespace
 System.Web.Services. (using System.Web.Services;)


[WebMethod()]
public static string GetData(int userid)
{
    /*You can do database operations here if required*/
    return "my userid is" + userid.ToString();
}


5) Add script tags and include the function to call the web method. Pass the parameter
 (in this case 'userid') to web method as JSON object


function asyncServerCall(userid) {
    jQuery.ajax({
 url: 'WebForm1.aspx/GetData',
 type: "POST",
 data: "{'userid':" + userid + "}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
     alert(data.d);
 }

    });
}


6) Add button on aspx page and call the ajax function on click event.


<input type="button" value="click me" onclick="asyncServerCall(1);" />

7) DONE! Run the app and click the button, you can see that the webmethod is 
called and data is returned.

Thursday, October 11, 2012

How to ping a device with Java


public class Pinger {
// byte[] addr1 = new byte[]{(byte)192,(byte)168,(byte)2,(byte)5};

public static long testDBConn(byte[] addr1, int port, int timeoutMs) {
//pass in a byte array with the ipv4 address, the port & the max time
out required
long start = -1; //default check value
long end = -1; //default check value
long total = -1; // default for bad connection

//make an unbound socket
Socket theSock = new Socket();

try {
InetAddress addr = InetAddress.getByAddress(addr1);

SocketAddress sockaddr = new InetSocketAddress(addr, port);

// Create the socket with a timeout
//when a timeout occurs, we will get timout exp.
//also time our connection this gets very close to the real time
start = System.currentTimeMillis();
theSock.connect(sockaddr, timeoutMs);
end = System.currentTimeMillis();
} catch (UnknownHostException e) {
start = -1;
end = -1;
} catch (SocketTimeoutException e) {
start = -1;
end = -1;
} catch (IOException e) {
start = -1;
end = -1;
} finally {
if (theSock != null) {
try {
theSock.close();
} catch (IOException e) {
}
}

if ((start != -1) && (end != -1)) {
total = end - start;
}
}

return total; //returns -1 if timeout
}
}


public static void main(String[] args) {

// byte[] addr1 = new
byte[]{(byte)192,(byte)168,(byte)2,(byte)5};
int port = 1521;
int timeoutMs = 2000; // 2 seconds
long value = testDBConn(addr1, port, timeoutMs);
System.out.println(value);
}

Wednesday, October 10, 2012

What is dotNet MVC

When ASP.NET 1.0 was fi rst released in 2002, it was easy to think of ASP.NET and Web Forms as
one and the same thing. ASP.NET has always supported two layers of abstraction, though:
‰ System.Web.UI: The Web Forms layer, comprising server controls, ViewState, and so on
‰ System.Web: The plumbing, which supplies the basic web stack, including modules, handlers,
the HTTP stack, and so on
The mainstream method of developing with ASP.NET included the whole Web Forms stack — taking
advantage of drag-and-drop controls, semi-magical statefulness, and wonderful server controls
while dealing with the complications behind the scenes (an often confusing page life cycle, less than
optimal HTML, and so on).
However, there was always the possibility of getting below all that — responding directly to HTTP
requests, building out web frameworks just the way you wanted them to work, crafting beautiful
HTML — using Handlers, Modules, and other handwritten code. You could do it, but it was painful;
there just wasn’t a built-in pattern that supported any of those things. It wasn’t for lack of patterns
in the broader computer science world, though. By the time ASP.NET MVC was announced in
2007, the MVC pattern was becoming one of the most popular ways of building web frameworks.


The MVC Pattern
 

Model-View-Controller (MVC) has been an important architectural pattern in computer science for
many years. Originally named Thing-Model-View-Editor in 1979, it was later simplifi ed to Model-
View-Controller. It is a powerful and elegant means of separating concerns within an application
(for example, separating data access logic from display logic) and applies itself extremely well to
web applications. Its explicit separation of concerns does add a small amount of extra complexity
to an application’s design, but the extraordinary benefi ts outweigh the extra effort. It has been used
in dozens of frameworks since its introduction. You’ll fi nd MVC in Java and C++, on Mac and on
Windows, and inside literally dozens of frameworks.
The MVC separates the user interface of an application into three main aspects:
‰ The Model: A set of classes that describes the data you’re working with as well as the business
rules for how the data can be changed and manipulated
‰ The View: Defi nes how the application’s user interface (UI) will be displayed
‰ The Controller: A set of classes that handles communication from the user, overall application
fl ow, and application-specifi c logic
 

MVC AS A USER INTERFACE PATTERN
 

Notice that we’re referred to MVC as a pattern for the User Interface. The MVC
pattern presents a solution for handling user interaction, but says nothing about how
you will handle other application concerns like data access, service interactions, etc.
It’s helpful to keep this in mind as you approach MVC: it is a useful pattern, but
likely one of many patterns you will use in developing an application.

a little rememberence about dotNet Extension Methods

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Sunday, September 30, 2012

Code Snippet

to select a ASP.Net Grid Row by click

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if(e.Row.RowType == DataControlRowType.DataRow )
                    e.Row.Attributes.Add(
                        "onclick",
                        Page.ClientScript.GetPostBackEventReference(sender as Control, @"Select$" + e.Row.RowIndex.ToString())
                        ) ;
...

Wednesday, September 19, 2012

Windows Azure Platform : AppFabric


The Windows Azure platform represents a radical change in the way applications can be
built and managed. This platform provides an Internet - based cloud computing environment
that anyone can use for hosting applications and storing the associated data. The platform
in general comprises two core services that any cloud - based application can use: compute
(e.g., executing an application) and storage (e.g., storing data on disk).
The compute service enables any application to run in the cloud. In essence, the applications
are deployed in a highly scalable environment where they share computer processor time
available in different virtual machines with Windows Server. These virtual machine
instances are spread around the world in different Microsoft data centers.
The storage service, as its name clearly states, provides simple storage capabilities using
different schemas such as BLOBs (binary objects), queues, or simple tables through a very
easy - to - use REST API based on Http calls. In case an application requires richer querying
capabilities for the storage (e.g., relational databases), an additional service, SQL Azure, is
also provided by Microsoft in this platform.
In both cases, Windows Azure assures the availability and high scalability that any
cloud - based application requires.
AppFabric extends the Windows Azure platform by providing two common building blocks,
the Service Bus and Access Control, to make it easier to extend the reach of any .NET applications in this platform. They currently provide key functionality to support bi - directional
connectivity and federated claims - based access control in any application trying to migrate to
Windows Azure.
The primary feature of the Service Bus is to “ route ” messages from clients through the Windows
Azure cloud to your software running on - premise, bypassing any NAT, fi rewalls, or other network
obstacles that might be in the way. In addition to routing messages, the Service Bus can also help
negotiate direct connections between applications.

The primary feature of Access Control is to provide a claims - based access control mechanism
for applications running on - premises or on the cloud. This makes federated authentication and
authorization much easier to achieve, allowing third - party applications to trust identities provided
by other systems.
Although each of these building blocks is available using open protocols and standards such as
REST, Atom/AtomPub, and SOAP, Microsoft has also provided a SDK that simplifi es the work
for .NET developers by hiding many of the wire protocol complexities that they would otherwise
experience when working with them directly. As part of this SDK, you can take advantage of some
of the new WCF extensions. These include the relay bindings, to talk to the Service Bus, or custom
authorization managers for parsing the security tokens generated by the Access Control.