Wednesday, 19 July 2017

Get started in Queue, Topic and Subscription in Microsoft Azure

In this post we are going to see how to start in Microsoft Azure for Queue, Topic and subscriptions

Go to the Azure Portal and create a Service Bus Namespace and get a connection string, Next create a queue and Topic

using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static string connectionString = "Endpoint=sb://raj.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=sbxireNSHksjqaiorlkms";
        static string QueuePath = "test_queue";
        static string Topicpath = "test_topic";

        static void Main(string[] args)
        {
            // For Queue
            var _queueClient = QueueClient.CreateFromConnectionString(connectionString,QueuePath);

            // sender side for queue
            for (int i = 0; i < 10; i++)
            {
                var message = new BrokeredMessage("Message " + i);
                _queueClient.Send(message);
                Console.WriteLine(message);
            }

            // receiver side for queue
            _queueClient.OnMessage((mes) => processMessage(mes));
            _queueClient.Close();


            // sender side For Topic
            string username = "rajesh";
            var manager = NamespaceManager.CreateFromConnectionString(connectionString);
            if(!manager.TopicExists(Topicpath))
            {
                manager.CreateTopic(Topicpath);
            }

           
            var subscription = new SubscriptionDescription(Topicpath, username)
            {
                AutoDeleteOnIdle = TimeSpan.FromMinutes(5)
            };
            manager.CreateSubscription(subscription);


            var factory = MessagingFactory.CreateFromConnectionString(connectionString);
            var topicClient = factory.CreateTopicClient(Topicpath);

            // receiver side for topic that is subscription
            var subClient = factory.CreateSubscriptionClient(Topicpath, username);
            subClient.OnMessage(msg => processMessage(msg));

            var helloMessage = new BrokeredMessage("Has entered Room");
            helloMessage.Label = username;
            topicClient.Send(helloMessage);

            while (true)
            {
                string readText = Console.ReadLine();
                if (readText.Equals("exit")) break;

                var readTextMessage = new BrokeredMessage(readText);
                readTextMessage.Label = username;
                topicClient.Send(readTextMessage);
            }

            var leftMessage = new BrokeredMessage("Left the room");
            leftMessage.Label = username;
            topicClient.Send(leftMessage);

            factory.Close();

        }

        private static void processMessage(BrokeredMessage mes)
        {
            var label = mes.Label;
            var text = mes.GetBody<string>();
            Console.WriteLine("Received " + text);
        }
    }
}



From this post you can learn how to get started in Queue, Topic and Subscription in Microsoft Azure 

Saturday, 10 June 2017

Compressing web api response using GZip

In this post we are going to see how to create a compressed web api response to user,  because of compressing the result content-length will be less and it is more faster in get response. First let we create a new Web Api project.

    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Department { get; set; }

        public int Marks { get; set; }

    }

   public IEnumerable<Student> Get()
   {
            List<Student> studs = new List<Student>();
            studs.Add(new Student() { Id = 1, Name = "rajesh",
Department ="CSE", Marks=83});
            studs.Add(new Student() { Id = 2, Name = "suresh",
Department = "ECE", Marks=92  });
            studs.Add(new Student() { Id = 2, Name = "ramesh",
Department = "CSE", Marks = 76 });
            studs.Add(new Student() { Id = 2, Name = "ramu",
Department = "ECE", Marks = 94 });
            return studs;

    }

From the above code we can see the student list is returning, now we test this in post man rest client.









from the above , you can see the result is content-length is 219, now we will enable the GZip compression. For this we have to create actionFilterAttribute there we have to set the content-encoding as gzip. we have to add a package DotnetZip from nuget package manager


public class GZipCompression
    {
        public static byte[] GzipByte(byte[] input)
        {
            if (input == null)
                return null;
            using (var result= new MemoryStream())
            {
                using(var compress = new Ionic.Zlib.GZipStream(result,
Ionic.Zlib.CompressionMode.Compress))
                {
                    compress.Write(input, 0, input.Length);
                }
                return result.ToArray();
            }
        }
    }



public class ZipCompressionAttribute:ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext                                                actionExecutedContext)
        {
            var content = actionExecutedContext.Response.Content;
            var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
            var compressedContent = bytes == null ? new byte[0] :                                                                            GZipCompression.GzipByte(bytes);

            actionExecutedContext.Response.Content = new ByteArrayContent(compressedContent);
            actionExecutedContext.Response.Content.Headers.Remove("Content-Type");
            actionExecutedContext.Response.Content.Headers.Add("Content-encoding", "gzip");
            actionExecutedContext.Response.Content.Headers.Add("Content-Type",                                                                             "application/json");
            base.OnActionExecuted(actionExecutedContext);
        }

    }


Finally we have to add this action filter above the api method

[ZipCompression]
public IEnumerable<Student> Get()
{
            List<Student> studs = new List<Student>();
            studs.Add(new Student() { Id = 1, Name = "rajesh",
Department ="CSE", Marks=83});
            studs.Add(new Student() { Id = 2, Name = "suresh",
Department = "ECE", Marks=92  });
            studs.Add(new Student() { Id = 2, Name = "ramesh",
Department = "CSE", Marks = 76 });
            studs.Add(new Student() { Id = 2, Name = "ramu",
Department = "ECE", Marks = 94 });
            return studs;

}


Now we see the response in post man client, content-length will be reduced.











From this post you can learn how to create a compressing web api response using Gzip.

Sunday, 30 April 2017

Add authentication token in every http request call in angular js applications

In this post we are going to see how to pass the authentication token in every http request call in angular js application

authService:
*************
 mvcapp.service('authService', ['$localStorage', '$rootScope',function ($localStorage,$rootScope) {

    this.getAuthCode = function () {
        return $localStorage.authuser;
    }

    this.setAuthCode = function (authdata) {
        $localStorage.authuser = authdata;
    }

    this.removeAuthCode = function () {
        delete $localStorage.authuser;       
        var loggeduser = { Status: '', Username: '', Authcode: '' };
        $rootScope.$broadcast('loguser', loggeduser);
    }

    this.isLoggedIn = function () {
        return $localStorage.authuser != null && $localStorage.authuser.Authcode != null;
    }


}]);




Factory:
*********
mvcapp.factory('httpRequest', ['$q', 'authService', function ($q, authService) {

    var _interceptors = {
        request: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
                var loggedin = authService.getAuthCode();

                if (loggedin!=undefined && loggedin.Authcode != null)
                    config.headers["Authorization"] = "Bearer " + loggedin.Authcode;

            }
            return config;
        },
        response: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return response;
        },
        requestError: function (config) {
            if (angular.isObject(config)) {
                config.delay = new Date().getTime();
            }
            return $q.reject(config);
        },
        responseError: function (response) {
            if (angular.isObject(response.config)) {
                response.config.delay = new Date().getTime() - response.config.delay;
            }
            return $q.reject(response);
        }
    };

    return _interceptors;

}]);



mvcapp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequest');
}]);



From this post you can learn how to pass the authentication token in every http request call.