More About HTTP Protocol

Tutorial Introduction

Hi again and welcome in the 2nd part of “Building N-Tier RESTful API using ASP.NET Web API 2” Tutorial.

This part indeed intended to be part of the tutorial but it’s totally independent of ASP.NET as i’ll be discussing HTTP Protocol in abstract so if you’re interested to know more about the HTTP Protocol and you’re not a .NET Developer it’s still the right place for you ^^

It has been a long time since i wrote the first part and i didn’t continue to deliver the tutorial content i’m sorry for that, Now i promise that i’ll continue to deliver the whole content of the tutorial as i’ll write a new part on weekly basis, Hope you’ll enjoy.

In this tutorial you’ll learn how to develop an API using ASP.NET Web API 2, N-Tier Architecture, and a lot of stuff that will help you to get started building your awesome API confidently

Tutorial Parts

  1. Build Your First API using Web API 2
  2. More About HTTP Protocol

Tutorial Pre-Requests

  • Strong knowledge of OOP and C#
  • Experience with Web Development
  • Experience with JavaScript
  • A little knowledge of AngularJS (To build client app at the end of the tutorial)

What you’ll learn in this tutorial

I’m actually planning a lot of stuff and want to make it a complete tutorial so

  • RESTful API architecture
  • ASP.NET Web API 2
  • N-Tier architecture
  • Dependency Injection
  • OData protocol
  • Build a client application with AngularJS and awesome Angular Material for the UI
  • And a lot more..

Source Code:

You can find the code for this tutorial in this GitHub Repository.


Part 2: More About HTTP Protocol

HTTP Protocol is the heart of the web nowadays so it’s very important for web developers to have a great understanding of what’s the HTTP Protocol.

HTTP stands for “Hypertext Transfer Protocol”, Great so what’s that means? Lets split this definition into 3 segements

  • Hypertext: Is a text that contains links to another text. Given an example the blog post’s page you’re reading right now. It’s a text that contains links or references to another text you can click the link to get navigated to the other text.
  • Transfer: At some point the text you’re reading is located somewhere on the earth in some storage device. In order for you to read this text it has to be transferred to your device and that what’s transfer refers to. So using network communication between your device and wordpress server the text of this blog is being transferred to your device.
  • Protocol: Some guys are getting worried about this word but it isn’t this hard to understand. Okay assume you’re working in a warehouse and I’ll ship some products to you. So you’ll ask me for some stuff and I’ll ship it safely to your warehouse. But in order for this to work perfectly there has to be some agreement that we both know to minimize the mistakes for example there has to be a document describing the items being shipped a long with its quantities, ids, price, ..Etc. Also the items should arrive in closed boxes that’s labeled with the item id and quantity. If we didn’t do this every time I’ll deliver you the order and you’ll do millions of mistakes because you don’t know what’s product in which box and how many quantities. And that’s all should results a lot of mistakes. Simply this is called a Protocol.

So the HTTP is simply the agreement between all network devices using this protocol to understand the way in which the hypertext is going to be transferred via a network communication. HTTP is the heart of the internet nowadays everyone is using HTTP daily surfing the internet.

HTTP is Stateless Protocol

Well stateless means that you’re going to ask me to buy a product and I’ll ask you for your ID then I’ll give it to you. If you left and came back even after a second to buy another thing I’ll ask you for your ID again (I don’t know you, I Forgot).

That means HTTP Protocol treats each request independently of any other requests, Unlike TCP protocol which is stateful. However it’s great to note that HTTP uses TCP for transportation. Here’s come a question how can HTTP be stateless while its relying on a stateful protocol TCP. To answer that let’s give an example of your cell phone. Let’s assume that your cell phone is establishing a stateful connection to the network provider using the TCP protocol. And i’ve decided to call you so i’ve sent a HTTP request to do that, And you’ve responded and we had a great call then we’ve disconnected. After we disconnect the call you’re not anymore with me on the phone, And if want to call you again it’s a totally new call that’s independentent of the previous one.

It’s all about Request/Response

HTTP Protocol is all about a client that sends an HTTP Request to the server and the server process the request and respond back with an HTTP Response.

Figure 1- HTTP Request/Response

Understanding HTTP Request

HTTP Request is the way of how client will communicate with the server via HTTP Protocol, As we previously mentioned what’s protocol so an HTTP Request is having a well-defined elements and should be used correctly in order to follow the protocol guidelines.

HTTP Request Elements

1- URL

Of course everyone knows what URLs is. Well given an example this url http://www.blogwebsite.com/articles?title=http&author=ibrahim let’s split it into multiple segments

  1. http:// is the protocol that’s used it can be HTTPS instead of HTTP we may speak about HTTPS later but currently it’s out of the blog post scope
  2. http://www.blogwebsite.com is the Domain and it’s actually a unique name reserved for some server in the web. Your browser will look up for this domain in some DNS to get the server IP address that’s associated with this domain name in order to send the request to.
  3. /articles this is called the Resource Path and it’s handled by the server to locate the resource you’re looking for. Like in the previous part we’ve created some controllers and actions that we requested via its corresponding resource path.
  4. ?title=http&author=ibrahim This is called a Query String and we’ll check how it’s used later in this series. It’s a way of passing parameters to the server via the URL that it’ll going to be used somehow for purposes like filtering the results or it’ll be ignored by the server.

2- HTTP Methods (Verbs)

You want to send a request to the server and the server should take an action upon this request whether retrieving, creating, modifying or deleting some data. HTTP Methods describes the action that the server should take.

HTTP Methods are a well-defined methods by the standard Find it here (below a table describing most commonly used HTTP Methods)

Safe Methods: some HTTP methods are marked as “safe”. Which means they wont make any changes to a resource on the server and they’re used only for retrieval
Idempotent Methods: are methods that can be called many times without different outcome. (All safe methods are idempotent).

Method Description Safe Idempotent
GET Used to retrieve a resource Yes Yes
HEAD Used to obtain meta-information about the resource (HEAD is identical to get but doesn’t have request body, HEAD response header should be identical as if it was GET) Yes Yes
POST Used to create a new resource on the server No No
PUT Used to modify a resource (or create new one if not exists) No Yes
PATCH Used for a partial resource modifications No No
DELETE Used to delete a resource on the server. No Yes
OPTIONS Usually used before any preflight cross-origin request in order to know whether it’s safe to do it. Yes Yes

3- Request Headers:

Request headers are used to carry some information (metadata) about the request itself. Like Authentication Token, The language you want to retrieve the data with, ..etc. We’ll use many HTTP Headers in practice but not in this part.

HTTP Headers are well-defined headers by the standard some of it is used to be sent with the request and some other to be returned along with the response Find it here, However you can create your own Custom Header that you know how to use it on the server. (below is a list of the most commonly used Request Headers)

