Rss Feed Like Us on facebook Google Plus

February 23, 2013

Introduction to Asp.Net Web-API

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. With WebAPI content negotiation, one can return data based on the client requests. What I mean is, if the client is requesting the data to be returned as JSON or XML, the WebAPI framework deals with the request type and returns the data appropriately based on the media type. By default WebAPI provides JSON and XML based responses.

WebAPI is an ideal platform for building pure HTTP based services where the request and response happens with HTTP protocol. The client can make a GET, PUT, POST, and DELETE request and get the WebAPI response appropriately.

In Summary, the WebAPI is 
- An HTTP Service 
- Designed for broad reach
- Uses HTTP as an Application protocol, not a transport protocol

Web API Architecture
We shall see below the Web API architecture when you are hosting the WebAPI in ASP.NET and self-hosting through console or windows service.

      

Routing configuration in WebAPI is slightly different than the ASP.NET MVC Routing. The WebAPI uses HttpRouteCollection and Route. The WebAPI team have reused the routing logic of MVC in WebAPI. The only reason why it’s a different routing is in order to keep the WebAPI from having its dependency on ASP.NET Routing the team decided to make it independent so that the WebAPI will not have ASP.NET class dependencies and can be hosted in console or  windows service as self-hosting.

While in ASP.NET WebAPI routing, the system will not only register HttpRoute object but also it will create a wrapper Route object and in ASP.NET routing engine.

The significant difference that you can see here is you will not have access to Routing data in message handlers when you are trying to access the same in self-hosting , the reason is the route configuration is set and it will run at the later point in the life cycle.

The other significant difference between the ApiController and the normal MVC controller is with WebAPI ApiController, the actions are dispatched by default based on the HTTP request. However there is a flexibility to override the same so that the WebAPI will use the action name to select the action method within the ApiController.

What is Content Negotiation in Web API ?
This is something which you will here frequently in Web Api. Content negotiation is the process of selecting the best representation for a given response when there are multiple representations available. The underling Web API framework implements the content negotiation and that is the reason why and how the client can request the data with a specific media type.

By default the Web API returns data in JSON format, however while requesting for a resource we can specify the media type to return so that the Web API knows what you are requesting for and selects proper formatter to output the data. 
How to Implement Web API? 
We shall see a generic implementation of Web API.

One has to create a class which derives from ApiController. The methods defined in the WebAPI controller maps to the HTTP methods. If you have a method name prefixed with GET, it means you are trying to return some data based upon the GET Request. You just have to make sure that whatever actions you are implementing must be prefixed with the right request type (GET, POST, PUT, and DELETE).

Note: The method named need not be Get () or Post () etc. However it does not limits to prefixing the request types , You can still implement the actions with different naming but one has to make sure to use the suitable action filters [HttpGet] , [Post] , [Put], [Delete].

Routing in ASP.NET Web API?
To determine which action to invoke, the framework uses a routing table. Below is the default route which is configured as a part of Global.asax
The routing is quite similar to what we define for MVC controllers
routes.MapHttpRoute(
    name: "Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

The Web API framework receives an HTTP request, it tries to match the URI against one of the route templates in the routing table. If no route matches, the client receives a 404 error.
Action Parameters in Web API simple types are taken from URI - Route data, query parameters. 

Complex types come from the body - Configured MediaTypeFormatters are used to desterilize the request body based on the content type - JSON, XML and form-url-encoded are supported out of the box , also we can override using [FormUrl], [FormBody], [ModelBinder], custom parameter binding.

How to host a Web API ?
One can either go with self or web hosting.

• Self-hosting in any Windows process (e.g., console application or Windows service)
• Web hosting - using the ASP.NET pipeline on top of Internet Information Services (IIS) One has to make a reference and use the below ones if you are going with self-hosting.

Here is the code snippet for self-hosting Web API.
using System.Web.Http;
using System.Web.Http.SelfHost;      
 
var config = new HttpSelfHostConfiguration("http://localhost:8080");
 
config.Routes.MapHttpRoute(
    "API Default", "api/{controller}/{id}", 
    new { id = RouteParameter.Optional });
 
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
    server.OpenAsync().Wait();
    Console.WriteLine("Press Enter to quit.");
    Console.ReadLine();
}
In the above hosting, the application listens to the specified URL localhost 8080. One needs administrator privileges for that. If you are facing any issues like “HTTP could not register URL” then you will have to run the below statement in command prompt as Administrator
netsh http add urlacl url=http://+:8080/ user=machine\username
How to manually run the content negotiation and why it’s required?
We have seen above the content negotiation is something which is built inside the WebAPI which will make use of formatters to decode and encode the HttpRequest and HttpResponses.

