Monday, 25 March 2013

A CPU Friendly Infinite loop in C#

To run a infinite loop to do some process, we will be using While loop,System.Threading,System.Timer and so on.., each of this having its own pro's and con's and some of that will trash the CPU performance.

In this blog I am going to post the simple technique and that will utilize less CPU.To achieve this we have to use EventWaitHandle from System.Threading class.The following example will show the usage.

C# Console app Example :



private static void Main(string[] args)
{
EventWaitHandle waithandler = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());do
{
          eventWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
          Console.WriteLine("..........Entered........");
         
// ToDo: Something else if desired.
} while (true);
}


The above example will print the " Entered " word with every one second delay interval and infinitely.



If you want to do the same in Asynchronous way ,there are lot of ways to do and you can find one of the  method in the below example.


C# Console app Example(Asynchronously) :



//Declare a delegate for Async operation.

public delegate void AsyncMethodCaller();
class Program
{
private static void Main(string[] args)
{
           // Create the delegate.

            AsyncMethodCaller caller = new AsyncMethodCaller(Program.AsyncKeepAlive);
            // Initiate the asychronous call.
            IAsyncResult result = caller.BeginInvoke(null, null);}

private static void AsyncKeepAlive()

{
EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, Guid.NewGuid().ToString());

do
{
 eventWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
 Console.WriteLine("..........Entered........");
 // ToDo: Something else if desired.
 } while (true);

 }


}


Hope you enjoyed this post.
Thanks for Reading.Happy Coding!!

Friday, 1 March 2013

A KNOCKOUTJS CHEAT SHEET

After a long time again back with some web apps stuffs and got time to share my studies on Knockout JS a JavaScript library.

Introduction to Knockout:

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

  • Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.
  • Pure JavaScript library - works with any server or client-side technology
  • Can be added on top of your existing web application without requiring major architectural changes
  • Compact - around 13kb after gzipping
  • Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms
For more information you can refer here.

A KNOCKOUTJS CHEAT SHEET

This blog will gives you a glance at what is Knockout, why to use it and how to use it. If you are a newcomer to KO or if you are juggling between multiple JS libraries, this cheat-sheet is a handy guide to get your KO karma flowing.

  • Knockout is a JavaScript Library (as opposed to Backbone.js which is a framework) that helps you improve the User Experience of your web application. 

  • Knockout provides two way data-binding using a ViewModel and provides DOM Templating, it doesn’t deal with sending data over to server or routing.

  • You use Knockout as a drop-in enhancement library to improve usability and user experience, whereas Framework like Backbone is used ground up in new applications (Single Page Apps is a good example).

  • You can create a KO ViewModel as a JavaScript object or as a Function (known as prototype). It’s outside the jQuery document ready.

  • ViewModel as a function
                   var myViewModel = function() {
                              this.Email = “myemail@email.com”;
                              this.Name = “Sumit”;
                              this.LastName = “Maitra”;
                              this.WebSite = “http://www.dotnetcurry.com”; }


  • ViewModel as an object: you can follow the JavaScript Object Notation –
                var myViewModel = {
                            Email: “myemail@email.com”,
                            Name: “Sumit”,
                            LastName: “Maitra”
                                             }

  • Observable Properties are functions: When dealing with observable values you have to end the property with parenthesis like a function call, because computed values are actually functions that need to be evaluated on bind.
  • Applying a ViewModel
              // In case the View Model is defined as a function
                    ko.applyBindings(new orderViewModel());
              // In case the View Model is defined as a JSON Object
                   ko.applyBindings(orderViewModel);

             Here ko is the global reference to Knockout that you get once you add Knockout                                                  Script reference in your page.


  • Observable Properties: KO has the concept Observable properties. If you define a property as an observable, then DOM elements bound to it, will be updated as soon as the property changes.
                  e.g.
                   var myViewMode = {
                                 Email: ko.observable(“myemail@gmail.com”)
                                               }

  • Observable Arrays: When you define an array of Json objects as Observable, KO refreshes DOM elements bound to it when items are added or removed from the Array.
                           var orderViewModels = function() {
                                    …
                                 // Binds to an empty array
                                  this.Address = ko.observableArray([]);
                                                                }

          Note: When properties of an Item in the array changes then KO does not raise ‘modified’ events.

  • Assign value to observables: We saw how to declare observable Properties above. But when we have to assign a value to an observable in JavaScript we assign it as if we are calling a function, for 
                   example:
                          myViewModel.Email(“karan2vel@email.com”);


  • Simple Data Binding to properties
                  <input data-bind=“value : Email” />
                  Value of input element to the Email in the ViewModel.


  • Binding to Computed Values: Binding KO to a function gives you added flexibility of defining methods that do computation and return a computed value. KO can actually bind DOM elements to these methods as well.
       For example if we wanted to bind First Name and Last Name and show it in a single    DOM element we could do something like this:
On the View Model

                        var myViewModel = function() {
                        this.Email = “myemail@email.com”;                        this.Name = “Sumit”;                        this.LastName = “Maitra”;                        this.FullName = ko.computed(function () {                        return this.LastName() + “, ” + this.Name();                        }, this);                        }

       Binding to DOM Element

                        <label data-bind= “text: FullName” />
  • Binding to an array of objects: KO can bind the DOM to an array in the view Model. We use KO’s foreach syntax as follows
                        <table>                        <tbody data-bind= “foreach: Address”>                                                </tbody>                        </table>

        You can do the same for an Ordered <ol> List or an Unordered List <ul> too. Once you have done the foreach binding, KO treats anything DOM element inside as a part of a template that’s repeated as many times as the number of elements items in the list to which it is bound.
  • Binding elements of an array: Once you have bound an Array to a DOM element KO gives you each element in the array to bind against. So an Address object may be bound as follows:
                        <table>                        <tbody data-bind= “foreach: Address”>                        <tr> <td>                        Street: <label data-bind: “text: Street” />                        #: <label data-bind: “text: Number” />                        City: <label data-bind: “text: City” />                        State: <label data-bind: “text: State” />                        </td> </tr>                        </tbody>                        </table>
  • Binding to properties other than text and value: Now let’s say we want to bind the WebSite element of the ViewModel an anchor tag
                        <a data-bind=“attr : {href : WebSite}”>                        <span data-bind= “text: Name”</a>

      What we are doing here is using Knockout’s attribute binding technique to bind the ‘href’ attribute to the URL in the WebSite property of the View Model. Using attribute binding we can bind to any HTML attribute we Observable Properties: KO has the concept of want to.

  • Getting KO Context in jQuery: Now let’s say we want to have a Delete button for each address. The following markup will add a button 
                        <table>                        <tbody class=“addressList” data-bind= “foreach: Address”>                        <tr><td>                        Address: <label data-bind: “text: $parent.                        AddressString(Street, Number, City)” />                        </td> <td>                        <button class= “addressDeleter” ></button>                        </td> </tr>                        </tbody></table>

Now to handle the click even using jQuery. Since the button is generated on KO binding we cannot use the normal click handler assignment of jQuery. Instead we use the parent container and assign a delegate as follows

                        $(“#addressList”).delegate(“.noteDeleter”, “click”,                        function() {                        var address = ko.dataFor(this);                        // send the address to the server and delete it                        });

As we can see above the ko.dataFor(this) helper method in KO returns the object that was bound to that particular row of data. So it returns an Address object. If you need the entire ViewModel you can use ko.contextFor(this).

Thanks for reading.Happy coding!!!!