Header Usage
Accept What data formats in which the client wants. (e.g., text/html, application/xml)
Accept-Language What languages in whic the client wants the data to be in. (e.g., en-US, ar-EG)
Accept-Charset The characterset in which the client wants. (e.g., utf8, ISO-8859-1)
Cookie Used to send the cookie that’s saved on the user’s browser that could contain some information about the user to the server.
Authorization Used to send authorization token to verify if the requester is authenticated

There’s a lot more headers we were just peeking some of them. We’ll get in depth with HTTP Headers later on in the tutorial.

4- Request Body:

Request body is used to send data to the server. Calling from the previous part we wanted to create a news article so we sent the data in which we want the article to be created for the server to process.

The server is responsible for validating the request body’s data and if it matches the structure and contains the mandatory data for the resource to be created/modified, hence the server should process the request and return a success indicator otherwise the server should return an error

Here’s a figure showing request elements and how it look likes. I’ve used fiddler to capture HTTP Requests it’s a very useful tool that’ll going to need it Find it here

Figure 2- Showing Request Elements

Understanding HTTP Response

Okay a client has sent a request to the server. Now it’s the server turn to check the request elements to do the corresponding action, After the server finished its work it’ll respond back with an HTTP Response

Like HTTP Request an HTTP Response have some elements that describes what’s it all about.

HTTP Response Elements

1- Status Code

Assuming you’ve taken an exam in college and the result is now published. What’s the first thing you’ll look for is it the reasons and the grade of each question or what’s the answers you failed in.

Of course not you’ll look for some Indicator of Success and it’s likely a well defined range values [Excellent, Very Good, Good, Passed, Failed]

Same here the HTTP Response comes along with a Status Code that should be used to indicate the success of the request. The standard defines wide range of codes to indicate the action result as well not only success or failed Find it here (below a list of most commonly used status codes)

  • 100 Continue: Means server has recieved the request headers and the client should proceed and send the body.
  • 101 Switching Protocol: Means that client asked for switching the protocol and the server accepted.
  • 102 Processing: Means that server has recieved and is processing the request but no response available yet. (If the processing takes to long so this’s sent to prevent the client from timing out and assume that the request was lost)
  • 103 Checkpoint: Used in resumable requests proposal to resume aborted POST, PUT (think of it as an aborted upload scenario)

2xx Success:
Indicates that the action requested has been completed successfully

  • 200 Ok: The standard response for successful HTTP Requests. Response has a body enclosing a representation of the resource requested.
  • 201 Created: Indicates that a new resource has been created succesfully. Usually response has a body enclosing a representation of the newly created resource and a Location Header with a url to ‘GET’ the created resource.
  • 202 Accepted: The request has been accepted but the processing has not been completed.
  • 203 Non-Authoritative Information: The request has been processed successfully but is returning information that maybe from another source
  • 204 No-Content: The request has been processed successfully. But the server not returning any content (Empty Body).
  • 205 Reset-Content: Just like (204 No-Content). But requires the requestor to reset the document view (for instance clear the form for new input).
  • 206 Partial-Content: The server has processed the partial GET request (Usually used for retrieving big size data)

3xx Redirect:

  • 300 Multiple Choices: Server has several options and may choose one based on requestor (User Agent) or will give a list of options to the requestor to choose form.
  • 301 Moved Permanently: The requested page has been permanently moved to another location (When server responds with this status code the client automatically moved to the new location).
  • 302 Found: This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
  • 303 See Other: Server sent this response to directing client to get requested resource to another URI with an GET request.
  • 304 Not Modified: This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response.
  • 305 Use Proxy: This means requested response must be accessed by a proxy. This response code is not largely supported because security reasons.
  • 306 Unused: This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.
  • 307 Temporary Redirect: Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used.
  • 308 Permanent Redirect: This means that the resource is now permanently located at another URI. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used.

4xx Client Error:

  • 400 Bad Request: This response means that server could not understand the request due to invalid syntax.
  • 401 Unauthorized: Authentication is needed to get requested response. This is similar to 403, but in this case, authentication is possible.
  • 402 Payment Request: This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.
  • 403 Forbidden: Client does not have access rights to the content so server is rejecting to give proper response.
  • 404 Not Found: Server can not find requested resource.
  • 405 Method Not Allowed: The request method is known by the server but has been disabled and cannot be used. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
  • 406 Not Acceptable: This response is sent when the web server, after performing server-driven content negotiation, doesn’t find any content following the criteria given by the user agent.
  • 407 Proxy Authentication Required: This is similar to 401 but authentication is needed to be done by a proxy.
  • 408 Request Timeout: This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection.
  • 409 Conflict: This response would be sent when a request conflict with current state of server.
  • 410 Gone: This response would be sent when requested content has been deleted from server.
  • 411 Length Required: Server rejected the request because the Content-Length header field is not defined and the server requires it.
  • 412 Precondition Failed: The client has indicated preconditions in its headers which the server does not meet.
  • 413 Payload Too Large: Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.
  • 414 URI Too Long: The URI requested by the client is longer than the server is willing to interpret.
  • 415 Unsupported Media Type: The media format of the requested data is not supported by the server, so the server is rejecting the request.
  • 416 Requested Range Not Satisfiable: The range specified by the Range header field in the request can’t be fulfilled; it’s possible that the range is outside the size of the target URI’s data.
  • 417 Expectation Failed: This response code means the expectation indicated by the Expect request header field can’t be met by the server.
  • 421 Misdirected Request: The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
  • 426 Upgrade Required: The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
  • 428 Precondition Required: The origin server requires the request to be conditional. Intended to prevent “the ‘lost update’ problem, where a client GETs a resource’s state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.”
  • 429 Too Many Requests: The user has sent too many requests in a given amount of time.
  • 431 Request Header Fields Too Large: The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.

5xx Server Error:

  • 500 Internal Server Error: The server has encountered a situation it doesn’t know how to handle.
  • 501 Not Implemented: The request method is not supported by the server and cannot be handled.
  • 502 Bad Gateway: This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
  • 503 Service Unavailable: The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent.
  • 504 Gateway Timeout: This error response is given when the server is acting as a gateway and cannot get a response in time.
  • 505 HTTP Version Not Supported: The HTTP version used in the request is not supported by the server.
  • 506 Variant Also Negotiates: The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.
  • 507 Insufficient Storage: The server is unable to store the representation needed to complete the request.
  • 511 Network Authentication Required: The client needs to authenticate to gain network access.

2- Response Headers

Same as Request Headers a Response Headers are also HTTP Headers that contains some metadata about the response itself. (below a table of most commonly used Response Headers)

Header Usage
Content-Type The type of the data within the response body (e.g., application/xml, application/json, text/html)
Etag Entity Tag that’s used for client-side caching (We’ll discuss what’s caching in more details later)
Last-Modified Time Stamp indicating when the last time the resource being requested (i.e., the data requested) has been modified. (Also used for caching)

