Github WebHooks handler using Asp .Net

In previous post we have seen WebHooks handler for Instagram here.

In this post we will see WebHooks handler for Github.

Github gives very powerful support to the developers.

git

Currnetly there are more than 20 events supported by Github which includes Wildcard Event.

What is Wildcard Event?

When you add the wildcard event, it will be replaced by any existing events you have configured with the wildcard event and send you payloads for all supported events. You’ll also automatically get any new events we might add in the future.

(*) is Wildcard Event.

Considering that you have followed all the steps shown here, We will directly see code for Github handler which is as below:

public class InstagramWebHookHandler : WebHookHandler
{
   public InstagramWebHookHandler()
   {
       this.Receiver = "Github";
   }
 
   public override async Task ExecuteAsync(string generator, WebHookHandlerContext context)
   {     
       JObject entry = context.GetDataOrDefault<JObject>();

       // Extract the action -- for Bitbucket we have only one.
       string action = context.Actions.First();
       switch (action)
       {
           case "push":
           // Any Git push to a Repository, including editing tags or branches. Commits via               API actions that update references are also counted. This is the default event        
          break;
   
          case "*":
          // Any time any event is triggered (Wildcard Event).
          break;
         
          case "commit_comment":
          // Any time a Commit is commented on.
          break;

          case "issues":
          // Any time an Issue is assigned, unassigned, labeled, unlabeled, opened, closed,              or reopened.
          break;

          case "create":
          // Any time a Branch or Tag is created.
          break;
          
          case "delete":
          // Any time a Branch or Tag is deleted.
          break;
          
          case "fork":
          // Any time a Repository is forked.
          break;
          
          case "issue_comment":
          // Any time an Issue or Pull Request is commented on.
          break; 
          
          case "repository":
          // Any time a Repository is created. Organization hooks only.
          break; 
          
          case "team_add":
          // Any time a team is added or modified on a Repository.
          break; 
          
          case "watch":
          // Any time a User stars a Repository.
          break;
          
          case "page_build":
          // Any time a Pages site is built or results in a failed build.
          break;

          case "release":
          // Any time a Release is published in a Repository.
          break;

          case "pull_request":
          // Any time a Pull Request is assigned, unassigned, labeled, unlabeled, opened, cl             osed, reopened, or synchronized 
          break;

         default:
         Trace.WriteLine(entry.ToString());
         break;
     }

     return Task.FromResult(true); } 
}

Above are different events supported by Github. You can write your code as per your requirement.

There are other events as well like gollum, deployment_status, membership etc.

Now Let us see how WebHook POST request body looks like when it comes from Github.

For example below is an example of a WebHook POST request body from GitHub looks like this as a result if anyone comments on any issue in a particular repository:

{
   "action": "opened",
   "issue": {
                "url": "https://api.github.com/repos/NeelBhatt/NewBornVNext",
               "number": 1,
               ...
                 },
   "comment": {
             "url": "https://api.github.com/repos/NeelBhatt/NewBornVNext/issues/comments/1",
             "issue_url": "https://api.github.com/repos/NeelBhatt/NewBornVNext/public-repo/issues/2",
   "id": 1,
   "user": {
              "login": "human",
              "id": 6752317,
              ...
            },
             ...
              },
   "repository": {
             "id": 1,
             "full_name": "octocat/NewBornVNext",
            "owner": {
                    "login": "NeelBhatt",
                    "id": 1
                    ...
                    },
                    ...
                  },
   "sender": {
              "login": "NeelBhatt",
              "id": 1,
              ...
              }
 }

For more information regarding Event Types & Payloads for Github, Have a look here.

Stay tuned for more updates.

Advertisements

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?


A 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.

Agile with TFS 2015(Team Foundation Server)

Team foundation Server 2015 is out last month with tremendous new features.

First of all let us see basic introduction for those who does not know what is TFS or those who did not work with TFS.

Team Foundation Server (commonly abbreviated to TFS) is a Microsoft product which provides source code management (either via Team Foundation Version Control or Git), reporting, requirements management, project management (for both agile software development and waterfall teams), automated builds, lab management, testing and release management capabilities.

Talking about TFS 2015, it contains some awesome features which will push you to use TFS more than before!

Below is my favorite feature:

 Tools for Agile teams:

This is something what many people were watiing for since long time.

The agile boards in TFS are a critical tool for teams to track their work and progress on a day-to-day basis.

You might have seen these boards in your office:

Scrum-board1

Or you may have used some of the Kanabn baords as below:

agile_kanban_board

Now these all be supported by TFS!!

How? well just look in below image:

Kanban board

Shocked? Well it is included in TFS 2015!

Visual Studio Online provides you the tools you need to run your agile team. which includes:

  • Drag-and-drop backlog prioritization
  • Kanban and task boards
  • Sprint planning
  • Bug management
  • Charting & dashboards

Below are few images which demonstrates Agile boards in TFS 2015.

Dashboards:

Dashboards

Task Boards:

Taskboards

Charts:

Charts

Scrum:

Scrum

This is just one feature I explained. There are plenty more which i will explain later on.

Stay tuned for more updates!

Blog at WordPress.com.

Up ↑