Here i post both technical and non-technical articles

Vahid Taslimi's blog (وبلاگ وحید تسلیمی)

ASP.NET Web API

233 comments

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.

Most of the new websites 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.

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.

Create a Web API Controller

to create a new web API controller you just need to select template as API Controller

image

this would create a class with default empty methods to get you started. 

to test this lets create a new class called Product to send data back to JavaScript:
   1:      public class Product
   2:      {
   3:          public int Id { get; set; }
   4:   
   5:          public string Name { get; set; }
   6:   
   7:      }
 
and let’s update the controller method as below for testing:
 
   1:      public class MyAPIController : ApiController
   2:      {
   3:          // GET /api/myapi
   4:          public IEnumerable<Product> Get()
   5:          {
   6:              return new List<Product>
   7:                  {
   8:                      new Product { Id = 1, Name = "Product1" }, 
   9:                      new Product { Id = 2, Name = "Product2" },
  10:                  };
  11:          }
  12:   
  13:          // GET /api/myapi/5
  14:          public Product Get(int id)
  15:          {
  16:              return new Product { Id = 3, Name = "Product3" };
  17:          }
  18:   
  19:          // POST /api/myapi
  20:          public HttpResponseMessage<Product> Post(Product newProduct)
  21:          {
  22:              newProduct.Id = 23;
  23:              var response = new HttpResponseMessage<Product>(newProduct, HttpStatusCode.Created);
  24:              var relativePath = "/api/movie/" + newProduct.Id;
  25:              response.Headers.Location = new Uri(Request.RequestUri, relativePath);
  26:              return response;
  27:          }
  28:   
  29:          // PUT /api/myapi/5
  30:          public void Put(int id, Product productToUpdate)
  31:          {
  32:              if (productToUpdate.Id == 1)
  33:              {
  34:                  // Update the movie in the database        
  35:                  return;
  36:              }
  37:              // If you can't find the movie to update   
  38:              throw new HttpResponseException(HttpStatusCode.NotFound);
  39:          }
  40:   
  41:          // DELETE /api/myapi/5
  42:          public HttpResponseMessage Delete(int id)
  43:          {
  44:              // Delete the movie from the database     // Return status code   
  45:              return new HttpResponseMessage(HttpStatusCode.NoContent);
  46:          }
  47:      }
 
To use this ASP.net creates the following route in the global.asax
   1:              routes.MapHttpRoute(
   2:                  name: "DefaultApi",
   3:                  routeTemplate: "api/{controller}/{id}",
   4:                  defaults: new { id = RouteParameter.Optional }
   5:              );
 
 

 

and let’s start using the Controller:

Get Single Product

To invoke the Get functions from JavaScript using JQuery you do the following:

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Get product</title>
   5:  </head>
   6:  <body>
   7:      <div>
   8:          Title: <span id="Id"></span>
   9:      </div>
  10:      <div>
  11:          Director: <span id="Name"></span>
  12:      </div>
  13:      <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
  14:      <script type="text/javascript">
  15:          getProduct(1, function (product) {
  16:              $("#Id").html(product.Id);
  17:              $("#Name").html(product.Name);
  18:          });
  19:   
  20:          function getProduct(id, callback) {
  21:              $.ajax({ url: "/api/MyAPI", data: { Id: id }
  22:           , type: "GET",
  23:                  contentType: "application/json;charset=utf-8",
  24:                  statusCode:
  25:           {
  26:               200: function (product) { callback(product); },
  27:               404: function () { alert("Not Found!"); }
  28:           }
  29:              });
  30:          }     
  31:      </script>
  32:  </body>
  33:  </html>

Get Multiple Products

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Get product</title>
   5:  </head>
   6:  <body>
   7:      <div>
   8:          <span id="Products"></span>
   9:      </div>
  10:      <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
  11:      <script type="text/javascript">
  12:   
  13:          getProducts(function (products) {
  14:              var strproducts = "";
  15:              $.each(products, function (index, product) {
  16:                  strproducts += "<div>" + product.Name + "</div>";
  17:              });
  18:              $("#Products").html(strproducts);
  19:          });
  20:               function getProducts(callback) {
  21:               $.ajax(
  22:               {
  23:                  url: "/api/MyAPI/",                
  24:                  data: {},
  25:                  type: "GET",
  26:                  contentType: "application/json;charset=utf-8",            
  27:               }).then(function(products){                
  28:                  callback(products);
  29:               });        
  30:               }
  31:      </script>
  32:  </body>
  33:  </html>

 

Insert a new Product

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Create product</title>
   5:  </head>
   6:  <body>
   7:      <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
   8:      <script type="text/javascript">
   9:          var productToCreate = {Id: "4", Name: "Product4" };
  10:         
  11:          createproduct(productToCreate, function (newproduct) {
  12:              alert("New product created with an Id of " + newproduct.Id);
  13:          });
  14:   
  15:          function createproduct(productToCreate, callback) {
  16:              $.ajax({
  17:                  url: "/api/MyAPI",
  18:                  data: JSON.stringify(productToCreate),
  19:                  type: "POST",
  20:                  contentType: "application/json;charset=utf-8",
  21:                  statusCode: {
  22:                      201: function (newproduct) {
  23:                          callback(newproduct);
  24:                      }
  25:                  }
  26:              });
  27:          }     
  28:      </script>
  29:  </body>
  30:  </html>