3- Response Body

Same as Request Body a Response Body will contains the data the server wants to send back to the client

Figure 2- Showing Response Elements

Now i’m done for this part hope you enjoyed as i’ve said i promise to complete the series by posting a part every week so the next week i’ll be discussing REST Architecture hope you’ll enjoy it.

Building N-Tier RESTful API using ASP.NET Web API 2 (Part 1)

Tutorial Introduction

Hi everyone, and welcome in the first part of “Building N-Tier

RESTful API using ASP.NET Web API 2” Tutorial.
In this tutorial you’ll learn how to develop an API using ASP.NET Web API 2, N-Tier Architecture, and a lot of stuff that will help you to get started building your awesome API confidently

Tutorial Parts

  1. Build Your First API using Web API 2
  2. More About HTTP Protocol

Tutorial Pre-Requests

  • Strong knowledge of OOP and C#
  • Experience with Web Development
  • Experience with JavaScript
  • A little knowledge of AngularJS (To build client app at the end of the tutorial)

What you’ll learn in this tutorial

I’m actually planning a lot of stuff and want to make it a complete tutorial so

  • RESTful API architecture
  • ASP.NET Web API 2
  • N-Tier architecture
  • Dependency Injection
  • OData protocol
  • Build a client application with AngularJS and awesome Angular Material for the UI
  • And a lot more..

Source Code:

You can find the code for this tutorial in this GitHub Repository.

Part 1 – Build Your First API using Web API 2

API (Application Programming Interface) is an interface for building HTTP Web Service that can be used to retrieve, create or update data. ASP.NET WEB API is Microsoft’s Implementation of API that enables you to use the capabilities of the .NET Framework to develop a robust API. Web API is not like ASP.NET MVC some people think they’re the same but they aren’t, in ASP.NET MVC you’re building a Web Site you’ll render the html page and pass it directly to the client which in this case a web browser. In Web API you wont be building a website you wont be rendering html page to the client instead you’ll give it “Data” using whatever format JSON, XML, or whatever.

Q- But can’t i return a “Data” to the client using ASP.NET MVC there’s a JSON helper method for example that returns JSON and i also can return XML or whatever?

A- Of course you can but developing an API is not only by returning “Data” so let’s discuss the differences between both and clarify why you should choose Web API instead of ASP.NET MVC to build your API

1- Content Negotiation

In ASP.NET MVC usually you’re returning a View but if you want to return another data type it’s ok so let’s return a JSON

 public class NewsController : Controller
  {
    public ActionResult GetNews()
    {
       return Json(GetAllNews(), JsonRequestBehavior.AllowGet);
    }
  }

Now i’ve created an action to return some news in JSON format but what if a client wants XML format? Should i create an action for every data format (Ofc Not). Or should i create another ActionResult to return Xml and get a parameter in the action indicating whether to return Xml or Json? Or should i read the “Accept” request header and make some if .. else to return the appropriate data format? Before answering these questions let’s see how does Web API address this issue we face.

public class NewsController : ApiController
{
  public IHttpActionResult GetNews()
  {
    return Ok(GetAllNews());
  }
}

In Web Api you don’t specify the data format to return instead you’re more concerned about the response itself whether it’s succeeded, failed, unauthorized, or whatever. We’ll discuss these stuff later in the tutorial. And you’re not concerned about what’s the data format the user will get! instead you configure your API with the data formats you support! for example i want to support Xml and Json format. The request that wants Xml will get Xml response on the other hand if it wants Json it will get Json. Ofc this separation of concerns is a big win of ASP.NET Web API when developing an APIs.

2- OData support

Web API is supporting OData protocol that we’ll use later in our tutorial. It’s a very powerful protocol that allows you to write data queries in the query string that will be translated, executed and returning the data you’re expected as if you wrote a SQL query (Ofc with some limitations compared to SQL). As ASP.NET MVC is not designed for that it doesn’t

3- Based on REST Architecture

As Web API is made for designing RESTful APIs it’s by default supports that. For example routes are mapped by HTTP Verbs (GET, POST, PUT, ..etc) rather than Method Name (GetNews).

4- Authentication

In ASP.NET MVC usually you’re using cookies to place authentication tickets but what if your client was a native mobile app ??

And a lot more of differences and issues, with all the respect to ASP.NET MVC it’s a great platform i believe but great for what it’s great for (Building Websites) not APIs. So now let’s go through and create our first News API using ASP.NET Web API 2

Create First ASP.NET Web API

1- Open Visual Studio and Create New Project
2- Choose Web then ASP.NET Web Application. I’ll set NewsApi as the solution name i’ll use throughout this tutorial.
3- Choose the empty template and select Web API reference.
4- Hello Web API. as you can see everything seems normal and nothing different let’s discuss the project parts.

As you can see it seems like ASP.NET MVC project we’ve Web.config file that includes the configurations and package.config that includes our installed nuget packages

Global.asax that initialize our web application like in ASP.NET MVC (Will we need it? No) we’ll see how and why we’ll get rid of it.

WebApiConfig.cs Hmm that’s a new friend let’s see what it contains. But where’s the rest of files that’s created by default to our App_Start folder like BundleConfig.cs the answer here is (What’re you going to bundle?) there’s no scripts no css files it’s only an API that returns “Data”.

5- Exploring WebApiConfig.cs

This file is used to hold all the initial configuration to your API. Initially it includes the Routing Configurations. And if you look closer you’ll see a little difference between it and ASP.NET MVC. In ASP.NET MVC the route template is “{controller}/{action}/{id}” here it’s “api/{controller}/{id}”. Oh where is the action? how’s the routing engine will figure out what’s the correct action to map if all the routes going to the same url?. As we discussed earlier it will map them by HTTP Verb instead of Action Name and we shall see this later. Now let’s setup our environment.

6- Open Package Manager Console and type “Install-Package EntityFramework”

I’ll use Entity Framework Code First to create our database if you need some information about it i recommend you visit this website. Now let’s create our Model

Let’s go to Model folder and create 2 classes which are “Author” and “Article” as following

