Wednesday, 7 June 2017

Message pick up strategies for stream analytics jobs

What happens to messages when a stream analytics job is stopped and start again after some time.
What are the decisions that impact this. Here are few options that are necessary to consider.



Refer to diagram below.






1. Now - when this option is chosen, it will pickup messages that are ingested now on wards. All messages which got ingested into system when job was stopped will not be picked up.

2. Custom - You can specify the time from which you want to pick messages. Let's say job was stopped for 4 hours, so you want to select messages during that time, in case you can choose this option.

3. When last stopped - This option will enable the job to pick up messages which were ingested even when job was stopped, From last run of the job, it keeps are checkpoint and hence pick up messages post that checkpoint.

Usual recommendation option is "When last stopped", But your choice may vary as per your requirement.


Different ways to automate Stream analytics jobs on azure

Stream analytics job on azure can be created from azure portal using wizard and step by step graphical guideline process. However let's think of the scenario where we need to create same jobs to different environments testing, UAT, pre-prod, prod, regression test environment etc. It will be highly tedious job to create jobs manually for each environment. And that when one may feel need to automate this process.

Following are some of the ways in which stream analytics job on azure can be automated and reuse at different places. Each approach pros and cons are also compared in below section.

Using ARM template
Pros
•      Deployment of stream analytics jobs can be automated and solution can be deployed to different environment with minimal time span without repetitions of steps.
•      Deployment through portal to 10 different environments manually would be tiresome and error prone job.
Cons
•      Jobs need to be stopped till deployment and users need to be informed. **However same case is applicable even through portal.
•      For specifying PowerBI output in stream analytics, it's necessary to perform a logon to the powerbi service something that is not possible during the ARM Template deployment. (https://github.com/vtex/VtexInsights/wiki/Stream-Analytics).

Using Stream Analytics Powershell cmdlets

Pros
•      Jobs can be created with a simple PowerShell command.


Cons
•      Separate commands are available for creating jobname,outputs,transformations. Need to combine them at one place as write custom commands to deploy one job including all input,transformation,outputs.

Using Stream Analytics REST API References

Pros
•      Separate API’s for inputs, outputs, transformation. So we need to put all pieces together and customize to deploy all parts of SA-jobs at a time
Cons
•      We will need to authenticate the API requests.


Using stream-analytics-dotnet-management-sdk

Pros
•      Gives us more control over stream analytics job like programmatically monitor SA-jobs. Stream Analytics jobs created via REST APIs, Azure SDK, or Powershell do not have monitoring enabled by default. So this feature comes in use.

Cons
•      Use only if you need more control over jobs and when none of above options satisfy your needs. 



Recommendations
             
                  Use ARM template, It serves following 2 purposes

•      We can configure tumbling window of SA-jobs dynamically.
•      It helps to automate the deployment of SA-jobs to multiple environments. If there are multiple environments for the applications, once development is complete, we don’t want to spend same time as development to move the solution to other environments. So it’s better to have parameterized variables as per environments and deploy SA jobs.

Thursday, 27 March 2014

Dependency Injection in MVC4

Dependency Injection is a design pattern that helps to reduce tight coupling between software components.
Due to loosely coupled code, we can develop maintainable software systems. Dependency Injection pattern uses an object to initialize the objects and provide the required dependencies to object it allows you to inject a dependency, from outside the class.



DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means. For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.

 public class Customer
    {
        public Logger Log;
        public Customer(Logger obj)
        {
            Log = obj;
        }

    }

Now we can invoke the customer object with any kind of logger.

Customer obj = new Customer (new EmailLogger());
Customer obj1=new Customer (new EventViewerLogger());

 This approach helps in decoupling. Hence dependency injection helps us in developing testable, maintainable and decoupled software components. There are various tools available for implementing depency injection like Ninject, Unity etc. 



MVC4 Web API - Using Custom Action Names

By default, In MVC Web API, the route configuration follows RESTFUL conventions meaning that it will accept only the Get, Post, Put and Delete action names. However for better readability  a developer will definitely feel the need for his own meaning action names. In this blog, I will explain how to implement custom action names.

1. Let's first create a simple web API. Create ASP.NET MVC4 project by selecting the Web API project template.





2. By default valuescontroller and home controller is added as part of solution.
3. Following methods are added to values controller.
         // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "helloss yogita";
        }

            
3. Run the project, type the url "http://localhost:56355/api/values/" in addess bar. Here is the     response.
                            

4. Similarly, now type the url "http://localhost:56355/api/values/5" and observe the response.


5. Now, these methods are standard methods. But usually, a developer would like to give more logical and meaningful method names. For example, action name Get doesn't reveal much information about what kind of information is returned from a particular action. Let's say I want to call an action GetContactInfo(string id) where id can be EmployeeId.

6. Let's write a method now, in values controller which accepts a Id and returns contact information.
        public string GetContactInformation(string id)
        {
            return "Contact number is 1234567890";
        }
            
7. Now run the project to see what's is returned as output of this method. Type this url "http://localhost:56355/apis/values/GetContactInfo/5"


Oops!!! Ok, this happened because, Web API routing is not aware of this route. 

