DateTime – AngularJS, Javascript, C#

Since I normally develop backend (server side) with C#, I am passing dates from my WebAPI REST services as .NET local dateTime objects.

My Angular services call the webAPI and get a value like:

2015-03-04T09:02:16

I want to bind this to standard HTML inputs but it fails. I’ve found that I can easily fix this by converting my AngularJS model’s date value before it gets to the UI.

So I call my WebAPI as always, then once I get the response on the client side, I have to convert any date fields like this (notice the bold line):

ZTaskService.GetTask(taskId)
   .then(function(data){
     //happy path
     data.CreateDate = data.CreateDate != null ? new Date(data.CreateDate) : data.CreateDate; 
     $scope.task = data;  
   },function(data){
     //sad path
     console.info(data);
   });

Since the date has now been converted to a Javascript date, AngularJS will be happy with it and bind it in standard HTML input tag like:

<input type="datetime-local"  ng-model="task.CreateDate">

NOTE:
If you don’t check for the date to be null, and you accidentally convert null values to new Dates, they will be ‘Wed Dec 31 1969 19:00:00 GMT-0500 (EST)’.

AngularJS – Issues binding your model to select list when types don’t match

An issue I’ve run into a few times when binding a model’s foreign key field to a drop down is that my drop down list will have select items where the name and value are both strings, and the model will have a foreign key which is an int that I’m trying to bind to that select list. Since my model’s field is an int, and the values of the select list are strings, they fail to bind as expected.

A very simple fix is to multiply your values in your select list by 1 which converts the string to an int, and then the model binds as expected.

Since a code sample is worth a 1000 words, look at this situation. I have a ‘task’ model for the page. The task’s TaskTypeId is an int.

task.TaskTypeId = int (=23)

I have a list of taskTypes in a selectList. The Id value here is a number but it is a string

taskType.Id = string (=”23″)

This is not working:

<label>Type:</label> 
    <select
    ng-model="task.TaskTypeId"
    ng-options="taskType.Id as taskType.Name for taskType in taskTypes" ></select>

This does work:

<label>Type:</label> 
    <select
    ng-model="task.TaskTypeId"
    ng-options="taskType.Id*1 as taskType.Name for taskType in taskTypes" ></select>

I’m still looking for the best practice, but this is a simple working solution.

AngularJS TypeError: Cannot read property ‘then’ of undefined

This occurs if you forget to return the item that originally defines .then

For instance, my that caused this was in a function I was calling and it looked like this:

            $http.get(myurl) //, {params:params})
	    .then(
	    	function(response){
	    		return response;
	    	},
	    	function(response){
	    		return response
	    	}
	    ); 

I needed to add ‘return ‘ to it as follows:

            return $http.get(myurl) //, {params:params})
	    .then(
	    	function(response){
	    		return response;
	    	},
	    	function(response){
	    		return response
	    	}
	    ); 

I hope this helps someone else.

Javascript Q vs callbacks to return $.ajax or $http data

An issue that often occurs when using Javascript is that you will a call a function, which will eventually return a value (not now ,but eventually). In my recent case this was with a function that calls $.ajax() function, and tries to return that value to the caller.

For this test I signed up at http://home.openweathermap.org/
and got a key to use, you’ll need to use either the sample key at their site or get a key if you want to try this

Here is a sample (this doesn’t work so don’t use this method)

 
    <html>
        <head>
            http://bower_components/q/q.js
            http://bower_components/jquery/dist/jquery.js
             
                function CallAPI( city)
                { 
                    var key = 'bd82977b86bf27fb59a04b61b657fb6f';
                    
                    var url = 'http://api.openweathermap.org/'
                    var fullurl = url + 'data/2.5/weather';
                   
                    $.ajax({
                        dataType: "jsonp",
                        url: fullurl,
                        jsonCallback: 'jsonp',
                        data: { q: city,
                              appid: key},
                        cache: false,
                        success: function (data) { 
                           return data;  //PROBLEM: you can't return this data now!!!!
                        } 
                      }); 
                }
                
               function GetWeather(){
                     var city = 'greensboro,us'
                    
                    var data = CallAPI(city); 
                    alert(data.weather[0].description);   //alert is undefined because this is hit long before the ajax call returns.
               }
            
        </head>
        <body>
            <button id='mybutton' onclick="GetWeather()">Get Weather</button>
        </body>
    </html>
 

The problem is that if I try to return the value in the .success section, it will be undefined when I try to use it in the calling method.

The javascript way to handle this is to pass a callback function, and once the AJAX call completes, you load your return value into the callback function, which is then used by the originating caller. This is a bit unnatural for those of us used to languages other than Javascript. Here is a sample of that solution. This works but passing callbacks rather than using ‘return’ feels awkward.