public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Article> Articles { get; set; }
}

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime DatePosted { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

We’ll use these classes to initialize our Database now let’s create our DbContext and seed it with some data

public class NewsDbContext : DbContext
{
  public NewsDbContext()
  {
    Database.SetInitializer(new NewsDbInitializer());
  }
  public DbSet<Author> Authors { get; set; }
  public DbSet<Article> Articles { get; set;}
}

public class NewsDbInitializer : CreateDatabaseIfNotExists<NewsDbContext>
{
  protected override void Seed(NewsDbContext context)
  {
    List<Author> authors = new List<Author>();
    for (var c = 0; c < 100; c++)
    {
      Author author = new Author()
       {
         Name = "Author " + c,
         Articles = new List<Article>()
       };
      int numberOfArticles = new Random().Next(3, 10);
      for(var j = 0 ; j <= numberOfArticles ; j++)
      {
        author.Articles.Add(new Article()
         {
           Title = "New Article Title",
           Body = "New Article Body",
           DatePosted = DateTime.Now
         });
      }
      authors.Add(author);
    }
    context.Authors.AddRange(authors);
    base.Seed(context);
  }
}

Now i’ve created our NewsDbContext and NewsDbInitializer to initialize and seed our database with mock data. Now the database is ready so let’s create a controller that do some CRUD operations. But first we need to create View Models that’s responsible for transfering data from and to the client. Now create a folder and name it ViewModels and create 2 classes AuthorViewModel and ArticleViewModel as following

public class AuthorViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class ArticleViewModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public DateTime DatePosted { get; set; }
    public int AuthorId { get; set; }
    public string AuthorName { get; set; }
}

Well great now let’s create AuthorsController in Controllers Folder as following

public class AuthorsController : ApiController
{
  public async Task<IHttpActionResult> Get()
  {
    using (NewsDbContext ctx = new NewsDbContext())
    {
      var authors = await ctx.Authors.Select(o => new AuthorViewModel()
        {
         Id = o.Id,
         Name = o.Name
        }).ToListAsync();
      return Ok(authors);
    }
  }
}

Notice that in Web API all controller classes inherits from ApiController unlike Controller in ASP.NET MVC and Actions returns IHttpActionResult instead of the abstract ActionResult class in ASP.NET MVC. Now i’ve created only 1 action method and i’ve named it Get (I’ll discuss why i’ve named it like that later in the next part of the tutorial) it’s responsible for getting a list of all authors in our database. But what’s return Ok(). Well in Web API you’re not concerned here with the data format the user will receive you’re concerned with the response itself so Ok() will return (200 Http Status Code) and i’ll explain what’s status codes and how can we use it in a great way. But what’s the data format will be returned ?. By default Web API supports 2 data formats which are (JSON and XML).

Now let’s use the great tool Postman to test our API you can use your favorite tool.

7- Getting authors data

Notice here the url is http://localhost:15300/api/authors there’s nothing to indicate that we want the Get Action we created. That’s because of the HTTP Verb Look at the left of the url you’ll find that the request is sent as “GET” request. ASP.NET Web API routing by default map the action method name to the equivalent HTTP Verb without any configurations from your side like mark the method with HttpGetAttribute That’s why i’ve named the method Get. Now let’s see how if i decided to get XML instead of JSON. I’ll write Accept header in the request and we should get the data in XML format.

8- Getting data in XML Format

Now it’s obvious. You configure the data formats you want to support (By Default: Xml and Json) and you shouldn’t worry about what will the client recieve.

Now let’s prepare our controller to do CRUD operations to Authors in the API. First we’ll need to create 2 more View Models which are CreateAuthorViewModel and EditAuthorViewModel

public class CreateAuthorViewModel
{
  [Required(AllowEmptyStrings = false)]
  public string Name { get; set; }
}

public class EditAuthorViewModel
{
  [Required]
  public int? Id { get; set; }
 
  [Required(AllowEmptyStrings = false)]
  public string Name { get; set; }
}

Then let’s prepare our AuthorsController

public class AuthorsController : ApiController
{
    public async Task<IHttpActionResult> Get()
    {
      using (NewsDbContext ctx = new NewsDbContext())
      {
        var authors = await ctx.Authors.Select(o => new AuthorViewModel()
          {
            Id = o.Id,
            Name = o.Name
          }).ToListAsync();
        return Ok(authors);
      }
    }
    
public async Task<IHttpActionResult> Get(int id)
{
    using (var ctx = new NewsDbContext())
    {
      var author = await ctx.Authors.FirstOrDefaultAsync(o => o.Id == id);
      if (author == null)
        return NotFound();
      
      var data = new AuthorViewModel()
        {
          Id = author.Id,
          Name = author.Name
        };
      return Ok(data);
     }
  }
  
  public async Task<IHttpActionResult> Post(CreateAuthorViewModel model)
  {
    if (!ModelState.IsValid)
      return BadRequest(ModelState);
    
    using (var ctx = new NewsDbContext())
    {
      var author = new Author()
        {
          Name = model.Name
        };
      
      ctx.Authors.Add(author);
      await ctx.SaveChangesAsync();

      var data = new AuthorViewModel()
        {
          Id = author.Id,
          Name =  author.Name
        };
      return Created(new Uri(Request.RequestUri +"api/authors" + data.Id), data);
    }
  }
  
  public async Task<IHttpActionResult> Put(EditAuthorViewModel model)
  {
    if(!ModelState.IsValid)
      return BadRequest(ModelState);
    
    using (var ctx = new NewsDbContext())
    {
      var author = new Author()
        {
          Id = model.Id.Value,
          Name = model.Name
        };
      
      ctx.Authors.Attach(author);
      ctx.Entry(author).State = EntityState.Modified;
      await ctx.SaveChangesAsync();
      return StatusCode(HttpStatusCode.NoContent);
    }
  }
  
  public async Task<IHttpActionResult> Delete(int id)
  {
    using (var ctx = new NewsDbContext())
    {
      var author = await ctx.Authors.FirstOrDefaultAsync(o => o.Id == id);
      if (author == null)
        return NotFound();
    
      ctx.Authors.Remove(author);
      await ctx.SaveChangesAsync();
      return StatusCode(HttpStatusCode.NoContent);
    }
  }
}

Now let’s test these end points then discuss them. First let’s create an Author and him “Ibrahim Abdel Kareem” then let’s get this author’s data and then let’s update it to be “Ibrahim Abdel Kareem (Hema)” and get it again and then we’ll remove it.
Note: in the following figures try to observe the HTTP Verbs i’ll use and the returned HTTP Status Codes as i’ll discuss it later.

9- Creating an author

Here i’ve used the HTTP Verb Post to create a new Author, i’ve passed the data i want in the request’s body in json format and i got HTTP Status Code (201) which refers to Created. You’ll notice in the Action Method i’ve passed a url to the Created helper method. I’ll discuss why i did this in the next post when i’m going to discuss REST Architecture in more details as well i’ll explain what’s HTTP Status Codes and why we should use them correctly.

10- Retrieving the author we’ve created

Now i sent a GET request to retrieve the author i’ve created. But wait how is the GET request getting a single object of a single author not like before a list of all authors. Yes that’s because of the overloaded Get Action method i’ve created that takes an id as parameter. If you looked at the Url you’ll see /104. This indicates i want the method with the id parameter and i’ve got an HTTP 200 Status code which refers to Ok with the data of the author i’m requesting in the response body

11- Create another author with empty data

Now i’m trying to create another author but i’m passing an empty name in the request body and here’s the data annotations comes to play. I’ve got an HTTP Status Code 400 which refers to Bad Request along with the errors in the response body.

