Saturday, May 9, 2015

SQL Tuning test environment

Setting up a stable and predictable test environment is crucial to any performance tuning and measurements.

Clear Caches:
  • Execute Checkpoint to flush the dirty pages out into the IO sub-system
  • Clear the plan cache using DBCC FREEPROCCACHE ( clears plan cache for all db instances in the box), you can clear for only a db with FLUSHPROCCACHEINDB(db_id) or even better just for that individual plan knowing the plan handle id.
  • Run DBCC DROPCLEANBUFFERS - clears all data from memory -NEVER do this in PROD!
Set Measurements:
  • SET Statistics time on - elapsed time and CPU time
  • set statistics io on - logical reads (data from memory) and physical reads(from IO - slower)
  • Use Graphics Execution plan or SET SHOWPLAN TEXT|XML
Use DMVs:
  • System Info - sys.dm_os_wait_stats,  sys.dm_os_performance_counters
  • Query Info - sys.dm_exec_requests
  • Index Info - sys.dm_db_index_usage_stats
TIPS:

1) Look out for table scans and clustered index scans - not necessarily bad say if it is only 64Kb, that is eight 8Kb pages, but one has to assume that the table could be very large. Remember that the clustered index scan is the scan of the table in its physically sorted order!

2) Look out for lookups - bookmark(legacy), Key and RID lookups. We might benefit from a new index?

3) check for spools - means something is getting spooled out to tempdb - so a lot of IO is taking place.

4) Parallelism - may be good or bad for the plan with MAXDOP?

5) And here's one BIG tip - if the stats between the estimated and actual execution plans are wildly different, that means your stats are usually (not always) very outdated/stale - indexes have not been updated or rebuilt for a long time! It could also be incorrect because the optimiser has no information, like form a scalar UDF, table variable or multistatement TVF - assumes only 1 row coming out. Another cause could be due to parameter sniffing - so sniffing is a double edge sword.

6) If too many physically reads, usually a sign of lack of memory and you can throw a lot of memory to solve that problem!

7) Whenever there is Sorting , say in  hash joins or some kind of merge joins, it means Sql Server will use tempdb (physical io) a lot for the sorting operation,

8) and then there is Implicit Data Conversions - avoid them.

9) Note that Cursors are not always bad - in fact before sql 2012, they are the most efficient for running totals and say keeping a running balance - it will outperform self-joins! In 2012 they introduced windowing functions like LAG and LEAD that will outperform Cursors. A lot of DDL uses Cursors. Another good use case, is maintenance scripts - say calling a stored procedure for every database in some kind of loop, or sending an email from a list etc. There is no good way to do that in a set.

From Adam Machanic https://www.youtube.com/watch?v=GSZPvF2u6WY
The top 5 culprits are
Lookup
Sort
Spools
Hash
Nested Loops (serial)
and of course Table and Index scans

Also look at moving the fat arrows from left to right (logical interpretation) in the execution plan.
Then the optimizer can filter the rows earlier. That's another reason why Nested views are no good. The optimizer cannot filter the data using the where clause predicates. Replacing the views with an inline table valued function is the solution as the optimizer now knows how to build the correct estimated plan for the query.

Sunday, May 3, 2015

WebSockets, SignalR and Real Time web applications

WebSockets changed the way we can communicate in our web apps between the client and server. Previously we could keep http 1.1 persistent connection between client and server, but it was used only for the client to keep the connection open for making another request to get any updates.

The TCP protocol used by websockets now allows the server to communicate to the clients without the clients initiating a request! In short, it allows for bi-directional full-duplex communication between the client and the web server.

That means these messages can be transmitted between client and server concurrently. And the messages don't rely on any rigid specfications like headers and cookies, which means it can be very lightweight and very fast!


The WebSockets API looks very simple

var socket = new WebSocket("ws://echo.websockets.org");

//Once connection opens, send message to server
socket.send("hello from websockets!");

//To receive messages from the server, subscribe to an onmessage event
socket.onmessage( function(event){
            alert("I got server data! " + event.data);
});

But to work at this low level, you still have to worry about serializing data to send to the server and deserializing data from the server, managing connections, supportability in browsers, ordering of messages etc. The answer - SignalR!

SignalR is just an encapsulation wrapper around WebSockets so we no longer need to use long polling Javascript methods to get instant updates from the Server. This opens up a slew of opportunities for developing all kinds of real time web applications.

Learning demo on GitHub:
https://github.com/yashish/RealTime-PerfMon-using-SignalR-Knockout.git

Kendo Grid and Chart

Wetting my hands with the Kendo widget

http://jsfiddle.net/yaraj/hfwzzss1/13/

Saturday, May 2, 2015

AngularJS ui-router nested states Hint

The cool thing about nested states in ui-router is we can define a resolve property to materialize any data (say from a service) in the parent state, and this data is now available to all the children states! Very cool, as this allows data to be shared across different states - read different views - without fetching them again and again and retaining context. Note that a single controller can be used to serve all the states within a nested states hierarchy.

Example code below. The coupon data from the parent state is available across all nested views!