So the question comes when exactly we need to manually run the content negotiation logic. Here’s one that we can think of, say you are consuming a third party service which always returns the data in JSON format. Your client is accepting or willing to process xml based responses or maybe you have other clients consuming data in different formats like Json or xml. In such scenarios you can think of building a WebAPI as a wrapper around the services that you are consuming. Isn’t it meaningful to build something and return data based on the media type?

Below is the generic code which runs the content negotiation
// Get the IContentNegotiator
IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
 
// Run content negotiation to select a formatter
MediaTypeHeaderValue mediaType;
MediaTypeFormatter formatter = negotiator.Negotiate(
typeof(Contact), Request, Configuration.Formatters, out mediaType);
 
// Create a response message with an object content using the selected formatter
HttpResponseMessage response = new HttpResponseMessage() 
{ 
     Content = new ObjectContent<contact>(contact, formatter), 
     RequestMessage = Request 
}; 
Get the content negotiator instance and run the Negotiate method with the following parameters, the type of object you want to return, request object, the default formatters and out param for the media type. At last create a HttpResponseMessage and format the content as per the media formatter which is obtained while doing content negotiation.  

Background

This article is just a start off, a beginner article for WebApi. Basic understanding of MVC is sufficient to understand and implement ASP.NET WebAPI.

Using the code

We shall create a very basic sample WebAPI project and host the same in console and make a request from browser. I am referring the example mentioned in http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api
  1. First create a console project
  2. From NuGet manager , Search for ‘Microsoft.AspNet.WebApi.SelfHost’ and install the same
  3. Create a controller and make sure it should inherit from ApiController
  4. Implement required actions based on the HTTP verbs
  5. Now we are ready for hosting.

    1. In program.cs , create an instance of HttpSelfHostConfiguration by specifying the URL to listen, then set the default route map.
    2. Create an instance of HttpSelfHostServer with the above configuration and open the connection and wait for the client requests. 
  6. Requesting for Products , just copy paste or type in the url - http://localhost:8080/Products in browser and hit enter. That's all you should be able to see the response.
When you are requesting for Products with the url - http://localhost:8080/Products , the GetAllProducts method of ApiController will serve the request. Similarly if you wish to get product by Id, you will have to pass the Id while making a request to Web Api controller. Here is an example http://localhost:8080/Products/1 , upon requesting the GetProductsById method will be invoked and it will return a single product based on the product Id.
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]  
        {  
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },  
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
        };
 
        public IEnumerable<product> GetAllProducts()
        {
            return products;
        }
 
        public Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }
 
        public IEnumerable<product> GetProductsByCategory(string category)
        {
            return products.Where(p => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
 
    static void Main(string[] args)
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8080");
 
        config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
 
        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }
    } 
Now we will see another sample implementation of WebAPI handles GET, PUT, POST, DELETE requests. For demostration purpose , I have created a WebAPI based Contact Manager application.