12- Updating the author

Now i’ve sent a PUT request to update the author and i’ve got HTTP Status Code 204 which refers to No Content. As i’ve said this all will be very obvious to you in the next post. but so far it’s an indication of success let’s get more sure by retrieving the author again.

13- Retrieving the author we’ve updated

Notice now the name has been changed. Now let’s delete this author.

14- Deleting the author

Now i’ve sent a DELETE request with the id in the url and i’ve got HTTP Status Code 204 No Content which indicates the success of the operation. Let’s try to retrieve it.

15- Retrieving the deleted author

Oooops! We got HTTP Status Code 404 which refers to Not Found. Usually if you came from MVC background you’ll wonder isn’t 404 indicates that page not found. Yes you’re totally right but here we’re not dealing with pages we’re dealing with resources, That means the API couldn’t find the resource you’re requesting.

Now i’m done for this part of the tutorial. Next i’ll be discussing the REST Architecture.

Hope you enjoyed this part you can find the source code in Github by following this Url.

Value Types & Reference Types – In C# (Part I)

Along with your C# learning process you have been working with different types, You maybe a starter so you just used primitive types (e.g., int, string, double, ..etc), Exposed some functionality within a specific type (e.g., Console.WriteLine() ), Or you maybe gone deeper and have been creating your own types and instantiating objects from it. So you should have been noticed that in C# it’s all about types, I’m sure also that the you’ve at least seen the term (Value & Reference Types) or having some knowledge of it, From my point of view understanding the difference between Value & Reference Types is critical important for any .Net Developer.

In this blog post I’ll explain the differences between Value Types & Reference types and I’ll try to cover most parts of these two concepts hope you will enjoy reading it ^^ Kindly if you have any questions comment it down and I’ll be glad answering it once I’m available.

So you learned how to create your own types to represent set of data and behavior, And you have been creating objects from these types to hold data and to expose it’s functionality. I think you declared these various types using the “class” keyword. If that’s right so you have declared a Reference Type, Any Type you create using “class” keyword is a Reference Type, Figure 1 will show you an example.

