Wednesday, March 14, 2012

.NET/ASP.NET Interview Question -What role does Session object play?

HTTP is a stateless protocol; it can't hold the client information on page. In other words after every request and response the server does not remember the state, data and who the user was. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information.So, Session provides that facility to store information on server memory. Below is the diagram to understand in better manner. In the above example, when the user request the IIS server for the Page1.aspx then the request is broadcasted to the user/client browser and the connection is broken, Now when the same user request the IIS server for the Page2.aspx then again the request is broadcasted to the user/client browser but this time again the same user is treated as a new user as the connection was broken by IIS server after displaying the Page1.aspx page. Note:- So every single time a new request is made the same user is treated as a new one, so in order to maintain this we need Sessions.

.NET/ASP.NET Interview Question - Various types of Validators?

A validator is a computer program used to check the validity or syntactical correctness of a fragment of code or text. IN ASP.NET there are six different types of Validators. 1.Required Field Validator. 2.Regular Expression Validator. 3.Compare Validator. 4.Range Validator. 5.CustomValidator. 6.Validation Summary RequiredFieldValidator:-Ensure that the control has a value to assign in it or user does not skip an entry. For Example:- Regular ExpressionValidator:-Ensure that the value of the control matches the expression of validator that is specified. This type of validation enables you to check for sequence of character, such as e-mail address, telephone number, postal code and so on. For Example:- // for internet E-Mail. CompareValidator:-Ensure that the value of one control should be equal to value of another control.which is commonly used in password,less than,greater than or equal to. For Example:- RangeValidator:-Ensures that the value of the control is in specified lower and upper boundaries or specified range. You can check ranges within pairs of numbers, alphabetic characters. For Example:- > CustomValidator:-This control is used to perform user defined validations. ValidationSummary:-This validator is used to displays a detailed summary on the validation errors that currently exist.

.NET and ASP.NET interview question -Elaborate differentiation between Cache and Application?

Application and Cache both help to share global data and cache data across the users.but cache object is proactive and you can define dependency.In application object you can't define depenency. Below is the code for declaring application and cache object. CacheDependency objCacheDependency = new CacheDependency(Server.MapPath ("Banner.txt")); Cache.Insert("Banner", strBanner, objCacheDependency); Application["Banner"] = "strBanner"; In the above code, for Cache object you can define dependency but in Application object you can't define dependency.when the banner file is changed the Cache object can be refreshed but the application remain static and holds the old text of banner file.

WCF Interview Question - Method to perform Self-Hosting in WCF?

The following steps are followed to do Self-hosting. Step1: //Create a URI to serve as the base address // Address as well binding Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld"); Step2: //Create ServiceHost ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService),httpUrl); Step3: //Add a service endpoint host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService) , new WSHttpBinding(), ""); Step4: //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); Step5: //Start the Service host.Open(); Step6: Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press key to stop"); Console.ReadLine();

.NET/ASP.NET interview Questions - how to do Render and PreRender?