Use case: 
1. Ability to manage contacts , The user should be able to add/update/delete contacts.
2. Display all contacts in Home page.
Below is the Contacts Controller implementation. We are encapsulating all the CRUD operations in a repository named ContactRepository.
    public class ContactsController : ApiController
    {
        private static readonly IContactRepository _contacts = new ContactRepository();
 
        // Get All Contacts
        public IEnumerable<contact> Get()
        {
            return _contacts.GetAllContacts();
        }
 
        // Get Contact by Id
        public Contact Get(int id)
        {
            try
            {
                Contact contact = _contacts.GetContact(id);
                return contact;
            }
            catch (Exception ex)
            {
                 throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, ex.Message));                
            }
        }
        
        // Insert Contact
        public HttpResponseMessage Post(Contact value)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Contact contact = _contacts.AddContact(value);
                    var response = Request.CreateResponse<contact>(HttpStatusCode.Created, contact);
                    return response;
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.InternalServerError, "Model state is invalid");
                }
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }
        
        // Update Contact by Id
        public HttpResponseMessage Put(int id, Contact value)
        {
            try
            {
                _contacts.UpdateContact(id, value);              
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
 
        // Delete Contact by Id
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                _contacts.RemoveContact(id);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }             
Below is the code for Contact Repository.
It is built on Entity Framework Code First Approch. The Repository is composed of ContactsDbContext , with it's help we are performing CRUD operations.
    public class ContactRepository : IContactRepository
    {
        private ContactsDbContext context;
 
        public ContactRepository()
        {
            context = new ContactsDbContext();
        }
 
        public IEnumerable<contact> GetAllContacts()
        {
            try
            {
                return context.Contacts.ToList();
            }
            catch
            {
                throw;
            }  
        }
 
        public Contact GetContact(int id)
        {
            try
            {
                return context.Contacts.SingleOrDefault(c => c.Id == id);               
            }
            catch
            {
                throw;
            }  
        }
 
        public Contact AddContact(Contact item)
        {
            try
            {
                context.Contacts.Add(item);
                context.SaveChanges();
                return item;
            }
            catch
            {
                throw;
            }           
        }
 
        public bool RemoveContact(int id)
        {
            try
            {
                var contact = context.Contacts.SingleOrDefault(c => c.Id == id);
                if (contact == null)
                    throw new Exception(string.Format("Contact with id: '{0}' not found", id.ToString()));
             
                context.Contacts.Remove(contact);
                context.SaveChanges();
                return true;
            }
            catch
            {
                throw;
            } 
        }
 
        public bool UpdateContact(int id, Contact item)
        {
           try
            {
                var contact = context.Contacts.SingleOrDefault(c => c.Id == id);
             
                if( contact == null)
                    throw new Exception(string.Format("Contact with id: '{0}' not found", id.ToString()));
 
                contact.Name = item.Name;
                contact.Email = item.Email;
                contact.Phone = item.Phone;
 
                context.Entry(contact).State = EntityState.Modified;              
                context.SaveChanges();
                return true;
            }
            catch
            {
                throw;
            } 
        }
    }
 
    public class ContactsDbContext : DbContext
    {
        public ContactsDbContext()
            : base("name=ContactsDbContext")
        {
        }
 
        public DbSet<contact> Contacts { get; set; }
    } 
Setting Up the Database for Managing Contacts
Open solution - WebApi-ManageContacts in Visual Studio and Following the below steps
1. (Optional Step) Open web.config and make changes to connection string "ContactsDbContext" if required.

2. Go to Tools -> Library Package Manager -> Package Manager Console
Run Update-Database command as show below, You should be able to see the command runs successfully without throwing any errors.

PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Applying automatic migration: 201302171855006_AutomaticMigration.
Running Seed method.

Rendering contacts (MVC + Web Api Controller)
Here is a code snippet for HTTP GET verb. We are making an ajax request to get all the contacts. The request will hit the Home controller and it will execute "ContactsGrid" action. Within the action , we are creating an instance of WebAPI controller , get all the contacts and then return a partial view - ContactsGrid.
function GetContacts() {
        $.ajax({
            url: '/Home/ContactsGrid',
            type: "GET",
            success: function (response) {
                $("#contactsGrid").html(response);
            },
            error: function (data) {
                $("#contactsGrid").html(data.responseText);
            }
        });
    }
Add contacts with Web Api
Below is the code snippet for adding a new contact. Here we are making a jquery request with the url to WebApi controller, passing the contact information by serializing the data as Json object in the HTTP Request body. The content negociation with in the WebApi will understand and decode the contact information.

Note - Set the proper content type while making a request. Below you can see the content type set to 'application/json'
function AddContact() {
        var contact = {
            Name: $('#Name').val(),
            Email: $('#Email').val(),
            Phone: $('#Phone').val()
        };
 
        $.ajax({
            url: '/Api/Contacts',
            type: 'POST',
            data: JSON.stringify(contact),
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                alert('Contacts added successfully');
                GetContacts();
            },
            error: function (data) {
                alert('Problem in adding contacts:' + data.responseText);
            }
        });
    }            