8. Let's fix it. App_Start->WebApiConfig.cs and provide the route information.

 //declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
            config.Routes.MapHttpRoute(
                name: "ContactsApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

9. Now, we have mapped the route handler with controller and action methods. Now run the project and try                                

Oops!! Its not finding the resource again. 

10. Let's be more specific and provide the actionname information is web uri template as follows.
       //declare the route handler for contacts api to handle CustomActionMethod GetContactInfo
           config.Routes.MapHttpRoute(
                name: "ContactsApi",
                routeTemplate: "api/{controller}/{GetContactInformation}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

           
11. Let's run the URL again. And observe the output.

Therefore we saw how we can use meaningful action names and map them using Web API routing template. 

Sunday, 14 April 2013

My Learnings with DataGridView in WinForms - Part 3

 Dynamically change images based on values based on other grid column
 
In this part, we will learn how to display appropriate images based on status(or any other grid column value). Let’s continue with the same code sample as in Part-2 and Part1.

Let’s consider a scenario that if a book is available we would like to display an image button “Buy” so that user can place order for that book. In case book is Not Available, we would let the user select “SMS” option so that whenever book is available user will be notified through SMS.

Status
ImageToDisplay
ImageIcon
Available
Buy
 


Not Available
SMS
                      
 

Let’s modify our grid in previous post to include one more column for Buy/SMS.
1.

 2.
 
3. New datagrid column will be added as shown.
 

4. Add CellFormatting event to the datagrid(dgvDashboard).
 
5.             Modify the code in dgvDashboard_CellMouseMove function as below. This function updates the mouse cursor to hand for newly added(Buy/SMS column).
 
private void dgvDashboard_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            //Skip the Column and Row header
            if (e.ColumnIndex < 0 || e.RowIndex < 0)
            {
                return;
            }
            //Check the condition as per the requirement casting the cell value to the appropriate type
            //column index 4 is delete column, column index 5 is Buy/SMS column
            if (e.ColumnIndex == 4 || e.ColumnIndex==5)
                dgvDashboard.Cursor = Cursors.Hand;
 else      {      dgvDashboard.Cursor = Cursors.Default;
}
6. Now add required images to the solution. Double  click on Resources.resx file from solution explorer.
 

Choose path of BuyNow and SMS images.
 
7.  Add the following code to cellformatting event.
private void dgvDashboard_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (!dgvDashboard.Rows[e.RowIndex].IsNewRow)
            {
                if (dgvDashboard.Columns[e.ColumnIndex].Name == "BuySMS")
                {
                    if ((dgvDashboard.Rows[e.RowIndex].Cells["Status"].Value).Equals("Available"))
                    {
                        e.Value = Properties.Resources.buy;
  dgvDashboard.Columns["BuySMS"].Tag = "Buy";
                    }
                    else
                    {
                        e.Value = Properties.Resources.sms;
  dgvDashboard.Columns["BuySMS"].Tag = "SMS";
                    }
                }
            }
        }
 
8. Let’s run the solution now and observe the output.
 

Oops!! Entire column contains “Buy” Image as status of all books is Available. To test properly lets change one of the row status to” NotAvailable”.
For this update the PopulateGrid() method as follows.
public IList<CourseEntity> PopulateGrid()
{
 List<CourseEntity> courseList = new List<CourseEntity>();
 courseList.Add(new CourseEntity { Id = "1", CourseName = "Asp.NET MVC3", Status = "Available" });
courseList.Add(new CourseEntity { Id = "2", CourseName = "Asp.NET MVC4", Status = "Available" });
courseList.Add(new CourseEntity { Id = "3", CourseName = "C#", Status = "Not Available" });
courseList.Add(new CourseEntity { Id = "4", CourseName = "Metro Apps", Status = "Available" });    
 return courseList;
 }
9. Now observe the output by running the solution again.

 
 Therefore, we are able to display appropriate images based on status column value. And also show hand cursor over them to make them clickable.
But nothing will happen as of now, if user clicks on BuyNow or SMS options. For that we need to write logic for “BuyNow” and SMS clicks.
Add the following code in MouseClick event of the datagrid.
private void dgvDashboard_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e){            //Skip the Column and Row headers
if (e.ColumnIndex < 0 || e.RowIndex < 0)  { return; }      
if (e.ColumnIndex == 4){  dgvDashboard.Rows.RemoveAt(e.RowIndex);}           
//if user click on Buy/SMS column   
         if (e.ColumnIndex == 5)            {
                //Add logic for Buy or SMS as per user selection
        if (dgvDashboard.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag.Equals("Buy"))
                {
                    //Add logic for Buying the product
                    MessageBox.Show("You click on Buy Image in row " + e.RowIndex);
                }
                else
                {
                   //Add logic for sending sms
                    MessageBox.Show("You have clicked on SMS Image in row " + e.RowIndex);
                }
            }
        }
** Please notice that in step7 while assigning images to appropriate rows, we have also set tag property of image. This property helps us distinguish between Buy and SMS image clicks in same column.

Conclusion

We learnt how to dynamically change images based on values based on other grid column using cellFormatting Event.