Wednesday, March 8, 2017

Swashbuckle : Documenting values passed via HTTP header

Refer https://github.com/domaindrivendev/Swashbuckle

Swashbuckle adds swagger documentation to .NET Web API project.

This article explains how to document parameters that are passed in via HTTPHeader.

for this create a custom operation filter:

 public class SwaggerHeaderparameters: IOperationFilter
    {

   
        public string Description { get; set; }      
        public string Key { get; set; }      
        public string Name { get; set; }      
        public string DefaultValue { get; set; }

        public void Apply(SwaggerDocsConfig c)
        {
            c.ApiKey(Key).Name(Name).Description(Description).In("header");
            c.OperationFilter(() => this);
        }    

        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            operation.parameters = operation.parameters ?? new List<Parameter>();
            operation.parameters.Add(new Parameter
            {
                name = Name,
                description = Description,
                @in = "header",
                required = true,
                type = "string",
                @default = DefaultValue
            });
        }
    }

How to use?

 var brandHeader = new SwaggerHeaderparameters
            {
                Description = "brand",
                Key = "brand",
                Name = "brand"
            };
            config.EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "API Documentation");
                c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority)
                + req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));          
                brandHeader.Apply(c);              
            }
           ).EnableSwaggerUi();

Autofac : resolve dependency per request based on parameter passed on HTTPHeader


Get the HTTP Context base

  builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration);

            builder.Register<HttpContextBase>(c =>
            {
                var context = (HttpContext.Current != null) ?
                new HttpContextWrapper(HttpContext.Current) :
                c.Resolve<System.Net.Http.HttpRequestMessage>().Properties["MS_HttpContext"] as HttpContextWrapper;
                return context;

            }).InstancePerRequest();

Resolve the dependency based on the request header value

  builder.Register(c =>
            {
                var route = c.Resolve<HttpContextBase>().Request.Headers.Get("provider");
                if (route == null)
                {
                    throw new ArgumentNullException($"A route must be specified");
                }
                return c.ResolveNamed<IInterfaceName>(route);
            }).InstancePerRequest();


Friday, January 27, 2017

TLS MQTT broker connection using MqttClient

Last week I was working on a C# application to publish messages using the MqttClinet - https://m2mqtt.wordpress.com/using-mqttclient/

The IBM Watson IoT C# library use the same package :) https://github.com/ibm-watson-iot/iot-csharp

The library is amazing. However a few suggestions from my side:
  1. The documentation is very generic, not explaining the complex scenarios.
  2. The error codes are very generic and the documentation doesn't cover what the return error code number means.
The MQTT broker which we use is configured to use TLS. So, I was looking for a proper documentation to connect to the MQTT using TLS and I couldn't find one. So, I copy pasted the code we used for the connection:

var serverCert = new X509Certificate("certificte path *.cer");

//I  exported the certificate from the server and stored in a project folder.

            _client = new MqttClient("Host name", "port", true, serverCert, null - if you use client certificate, MqttSslProtocols.TLSv1_2);
            if (_client.Connect("Client name", "user name", "password") != 0)
            {
                throw new Exception("Unable to establish connection to MQTT broker");
            }

Clean code, better code

Last week I was working with my team to create a REST API for our sensor to publish data. At the time of writing, the sensor XDK we used supports only HTTP GET and we need a way to pass the temperature and acoustic data to our MQTT broker.

The quick and dirty suggestion is to create a WebAPI GET method and pass the message to our MQTT broker using M2Mqtt client.
This post, I don’t like to explain the implementation details, however I explain how neatly you can write the code.

The developer wrote the code like this
  [Route("publish")]
 public IHttpActionResult Get(string id, string noise, string temp){
              -compare mac id with database, if not throw error
              - convert noise to integer and find the noise level (low, medium or high based on the value matrix - a set of if else)
              -convert temperature to integer. Since the sensor returns mill-degree Celsius, convert it to Celsius
               - send data to MQTT using M2Mqtt
}
The controller contains > 200 lines code and it worked!!! I talked to the developer and asked, are you satisfied with the code you had written. He said it works well.
Then I explained the ways to organize the code
  • Write a class for noise. All conversion (string to double) can be handled there. So the code is completely unit testable.
  •   Create a class for temperature. Create properties for Degree Celsius, Fahrenheit…..
  •   Create a NoiseRange class with max, min and "text" which specifies what that range means (refer Martin Fowler’s range pattern) and implement a method Includes (Noise noise) 
  •  Create a NoiseManager class that contains the list of noise ranges (I've added noise ranges in a json file and stored in App_Data folder)
  •  Create a repository pattern to interface with the data base (to verify the macid).
  •  Create a MqttManager class to interface with the MQTT broker
  •   Inject the repository, Noise Manager and MqttManager as dependencies. I prefer Autofac

Now each and every part of the program is modular and self-containing which can be unit tested individually


It takes some time to understand what a better clean code means. When you get it right, you always follow the right ritual. Happy coding !!!

Tuesday, December 27, 2016

Entity framework data model generator from data context

I always prefer to visually see the data model generated by the code first migrations.

Entity framework power tools was a handy extension for this purpose. However,  this tool is not working with VS 2015. So, I thought of creating a VS extension to generate data model diagram from a data context class.

The extension is now available at https://marketplace.visualstudio.com/vsgallery/98588731-ffa7-46ab-bdbf-101c63271779 


Since I lead  some of the VS extension development at Allstate, it took around an hour to complete the task. Is it complete, no because I haven't wrote any test cases :)

happy coding!!!!

Monday, August 11, 2014

Windows Phone - I'm not impressed!!!

Last week I went to a Microsoft store and played with a windows 8.1 phone. One word, though it has got impressive hardware specs, it never has a WOW feeling.

The phone uses a different UX pattern. All other operating system provides:

  1. Horizontal navigation (multiple screens), the windows OS provides vertical navigation. 
  2. No task bar, where a user can pin applications. As an example, I cannot create a quick short cut for phone, messaging applications. To make a phone call or to find the messaging applications, I have to search inside the UI application hell. Please don't give recommendations like  - create a folder, keep it on the  top of the screen. I call these recommendations a work around and not actual solutions.
  3. Even if it offers a live tiles, it doesn't provide a one OS feeling (I have a windows PC)
What MSFT can do to improve Windows phone ecosystem:
  1. Provide a unified user experience across all the devices (phone, tablets, XBox, PC)
  2. Provide horizontal navigation (available in PC and Xbox)
  3. Provide a fixed task bar on the metro screen which has a windows icon. On clicking this window icon button will open up the Applications (start up menu) window.
  4. A user can pin apps to the the task bar (like window 8.1 )
  5. Live tile folders (PC, tablet, phone and XBox)

I know, for the Microsoft engineers, the device form factor may be a big concern, if they move from vertical to horizontal layout. But, if you want to increase the customer base, you have to make a choice. Don't throw your choices to the users and make them suffer. 

MSFT CEO gives more focus to cloud services. Cloud may be today, but future is innovation. You guys need to provide a best in class products and services and support model to customers. For that, you have to change.  You need to marry your products with services. See, how apple is making revenue. Products, services and customer satisfaction. 




Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts