Adding Swagger to Web API project

swagger_help_pages

Adding Swagger to your Web API does not replace ASP.NET Web API help pages (here the nuget package for Microsoft ASP.NET Web Api Help Page). You can have both running side by side, if desired.

To add Swagger to an ASP.NET Web Api, we will install an open source project called Swashbuckle via nuget.

Install-Package Swashbuckle –Version 5.2.1

After the package is installed, navigate to App_Start in the Solution Explorer. You’ll notice a new file called SwaggerConfig.cs. This file is where Swagger is enabled and any configuration options should be set here.

swagger_config-1

Configuring Swagger

At minimum you’ll need this line to enable Swagger and Swagger UI.

GlobalConfiguration.Configuration
  .EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API"))
  .EnableSwaggerUi();

Start a new debugging session (F5) and navigate to http://localhost:[PORT_NUM]/swagger. You should see Swagger UI help pages for your APIs.

swagger_ui

Expanding an api and clicking the “Try it out!” button will make a call to that specific API and return results.

swagger_get_superhero-1

And then you see the response:

swagger_get_response

Enable Swagger to use XML comments

The minimum configuration is nice to get started but let’s add some more customization. We can tell Swashbuckle to use XML comments to add more details to the Swagger metadata. These are the same XML comments that ASP.NET Help Pages uses.

First, enable XML documentation file creation during build. In Solution Explorer right-click on the Web API project and click Properties. Click the Build tab and navigate to Output. Make sure XML documentation file is checked. You can leave the default file path. In my case its bin\SwaggerDemoApi.XML

build_xml_docs

Next, we need to tell Swashbuckle to include our XML comments in the Swagger metadata. Add the following line to SwaggerConfig.cs. Make sure to change the file path to the path of your XML documentation file.

GlobalConfiguration.Configuration
  .EnableSwagger(c =>
    {
      c.SingleApiVersion("v1", "SwaggerDemoApi");
      c.IncludeXmlComments(string.Format(@"{0}\bin\SwaggerDemoApi.XML",           
                           System.AppDomain.CurrentDomain.BaseDirectory));
    })
  .EnableSwaggerUi();

Finally, if you haven’t already, add XML comments to your Models and API methods.

xml_comments

Run the project and navigate back to /swagger. You should see more details added to your API documentation. I’ve highlighted a few below with their corresponding XML comment.

swagger_xml_comments

Under Response Class, click Model. You should see any XML comments added to your models.

swagger_xml_comments_model

Describing Enums As Strings

My Superhero class contains an Enum property called Universe which represents which comic universe they belong to.

universe_enum

By default, Swagger displays these Enum values as their integer value. This is not very descriptive. Let’s change it to display the string representation.

GlobalConfiguration.Configuration
  .EnableSwagger(c =>
  {
    c.SingleApiVersion("v1", "SwaggerDemoApi");
    c.IncludeXmlComments(string.Format(@"{0}\bin\SwaggerDemoApi.XML", 
                         System.AppDomain.CurrentDomain.BaseDirectory));
    c.DescribeAllEnumsAsStrings();
  })
  .EnableSwaggerUi();

If I look at Swagger now, the Universe Enum values are displayed as strings.

swagger_xml_comments_enum

These are just a few of the many configuration options you can specify in Swashbuckle to create your Swagger metadata. I encourage you to review the other options on Swashbuckle’s GitHub.

Happy coding!

Announcing Microsoft ASP.NET WebHooks V1

WebHooks provide a simple pub/sub model for wiring together Web APIs and services with your code. A WebHook can be used to get notified when a file has changed in Dropbox, a code change has been committed to GitHub, a payment has been initiated in PayPal, a card has been created in Trello, and much more — the possibilities are endless! When subscribing, you provide a callback URI where you want to be notified. When an event occurs, an HTTP POST request is sent to your callback URI with information about what happened so that your Web app can act accordingly. WebHooks happen without polling and with no need to hold open a network connection while waiting for notifications.

Receiving WebHooks

Dealing with WebHooks depends on who the sender is. Sometimes there are additional steps registering a WebHook verifying that the subscriber is really listening. Often the security model varies quite a bit. Some WebHooks provide a push-to-pull model where the HTTP POST request only contains a reference to the event information which is then to be retrieved independently.

The purpose of Microsoft ASP.NET WebHooks is to make it both simpler and more consistent to wire up your API without spending a lot of time figuring out how to handle any WebHook variant:

WebHoks-Receiving

A WebHook handler is where you process the incoming WebHook. Here is a sample handler illustrating the basic model. No registration is necessary – it will automatically get picked up and called:

public class MyHandler : WebHookHandler
{
    // The ExecuteAsync method is where to process the WebHook data regardless of receiver
    public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
    {
        // Get the event type          
        string action = context.Actions.First();
 
        // Extract the WebHook data as JSON or any other type as you wish
        JObject data = context.GetDataOrDefault();
 
        return Task.FromResult(true);
    }
}