Deleting contacts with Web Api
Below is the code snippet for deleting contacts. We make a jquery request with the url to the Web Api controller. You will also notice that by setting the request type to 'DELETE' , helps to execute Delete method in the Contacts Web Api Controller.
function DeleteContact(id) {       
        $.ajax({
            url: '/Api/Contacts/'+ id,
            type: 'DELETE',
            success: function (data) {
                GetContacts();
            },
            error: function (data) {
                alert('Problem in deleting contacts:' + data.responseText);
            }
        });
    }            
Update contacts with Web Api
Below is the code snippet for updating the contacts. We are using Jquery model dialog, We will get the contact to update and then show up a dialog so that we can edit the contact. When we click on update button , we will make an Ajax request with the url to WebApi controller.

You can also notice the request type is 'PUT' and we are also serializing the contacts before making the request. If the update operation succeeds, we will call GetContacts() method so that it will update the contacts grid. 
function EditContact(id) {
        $.ajax({
            url: '/Home/GetContactsById/' + id,
            type: "GET",
            success: function (response) {
                $("#editContact").html(response);               
            },
            error: function (data) {
                $("#editContact").html(data.responseText);
            }
        });
 
        $(dialog).dialog('open')
    }
 
  dialog = $("#editContact").dialog({
            autoOpen: false,
            resizable: false,
            closeOnEscape: true,
            show: "explode",
            hide: "explode",
            width: 300,
            title: "Edit Contact",
            buttons: {
                Update: function () {
                    var contact = {
                        Name: $('#Name').val(),
                        Email: $('#Email').val(),
                        Phone: $('#Phone').val()
                    };
 
                    $.ajax({
                        url: '/Api/Contacts/' + $('#Id').val(),
                        type: 'PUT',
                        data: JSON.stringify(contact),
                        contentType: "application/json;charset=utf-8",
                        success: function (data) {
                            GetContacts();
                        },
                        error: function (data) {
                            alert('Problem in updating contacts:' + data.responseText);
                        }
                    });
 
                    $(dialog).dialog("close");
                },
                Cancel: function () {
                    $(dialog).dialog("close");
                }
            }
        });
Web.config changes
In order to execute HTTP requests for DELETE, PUT etc we need to add the below mentioned line under <system.webserver> so that the application handles all type of requests.

<modules runallmanagedmodulesforallrequests="true">  
Read More

February 20, 2013

Software Design Pattern - abstract factory pattern

The abstract factory pattern is a software creational design pattern that provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() and createResume()). 

The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation ofcreateLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class likeLetter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would need to know how to handle only the abstract Letter or Resume class, not the specific version that it got from the concrete factory.
A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.[2] This allows for new derived types to be introduced with no change to the code that uses the base class.
Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at run-time. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain. Therefore, as in all software designs, the trade-offs must be carefully evaluated.

Class diagram

Abstract factory.svg

The method createButton on the GuiFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GuiFactory is handling the method call.
Note that, for conciseness, this class diagram only shows the class relations for creating one type of object.

Read More

November 1, 2012

8 Outstanding Features of Windows 8 Phone


Microsoft has unveiled Windows Phone 8, the most awaited version of its Smartphone operating system. The new OS is to give stiff competition to the reigning Apple iOS and Google’s Android.


The Smartphones running Microsoft’s new OS will be available by this weekend in Europe and allover world from November.


"We had a very different perspective on what a Smartphone should be," Steve Ballmer, Microsoft’s CEO said at the press event. The statement increases speculation about how far Windows Phone 8 will fare in being the third desired option after iOS and Android among Smartphone users.


But it is definitely packed with some amazing features, which are able to satisfy every Smartphone users out there. Read on to know the 8 most outstanding features of Windows Phone 8.


#8 Lock Screen:



Windows Phone 8’s Lock Screen shows all necessary information in one screen. Microsoft always had live tiles as top priority, and it can be noticed in the Lock Screen. The tiles or the apps on the home screen refresh with new information on their own; so you need not to tap on app to see new Facebook notifications or the weather updates. And you can customize it with the tiles of your favorite apps or contacts. "It will automatically surface photos and notifications and content from your favorite apps," Joe Belfiore, manager of the Windows Phone Program at Microsoft said.



#7 Kid's Corner



This feature enables a “guest user” mode, where parents can customize the content on phone that kids can have access to, like games, learning apps, videos, and music. This feature prevents the kids from wrecking havoc on once personal data, or misuse the mobile.



#6 Data Sense



Another new feature introduced in to newOS is focused on saving money and time. It is called Data Sense. You have to fill in your data plan and end date of your monthly billing cycle; the app will then monitors your data usage, and will warn you with pop-up notification if you’re reaching your monthly allotment. The app can also compress data sent over the wireless network, so you can save few bucks. It also helps you find nearby Wi-Fi hotspot so you can turn off of the mobile network. This feature can get you 40 percent more web browsing than other phones, Belfiore said. And lastly you can get snapshot of your data usage.



#5 Syncing your phone


Windows Phone 8 offers several ways to sync your phone so that you need not to go through Zune to access your stuff, be it music, videos, photos and many more. The devices on this platform can utilize MTP (Media Transfer Protocol) which means you can access phone as external hard drive. You can drag and drop files, and even go into media player and sync up songs.

In addition to it you can sync up with iTunes too, but it requires desktop companion app to do so. And for Mac users this is the only option to connect the Microsoft Phone 8 device to their machine.


#4 Compatibility with Windows 8



Even a single look at Windows 8 and Windows Phone 8 will let secret out—both share greater kinship. Microsoft seems to be betting heavily on the Modern UI, and worked hard to combine desktop, mobile and tablet experience into one platform. Which means that, windows 8 developers can use same code for Windows Phone 8 too; the company is hoping that this feature can bring third party developers to come together and strengthen its unproven ecosystem of Apps.



#3 Wallet and NFC



Microsoft taken notice of Google Wallet and Apple’s Passbook, and is coming up with its own Wallet app, which may combine the features of both its compotators and can add more. It serves as hub for storing your credit card information, which can be used to purchase stuff on stores or for NFC (near field communication) enabled mobile payments.


The feature doesn’t stop here, you can use this to share videos, music, contact information and Internet Explorer links between phones and other devices.


#2 Photos and Camera



Even though the new OS could have been reason to add something creative to the camera, Microsoft has came up with only few but differentiating camera feature. The view finder UI has received few tweaks, like zoom is no longer on side bar for you can pinch-to-zoom on the viewfinder itself. The sidebar sports flash toggle switch and ability to select a lens. The camcorder and front-facing camera toggles remain same. 

In addition to it the developers may come with apps that can enhance overall photo-taking experience. The apps can be like Photostrip, which lets you take shots in burst mode or Photosynth that offers panoramic shots and many more.


#1 Music and Video



The old is gone, Zune is yesterday’s news. The music section is ruled by Xbox Music Store; likewise Zune pass is now Xbox music pass.


The best feature is the phones’ deep integration with cloud. The purchases you made within Music stores are available on cloud for you to listen anytime you want. And every song and video associated with your Microsoft account will get listed in to your collections, which you can download or stream. 






Read More

September 10, 2012

Google Launches Free Voice Navigation In India


Finally, Indians can enjoy the privilege of a free and accurate voice assisted navigation, as Google launched its navigation service in India which would allow the Smartphone and Tablet owners to get turn-by-turn voice instructions to reach the destination by walk or drive. The service will be available free for Android platforms.


Even though the app was available free with the Android versions, it lacked official supported till now. The current beta version of this app was found to be accurate in a test by TOI. The users can select instructions either for walking or driving and the app automatically reroutes its coordinates, in case the user deviates from proposed path. It also provides layered information on the popular landmarks, petrol bunks, ATMs and restaurants on the way.


According to Darren Baker, product manager for Google Maps, “the service, which is available in 40 languages in 74 countries, is now offered only in English. However, the announcement of upcoming directions in the navigation service is in a ‘friendly, familiar Indian accent’”. India is a ‘dynamic and fast-growing’ market for online map services, he continued.