Update a Product

 

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Put product</title>
   5:  </head>
   6:  <body>
   7:      <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
   8:      <script type="text/javascript">
   9:          var productToUpdate = { id: 1, title: "Product5" };
  10:          updateproduct(productToUpdate, function () {
  11:              alert("product updated!");
  12:          });
  13:          function updateproduct(productToUpdate, callback) {
  14:              $.ajax({
  15:                  url: "/api/MyAPI",
  16:                  data: JSON.stringify(productToUpdate),
  17:                  type: "PUT",
  18:                  contentType: "application/json;charset=utf-8",
  19:                  statusCode: {
  20:                      200: function () {
  21:                          callback();
  22:                      },
  23:                      404: function () {
  24:                          alert("product not found!");
  25:                      }
  26:                  }
  27:              });
  28:          }     
  29:      </script>
  30:  </body>
  31:  </html>

Delete a Product

   1:  <!DOCTYPE html>
   2:  <html xmlns="http://www.w3.org/1999/xhtml">
   3:  <head>
   4:      <title>Delete product</title>
   5:  </head>
   6:  <body>
   7:      <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
   8:      <script type="text/javascript">
   9:          deleteproduct(1, function () {
  10:              alert("product deleted!");
  11:          });
  12:          function deleteproduct(id, callback) {
  13:              $.ajax({
  14:                  url: "/api/MyAPI",
  15:                  data: JSON.stringify({ Id: id }),
  16:                  type: "DELETE",
  17:                  contentType: "application/json;charset=utf-8",
  18:                  statusCode: {
  19:                      204: function () {
  20:                          callback();
  21:                      }
  22:                  }
  23:              });
  24:          }
  25:      </script>
  26:  </body>
  27:  </html>

 

having a quick look at the above sample, you’ll definitely agree that it’s quite simple to expose services through ASP.NET Web API. I am personally very excited about this Smile

 

Written by vahid

Thursday, March 8, 2012 at 4:11 AM

Tagged with

ASP.Net Page Lifecycle Events

163 comments

We all know a asp.net page events, but do we exactly know the orders? and what each event is good for?

well I am putting this list together to talk about the events.

  • PreInit
  • use this event to:
    • Set a master page dynamically.
    • Set the Theme property dynamically.
    • Read or set profile property values.

  • Init
  • Use this event to read or initialize control properties
  • InitComplete
  • Use this event to make changes to view state that you want to make sure are persisted after the next postback.
  • LoadState
  • ProcessPostData
  • PreLoad
  • Load
  • LoadComplete
  • PreRender
  • if you have got custom controls on your page and you want to manupulate the final page output based on some values in a custom control, you need to put your logic in this event.
  • SaveState
  • Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
  • Render

Written by vahid

Wednesday, March 7, 2012 at 5:10 AM

Tagged with

Visual Studio 2010 not opening CSS files

205 comments

if you are not able to open css files in Visual Studio 2010 because of any reason and keep getting this error message:

“visual studio 2010 the operation could not be completed css”

here is what you need to do:

Click on the Tools Menu => Extension Manager => Select Online Extensions => Search for “Web Standards Update for Microsoft Visual Studio 2010 sp1” and install the extension.

if you have already installed the extension, run the setup and repair it.

in my case it happened after I installed MVC4 beta. and althogh I had already had the extension installed it was not opening CSS files and repairing the extension fixed it.

Written by vahid

Monday, March 5, 2012 at 4:02 AM

Tagged with , ,

Why I believe in lean software development

171 comments

Few weeks ago I got myself an Amazon Kindle to facilitate book reading and hopefully get back my reading habits. I am so amazed by the device that today I twitted “it’s my best gadget”. now there are very genuine reasons behind the twit.

it’s meant to be used to read books and it does it perfectly.

  • it has a great screen which is optimized for the reading.
  • does not hurt your eyes.
  • you can read books even in the direct sunlight.
  • it’s handy and light so very easy to carry with you
  • it’s got a long lasting battery life
  • bot built in dictionary which is extremely easy to use
  • has got a great search functionality
  • has got wireless connection so that Amazon can push the books immediately to the device
  • it’s very very easy to use

I have just mentioned couple of it’s great features. don’t get me wrong, I don’t work for Amazon and I am not doing any promotion for the Kindle. the moral of what I have mentioned above it that IT DOES WHAT IT IS SUPPOSED TO DO AT IT’S BEST.

I mean when I need a device to read books on it, I don’t need to have a million color screen with back light which would hurt my eyes and make them tired after couple of pages. yap I agree it would be good to be able to play 3d games on it BUT it requires changing the display type or maybe putting two different displays in the device –crazy but possible-. I would call either of them over engineering which will work against the device objectives. the same scenario is true with almost all characteristics of the Kindle.

now the reason I believe that software development and management should be done in the same way that Kindle development is done is:

  • before starting a new software project, the team should be clear about what they are going to do. i.e. they should know they going to create a book reading device or a gaming device
  • they need to focus on what they are supposed to deliver and how they can deliver it with the best quality. i.e. they need to focus on delivering a device on which reading the book is easy and it’s not important if you can play games on it.
  • they should keep the life as simple as possible not try to inject extra functionalities to the deliverables until and unless it’s absolutely required. i.e. I don’t need to have joy stick on the Kindle I’d rather have to buttons to navigate through the pages.
  • stop over engineering the project. gold plating and over engineering the deliverables most of the time will distract you from focusing on the core values of the project and very often will be your own headache cause you don’t know the impact it. i.e. Kindle does not come as a dual screen device on which you can watch movies and read books because this is not Kindle’s objective.
  • keep your solutions easy to use
  • and finally never give up improving the quality of the functionalities you provide

so these were some of my ideas on delivering software systems the same way Kindle was delivered. I strongly believe most of the software systems development fail either because of the ambiguity of the deliverables specifications or because of over engineering the solution.

Written by vahid

Wednesday, March 7, 2012 at 4:52 AM

Tagged with