Finally, we want to ensure that we only receive HTTP requests from the intended party. Most WebHook providers use a shared secret which is created as part of subscribing for events. The receiver uses this shared secret to validate that the request comes from the intended party. It can be provided by setting an application setting in the Web.config file, or better yet, configured through the Azure portal or even retrieved from Azure Key Vault.

For more information about receiving WebHooks and lots of samples, please see these resources:

More detail on Microsoft Blog.

Chart.js Asp.net : Create Pie chart with database jQuery Ajax C#

This article explains using Chart.js in Asp.net C# Web Application we can create a pie chart with database MS SQL server connectivity via jQuery ajax call.  You can also have a look on related article, .

Now in this post here we create a pie chart by using chart.js library and bind data from our database MS Sqlserver, with jQuery ajax calling.

Here we are creating a pie chart, which shows data from the database (Ms SQL server).  In my database, I have a table which stores data (website traffic source info).

So basically our pie chart data will shows traffic source info .i.e. (how much of page views referral by facebook, twitter, google+, Tumblr etc ).

Chart.js: Simple,clean and engaging charts for designers and developers developed by Nick Downie . It uses the HTML5 canvas element.

It’s supported in all modern browsers, and polyfills support for IE7/8. Chart.js is dependency free and super lightweight.

Download – Chart.js file and include in Asp.net Webform

First download and include latest files of the chart.js , jQuery library in your web page.

HTML markup under head tag looks like as shown below.

<head runat="server">
    <title>Pie Chart Asp.net with database ms sqlserver</title>
    <script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="js/Chart.js" type="text/javascript"></script>
</head>

 

Html Markup (Design) – Adding HTML5 Canvas Tag

I have added 2 drop-down list control to select the year, month, along with a button and a  canvas tag.

Now on button click will call jQuery ajax, and then on ajax success our pie chart gets generated by using Chart.js library and HTML5 Canvas tag

<select id="ddlyear">
    <option>2010</option>
    <option>2011</option>
    <option>2012</option>
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
</select>
<select id="ddlMonth">
    <option value="1">Jan</option>
    <option value="2">Feb</option>
    <option value="3">Mar</option>
</select>
<button id="btnGeneratePieChart">Show</button>
<br/><canvas id="myChart" width="200" height="200"></canvas>

 

Code Behind – Ajax call WebMethod, and returns JSON format data to create Pie Chart

First add a WebMethod .i.e asmx file, and then we write our WebMethod which returns JSON format data, In our .asmx file will create a class named as trafficSourceData as shown below.

 public class trafficSourceData{
          public string label{get;set;}
          public string value{get;set;}
          public string color{get;set;}
          public string hightlight{get;set;}
    }

Now our WebMethod will pull data from database Ms Sqlserver for specific month and year, and return list of class object .i.e trafficSourceData class list as JSON formatted data, so our pie chart get created using chart.js.

[WebMethod]
    public List getTrafficSourceData(List gData)
    {
        List t = new List();
        string[] arrColor = new string[] { "#231F20", "#FFC200", "#F44937", "#16F27E", "#FC9775", "#5A69A6" };

        using (SqlConnection cn = new SqlConnection(conn))
        {
            string myQuery = "select * from traffic_data where YEAR =@year and MONTH=@month";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = myQuery;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@year", gData[0]);
            cmd.Parameters.AddWithValue("@month", gData[1]);
            cmd.Connection = cn;
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                int counter = 0;
                while (dr.Read())  {
                    trafficSourceData tsData = new trafficSourceData();
                    tsData.value = dr["visit_count"].ToString();
                    tsData.label = dr["traffic_source"].ToString();
                    tsData.color = arrColor[counter];
                    t.Add(tsData);
                    counter++;
                }
            }
        }
        return t;
    }

 

jQuery –  initializing Chart.js in Asp.net WebPage

Now back to client side coding, we have already done with the server-side code by creating WebMethod which return JSON format data. So now in our Ajax call on success will initialize Chart.js variable.

Client-side code looks like as written below

$(document).ready(function () {

    $("btnGeneratePieChart").on('click', function (e) {
        e.preventDefault();
        var gData = [];
        gData[0] = $("#ddlyear").val();
        gData[1] = $("#ddlMonth").val();

        var jsonData = JSON.stringify({
            gData: gData
        });
        $.ajax({
            type: "POST",
            url: "WebService.asmx/getTrafficSourceData",
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess_,
            error: OnErrorCall_
        });

        function OnSuccess_(response) {
            var aData = response.d;
            var arr = [];
            $.each(aData, function (inx, val) {
                var obj = {};
                obj.color = val.color;
                obj.value = val.value;
                obj.label = val.label;
                arr.push(obj);
            });
            var ctx = $("#myChart").get(0).getContext("2d");
            var myPieChart = new Chart(ctx).Pie(arr);
        }

        function OnErrorCall_(response) {}
        e.preventDefault();
    });
});

 

Finally, we are done with coding, Now every time we click button our pie chart gets created.

pieChartDB

Advertsing

125X125_06





TagCloud

MonthList

CommentList