Even though India is a strong customer base for many Smartphone manufacturers and internet based services, not many free navigation services were available to the customers on devices, except Nokia, which offered a navigation service in some of its high end phones. Some paid navigation apps were also available. However, none of these were purely effective in helping people navigate through the highly unorganized Indian routes. But with the availability of Google’s navigation, along with some of its other services like ‘Local’- a dynamic directory of places around a user, and ‘transit’- that uses data supplied by public transport authorities to allow users to get information on routes and times of buses or trains by public transport, the navigation in India, is expected to get much easier.
Read More

September 2, 2012

Ants Speak the Language of the Internet


If you have thought than only humans are intelligent, then pay close attention. According to a paper written by a Stanford biologist and computer scientist, ants speak the language of the Internet - “ifs,” “elses” and “end ifs.”


Deborah Gordon, a biology professor, had recently prepared an algorithm that described how harvester ants go out and search for food. There was something suspicious in the algorithm, so Gordon called up computer science professor Balaji Prabhakar and asked him if that reminded him in any way of file transfers on computer networks.


Prabhakar told Bjorn Carey of Stanford engineering’s in-house news site, “The next day it occurred to me, ‘Oh wait, this is almost the same as how Internet protocols discover how much bandwidth is available for transferring a file!’ The algorithm the ants were using to discover how much food there is available is essentially the same as that used in the transmission control protocol.”


Carey explained the whole process, “Gordon has found that the rate at which harvester ants — which forage for seeds as individuals — leave the nest to search for food corresponds to food availability. A forager won’t return to the nest until it finds food. If seeds are plentiful, foragers return faster, and more ants leave the nest to forage. If, however, ants begin returning empty handed, the search is slowed, and perhaps called off.”


That process is almost identical to how computers transfer files on computer networks using transmission control protocol (TCP). The system divides data into numbered packets. When the destination receives a packet, it sends back an acknowledgment to the source. If that comes back slowly, the source will decrease speed, and if it comes back quickly, it will increase speed.
Read More

August 22, 2012

India Spends 1 Of Every 4 Online Minutes In Social Networks


The online population of India literally lives inside social networks, as it is revealed that more than 25 percent of the total online Indian minutes were spend on social networking activities. Indians are also fond of Google sites as it turned out to be the destination of more than 95 percent of them.


The findings came out on a latest report from ComScore on top online sites and activities in India. Google stand as the most popular site in the country followed by Facebook and then Yahoo sites. Microsoft sites have finished in the fourth position. Adding to it, many local websites secured spot in the top 10 ranks.


Considering the engagement in websites, the difference was huge between the best of local brands and the topper, Facebook. People spent an average of four hours on Facebook in June whereas Network 18, the local leader engaged people for an average 31.6 minutes during the month. The Google sites, including YouTube had visitors spending an average of 2.5 hours.


In India, social networks have turned to be the primer driver of daily digital Media Consumption followed by the entertainment sites. The time spent on online retail shops in the country grew 0.5 percent as the trend is gaining momentum within the country.
Read More

August 21, 2012

Delete un-necessary emails without checking from your Gmail

It had usually been irritating to receive useless emails or spam emails in your account. Few days back I received almost 15 to 20 useless emails everyday amongst those which were useful. Then someone told me about a new feature “FILTER” that Gmail provides you to get rid of unwanted emails.
You cannot Block unwanted types of emails from marked addresses or domain but you can simply set a “FILTER” to move these emails or messages directly to trash and can delete without checking them.
To set a Filter follow the steps below:
• Login to your Gmail account.
• Click on Mail settings and then click on “FILTER” and select “Create a new Filter”.

• Now fill up the field with Filter’s details and then click on “Create Filter with this search”.

• Now select the action that you would like for these unwanted emails by Tick marking on the appropriate box.
• And then, finally click on “Create Filter”.

Now you had set a Filter to those emails that used to disturb you a lot. And no more unwanted emails are going to disturb you from now.
Read More

August 14, 2012

WCF concepts implementation with examples and interview questions