PreRender: -PreRender is an event which is used for modifying server controls just before sending them to the client. Render: -Render is an method which actually puts the HTML output to the response stream. Lets see an simple example to get an better idea, below is the code snippet for the same. To use PreRender event, we have to override it and can make necessary changes to the controls we want to. protected override void OnPreRender(EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { row.ForeColor = Color.Blue; } } In the above code snippet, I have override the PreRender event and just changed the forecolor of the GridView. Now lets see how we can code for Render. Below is the code snippet for the same, in which I have override the Render and using “HtmlTextWriter” just displayed a simple HTML text output. protected override void Render(HtmlTextWriter writer) { writer.Write("This displays the grid in blue color"); base.Render(writer); } Below is the full code snippet so that you can try it by yourself and see the respective result. using System.Drawing; using System.Collections; namespace Data { public class Customer { public string CustomerCode { set; get; } public string CustomerName { set; get; } } public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoadGrid(); } public void LoadGrid() { ArrayList objArray = new ArrayList(); Customer ObjCustomer = new Customer(); ObjCustomer.CustomerCode = "1001"; ObjCustomer.CustomerName = "shiv"; objArray.Add(ObjCustomer); ObjCustomer = new Customer(); ObjCustomer.CustomerCode = "1002"; ObjCustomer.CustomerName = "Feroz"; objArray.Add(ObjCustomer); GridView1.DataSource = objArray; GridView1.DataBind(); } protected override void OnPreRender(EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { row.ForeColor = Color.Blue; } } protected override void Render(HtmlTextWriter writer) { writer.Write("This displays the grid in blue color"); base.Render(writer); } } } In the above code snippet, I have used prerender event to change the forecolor of the girdview before the gridview is displayed on the client browser and I have override the render method to display the html output to the response stream. PreRender event executed before the render method gets called which creates the HTML code using the HtmlWriter.so in other words prerender event fires first and do the necessary changes to the server control and later the render method is called.

Steps to create window service in Visual Studio

(1) Open Visual Studio (2) Create a window service with any name (3) Now write your logic there (4) Build. If successfully build (5) Now on service file (service1.cs designer), right click and select "Add Installer" It will add "serviceProcessInstaller1" and "serviceInstaller1" (6) Add description/name/service name (7) Now select the properties of "serviceProcessInstaller1" and set Account=LocalSystem. If you will not select this then it will ask local system username and password every time. (8) Mention StartType as 'Automatic'. If select 'Manual' it needs to start manually. (9) Build this service. If its successfully build. the go on next step. (10) Go to Visual Studio command prompt. Write there C:\Program Files\Microsoft Visual Studio 8\VC>installutil -i "C:\Inetpub\wwwroot\ServiceName\bin\Debug\Service.exe" If you want to uninstall window service the just write the -u instead of -i. C:\Program Files\Microsoft Visual Studio 8\VC>installutil -u "C:\Inetpub\wwwroot\ServiceName\bin\Debug\Service.exe" If starttype is manual, then it needs to run manually. Every time it install. It need to start manually from servies. To Start it . Go to Run > Services.msc. Right click on service and click Start.

Monday, March 12, 2012

.NET Interview Questions: - Mention LeaseTime, SponsorshipTime, RenewonCallTime and LeaseManagerPollTime?

.NET Interview Questions: - Mention LeaseTime, SponsorshipTime, RenewonCallTime and LeaseManagerPollTime?:
This is a very important question from practical implementation point of view. Companies who have specific requirement for Remoting projects will expect this question to be answered.
In normal .NET environment objects garbage collector manages lifetime. However, in remoting environment remote clients can access objects, which are out of control of garbage collector. Garbage collector boundary is limited to a single PC on which framework is running; any remote client across physical PC is out of control of GC (Garbage Collector).
This constraint of garbage collector leads to a new way of handling lifetime for remoting objects, by using concept called as “LeaseTime”. Every server side object is assigned by default a “LeaseTime” of five minutes. This lease time is decreased at certain intervals. Again, for every method call a default of two minutes is assigned. When i say method call means every call made from client. This is called as “RenewalOnCallTime”.
Let’s put the whole thing in equation to make the concept more clear.
Total Remoting object life time = LeaseTime + (Number of method calls) X (RenewalTime).
Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in minutes)
When total object lifetime is reduced to zero, then it queries the sponsor that should the object be destroyed. Sponsor is an object, which decides should object Lifetime be renewed. So it queries any registered sponsors with the object, if does not find any then the object is marked for garbage collection. After this garbage, collection has whole control on the object lifetime. If we do not foresee how long a object will be needed specify the “Sponsorship Timeout” value. Sponsorship Timeout is time unit a call to a sponsor is timed out.
“LeaseManagerPollTime” defines the time the sponsor has to return a lease time extension.
View the following video on Garbage Collector, Gen 0, 1 & 2 asked in C#.Net interview: -