<html>
        <head>
            http://bower_components/jquery/dist/jquery.js
             
                function CallAPI( city,mycallback)  //receives a callback function
                { 

                    var key = 'bd82977b86bf27fb59a04b61b657fb6f';
                    
                    var url = 'http://api.openweathermap.org/'
                    var fullurl = url + 'data/2.5/weather';
                   
                    $.ajax({
                        dataType: "jsonp",
                        url: fullurl,
                        jsonCallback: 'jsonp',
                        data: { q: city,
                              appid: key},
                        cache: false,
                        success: function (data) { 
                            mycallback(data);		//put data in your callback function
                        } 
                      }); 
                }
                
               function GetWeather(){
                    var city = 'greensboro,us'
                    
                    var data = {}; //an empty object for now
                    CallAPI(city,function(data){ 
                    	//this executes whenver the data is sent back via the callback function in CallAPI
                    	//this is the call back function
                        alert(data.weather[0].description);      
                    }); 
                }
                
            
        </head>
        <body>
            <button id='mybutton' onclick="GetWeather()">Get Weather</button>
        </body>
    </html>

If you run that you will have a button on your screen that says ‘Get Weather’. This triggers the ‘GetWeather()’ function, which in turn calls ‘CallAPI(city,mycallback)’. The CallAPI function makes an ajax call to the API to get some weather info in the form of JSON data. Once the callback function runs in the original function (GetWeather()), an alert window displays the value I returned from ‘CallAPI’.

Using Q
The solution is Q (or $q in AngularJS).

Q is on GitHub at https://github.com/kriskowal/q, and can be installed in using Nuget, or if you rather use bower, you can install it with the command line ‘bower install q#1.0.1’.

There is also a variation of it included in AngularJS so you see the same functionality in AngularJS automatically without separately installing Q.

Now we’ll look at an example using Q. Notice that this method does the same thing but there is no callback function being passed from one function to another. Instead we use the more natural method of returning a value from a function.
Also note that this one looks longer because I’ve included error paths where I didn’t above.

<html>
        <head>
            http://bower_components/q/q.js
            http://bower_components/jquery/dist/jquery.js
             
                function CallAPI(city)
                { 
                    var key = 'bd82977b86bf27fb59a04b61b657fb6f';
                    
                    var url = 'http://api.openweathermap.org/'
                    var fullurl = url + 'data/2.5/weather';
                    
                    //I return this rather than working with callback functions
                    return $.ajax({
                            dataType: "jsonp",
                            url: fullurl,
                            jsonCallback: 'jsonp',
                            data: { q: city,
                                  appid: key},
                            cache: false 
                          })
                        .then(
                            function(response){
                                //Happy path -- returns expected data
                                return response;
                            },
                            function(response){
                                //Sad path -- an error occured
                                return response;
                            }
                          );
                       
                }
                
               function GetWeather(){
                     var city = 'greensboro,us'
                    
                     CallAPI(city)
                     .then(
                         function(data){
                            // Happy path -- this first function returns expected data
                            alert(data.weather[0].description);
                         },
                         function(data){
                             //Sad path -- this second function is hit if there was an error
                             alert ("So sad... There was an error : " + data);
                         }
                     );
                }
                
            
        </head>
        <body>
            <button id='mybutton' onclick="GetWeather()">Get Weather</button>
        </body>
    </html>

So what do we see here?
A ‘Get Weather’ button appears on your page. You click it. It triggers the ‘GetWeather’ function. This, in turn, calls ‘GetAPI(city)’, and because we are now using Q, GetAPI(city) promises to return a value (good or bad it will return something so we can rely on it).

We’ve chained a ‘.then(…)’ statement onto the $.ajax call, so our .ajax call can go do it’s work and take it’s time, but whenever it gets done, it will either have a valid response (promise fulfilled) or it will have an error (promise rejected). If all worked as planned, the first function within the .then section will be executed, and if an error occurs, the second function in the .then section will be executed. In both cases, I’ve set it to return that data back to the original caller. The original caller also uses the .then section with 2 functions so it can react to both positive and negative responses.

SQL Script to locate fields that should be indexed

Thanks Paul!
And Thanks to the site: http://www.i-programmer.info/programming/database/3208-improve-sql-performance-find-your-missing-indexes.html

SET TRANSACTION ISOLATION LEVEL 
READ UNCOMMITTED;
SELECT TOP 20
       [Total Cost] = ROUND(s.avg_total_user_cost * s.avg_user_impact * (s.user_seeks + s.user_scans), 0)
       ,[Table Name] = d.statement 
       ,d.equality_columns
       ,d.inequality_columns
       ,d.included_columns
       ,d.database_id
FROM
       sys.dm_db_missing_index_groups g
       INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle
       INNER JOIN sys.dm_db_missing_index_details d ON d.index_handle = g.index_handle
WHERE d.database_id = 19 -- disable where, get value from result for proper db, set then apply to where
ORDER BY
       [Total Cost] DESC;