Calling function from your angularjs directive


Calling function from your angularjs directive


Calling function from your angularjs directive is super easy. To call a function from your directive you need to get the expression from your custom attribute and then by using $parser service we can parser the given expression and can call that parsed expression very easily.

Here is the code for directive that using isolated scope.

var module = angularjs.module('myApp',[]);
module.directive('myCustomFunction',['$parse', function($parse) {
return {
scope : false, // no isolated scope
replace : false,
link:function(scope, element, attr) {
    element.click = function() {
        // Calling function parsing the expression first and then 
        // executing the expression under directive scope here 
        // directive scope is parent controller scope
        $parse(attr.myCustomFunction)(scope);
    };
};
}]);
If you are using isolated scope you can do the same by using function binding to the scope variable. Here is the example.

module.directive('myCustomFunction',['$parse', function($parse){
return {
scope : {
    // Isolated scope binding a function to scope variable
    myCustomFunction : '&'
},
replace : false,
link : function(scope, element, attr) {
    element.click = function() {
        // Calling bind function
        scope.myCustomFunction();
    };
};
}]);
Html code (View code)
<button my-custom-function="someControllermethod()">My Custom Directive example</button>

Thats all. Thanks.

Do more with Mongo shell


Mongo ( mongo.exe )


Mongo is a client program use to execute query and command against a mongodb server. This program ships with Mongodb package.
I don't like to work with command line tools (specially windows based) but in case of mongo its really fun. Mongo provides us a javascript interpreted shell and developer who loves javascript is also felt in love with mongo shell.
To  demonstrate some features of mongo shell lets open your mongo client shell and connect with your mongod instance.

Insert a document in product collection and then update it using help of javascript object.

 

Below is the commands that I used. Do copy paste to save your time
> db.product.insert({ "_id" : "ac3", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone", "price" : 200, "warranty_years" : 1, "available" : true })

Now to update the inserted document we can use a javascript  object like below.
> p = db.product.findOne({"_id":"ac3"}) // set to find document
> p.price = 199  // update price field
> p.warranty_years = 2
> db.product.save(p) // update product into database ... easy hum.
The above object p only exist for the current mongo shell session.

Writing multiline script in shell

 

Mongo shell support line continuation and it does this intelligently. If you end a line with an open parenthesis ('('), an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')'), the closing brace ('}') or the closing bracket (']'). To end continuation mode press enter/return key twice.
> db.product.update({ "_id" : "ac3"},
... { "_id" : "ac3", "name" : "AC3 Phone", "brand" : "ACME", "type" : "phone",
... "price" : 200, "warranty_years" : 1, "available" : true })
Once you complete the expression the mongo shell execute your query.

See method implementation details to know more

 

In mongo shell to print value of an object to the console you just need to specify the object name and press enter. As because in javascript a function is an object you can also see its value i.e.; it definition in similar fashion. Its some time helpful when you want to know the actual command applied by the method in mongo shell. Lets see a example below.
> db.getCollectionNames  // use to get collection names present in current database

function (){
    var all = [];

    var nsLength = this._name.length + 1;

    var c = this.getCollection( "system.namespaces" ).find();
    while ( c.hasNext() ){
        var name = c.next().name;

        if ( name.indexOf( "$" ) >= 0 && name.indexOf( ".oplog.$" ) < 0 )
            continue;

        all.push( name.substring( nsLength ) );
    }

    return all.sort();
}

You can see above this method uses system.namespaces' collection to get details about collection names present in database. Cool isn't it.

Running javascript file with mongo shell

 

To run your own javascript files with mongo shell you can use command like below
mongo <databasename> <your_js_file>

You can also save resulting execution output  by mongo shell in file. Lets see the command below;
mongo <databasename> <your_js_file> >> <result_file>

Note : The mongo shell, by default, doesn't print out anything when running a script file.  This behavior is different than when run interactively.
To print out to the file in non-interactive mode use printjson like this
printjson( db.product.find());
For more difference between interactive and non interactive execution environment go here

Conclusion

 

I would like to say that its about the right decision made by mongodb team to use javascript interpreter for command line tool.
There are many more feature I will discuss with you later. Please comment to enhance my blog.

Up and running Mongodb with C#

Following is the step for up and running Mongodb with C#

Download the Mongodb package from here

Mongodb package come with binary executable and msi (Microsoft Installer) in 32bit and 64bit version. I would prefer to use 64bit msi version if your OS is capable of.Here is the url to download from.

Running mongod instance server

After installing your package to run mongodb instance server open a command prompt window and execute command mongod -dbpath="<your database storage path>". To test every thing is OK run a mongo client executable from command prompt to connect with running server. Use this command below like that mongo. mongo client automatically connect to the localhost server with default port 27017.  To know more about the mongod and mongo command use -help argument.
Here is the output generated by mongod command on my machine


And output generated by mongo client


After executing mongod command it create some files and allocate few space on disk for data storage. Open a visual studio editor and create a new console project. To install mongodb official drivers using nuget package manager console and type the following command into the console PM> Install-Package mongocsharpdriver It will install the most recent driver for you. If you are interested in particular version of driver use -version command argument to specify in nuget command.

Lets write the first code to connect to our mongodb server

namespace MongoFirst
{
    using MongoDB.Bson;
    using MongoDB.Driver;
    using System;

    public class Program
    {
        static void Main(string[] args)
        {
            // create a client object
            MongoClient client = new MongoClient("mongodb://localhost:27017/"); // mongodb connection string
            // create a server object
            MongoServer server = client.GetServer();
            // create a database object with database name "test"
            MongoDatabase db = server.GetDatabase("test");
            // get collection object cars from test database
            MongoCollection cars = db.GetCollection("cars");
            // insert documents
            cars.Save(new Cars { Name = "Mongodb" });
            cars.Save(new Cars { Name = "Oracle" });

            // loop throug each item in cars collection
            foreach (var car in cars.FindAllAs())
            {
                Console.WriteLine("Database : {0}", car.Name);
            }

            Console.ReadKey();
        }
    }

    public class Cars
    {
        // a collection always have a field '_id' in mongodb, 
        // you can also use different type rather that ObjectId here
        public ObjectId Id { get; set; } 
        public string Name { get; set; }
    }
}
You can also specify mongodb database name in connection string. For more details about the mongodb connection string visit here

What is 'await' looking for !

The way of running asynchronous operation from C# 5.0 is now has dramatic changes. Specifically there are two new operators async and await introduce by C# 5.0 language to support linear asynchronous programming model.

async

operator use as a modifier to specify that a method, lambda expression, or anonymous method is asynchronous.If you use this modifier on a method or expression, it's referred to as an asynchronous method.

await

operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

We are going to look into the internals of how await operator works,
C# code uses await operator,
public async void DoSomething()
{
    string result = await obj.GetResultAsync(); // return immediately to calling code
    Console.WriteLine(result); // execution continue from here once above work completed 
}
A pseudo code generated by compiler is give below, When an await operator encounter by compiler.
public async void DoSomething()
{
    // obj - any object that have GetAwaiter method with appropriate return type
    var temp = obj.GetAwaiter(); 
    if (!temp.IsCompleted)
    {
        SAVE_STATE()
        temp.OnCompleted(&cont);
        return;
        cont:
        RESTORE_STATE()
        result = temp.GetResult();
        Console.WriteLine(result); // code below await expression
    }
}
snippet taken from (http://stackoverflow.com/questions/12661348/custom-awaitables-for-dummies)

Here program try to get the awaiter instance from the asynchronous method. This instance temp has an IsCompleted boolean property member which is use to determine if asynchronous task execution completes. If it return false the program store the current machine state and inject an Action (&cont) delegate by using OnCompleted() method of the awaiter instance. Note that this method is part of INotifyCompletion interface. Once the blocking operation execution completes program restore the machine state and get output result by calling GetResult() on awaiter instance. Further program continue below the await statement where its left control.

Condition that compiler check when we use await operator

  1. It check if the return type of await expression does have GetAwaiter() method. This method can also be a extension method for the instance type.
  2. GetAwaiter() must return type that have boolean type property IsCompleted.
  3. Return type of GetAwaiter() must implement INotifyCompletion interface.
  4. Return type of GetAwaiter() must have GetResult() method that return instance of expected type by await expression

A Search extension on DataTables


Hi, This article is the second part of my article grid in mvc using datatables . As this article is a bit more coupled with the first one therefore I recommend you to go through the first one before the second article. Its up to you.

While DataTables has a lot of flexibility built-in by default, there might come a time when you wish to add your own features or override some existing one provided by DataTables. This is possible through the plug-in architecture that DataTables provides for developers.

As we know, DataTables only provide a simple text box for query the data. We now going to convert this search box to do something interesting for us. So I write an extension to provide users with option of searching data for different columns at the same time. What our multiple search extension does is when some one click on search text box of DataTables, it open a search dialog box with configured check boxes and corresponding text boxes. One can just need to tick out the fields and type the query value. Now when user press return key the extension search the data table by calling dataTables API function "fnFilter".

The extension does one more interesting thing it set search parameters so that server can get the query data from the request object. Now again we come back to our debtors table and set our multiple search extension.

Here use case of my custom search plugin

oTable = $('#tableid').dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "sServerMethod": "POST",
                "sAjaxSource": "/data/debtors",
                "aoColumnDefs": [
                    { "mDataProp": "Debtor", "aTargets": [0] },
                    { "mDataProp": "Iban", "aTargets": [1] },
                    { "mDataProp": "Bic", "aTargets": [2] }
                ],
                "aaSorting": [[1, 'desc']]
               });
oTable.fnAddSearchBox($("#exampleSearch"),
                        {
                          option:{"1":{ tip:'please enter IBAN'},
                                  "2":{ tip:'please enter BIC'}}
                        });
The search dialog html code

<div id="exampleSearch"  title="Search">
    <div>
        <input id="Name" type="checkbox" value="1" />
        <label class="sfieldslbl">Iban</label>
    </div>
    <div>
        <input id="Address" type="checkbox" value="2" />
        <label class="sfieldslbl">Bic</label>
    </div>
</div>

Look at jsbin cast ... JS Bin

Grid in MVC using Datatables

I rewrite this article to add some more information about how to use data tables (a Jquery plugin) in a MVC project. As because it is going to be a big article therefore I decided to split this into two small articles. The first article demonstrate you to convert a simple HTML table into a nice looking data grid and also add data loading and searching power from server side. And then in second article we will write a simple plugin for data tables for enhancing the search functionality. As we step further with this article I also recommand you to look parallel at the data tables site for more in depth information.

What Exactly DataTables  Is ? 

"DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table ."

Below is a small code sample that attach the data tables to a normal html table.

$(document).ready(function(){
$("#tableid").datatable();
});
Don't forget to include the script and css file for the datatable.
<link href="@Url.Content("~/media/css/jquery.dataTables_themeroller.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/media/js/jquery.dataTables.min.js")" type="text/javascript"></script>
Look at jsbin cast...
JS Bin

Now as we have nice grid we now try to bind our grid using a ajax call and also use the MVCContrib Grid to create table.
@{Html.Grid(Model).Columns(column =>
  {
      column.For(c => c.DebtorName).Named("Debtor");
      column.For(c => c.Iban);
      column.For(c => c.Bic);
      column.For(c => c.IsDeleted).Named("Hidden");
  }).Attributes(id => "tableid").Render();
 }

Setting option for data tables to populate data from server using Ajax Post call.
oTable = $('#tableid').dataTable({
                "bProcessing": true,
                "bServerSide": true,
                "sServerMethod": "POST",
                "sAjaxSource": "/data/debtors",
                "aoColumnDefs": [
                    { "mDataProp": "Debtor", "aTargets": [0] },
                    { "mDataProp": "Iban", "aTargets": [1] },
                    { "mDataProp": "Bic", "aTargets": [2] }
                ],
                "aaSorting": [[1, 'desc']]
               });
Action code
[Post]
public JsonResult debtors()
{
   return View(GetAllDebtor().Select(d=> new {Debtor = c.debitor,Iban=c.iban,Bic=c.bic}));
}
Here setting bProcessing option to true tells data table that it should automatically call server to load data when page load in browser. The property aoColumnDefs use to define columns behaviour. The most important property mDataProp use to define JSON data (sent by the server) property name that data tables should use to populate the column.
Datatables support long range of option from custom data column rendering to custom data loading. For short example mRender is property which take funtion object that execute for every row in table when data populated by data tables.

Now we are proceed on development of custom model binder for our data table. This will be useful to leverage the sorting, searching and paging functionality on server side. When Data tables request data from the server it passes some useful parameter to server on the basis of which server can filter, sort and most important can page data. I would suggest you to use some tool like firebug to trace these parameters for more understanding. Below is our code for custom model binder,
public class GridRequestModelBinder : ModelBinderBase, IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            GridRequest GridrequestObject = new GridRequest();
            // iColumns no of cols
            GridrequestObject.iColumns = Convert.ToInt32(GetValue(bindingContext, "", "iColumns"));
            //iDisplayLength
            GridrequestObject.iDisplayLength = Convert.ToInt32(GetValue(bindingContext, "", "iDisplayLength"));

            //iDisplayStart
            GridrequestObject.iDisplayStart = Convert.ToInt32(GetValue(bindingContext, "", "iDisplayStart"));

            //bregex
            GridrequestObject.bRegex = Convert.ToBoolean(GetValue(bindingContext, "", "bRegex"));

            //bregex_params
            GridrequestObject.bRegex_params = GetValue(bindingContext, "_", "bRegex", GridrequestObject.iColumns);

            //bSearchable

            GridrequestObject.bSearchable_params = GetValue(bindingContext, "_", "bSearchable", GridrequestObject.iColumns);

            //iSortingCols ** 1
            // iSortingCols 
            GridrequestObject.iSortingCols = Convert.ToInt32(GetValue(bindingContext, "", "iSortingCols"));
            //iSortCol_param * 1
            GridrequestObject.iSortCol_params = GetValue(bindingContext, "_", "iSortCol", GridrequestObject.iSortingCols);

            //bSortable
            GridrequestObject.bSortable_params = GetValue(bindingContext, "_", "bSortable", GridrequestObject.iColumns);

            //sSortDir_params * 1
            GridrequestObject.sSortDir_params = GetValue(bindingContext, "_", "sSortDir", GridrequestObject.iSortingCols);
            //mDataProp_params
            GridrequestObject.mDataProp_params = GetValue(bindingContext, "_", "mDataProp", GridrequestObject.iColumns);

            //sColumns 
            GridrequestObject.sColumns = GetValue(bindingContext, "", "sColumns");
            //sEcho 
            GridrequestObject.sEcho = Convert.ToInt32(GetValue(bindingContext, "", "sEcho"));
            //sSearch
            GridrequestObject.sSearch = GetValue(bindingContext, "", "sSearch");
            // sSearch_params
            GridrequestObject.mDataProp_params = GetValue(bindingContext, "_", "mDataProp", GridrequestObject.iColumns);

            // sSearch_params
            GridrequestObject.sSearch_params = GetSearchParams(bindingContext, GridrequestObject.mDataProp_params);

            return GridrequestObject;
        }

        private Dictionary<string,string> GetSearchParams(ModelBindingContext bindingContext, Dictionary<string,string> Propdictionary)
        {
            Dictionary<string,string> RetDicxs = new Dictionary<string,string>();
            for (int i = 0; i < Propdictionary.Count; i++)
            {
                RetDicxs.Add(Propdictionary["mDataProp_" + i.ToString()], GetValue(bindingContext, "_" + i.ToString(), "sSearch"));
            }
            return RetDicxs;
   }

public class ModelBinderBase
    {
        public string GetValue(ModelBindingContext context, string postfix, string key)
        {
            ValueProviderResult vpr = context.ValueProvider.GetValue(key + postfix);
            return vpr == null ? null : vpr.AttemptedValue;
        }

        public Dictionary<string,string> GetValue(ModelBindingContext context, string postfix, string key, int MaxParam)
        {
            Dictionary<string,string> RetDicxs = new Dictionary<string,string>();
            for (int i = 0; i < MaxParam; i++)
            {
                RetDicxs.Add(key + postfix + i.ToString(), GetValue(context, postfix + i.ToString(), key));
            }
            return RetDicxs;
        }
    }
public class GridRequest
    {
        public bool bRegex { get; set; } // Regular expression for _sSearch Text
        public Dictionary<string,string> bRegex_params { get; set; } // Regular expression for _sSearch[i] Text

        private string _sSearch; // text of search box
        public bool bSearchable { get; set; } // do client want to search
        public string sSearch
        {
            get { return _sSearch; }
            set { _sSearch = value == null ? "" : value; }
        }
        public Dictionary<string,string> bSearchable_params { get; set; } // do client want to search on particular column with different search text
        public Dictionary<string,string> sSearch_params; // search on particular column with different search text

        public int iSortingCols { get; set; }
        public Dictionary<string,string> iSortCol_params { get; set; }
        public Dictionary<string,string> bSortable_params { get; set; }
        public Dictionary<string,string> sSortDir_params { get; set; }

        public int iColumns { get; set; }
        public string sColumns { get; set; }

        public int sEcho { get; set; }
        public int iDisplayStart { get; set; } // Start Index
        public int iDisplayLength { get; set; } // Complete number of records

        public Dictionary<string,string> mDataProp_params { get; set; }
    }
Now we cooked our model binder for data tables its time to use it. For that all I want to say is we already done the hard work. Please don't forget to add the model binder at Application start.
ModelBinders.Binders.Add(new typeof(GridRequest), new GridRequestModelBinder());
Below is a simple code for enabling search on data table from server side.
public JsonResult debtors(GridRequest greq)
{
  return View(GetAllDebtor()
 .Where(d=>d.debitor.Contains(greq.sSearch)||d.iban.Contains(greq.sSearch)||d.bic.Contains(greq.sSearch)
 .Select(d=> new {Debtor = c.debitor,Iban=c.iban,Bic=c.bic}));
}
The above code simply search all the columns for the entered query. Data tables use sSearch parameter to send the query text to the server. After expending several hour you may notice that data table only provide single text box for querying data. This gives the point of birth for my second article on writing a plugin for enhancing search functionality for the data tables. Data table provide a large set of API that make way lot easier to write plugin for additional functionality on it. The first part is completed here and we will meet on second part later.

Proxy Pattern

Intent:
                    The pattern Provide a surrogate or placeholder for another object to control access to it. The proxy object have the code for access control that will be executed before calling the real function of its base class.(Not understand read after finished the article).

Motivating Example:
                    The pattern specially need while you need a placeholder for an actual object that is expensive to create. For example a document containing lots of images or bulky objects which are expensive in use instead of that you can replace these bulky objects with proxy objects which will create the real objects while needed. This example is very much similar with flyweight pattern. In flyweight pattern you considered with intrinsic and extrinsic element of the object and the object does not need another substitution.

                    One more example would be when you need to interact with a remote service over the network, but want to keep your code decoupled from networking detail. (It could be demonstrated by WCF service).

Applicability:
                    The Proxy pattern is applicable in several common scenario:
  • A remote proxy acts as local representative of remote object, and abstracts away the details of communicating with remote object.
  • A virtual proxy creates expensive objects on demand. A common example is an Image Proxy that show a placeholder while the Image is being loaded.
  • A Protection Proxy can be used to control access to an object, based on authorization rules.
Structure:
How It Gets Used:

  • Clients work with Proxy as if it were the actual object. Usually the proxy object have common interface with real object.
  • This pattern also use to control the access to the actual object and delegated the calls to it as needed. This also mean that Proxy pattern support the Open Close system i.e., the object is open for extension but close for modification.
  • This pattern is use to- Improve performance and load time of an application, Simplify interactions with with remote objects, defer expensive calls until needed- implement lazy loading of objects from persistence.   
Implementation Example: 

Consequences:
                      The significance of Proxy Pattern are :
  • Client code does not need to be changed to work with a proxy object because proxy will give the same interface or structure like real object when replacing the real object. However, proxy object must be synchronized with the real object. The proxy object adsorb the change in real object and continue to support the same interface expose to the client. 
  • Proxy may be used to optimize performance in existing system without touching existing class behavior this means that proxy pattern support Open/Close Principle i.e., extension can be possible but modification can't.
  • Client code may make incorrect assumption about behavior of real object as proxy object masked the real object behavior. The interface use by the proxy may describe the interface methods in such a way that it may use many calls to real object method rather than few, large call. This gives rise born of the two different interface which may be implemented by the proxy pattern one is chatty another is chunky. While use Chatty type interface proxy do many small calling to real object method and while use Chunky type interface proxy do less number of calling to real object method.
  • A disadvantage of using chatty interface is that it may required more database calls than necessary.
I hope that this article benefit you Thanks for reading.
Please feel free to contact me lxbalder@gmail.com