Learn more on .NET interview questions
Regards,
From more on author’s blog related to .NET interview questions click and visit.

Wednesday, March 7, 2012

Mobile CRM Sync Set up

Mobile CRM Sync Set up:

If you use Microsoft Dynamics CRM and now look for a convenient mobile add-on, you can easily grab an app that offers full functionality and no time limitation—Resco Mobile CRM app. As it is available for free on the most popular platforms (iPhone, iPad, Android, Android tablet and Windows Phone), there are tens of thousands of users globally.


Some of them slip into little confusion when setting up the sync with the Dynamics CRM server. Therefore, we created a new User Sync Guide. Check the app yourself and if having issues with the sync setup, use the new manual.



Introduction to the ASP.NET Web API

Introduction to the ASP.NET Web API:

I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers.

We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser.

One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions.

Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications.

The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API.

Creating an ASP.NET Web API Controller


The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box.

Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template:

clip_image001

A brand new API controller looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPIApp.Controllers
{
public class MovieController : ApiController
{
}
}

An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class.


Using jQuery to Retrieve, Insert, Update, and Delete Data


Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this:

namespace MyWebAPIApp.Models
{
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public string Director { get; set; }
}
}

Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page.


Getting a Single Record with the ASP.NET Web API


To support retrieving a single movie from the server, we need to add a Get method to our API controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
public class MovieController : ApiController
{

public Movie GetMovie(int id)
{
// Return movie by id
if (id == 1)
{
return new Movie
{
Id = 1,
Title = "Star Wars",
Director = "Lucas"
};
}

// Otherwise, movie was not found
throw new HttpResponseException(HttpStatusCode.NotFound);
}

}
}

In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code.


After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port).


clip_image002


In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke.


The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1.


The default route for the Web API is defined in the Global.asax file and it looks like this:

routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

We can invoke our GetMovie() controller action with the jQuery code in the following HTML page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Movie</title>
</head>
<body>

<div>
Title: <span id="title"></span>
</div>
<div>
Director: <span id="director"></span>
</div>

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

getMovie(1, function (movie) {
$("#title").html(movie.Title);
$("#director").html(movie.Director);
});

function getMovie(id, callback) {
$.ajax({
url: "/api/Movie",
data: { id: id },
type: "GET",
contentType: "application/json;charset=utf-8",
statusCode: {
200: function (movie) {
callback(movie);
},
404: function () {
alert("Not Found!");
}
}
});
}

</script>

</body>
</html>

In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page.


Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application).


You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method:


clip_image004


Getting a Set of Records with the ASP.NET Web API


Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
public class MovieController : ApiController
{

public IEnumerable<Movie> ListMovies()
{
return new List<Movie> {
new Movie {Id=1, Title="Star Wars", Director="Lucas"},
new Movie {Id=1, Title="King Kong", Director="Jackson"},
new Movie {Id=1, Title="Memento", Director="Nolan"}
};
}

}
}

Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method):

routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

This route enables us to invoke the ListMovies() method with the URL /api/movie/listmovies.


Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>List Movies</title>
</head>
<body>

<div id="movies"></div>

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

listMovies(function (movies) {
var strMovies="";
$.each(movies, function (index, movie) {
strMovies += "<div>" + movie.Title + "</div>";
});
$("#movies").html(strMovies);

});

function listMovies(callback) {
$.ajax({
url: "/api/Movie/ListMovies",
data: {},
type: "GET",
contentType: "application/json;charset=utf-8",
}).then(function(movies){
callback(movies);
});
}

</script>

</body>
</html>

 

 

clip_image005


Inserting a Record with the ASP.NET Web API


Now let’s modify our Movie API controller so it supports creating new records:

public HttpResponseMessage<Movie> PostMovie(Movie movieToCreate)
{
// Add movieToCreate to the database and update primary key
movieToCreate.Id = 23;

// Build a response that contains the location of the new movie
var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created);
var relativePath = "/api/movie/" + movieToCreate.Id;
response.Headers.Location = new Uri(Request.RequestUri, relativePath);
return response;
}

The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database.


When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response.


Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request.


The following HTML page invokes the PostMovie() method.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create Movie</title>
</head>
<body>

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

var movieToCreate = {
title: "The Hobbit",
director: "Jackson"
};
createMovie(movieToCreate, function (newMovie) {
alert("New movie created with an Id of " + newMovie.Id);
});

function createMovie(movieToCreate, callback) {
$.ajax({
url: "/api/Movie",
data: JSON.stringify( movieToCreate ),
type: "POST",
contentType: "application/json;charset=utf-8",
statusCode: {
201: function (newMovie) {
callback(newMovie);
}
}
});
}

</script>

</body>
</html>

This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie:


clip_image006


The HTTP Post operation is performed with the following call to the jQuery $.ajax() method:

$.ajax({
url: "/api/Movie",
data: JSON.stringify( movieToCreate ),
type: "POST",
contentType: "application/json;charset=utf-8",
statusCode: {
201: function (newMovie) {
callback(newMovie);
}
}
});

Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method.


Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string.


Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code.


Updating a Record with the ASP.NET Web API


Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request:

public void PutMovie(Movie movieToUpdate)
{
if (movieToUpdate.Id == 1) {
// Update the movie in the database
return;
}

// If you can't find the movie to update
throw new HttpResponseException(HttpStatusCode.NotFound);
}

Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404.


The following HTML page illustrates how you can invoke the PutMovie() method:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Put Movie</title>
</head>
<body>

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

var movieToUpdate = {
id: 1,
title: "The Hobbit",
director: "Jackson"
};
updateMovie(movieToUpdate, function () {
alert("Movie updated!");
});

function updateMovie(movieToUpdate, callback) {
$.ajax({
url: "/api/Movie",
data: JSON.stringify(movieToUpdate),
type: "PUT",
contentType: "application/json;charset=utf-8",
statusCode: {
200: function () {
callback();
},
404: function () {
alert("Movie not found!");
}
}
});
}

</script>

</body>
</html>

Deleting a Record with the ASP.NET Web API


Here’s the code for deleting a movie:

public HttpResponseMessage DeleteMovie(int id)
{
// Delete the movie from the database

// Return status code
return new HttpResponseMessage(HttpStatusCode.NoContent);
}

This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204).


The following page illustrates how you can invoke the DeleteMovie() action:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Delete Movie</title>
</head>
<body>

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

deleteMovie(1, function () {
alert("Movie deleted!");
});

function deleteMovie(id, callback) {
$.ajax({
url: "/api/Movie",
data: JSON.stringify({id:id}),
type: "DELETE",
contentType: "application/json;charset=utf-8",
statusCode: {
204: function () {
callback();
}
}
});
}

</script>

</body>
</html>

Performing Validation


How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free.


Let’s modify our Movie class so it includes some of the standard validation attributes:

using System.ComponentModel.DataAnnotations;
namespace MyWebAPIApp.Models
{
public class Movie
{
public int Id { get; set; }

[Required(ErrorMessage="Title is required!")]
[StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")]
public string Title { get; set; }

[Required(ErrorMessage="Director is required!")]
public string Director { get; set; }
}
}

In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters.


Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database:

public HttpResponseMessage PostMovie(Movie movieToCreate)
{
// Validate movie
if (!ModelState.IsValid)
{
var errors = new JsonArray();
foreach (var prop in ModelState.Values)
{
if (prop.Errors.Any())
{
errors.Add(prop.Errors.First().ErrorMessage);
}
}
return new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest);
}

// Add movieToCreate to the database and update primary key
movieToCreate.Id = 23;

// Build a response that contains the location of the new movie
var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created);
var relativePath = "/api/movie/" + movieToCreate.Id;
response.Headers.Location = new Uri(Request.RequestUri, relativePath);
return response;
}