WCF - Windows Communications Foundation

"WCF is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication."

A WCF Service is composed of three components parts viz,


1) Service Class - A WCF service class implements some service as a set of methods.


2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.


3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address
The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.

Ex:      http://localhost/WCFServiceSample/Service.svc


Binding
The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.
·         "A" stands for Address: Where is the service?
·         "B" stands for Binding: How can we talk to the service?
·         "C" stands for Contract: What can the service do for us?

Different bindings supported by WCF:

Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract
The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Types of contracts in WCF

Service Contract
Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract
Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract
Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Delete [OperationContract] attribute:
When we delete  [OperationContract] attribute we get an exception
“Contract OR Binding mismatch between the sender and receiver”


Read More

July 1, 2012

Want to become an App Developer , follow these Steps


Ever heard of any rags to riches stories of app developers? Ever heard of iShoot? Written by a programmer at Sun Microsystems in his spare time, the iShoot game rocketed to the top of the App Store charts earlier this year and earned its creator enough money to pursue a career as a professional developer.



Keith Stuart on guardian.co.uk charts the steps that any app/ game developer could adopt to become a top one.



1. Buy a Mac:


You don’t need a top of the range model; just one that has an Intel-based processor and runs the Leopard version of MacOS X. Any machine offering a degree of maneuverability should be preferred.


Peter Scott, CTO at Connect2Media recommends Mac Minis, "They are more than powerful enough, small and easy on desk space when you already have PCs, three LCD monitors and a bunch of devices. They are also easy to move round, developers can take them home at the weekend if they want to continue work."


2. Getting the SDK (Software Development Kit):

Apple provides the free SDK for iPhone development from their Developer site. Stuart Varrall, Creative Director at Fluid Pixel says, "This includes everything you need to get going, including the development environment Xcode, the iPhone Simulator for testing, performance analyzers, interface builders and the full documentation reference library."

3. Read up on Objective C:




This is the primary programming language for development on iPhone. "It's an extension of C to include object-orientated principles," says Varrall. "It has scripting elements to it, so is easier to pick up than some languages and anyone with programming experience should be able to transfer their skills."


 
4. Just Start Writing:

Give yourself a project and start working. If you can't face starting out on an original project, Varrall suggests a couple of modification tasks. "The SDK actually comes with a whole host of sample projects that cover most aspects of development. So the best place to start would be to take one of those and reverse engineer it and work out how it has been constructed. You can then build on these by adding new features and create your very own game very quickly."

5. Sign-up as an Official Developer:

If you plan to release your app, you'll have to sign up with the iPhone Developer Program. The standard cost is $99, and you will have to agree to Apple's terms and conditions, and sign and return the contract. It’s important you know that you'll need to sign up in order to test your code on an actual iPhone instead of an onscreen emulator. Once you're on the Developer Program you will receive a certificate, which allows you to pair up with an iPhone device.


 
6. Gear Up for a Few Months of Hard Work:

Depending on how much time you can devote to it and how many resources you have, developing a game or app could take weeks or months. You also need to face the possibility of dealing with crashes and debugging.





7. Submitting Your App to Apple:

Using an interface which is similar to the one used by music producers to submit albums, a finished app will have to be submitted. The process is straightforward enough- zip your file, upload it with a description, large and small icons and screenshots. If your app is good to go, Apple will take a week to approve the content and it will be made available in the store. If your app has bugs, it may take longer time to review and it may be rejected. In such a scenario, you can fix the issue and resubmit it.


8. Market and Adapt to Survive:

Things don’t get simpler once your app makes it to the App store. It is a possibility that your app has some design issues or a few bugs which is an issue that you will only know about when many users try out your app. In this case, you can submit your modifications.


To garner recognition for your app, you need to stand out in the crowd of over 20,000 apps. You need to have your marketing strategy in place from the inception of the developing process. Blog about your programming procedure, produce screenshots, stay in touch with developing communities, and send out press releases to iPhone news sites. You could always use social networking websites as well.


Read More

© 2011-2016 Techimpulsion All Rights Reserved.


The content is copyrighted to Tech Impulsion and may not be reproduced on other websites.