.state("couponEditParent", {
                abstract: true,
                 url: "/coupons/edit/:couponId",
                 templateUrl: "app/coupons/couponEditView.html",
                 controller: "CouponEditCtrl as vm",
                 resolve: {
                       couponService: "CouponService",
                       coupon: function(couponService, $stateParams) {
                                           var couponId = $stateParams.productId;
                                           return couponService.get({couponId: couponId})
                                    }
                       }
  })
.state("couponEditParent.basicInfoChild", {
                 url: "/basicInfoChild",
                 templateUrl: "app/coupons/couponEditBasicInfoView.html"
  })
.state("couponEditParent.detailsInfoChild", {
                 url: "/detailsInfoChild",
                 templateUrl: "app/coupons/couponEditDetailsInfoView.html"
  })

Note that if your app does not require activating the Parent state alone (without activating a child state), ui-router provides a property called "Abstract State" that can be applied to the parent state, so it can never be explicitly activated. Activation attempt will throw an exception! It is only activated implicitly when one of the child states is activated.

Wednesday, April 29, 2015

.NET C# TimeSpan Comparison Tip

If you ever find yourself in  need of comparing hour, minutes and seconds in a database table stored as integers to say the hour and minute of the day, you can do something like this very simple.

       static void Main(string[] args)
       {
            bool timeOfTheDayEqual= false;
            int hours = 8;
            int minutes = 52;

            TimeSpan scheduledStartTime = new TimeSpan(hours, minutes, 0);
            TimeSpan timeNow = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0);

            if (timeNow == scheduledStartTime)
            {
                timeOfTheDayEqual =  true;
            }

            Console.Write(timeOfTheDayEqual);
            Console.ReadKey();
      }


This comparison of the TimeSpan values will always be accurate.

Saturday, April 18, 2015

How to create your own Katana middleware component - at the metal


//using a C like typedef alias for the Func() inside the class file
using AppFunc = Func<IDictionary<string,object>,Task>();

In the Configuration method of Statup, use my OWIN Katana component

public void Configuration(IAppBuilder app)
{
       app.Use<MyOwinComponent>();
}


// My lowest level OWIN component
public class MyOwinComponent
{
        //Required to pass processing on to the next OWIN component
       AppFunc _next;

       public MyOwinComponent(AppFunc next)
      {
             _next = next;
       }
        
       // If not using await, remove the async keyword   
       //This method should match the AppFunc signature
       public async Task Invoke(IDictionary<string,object> environment)
       {
                var response = environment["owin.ResponseBody"] as Stream;
                using( var writer = new StreamWriter(response))
                {
                      return await writer.WriteAsync("Hello from my Owin Component!");
                 }


                //Example await next component and pass along the dictionary 
                // await _next(environment);
       }
}

We can also add syntactic sugar to this so we can specify in configuration method as

              app.UseMyOwinComponent();

by creating an extension method like so

public static class AppBuilderExtensions
{
        public static void UseMyOwinComponent(this IAppBuilder app)
        {
               app.Use<MyOwinComponent>();
         }
} 

******************************************************************

NOTE: Katana provides higher abstractions using app.Run or app.Use with its overloaded functions to write our middleware components, and we should actually use that.

For instance, using just a lambda expression

         app.Use( async (environment, next) =>
         {
                 Console.Write("Requesting: " + environment.Request.Path);

                  await next();

                Console.Write("Response: " + environment.Response.StatusCode);
          }

          app.UseMyOwinComponent();


How to create a Katana WebServer in a console application

Create a new Console app and add these 2 packages:

install-package Microsoft.Owin.Hosting
install-package Microsoft.Owin.Host.HttpListener

Add a class called Startup and a configuration method that takes an IAppBuilder interface. IAppBuilder is in the Owin namespace.

public class Startup
{
      public void Configuration(IAppBuilder app)
     {

             //Add other features from other Katana components through 
             //the Use extension method. For instance, this below method 
             // asfter installing the Microsoft.Owin.Diagnostics package
             // can be used instead of app.Run() to start a Web server 
             //with a Welcome Page.
             
             //app.UseWelcomePage();

              //Process all requests. Returns a task and is a wrapper to calling AppFunc.
              // app.Run can be used to dynamically add your middleware as done here.
              app.Run(ctx =>
              {
                    return ctx.Response.WriteAsync("Hello Katana!");
               });
      }
}

The IAppBuilder interface has methods that allows us to configure and respond to HTTP requests. As we add additional Katana components (nuget packages), we may see additional extension methods that we can use to turn on to use additional Katana features.

Run() takes an OwinContext which has an Environment property, and returns a Task. This property is a Dictionary<string,object> and has all the information about the request - the Http Headers, cookies, the URL path, the Verb that was used etc. This is the core abstraction of OWIN and makes it very simple to add Owin components and middleware as needed in the request processing pipeline. Does away with all the bells and whistles with the conventional ASP.NET and System.Web assembly processing pipeline.

To start the web server on say port 8080, use a Katana component called WebApp to run this Startup class as below:

public static Main(string[] args)
{
      string url = "http://localhost:8080";

      using (WebApp.Start<Startup>(uri)
      {
             Console.WriteLine("Web Server started....");
             Console.ReadKey();
             Console.WriteLine("Web Server ended...");
      }
}

Reference: This example has been taken from the Scott Allen Pluralsight course on OWIN.