Friday, 1 January 2016

Hello World with MVC 6

In this post we will see how to write your first application using MVC 6 and Visual studio 2015.
We will go step by step.

First of all let us add simple MVC 6 project.

For that Open your Visual Studio 2015 and Create new project as shown below:
new-project-mvc6
and then select empty Asp.Net 5 preview.
new-project-select-empty-aspnet5-template

You can see the project structure like this:

aspnet5_beginning_demo_2

What is new in folder structure?
  • src folder – contains all projects that contain source code that make up your application.
  • global.json – this is where you put solution-level settings, and allows you to do project-to-project references.
  • wwwroot – is a folder in which all your static files will be placed. These are the assets that you web app will serve directly to the clients including HTML, CSS, Image and JavaScript files.
  • project.json – contains project settings
  • startup.cs – this is where you put your startup and configuration code.

But wait! Is it MVC?

No it is not.

Our next step is to configure the site to use MVC. This requires changes to the project.json file and Startup.cs file. First, open project.json and add “Microsoft.AspNet.Mvc” to the “dependencies” property:

So our project.json would be like this:
{
  "dependencies": {
       "Microsoft.AspNet.Mvc": "6.0.0-*",
       "Nowin.vNext": "1.0.0-*",
       "Kestrel": "1.0.0-*"
    },
  "commands": {
        "web": "Microsoft.AspNet.Hosting --server Nowin.vNext",
        "web-kestrel": "Microsoft.AspNet.Hosting --server Kestrel"
    }
}

Ok, so now it is Mvc project right?

Wait, we forgot to add configurations.

For that open Startup.cs and modify it as follows:

using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseServices(services =>
        {
             services.AddMvc();
        });

        app.Use(async (context, next) => 
        {
             Console.WriteLine(context.Request.Path);

             try
             {
                  await next();
             }
             catch(Exception ex)
             {
                   Console.WriteLine(ex);
             }
         });

       app.UseMvc();
      }
}

This code enables MVC and defines a route.

Voila! Yes now it is an Mvc Project.

Now let us add controlls and views.

Oh! Well we need to follow some steps to add controlers and views because we need to add simple class and make it a controller as below:
  • Add a Controllers folder
  • Add an MVC Controller called HomeController.cs class to the Controllers folder
  • Add a Views folder
  • Add Home folder in the Views folder
  • Add an Index.cshtml MVC View Page to the Views/Home folder.
The project structure should be as shown:
project-structure-controller-view

Now, Edit Index.cshtml as below:

<h1>Hello from Razor!!<h1>

And in HomeController:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Run the application – you should see Hello World output in your browser.

hello-world

Congratulations for your first MVC 6 project!


Stay tuned for more!

Wednesday, 30 December 2015

WebHooks in Asp.Net : A Visual Studio Extension

Before couple of weeks Asp.Net team has announced to support Web Hooks with Visual Studio.
First of all let us see What is WebHooks?

WebHooks in web development is a method of augmenting or altering the behavior of a web page, or web application, with custom callbacks. These callbacks may be maintained, modified, and managed by third-party users and developers who may not necessarily be affiliated with the originating website or application.
In simple words WebHooks is a HTTP callback(user-defined HTTP Callback) which providing a simple pub/sub model for wiring together Web APIs and SaaS services.
Ok, above explanation is a kind of theoretical, can you tell some real time example?
Suppose you have a company account in Instagram! Now a new photo is tagged with tags of your choosing and you want to do some instant event like saying “Thank you!” or to answer if someone has asked anything or deletion of comments in case of some spamming!
WebHooks does it for you!
That is awesome! How to get WebHooks in Asp .Net?
You can install the extension directly in Visual Studio using the Tools -> “Extensions and Updates” dialog, as shown below. Simply search for “WebHooks” and you will see below screen:
image
After getting this Visual Studio extension you will see some wizard as shown below:
image
The above wizard is used to select which client you want to use.
image
Above wizard is used to enter secret number of client. It captures the secrets for each of them individually.
Now Let us go step by step with the example of Instagram I explained above. Let us code it out!!
We will take Instagram sample in which we will connect WebHooks to get the notification generated in Instagram account.
Instagram WebHooks support four kinds of subscriptions:
  • Users: receive notifications when users registered with your application post new photos.
  • Tags: receive notifications when a new photo is tagged with specific tags.
  • Locations: receive notifications when new photos are posted and tagged with a specific location.
  • Geographies: receive notifications when new photos are posted in a given geo location defined by a center point and radius.
First of all get secret number for your Instagram account as shown below:
2474.InstagramCreateClient_08DD1A9E
which will be stored in your web.config file as below:
<appSettings>
   <add key="MS_WebHookReceiverSecret_InstagramId" value="Instagram Client ID" /> 
   <add key="MS_WebHookReceiverSecret_Instagram" value="Instagram Client Secret" />
</appSettings>
After installation you will see a WebHookConfig.cs class in your App_Code folder which would be created automatically. It is used to initialize the process as shown below:
namespace WebHookReceivers
{
   public static class WebHookConfig
   {
      public static void Register(HttpConfiguration config)
      { 
           // Load receivers
           config.InitializeReceiveInstagramWebHooks();
      }
   }
}
Once you select the receiver as shown in figure, a class is added to the project that inherits from the WebHookHandler class, the base class for all WebHook handler customization you intend on doing.
Each receiver is identified by name, with the name being used in the route wire-up, so each generated handler checks to see if it’s the one who should be handling the incoming requests.
Instagram generated handler is below:
public class InstagramWebHookHandler : WebHookHandler
{
   public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
   {
      string action = context.Actions.First();
      JObject data = context.GetDataOrDefault<JObject>();

      return Task.FromResult(true);
   }
}

Now let us make some changes in above code as below:
public class InstagramWebHookHandler : WebHookHandler
{
   public InstagramWebHookHandler()
   {
       this.Receiver = "instagram";
   }
 
   public override async Task ExecuteAsync(string generator, WebHookHandlerContext context)
   {
       // Get the WebHook client
       InstagramWebHookClient client = Dependencies.Client;
 
       // Convert the incoming data to a collection of InstagramNotifications
      var instagramNotifications = context.GetDataOrDefault<IEnumerable<InstagramNotification>>();
      foreach (var notification in instagramNotifications)
      {          
          var entries = await client.GetRecentGeoMedia(context.Id, notification.ObjectId);
          foreach (JToken entry in entries)
          {
              // Different sizes of images
              var thumbnail = entry["images"]["thumbnail"].ToObject<InstagramMedia>(); 
          }
      }
   }
}
In the case above we extract information about different image resolutions (i.e. thumbnail here). However, the information provide by Instagram is huge and we can extract much other information.
Here we have used InstagramWebHookClient to retrieve additional data and then extract information about the images posted.
In above code it gets the notification generated in Instagram for you and you can do different code as per your requirement.
I will update if something would be updated by .Net team.
In my next post I will write demo code for Github handler of WebHooks.(Post is available now)
Stay tuned for more updates.