If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property — can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code).


The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create Movie</title>
</head>
<body>

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

var movieToCreate = {
title: "The Hobbit",
director: ""
};

createMovie(movieToCreate,
function (newMovie) {
alert("New movie created with an Id of " + newMovie.Id);
},
function (errors) {
var strErrors = "";
$.each(errors, function(index, err) {
strErrors += "*" + err + "\n";
});
alert(strErrors);
}
);

function createMovie(movieToCreate, success, fail) {
$.ajax({
url: "/api/Movie",
data: JSON.stringify(movieToCreate),
type: "POST",
contentType: "application/json;charset=utf-8",
statusCode: {
201: function (newMovie) {
success(newMovie);
},
400: function (xhr) {
var errors = JSON.parse(xhr.responseText);
fail(errors);
}
}
});
}

</script>

</body>
</html>

The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created.


If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert:


clip_image007


(Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness)


This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action:


http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation


His validation filter looks like this:

using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace MyWebAPIApp.Filters
{
public class ValidationActionFilter:ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
dynamic errors = new JsonObject();
foreach (var key in modelState.Keys)
{
var state = modelState[key];
if (state.Errors.Any())
{
errors[key] = state.Errors.First().ErrorMessage;
}
}
actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest);
}
}
}
}

And you can register the validation filter in the Application_Start() method in the Global.asax file like this:

GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter());

After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter.


Querying using OData


The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here:


http://odata.org


For example, here are some of the query options which you can use with OData:


· $orderby – Enables you to retrieve results in a certain order.


· $top – Enables you to retrieve a certain number of results.


· $skip – Enables you to skip over a certain number of results (use with $top for paging).


· $filter – Enables you to filter the results returned.


The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable.


For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies:

public IQueryable<Movie> GetMovies()
{
return new List<Movie> {
new Movie {Id=1, Title="Star Wars", Director="Lucas"},
new Movie {Id=2, Title="King Kong", Director="Jackson"},
new Movie {Id=3, Title="Willow", Director="Lucas"},
new Movie {Id=4, Title="Shrek", Director="Smith"},
new Movie {Id=5, Title="Memento", Director="Nolan"}
}.AsQueryable();
}

If you enter the following URL in your browser:


/api/movie?$top=2&$orderby=Title


Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results:


clip_image008


By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time.


The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples:


Return every movie directed by Lucas:


/api/movie?$filter=Director eq ‘Lucas’


Return every movie which has a title which starts with ‘S’:


/api/movie?$filter=startswith(Title,’S')


Return every movie which has an Id greater than 2:


/api/movie?$filter=Id gt 2


The complete documentation for the $filter option is located here:


http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption


Summary


The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API.


I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery.


Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option.


I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.




Friday, March 2, 2012

Earn $ with Your Business Mobile App

Earn $ with Your Business Mobile App: An article that discusses how to earn more on today's mobile market

Technical Resumes and Interviews

Having done a few horrible technical reviews lately, I figured I should post a little info to help prospective interviewees out. So here are some of my pet peeves that I run across during interviews (or on resumes) that will immediately get you removed from consideration.
Listing Skills or Technologies You Don’t Know

Seems obvious, but clearly it is not. If you list a technology on your resume (especially the harder ones or ones not strictly in your specialty), I’m going to ask about it. For instance, if you list all the technologies in a project you were on, but all you did was update ASP.NET pages and someone else did the WCF/SQL Server/whatever it is, you shouldn’t list it. Technology acronyms may get the recruiter’s attention, but I am going to ask you about it, and if you don’t know it, I’m going to assume your resume is a batch of lies. I don’t have the time to figure out what you do know so I’m just going to eliminate you.
Listing Clients as Employers

Your clients did not hire you as an employee, but a contractor. Those are very different scenarios. If you work for a contract house and worked on a project at Proctor & Gamble, P&G is not your employer. I have personally seen contractors list Microsoft as an employer because they worked on a project led by MCS. You were not an employee of Microsoft, you were a sub-contractor. You did not go through the extensive hiring process at Microsoft and pass. Someone at MS hired your company to provide developers, and not specifically to hire you. That’s not the same thing at all.
Brush up on Basics

If you are a developer whose main skill set is Java or .NET, you should know OOP basics. How about the four pillars of OOP? I am amazed that interviewees with 10+ years of experience can’t answer this question. If you know C#/Java/whatever, you should be able to tell me what the language keywords mean and their effect. I expect you to be able to write code in the interview. I don’t think you should be able to write up a connector for WIF, but some basic coding without the benefit of Uncle Google is a prerequisite.
Opinions

I am consistently shocked by the number of developers who won’t express an opinion, on even the simplest of questions, like what do you like better about C# compared to language X?. I don’t want team members who won’t tell me what they think or even tell me if I’m wrong. I’m pretty sure if you can’t express your opinion in an interview you can’t work on my team.
Look up your Interviewer

Again, seems pretty basic, but it doesn’t happen. I know the recruiter gave you my name. In almost 10 years of interviews, only two people actually looked me up ahead of time. If you are reading this before I interview you, congratulations, you are on the right track, but I’m pretty sure you are the minority. This is an easy way to demonstrate some initiative.
Ask Questions

If your only question is what is the project this interview is for, I’ll just assume you are a contractor looking for a gig and not looking for a career at my company. Again, I don’t want you. If you don’t know anything about my company going in, I’m going to assume you are lazy in your work as well.
Read These

Do yourself a favor, read about tech interviewing:

What Great .NET Developers Ought To Know
On Interviewing Programmers
The Guerrilla Guide to Interviewing

WCF REST Service with JSON

WCF REST Service with JSON: WCF REST Service with JSON in C#

DLL Dependency Viewer or How To Fix Exception: “Unable to load DLL “…” The specified module could not be found. (Exception from HRESULT: 0x8007007E)”

DLL Dependency Viewer or How To Fix Exception: “Unable to load DLL “…” The specified module could not be found. (Exception from HRESULT: 0x8007007E)”: How to fix this DLL importing error.

ASP.NET Interview Questions: - Show Post Cache substitution?

ASP.NET Interview Questions: - Show Post Cache substitution?:
This is one of the asked ASP.Net Interview Questions during the Interview by the Interviewer.
Post cache substitution is used when we want to cache the whole page but also need some dynamic region inside that cached page. Some examples like QuoteoftheDay, RandomPhotos, and AdRotator etc. are examples where we can implement Post Cache Substitution.

Post-cache substitution can be achieved by two means:








Figure: - “Writesubstitution” in action
You can see we have a static function here “GetDateToString()”. We pass the response substitution callback to the “WriteSubstitution” method. So now, when ASP.NET page framework retrieves the cached page, it automatically triggers your callback method to get the dynamic content. It then inserts your content into the cached HTML of the page. Even if your page has not been cached yet (for example, it's being rendered for the first time), ASP.NET still calls your callback in the same way to get the dynamic content. So you create a method that generates some dynamic content, and by doing so you guarantee that your method is always called, and it’s content is never cached.



Figure: - Substitution Control
Figure: - Substitution in Action
Below is a sample code that shows how substitution control works. We have ASPX code at the right hand side and class code at the behind code at the left hand side. We need to provide the method name in the “methodname” attribute of the substitution control.

View following video on Web.config transformation in ASP.Net: -



Learn more on ASP.NET interview questions

Regards,

From more on author’s blog related to ASP.NET interview questions click and visit.

Could not find a part of the path ... bin\roslyn\csc.exe

I am trying to run an ASP.NET MVC (model-view-controller) project retrieved from TFS (Team Foundation Server) source control. I have added a...