//Figure 1 - Creating Class Example
class Person
    {
        //Instance Fields
        private string name;
        private int age;

        //Instance Constructors
        public Person()
        {

        }
        public Person(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        //Properties
        public string Name
        {
            get { return name; }
            set
            {
                if(!string.IsNullOrEmpty(value))
                  name = value;
            }
        }

        public int Age
        {
            get { return age; }
            set
            {
                if (value &amp;lt; 0)
                    throw new ArgumentOutOfRangeException("Age", "A Person Age Cannot Be Less Than 0.");
            }
        }

        //Instance Method
        public void DisplayName()
        {
            Console.WriteLine(Name);
        }
    }

let’s analyze the code shown above. We have a very simple Type called Person which have some instance fields, methods and properties, Person type is a Reference Type because it’s created using “class” keyword. Until now everything you have seen should be very clear to you. But you should have to know somethings that happens when you work with Reference Types ?

  • Memory allocated from the Managed Heap.
  • Variable contains pointer to the Instance in Managed Heap.
  • Any Reference Type Object has two overhead members that have to be initialized.
  • Bytes for the instance fields are Zeroed out.
  • Garbage Collector may occur to free the memory when the object is unused.

Okay great, i think you now saying “So What” but think for a moment if every time you create a small int a memory allocation occur and initialization of two overhead members occur and that you’ll have to wait GC to free out the memory used by this int and whenever you need to manipulate this int a pointer dereference occurs. It wont be good for your application performance, Actually it will be horrible for your application performance. That’s why the .Net Framework offers Value Types which are lightweight types, according to the previous speech of Reference Types what is the difference working with Value Types?

  • Value Types Instances allocated directly in the Thread Stack not in the Managed Heap.
  • Variable contains the value of the instance.
  • It has no overhead members.
  • When the instance is unused it’s removed directly from the stack (GC doesn’t need to occur).

Wow that’s great so why we don’t use Value Types always instead of classes ? The answer to this question is coming below by the end of this topic ^^ let’s check Figure 2 which shows an example of creating a Value Type.


//Figure 2 - Creating Value Type

struct VPerson
    {
        //Instance Fields
        private string name;
        private int age;

        //Instance Constructors
        public VPerson(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        //Properties
        public string Name
        {
            get { return name; }
            set
            {
                if(!string.IsNullOrEmpty(value))
                  name = value;
            }
        }

        public int Age
        {
            get { return age; }
            set
            {
                if (value &amp;lt; 0)
                    throw new ArgumentOutOfRangeException("Age", "A Person Age Cannot Be Less Than 0.");
            }
        }

        //Instance Method
        public void DisplayName()
        {
            Console.WriteLine(Name);
        }
    }

Okay now a Value Type called VPerson (V for Value Type) that have almost everything like the Person class, But hey where is the parameterless constructor that was in the Person class ? Well as Value Types considered lightweight Types it has some limitations compared to Reference Types that i’ll cover but first let’s use our two Types so you can better understand the differences between both Types.

        //Figure 3 - Reference Types Vs. Value Types
        static void Main(string[] args)
        {
            Person p1 = new Person("Ibrahim",24); // Allocated In Heap
            VPerson vp1 = new VPerson(); // Allocated On Stack
            vp1.Name = "Nada";
            vp1.Age = 19;

            Person p2 = p1; //Reference (pointer) Copy
            VPerson vp2 = vp1; //Value Copy

            p1.Name = "Hema" //Change p2 Name as well
            vp1.Name = "Nody" //Doesn't change vp2 Name

            Console.WriteLine(p1.Name); //Displays Hema
            Console.WriteLine(p2.Name); //Displays Hema
            Console.WriteLine(vp1.Name); //Displays Nody
            Console.WriteLine(vp2.Name); //Displays Nada
        }

Okay here our Main method where we use our Person and VPerson types, In Line 4 Person object is allocated in managed heap and pointer saved to variable p1 (Shown in Figure 4), In Line 5 VPerson object allocated in Thread-Stack but wait a second! There’s no parameterless constructor defined in VPerson so an error should occurs. Well no a Value Type Implicitly define a parameterless constructor that set all instance fields to 0/null depending on the field’s type, However you can’t explicitly define parameterless constructor. Reference Types only implicitly define a parameterless constructor in case that you haven’t define any constructor so if VPerson was a class an error was to occur. Okay in line 6 & 7 we set values for vp1 which will be changed directly on the stack (No pointer Dereference), however if we used the same syntax to change p1.Name or p1.Age a pointer dereference will occur to do such a thing. In Line 9 we create p2 Variable of type Person and assign p1 to it what’s actually happens that p1 reference to the Person object on the Heap copied to p2 variable so no memory allocation for new object occurred just the reference is copied so the two variables are pointing to the same object. Line 10 looks similar but it’s not because VPerson is a value type a new instance is allocated on the stack for vp2 and vp1 instance fields values are copied to vp2 instance fields, So now vp1 & vp2 are holding two different instances unlike p1 & p2. Line 12 & 13 Changes p1, vp1 Name respectively of course you should have knew that in p1 a pointer dereference occur because it’s Reference Type, But in vp1 the value changed directly from the stack. Line 15 & 16 displays p1, p2 Name property respectively and Wow both show same result which is “Hema” however we changed p1.Name only, That happened because both variables hold a reference to the same instance so change in one reflects on the other. Line 17 & 18  displays vp1, vp2 Name property respectively but it shows “Nada” then “Nody” wired!! No it’s not, Because vp1, vp2 are Value Types they are holding two different instances of VPerson Type even when we assigned vp1 to vp2 in Line 10 a whole new Instance allocated on the stack and only values of the instance fields are copied to the newly created instance. Check Figure 4.

Reference Types Vs. Value Types Figure 4

I know these concepts are confusing somehow at the beginning but it’s really very important to understand it, I assume that you knew what’s Value Types and how you create it and you understood some differences compared to Reference Types i’ll explain more differences in depth in the next part of this post, but for now you have the good knowledge you need to start exploring the Value Types yourself ^^. The preceding table is a summary of what i’ve explained already and what i’ll explain in the next part regarding differences between both Types.

Reference Types Compared To Value Types
Comparison Key Reference Types Value Types
Allocated On Managed Heap Thread-Stack
Variable Contains Pointer to the instance The instance itself
Keyword Used ”class” ”struct” Or “enum” (For Enumerated Type)
Implicitly Derived From System.Object
  • For “struct” System.ValueType which itself derived from System.Object
  • For “enum” System.Enum which itself derived from System.ValueType
Can Explicitly Choose Base Type Yes No
Can Be Used As A Base Type Yes No (Implicitly Sealed)
Can Implement Interfaces Yes Yes
Passed As Argument To Method Copy of the pointer is passed New Instance is created on the stack and fields values are copied to it
Assigning Variable To Another Copy of the pointer New instance is created on the stack and fields values are copied to it
Instance Field Manipulation Pointer dereference occurs Manipulated directly from the stack
Boxed & Unboxed Forms Always Boxed Unboxed And Boxed
Single Instance Can Be Shared Yes No
When Instance Is Unused Wait for GC to occur to free its memory Memory allocated is freed immediately
Explicitly Define Parameterless Constructor Yes No (But always defined implicitly)
Can Define Multiple Constructors Yes Yes (You have to initialize all instance variable to initial value in constructor body)
Can Define Static Constructor Yes Yes

Hope you enjoyed the post and understood it very well ^^ Kindly if you have any question comment it and i’ll reply all your answers ^^ And wait for the next part very soon.

Instance Constructors & Type Constructors In C#

In this article i’ll explain what’s instance constructor and what’s type constructor, and how each of them works.

Of course everybody reading this article is already a developer or at least have a slight knowledge of OOP concepts so i assume all of you know already what a constructor is but many of you have confusion and always asking (What’s the difference between instance constructor and type constructor aren’t they the same??) the answer is simply No!!

Instance Constructors

Is a special method allow an instance of a type to be initialized to a good state. This means when you create an instance of a type memory allocated for the instance’s data fields and the object’s overhead fields (Described below) and initialize them, then the instance constructor is called to set the initial state of the object (i.e., set the instance’s fields values either to their default values according to their type or to values you have explicitly wrote in the constructor body).

Object’s Overhead Fields:

1 – Type Object Pointer : Of course a type is itself an Object. Confusing right! No it’s not, think for a moment if you defines the type Animal how do you expect the runtime to know about Animal and also how you call GetType() method to check any object’s type without having any problems and how polymorphism works!! Now it’s clear i think that every type is an object itself which is created on the heap at the first time you are attempting to access the type or any of it’s static fields or methods. The static fields are allocated within the Type Object as well as a method table which contains one entry for each method defined within the type as well the two overhead members like any other object but the Type Object Pointer which contained in the Type Object is pointing to itself, But any instance created of this type it’s Type Object Pointer will be pointing to the one in the Type Object ( Check Figure 1 ).

2 – Sync Block Index: Contains an integer index into the array of sync blocks.

Fig1-CodeFig1
  So What’s Instance Constructor Characteristics:

  • Each class (Reference Type) must have at least one Constructor (If you didn’t define a constructor inside your class a parameterless constructor is automatically added which implementation simply call the base class constructor).
  • A struct (Value Type) may have a constructor if you explicitly add one if you didn’t no parameterless constructor is implicitly added.
  • If you defined an Instance Constructor in a value type you have to assign a value for every field of the struct within the constructor otherwise a compilation-error occurs.
  • Instance Constructors can’t be inherited.
  • You can have several constructors defined within your class but with different parameters list.
  • Instance Constructor is called using ‘new’ keyword every time you want to instantiate an object of the type.

Type Constructors:

some people call it (Static Constructor) so what’s it? Simply lnstance Constructor is used to set the initial state of an instance fields, a static constructor is used to set the initial state of static fields. Does that means i can set an initial values for my static fields in that constructor (Yes) and how should i invoke it? Do i use something like the new operator which i’m using to call Instance Constructors? (No, you can’t call a type constructor it’s got called automatically for you when first accessing the class or any of it’s static fields) Interesting so what’s the Type Constructor Characteristics:

  • A Type can have a static constructor only if you explicitly added it or it will be added implicitly in only one case (If you have a static field and assigned value to it via in-line initialization. Check Person class in Figure-1).
  • A Type can’t have more than one static constructor.
  • Type Constructor must be parameterless.
  • You can’t specify an access modifier (public/private/protected/..etc) to the Type Constructor specifying one will result Compilation-Error. In fact the Type Constructor have implicit private accessibility preventing developers from calling it.
  • Have to be marked as ‘static’.
  • Type Constructor Invoked only one time during the application lifetime which is when your first attempt to access the class or any of it’s static fields.

Finally, Hope you found this article useful and that you are now aware of the difference between Instance & Type Constructors. If you have any questions regarding this topic i’ll be welcomed to answer it just leave a comment and i’ll answer it as soon i’m available. Thanks a lot ^^

Generics Part I

When we talk about Generics first thing should come into our heads is “General Model”, But what do i mean with General Model or Generic?

Well lets assume that i want to write a simple 3 overloaded methods each one of these methods take an array as an argument and display the array elements separated by commas, But first method takes a string array as an argument, Second method takes an int array, And third takes double array … Well we will do thing using Overloading methods and everything will be fine right ?? Let’s check it

static void Main(string[] args)
{
int[] intarray = { 1, 2, 3, 4, 5, 6, 7 };
double[] doublearray = { 1.12, 2.58, 3.65, 4.29, 5.78 };
string[] stringarray = { “Ibrahim”, “Zeyad”, “Emad”, “Nader”, “Amr” };
Disp(intarray);
Console.WriteLine();
Disp(doublearray);
Console.WriteLine();
Disp(stringarray);
}

public static void Disp(int[] x)
{
foreach (int element in x)
Console.Write(element +”, “);
}

public static void Disp(double[] x)
{
foreach (double element in x)
Console.Write(element + “, “);
}

public static void Disp(string[] x)
{
foreach (string element in x)
Console.Write(element + “, “);
}

In the previous example we created 3 arrays of types (int, double, string) and we created method Disp to display the array elements separated by commas well we had to overload method Disp 2 more times to make it able to process the 3 different types, But do we actually notice a difference between these 3 methods for me i see 1 difference only (The parameter type) which the method ask for .. But the method name is the same and even the method body is the same.

Generic Methods

Generic Methods enable you to specify with a single method declaration, a set of related methods .. Which means in the previous example i can use a generic method rather than make 3 methods, And the generic method will process any data type .. Little confused right ^^ Okay let’s check the next example which will make everything clear .. Have a look to the example and i’ll explain it.

static void Main(string[] args)
{
int[] intarray = { 1, 2, 3, 4, 5, 6, 7 };
double[] doublearray = { 1.12, 2.58, 3.65, 4.29, 5.78 };
string[] stringarray = { “Ibrahim”, “Zeyad”, “Emad”, “Nader”, “Amr” };
Disp(intarray);
Console.WriteLine();
Disp(doublearray);
Console.WriteLine();
Disp(stringarray);
}

public static void Disp <T> ( T [] x )
{
foreach (T element in x)
Console.Write(element + “, “);
}

Yes it’s real the method worked for int array, double array and string array, and if i passed a char or an object array or whatever array i’ll pass it will work very fine … I think now the word i said “General Model” is clear, But i didn’t explain yet and of course you have many answers in your thoughts.

All generic methods declaration have a Type-Parameter List delimited by angel brackets (<T> in this example) which follows the method name, Each Type-Parameter List contain one or more Type Parameters separated by commas, A Type Parameter is an identifier that’s used rather than actual type names, Type Parameter can be used as a return type for the method (Method return type can be T), Also the Type Parameter can be used in the method local variables and arguments (Check previous example method take argument x of type T means you can pass any array whatever it was it’s type as an argument for this method)

Note: Forget to include the Type-Parameter List when declaring a generic method will result a compilation error as the compiler wont recognize the Type Parameter names when they’re encountered in the method.

Note: If the compiler can’t find a single non-generic or generic method declaration that’s match the method call, Or if the compiler found multiple method matches the call, a compilation error will occur

Type Constraints

Well have anybody thought that you might need to delimit the types that the generic method process, I mean sometimes i may need a function that can’t be processed on all type, For example now i need to make a generic method that take 3 argument and return it’s maximum well since that i’ll have to use the > operator which i don’t know if every type provide the use of it … So what should i do!! Well it’s possible for me to compare objects of the same type using another thing rather than the > operator which is ICompareable<T> Interface lets discuss it and back again to our problem.

ICompareable<T> Interface: it’s an interface of namespace System, Types that implement ICompareable<T> must declare a method named CompareTo for comparing object we can use something like that x.CompareTo(y); well the method will return 0 if the two objects are equal, negative number if x is less than y, And positive number if x is greater than y, Well that’s great but we are talking about Objects, How about the simple data types (i.e., int, float, double, char, ..etc.), Well there is something called Structure for each data type in the Framework enable you to use the simple data type as an object and all the Structures implement ICompareable<T> interface, Structures Like (i.e., Int32 for int, Double for double, String for string, ..etc.)

Back to our problem okay now i’ll use CompareTo method to compare rather than > operator, But there is another problem !! Not all objects implements ICompareable<T> Interface so i need to do something telling the generic method (“Take only objects that can be compared as an argument”) Do you think i can do something like that?? Well yes and that what’s called Type Constraints

Type Constraints means that i restrict the type of the argument supplied to a particular Type Parameter let’s Check the next example and back again to explain it!!

static void Main(string[] args)
{
Console.WriteLine( Max(3, 5, 7));
Console.WriteLine( Max(4.5, 7.8, 8.9));
Console.WriteLine( Max(“Ahmed”,”Mohamed”,”Hussien”));
}

public static T Max <T> (T x, T y, T z)
where T: IComparable<T>
{
T max = x;
if (y.CompareTo(max) > 0)
max = y;
if (z.CompareTo(max) > 0)
max = z;
return max;
}

Well the method work properly ^^ But have anybody noticed anything new!! Yes the Where T: ICompareable<T> Hmmm.. Well i told that method “Don’t accept any object as an argument unless it implements ICompareable<T> Interface!! So by now the generic method will accept any object as it’s arguments only if i can compare them ^^ Well there is several Type Constraints C# provides let’s talk about them.

  • Class Constraint: Indicate that the Type Argument must be an object of specific class or an object of it’s subclasses.
  • Interface Constraint: Indicate that the Type Argument must be an object of a class that implement that interface (Like previous example).
  • Reference-Type Constraint: Indicate that the Type Argument must be a reference type argument using keyword class.
  • Value-Type Constraint: Indicate that the Type Argument must be a value type argument using keyword struct
  • Constructor Constraint: Indicate that the generic method can use the operator new() to create new objects of the Type Argument (which is passed to the method) using the keyword new().
  • Note: All Keywords that should be used as a Type Constraint you can declare them after where T:
  • Note: You can apply multiple constraints by separating them by commas, Taking in consideration that Class, Reference-Type, Value-Type Constraints MUST be listed first (And only one of these three can be used in a single generic method), Interface Constraint listed next, Constructor Constraint listed last!!

 

Well That was the first part discussing Generics there will be another part i’ll post later, Hope That You Liked It !! 🙂 🙂 🙂

Getting Familiar To XML

XML stands for Extensible Markup Language it was developed in 1996 by the World Wide Web Consortium’s (W3C’s).
XML is a markup language designed to store and exchange data between applications over the internet, Yes it’s a markup language just like HTML but it has some differences which we will discuss also XML describes data in a very easy way which both humans and computers can understand, let’s step into a small example to see how XML looks like.


<?xml version=”1.0″?>
<Employee>
<FirstName>Mohamed</FirstName>
<LastName>Ahmed</LastName>
<Salary>1500</Salary>
</Employee>

As we see in the previous example the XML is pretty easy and understandable, Also it looks like HTML consisting of tags and so on, However the tags aren’t predefined as in HTML (i.e., HTML tags like <img> , <p> , …etc are predefined and i only use them to satisfy my needs but in XML i create my own tags that i’ll need to describe my data as shown above).
XML document just store information but i still need an application to retrieve this data and use it, but the document on it’s own is kinda useless, Unlike HTML which i use to display the data XML i use only to store data.

Why I Should Use XML

  • Software & Hardware Independent (i.e., Can be used anywhere regardless of the platform you use)
  • High-Level of availability (i.e., Any application can use XML as a data source).
  • Easy to understand.
  • Easier to exchange (i.e., As a plain text will be the much easier than anything else when it comes to data exchanging)

XML Syntax


<?xml version=”1.0″?>
<Employee ID=”This Is Attribute”>
<FirstName>This Is Element</FirstName>
<LastName>This Is Element</LastName>
<Salary>This Is Element</Salary>
</Employee>

  • First Line defines the xml version 1.0.
  • Second Line defines the root element of the document which is Employee in this example, followed by ID attribute (Will discuss attributes).
  • Third, Fourth And Fifth Lines defines child elements of the root like when i say an Employee have FirstName, LastName and Salary.
  • Last Line defines the end of Employee element (Each Tag Must Be Closed)
  • Elements: Data stored in XML in a structured way so i use Elements to store my data, Check the previous example we will find that Element Employee have Elements (FirstName, LastName, Salary), now if i’m using that document in my application i’ve a guide showing me where the first name of that employee and where is the salary and i can use them easily.

    Syntax: <ElementName>Value</ElementName>
    Elements can contain (another elements, attributed, data)
    Note that Element Names can’t have spaces also XML is case sensitive (i.e.,FirstName != Firstname), Also avoid using (.) or (-) in xml because and application may treat (.) as u r calling property of a class, and application may think that (-) is a subtraction operator.
    Element can contain another elements to describe it (i.e., Employee have first name and last name)

  • Attributes: Provide additional information about element (NOT PART OF THE DATA), as in previous example i used ID as an attribute not as an Element because it’s not a part of employee’s data not like (FirstName, Salary).Syntax: <ElementName AttributeName=”Value”>
    There is no rule specify when to use Attribute or Element but as i mentioned you should use attribute only if you want to provide some information about the data Not the data itself.
    Attributes have some restrictions not like elements as attributes doesn’t contain Multiple values and not easily expanded (i.e., In previous Example i can expand the Salary element to contain FixedSalary & Bonus elements and each of those will be having a value but if i’m using attribute i can’t do this).
    Attributes must be written within a quotes like in the previous example.

Viewing and Editing XML document is pretty easy because xml is usually a text file with a .xml file-name-extension, So it doesn’t require a special software i can use my notepad to view or edit XML document, but of course there is some tools which make it more convenient to develop XML document (i.e., Visual Studio include XML editor that provide intellisense).

Processing an XML document requires software called XML Parser (XML Processor), A parser makes the document data available to application, The parser check that the document follows the syntax rules specified by the W3C’s XML Recommendation (XML syntax requires a single root element, a start tag and an end tag for each element and properly nested tags [End tag for nested element should appear before the end tag of the enclosing element], Also XML is case-sensitive) If all these rules respected so the XML document called Well-Formatted XML Document, Note that if the XML document was not well-formatted the parser will report and error.
Usually XML parser is built into software like Visual Studio also there is an open-source software called Expat XML Parser.

Validating XML Documents: An XML document can OPTIONALLY reference a Document-Type-Definition (DTD) or a W3C XML Schema that defines the XML document’s proper structure.
When XML referencing DTD or W3C XML Schema some parsers called (Validating Parsers) can use the DTD or the Schema to check that it has the appropriate structure, the XML is valid only if it has the appropriate structure.
(ex: In previous XML example if i’ve referenced DTD that specifies that an Employee element MUST have FirstName, LastName, Salary elements and i omitted the LastName [Haven’t Specified It] that will cause my XML document to be invalid, However it will be Well-Formatted XML Document but it doesn’t follow the structure which the referenced DTD specifies).
Note That : Valid XML Document is by default a Well-Formatted XML Document.
Syntax:


<?xml version=”1.0″?>
<!DOCTYPE Employee SYSTEM “Employee.dtd”>
<Employee ID=”This Is Attribute”>
<FirstName>This Is Element</FirstName>
<LastName>This Is Element</LastName>
<Salary>This Is Element</Salary>
</Employee>

Entity References: There is some characters i can’t use directly in XML because it’s used in language syntax like < > ” ‘ &

&lt; < Less Than
&gt; > Greater Than
&amp; & Ampersand
&apos; Apostrophe
&quot; Quotation Mark

That was a brief article about XML which supposed to help you understand the basics of XML, More will be coming later, Hope you enjoyed reading and you got rich information ^^ If there is any question about the topic please mention it 😉

Create Your First Azure App ( Hello Azure!! )

Well i’ve shared an overview of windows azure in a post earlier before this one 🙂 Hope you people to read it first to know what you are going to deal with 🙂

  • Make Your PC Ready For Azure
  • You should have supported version of Visual Studio installed on supported version of Windows.

    Supported versions of Windows as following: Windows 8, Windows 7, Windows Vista, Windows Server 2008, Windows Server 2012.
    Supported versions of Visual Studio as following: Visual Studio 2012, Visual Studio 2010, Visual Studio 2008. You can download the web express version for free from Here

    NOTE: Windows Xp & Windows Server 2003 aren’t supported because the Windows Azure Web Roles are built on IIS 7.0 while they use earlier versions of IIS that wont meet the need of Windows Azure SDK.

    You can download Windows Azure SDK (Software development kit) which contain (Simulation of Windows Azure Development Fabric, Templates for creating web applications, Windows Azure storage environment, ..etc.) Download it from Here.

  • Let’s Get Started!!
  • First run your visual studio as Administrator other wise the Windows Azure Emulator wont run.

    Now create a new project [File> New> Project> Cloud “From the left pane”], Choose Windows Azure Cloud Service Enter the name of your project and solution then click OK …Check the picture.
    1

    Now from this dialog box you choose the type of Windows Azure Project you want to create you’ll fine many types of roles (i.e., ASP.NET Web Role, ASP.NET MVC4 Web Role, WCF Service Web Role, Worker Role, Silver Light Business Application …etc.)
    Now select ASP.NET Web Role then click the right arrow button then click ok (.2

    After the Visual Studio load the solution you will find two project (WindowsAzure1, WebRole1).
    WindowsAzure1: This will contain the configuration that’s specific for your Windows Azure Web Role.
    WebRole1: It’s a regular ASP.NET web application you can modify default.aspx file as you would do if you developed ASP.NET projects before.

    3

    Now click on WebRole1 Project> Choose default.aspx, Now we have a ready template we have to modify it to meet our needs … Please Check The Picture.
    4

    Now after you have created your “Hello Azure” application you can press (Ctrl+F5) to run it on Windows Azure Development Fabric.

    Hope you liked the topic ^^ There will be more of windows azure just stay tuned 🙂 Thank you