C# basics: why we override Equals method

You may have come across questions,

  • Why to override Equals method?
  • How to determine whether two object are equal?
  • How to determine whether two objects are identical?

To get answer of all the above questions, let us consider Product class as listed next:

 


class Product
    {
        public int Price { get; set; }
        public string Name { get; set; }
            
    }

We are creating two instances of the Product class, foo and loo. The foo is assigned to loo. Both objects are pointing to the same reference, hence we will get true as expected output for all the Equals.

 


Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
             loo = foo; 
             var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);

Expected output is,

clip_image002

Now let us go ahead and modify the instances as listed next:

 


Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
            loo.Price = 10;
            loo.Name = "foo";
            var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);


This time you will get output as false for all the three Equals method.

clip_image002[6]

However if you closely observe, value of the both properties of both objects are exactly the same. Price and the Name property is set to 100 and foo respectively. But still we are getting Equals returns false for the foo and the loo object.

We can observe that, even though properties values are same Equals returns false. Essentially, when arguments are referring to different objects. Equals don’t check for the values and always returns false. We can say that by default Equals check for IDENTITICAL OBJECTS rather than EQUAL OBJECTS

Understanding Internal

To understand this behavior, let us examine the System.Object class. It contains,

  1. One virtual Equals method.
  2. One static Equals method. This takes two arguments. Returns true if they are identical otherwise false.
  3. One static ReferenceEquals method. This takes two arguments. Returns true if both arguments are same instance otherwise false.

Clearly CLR Equals method does not check for the values, when arguments refers to different objects. So by default it checks for the Object Identity rather than Object Equality.

Why to override Equals()

We may come across the requirement to check for object equality. To check whether both objects contains same properties value or not. This can be done by override the Equals method. We can override Equals method as listed next:

 

class Product
    {
        public int Price { get; set; }
        public string Name { get; set; }
        public override bool Equals(object obj)
        {
           if (obj == null)
                return false;
            if (this.GetType() != obj.GetType()) return false;

            Product p = (Product)obj;
            return (this.Price == p.Price) && (this.Name == p.Name);
        }        
    }


While overriding the Equals method, you should consider the followings

  • If object argument is null, return false
  • If type of object argument is different than type of this, return false
  • If object argument is neither null nor its type is different check for the values of the instance fields. If they are equal return true else return false

We have overridden Equals method, now if you compare the objects which is listed next, you will find that Equals returns true if Objects are equal whereas ReferenceEquals returns false when objects are different.

 

Product foo = new Product {Price = 10,Name= "foo"};
            Product loo = new Product();
            loo.Price = 10;
            loo.Name = "foo";
            var valueEqual = foo.Equals(loo);
            Console.WriteLine(valueEqual); 

            var objRefEqual= Object.ReferenceEquals(foo, loo);
            Console.WriteLine(objRefEqual);

            var objEqual = Object.Equals(foo,loo);         
            Console.WriteLine(objEqual);
            Console.ReadKey(true);


You will get the expected output true, false and true.

clip_image002[8]

Summary

We started with the question that why to override Equals method? We learnt that by default System.Object Equals method does not check for the equality of the objects. It checks only for the objects identity. To check objects equality, we override the Equals method.

C-Sharp Basics: What is Checked and Unchecked operations

You may have come across questions,

  • What is checked and unchecked primitive operations?
  • How to handle overflow in C-Sharp?
  • Does CLR handles overflow or developers?

So let us start with understanding a program. Consider the code listed below:

 


    static void Main(string[] args)
        {
           
                Byte b = 100;
                b = (Byte) (b + 200);
                Console.WriteLine(b);
         
            Console.ReadKey(true);
        }


On running you will get 44 as the output. There is one serious observation about the above output is that Bye is primitive type which is unsigned 8 bit value. Even though above add operation results an overflow, CLR is not complaining about that.

By default, CLR does not throw overflow exception.

However there may be a requirement in which, you may have to throw the overflow exception. CLR gives us the option to configure whether overflow exception should be thrown or not.

We can configure this at three level

  1. Statements level.
  2. Operations level
  3. Application level

Application level

You can configure to throw overflow exception at the project level. To configure, right click on the project, select properties and then build, and then advanced. In the advanced build setting check the checkbox- check for arithmetic overflow/underflow

clip_image002

After configuring check for arithmetic overflow/underflow at the project level, if you go ahead and run the application, CLR will throw an exception as shown next,

clip_image004

We are getting the overflow exception since we have configured at the project level that throw exception on arithmetic overflow/underflow.

Statements level

You may not want to throw the exception for all the operations in the project. So you can also configure whether to throw overflow/underflow exception or not at the statement or expression level.

C# provides us checked and unchecked operator and statement to configure overflow/underflow exception at the operation and statement level respectively.

Using the check statement, you can throw overflow exception in above code as listed below:

 


static void Main(string[] args)
        {
            checked
            {

                Byte b = 100;
                b = (Byte)(b + 200);
                Console.WriteLine(b);
            }
               
         
            Console.ReadKey(true);
        }


By using the check statement, we can as CLR to throw overflow or underflow exception caused by the arithmetic operations.

Operations level

C# also allows us to apply cheeked/unchecked operator on a single expression. Above code can be written as listed next:

 

static void Main(string[] args)
        {
                Byte b = 100;
                b = checked ((Byte)(b + 200));
                Console.WriteLine(b);
                Console.ReadKey(true);
        }


Understanding Internal

CLR has two instructions for each arithmetic operations.

Addition: add and add.ovf

Subtraction: sub and sub.ovf

Multiplication: mul and mul.ovf

Conversion: conv and conv.ovf

As instruction name suggests add instruction does not throw overflow exception whereas add.ovf throws overflow exception. When we perform add operation by default CLR executes add IL instruction. However when we perform checked add operation, CLR executes add.ovf exception which will throw overflow exception.

Summary

There were three questions in the beginning, let us see them one by one

What is checked and unchecked primitive operations?

Checked and unchecked operations check for the overflow in the arithmetic operations. If checked then operation may throw the overflow/underflow exception. If unchecked then it will not throw the overflow exception.

How to handle overflow in C-Sharp?

Using the checked and unchecked overflow can be handled in the C#.

Does CLR handles overflow or developers?

By default CLR does not throw overflow exception. However using checked and unchecked developer can configure whether to throw or not.

How to create a Container in Azure Storage from MVC application

I am working on a MVC application in which I need to work with Microsoft Azure storage .I had a requirement to create An Azure storage container from the MVC application. In this post I will share my learning that how I created a container programmatically.

I created the view as shown in below image. User has to enter the azure storage account name, azure storage key and the name of the container to be created.

image

Above View is MVC razor view, and it is created using the cshtml as shown below:

 


@{
    ViewBag.Title = "BLOB Manager";
}
<div class="jumbotron">
    <div class="row">
        <div class="col-md-8">
            <section id="loginForm">
                @using (Html.BeginForm("AzureInfo", "Manage", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    <h2> Manage BLOB Container</h2>
                    <hr />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountName", "", new { @class = "form-control", @placeholder = "Account Name" })
                            @Html.ValidationMessage("AccountName", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountKey", "", new { @class = "form-control", @placeholder = "Account Key" })
                            @Html.ValidationMessage("AccountKey", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("ContainerName", "", new { @class = "form-control", @placeholder = "Container Name" })
                            @Html.ValidationMessage("containername", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group input-group input-group-lg">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create Container" class="btn btn-lg btn-success" />
                        </div>
                    </div>

                }
            </section>
        </div>
    </div>
</div>

Above I am creating,

  • Three text boxes with the placeholder and the class set to bootstrap form-control
  • A submit button with the class set to bootstrap btn-lg and btn-success
  • All the controls are inside the form.
  • On form post operation, AzureInfo action of the Manage controller will be called.

Once the View is ready, let us go ahead and create an azure utility class. In this class we will put all the operations related to the azure storage. But before that you need to add Azure storage library to the project. Either you can use NuGet package manager or console to add the library. I am using console to install Azure storage library. I have taken the 4.3 version because at the time of writing this post, this was the latest stable version available.

image

Once package is successfully installed, add following namespaces.

 


using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;

To create the container in the Azure storage, I have created a function CreateContainer. This function takes three input parameters, account name, account key and the container name.

 


public static class AzureUtility
    {
        public static string  CreateContainer(string AccountName, string AccountKey, string ContainerName)
        {

            string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(UserConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
            if (container.CreateIfNotExists())
            {
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                return container.Name;
            }
            else
            {
                return string.Empty;
            }
        }
    }

Now let us examine the above code line by line.

  • In first line I created the connection string for the azure storage. It takes two parameters, account name and the account key. These values are passed as input parameter to the function. I am using these two parameter to create connection string.
  • Using CloudStorageAccount to parse the connection string from the constructed string.
  • Creating the CloudBlobClient
  • Getting the container reference of the BLOB.
  • If container reference does not exist, creating new container.
  • On successful creation of the container function returns name of the container else empty string.

 


[HttpPost]
        public ActionResult AzureInfo(string AccountName, string AccountKey, string ContainerName)
        {

           var result= AzureUtility.CreateContainer(AccountName, AccountKey, ContainerName);

           if (result != string.Empty)
             {

                 return RedirectToAction("Index", "Home");
             }
             else
             {
                 return RedirectToAction("Index");
             }
        }

In the action we are using the utility class to create the container. In this way an azure container can be created from the MVC application.

I hope it is useful. Thanks for reading. Happy Coding.

Related entities in Entity Framework Code First approach

In this post we will learn to create relationship between entities in the Entity Framework Code First approach.

Setting up

We are going to create three tables and set up the relationship between them.

  1. BankUser
  2. BankUserAccount
  3. Nomniee

To create tables we will create entities further in the post. For table creation the context class has been created as follows.

 

public class Context : DbContext
    {

        public Context ()
	        {
                     Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());
	        }

        public DbSet<BankUser> BankUser {get;set;}
        public DbSet<BankUserAccount> BankUserAccount  {get;set;}

        public DbSet<Nominee> Nomniee { get; set; }
    }


Keep in mind that, very likely you will get build error if you try to build the project as of now.

One to many relationship

Let us say we have two entities. One for the bank user and another for the bank user’s accounts. A bank user can have any numbers of the bank accounts. Typically a bank user will have following properties

    public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

    }


A bank user can have any number of bank accounts. To map this we will have to create one NAVIGATION PROPERTY in the BankUser class. A navigation property holds entities which are related to this particular entity. An entity can have any number of related entities. Since BankUserAccount(we will create this entity later) is a related entity of the BanUser entity. So it will be as the navigation property of the BankUser account. One bank user can have any numbers of bank user account, so we will have to create collection BankUserAccount entity as the navigation property of the BankUser entity. To do this, modify the above class as below:

public class BankUser
    {
   
        public string   ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set;  }
        public string Sex { get; set; }

        public virtual ICollection<BankUserAccount> Accounts { get; set; }

    }

We define navigation property as virtual such that while reading the data we can take advantage of the entity framework lazy loading feature.

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string? EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
    }

By this time relationship between the two tables has been created as shown below:

image

And BankUserAccount table is created as follows:

image

One to one relationship

In one to one relationship between two entities, one act as the primary entity and another as the dependent entity. Primary key of the primary entity will be used as foreign key of the dependent entity. An entry cannot be created in the dependent entity without having a reference in the primary entity. Okay enough of theory let us go ahead and see an example. So far we have seen that a bank user can have multiple bank accounts. However a particular bank account can have only one nominee. So primary key of BankUserAccount entity will act as foreign key of the Nominee entity. You can create a Nominee entity with the foreign key as shown below:

 

  public class Nominee
    {


       public string ID { get; set; }

       public string Name { get; set; }

       public string Age { get; set; }      
       [Required]
       public virtual BankUserAccount BankUserAccount { get; set; }
    }


As you see navigation property BankUserAccount is attributed with the REQUIRED. So we cannot create a Nominee entity without providing the bank user account.

By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is created as below:

image

As you can see that in the Nominee table BankUserAccountID is the foreign key. Primary key of the Nominee table is different than the foreign key. So one person can be nominee of any number of bank accounts.

Other options could be, and in my opinion absolute one to one relationship. In this scenario one person can only be nominee to one bank user account. In this case you will have to modify the BankUserAccount as follows:

 

public class BankUserAccount
    {
        public string ID { get; set; }
        public double Amount { get; set; }
        public string EmergencyContact { get; set; }
        public DateTime LastTransaction { get; set; }
        public virtual BankUser BankUser { get; set; }
        public virtual Nominee Noinee { get; set; }
    }


By this time relationship between the two tables has been created as shown below:

image

And the Nominee table is modified as below:

image

Now to create the database in the local db you don’t need to modify the connection string and make a use of context class as below,

 

Context context = new Context();
            BankUser c1 = new BankUser
            {
                ID=  "C5",
                Age = 32,
                Name= "DJ",
                Sex= "Male",
               

            };
            context.BankUser.Add(c1);
            context.SaveChanges();

            var result = context.BankUser.ToList();
            foreach (var r in result)
            {
                Console.WriteLine(r.Name);
            }
            Console.ReadKey(true);

In this way you can create relationship between entities in the entity framework. I hope this post is useful.

Happy coding.

How to Clone a Git repository in Visual Studio

In my trainings, often I get a question from junior developers that how to clone a Git repository in the visual studio? Perhaps it may be very simple for senior developers, however for the developers who struggle to get it right steps are discussed below,

Step 1

Find the URL of the remote git repository. For GitHub repository URL can be found as shown in the image below. Copy the URL from here.

image 

Step 2

Launch Visual Studio and from the View select Team Explorer. In the Team Explorer window select Clone.

clip_image002

On clicking Clone, you will get an option to provide the URL of the Git repo and the choose folder in which repository will be cloned. In the URL section paste the remote repository URL as whon in the below image:

clip_image004

As the last step click on the Clone and the remote Git repository will be cloned in the Visual Studio in the given folder. If everything goes right you will get success message as shown below.

clip_image006

I hope it helps. Thanks and Happy Coding.

ListView in WinJS based Windows Store Application

In 2012 I wrote a post List View Data Binding in Windows 8 JavaScript Metro Application. If you follow along this post some of the code will not work. So I decided to write a post again on working with ListView in WinJS. There are three simple steps to work with the ListView.

Step1: Create the Data Source

Let us use JavaScript array as the data source. In the real application you may want to call a service to fetch the data and create the data source. The JavaScript array is created as follows:

 


var MovieData = [
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                            { Name: 'Abduction', Photo: 'images/abduction.jpg' },
                            { Name: 'A Better Life', Photo: 'images/abetterlife.jpg' },
                            { Name: 'A Dangerous Method ', Photo: 'images/adangerousmethod.jpg' },
                            { Name: 'Begineers', Photo: 'images/beginners.jpg' },
                            { Name: 'Bell Flower', Photo: 'images/bellflower.jpg' },
                            { Name: 'Black Thorn', Photo: 'images/blackthorn.jpg' },
                   ];

We cannot set an array directly as the data source of ListView. So to set array as the data source we need to convert the array as List object. MovieArray can be converted to the List object as shown follows:

 


var dataList = new WinJS.Binding.List(MovieData);

Step2: Create the Template

Once the data source is in placed we need to decide how to display the data in the ListView. Using the Template we decide the way ListView item will be rendered. Binding template can be created setting data-win-control attribute of a div to WinJS.Binding.Template. We are displaying and Photo from the data source. You need to make sure to use exact the same property name as it is in the data source.

 


<div id="movieitemtemplate"
         data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText:Name"
             style="height:20px;">
        </div>
        <img data-win-bind="src:Photo"
             style="width:200px;height:150px;" />
    </div>


Step3: Create the ListView

A div can be converted to a ListView setting data-win-control property to WinJS.UI.ListView. We are setting the itemTemplate to movieitemtemplate which we created in the previous step.

 


<div id="MovieListView"
         data-win-control="WinJS.UI.ListView"
         data-win-options="{itemTemplate: select('#movieitemtemplate')}">
    </div>


After the ListView is created last step is to bind the ListView to the data source. We have already created List using the JavaScript array. To bind set data source of the list as the itemDataSource of the ListView. It is shown as follows:

 

args.setPromise(WinJS.UI.processAll());
            var dataList = new WinJS.Binding.List(MovieData);
            var MovieList = document.getElementById('MovieListView').winControl;
            MovieList.itemDataSource = dataList.dataSource;


That’s it. These three steps are needed to work with a ListView in WinJS. Hope you like it. Happy coding.

Working with app bar in WinJS based Windows Store Application

In this post we will learn to work with the app bar in a WinJS based Windows Store application. Let us start with creating an app bar. The app bar can be created by setting the data-win-control value of a div to WinJS.UI.AppBar.

 


<div data-win-control="WinJS.UI.AppBar" data-win-options="{placement:'bottom'}">


</div>

Now you can add command buttons in an app bar as follows:

 


   <div data-win-control="WinJS.UI.AppBar" data-win-options="{placement:'bottom'}">
        <button data-win-control="WinJS.UI.AppBarCommand"
                data-win-options="{id:'cmdhome',icon:'home',section:'selection',tooltip:'home'}"></button>
        <button data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdsave',icon:'save',tooltip:'click to save'}">
        </button>
       
    </div


As of now we have added two command buttons with the icon, tooltip etc. A command button can be added to a app bar using the button control attributed with the WinJS.UI.AppBarCommand attribute.

image

Let us say you want to add a flyout on the click of the app bar command. That can be added in two steps.

 


<div id="volumeFlyout"
         data-win-control="WinJS.UI.Flyout">
        <h3>Volume</h3> <input type="range" />
    </div>

As the second step we can use this flyout as option in app bar command. This can be done as follows

 

<button data-win-control="WinJS.UI.AppBarCommand"
                data-win-options="{
            id: 'flyout',
            icon: 'volume',
            label: 'Volume',
            type: 'flyout',
            flyout: select('#volumeFlyout')}"></button>

On running application you will find that click of volume command gives a flyout .

image

You can also style the app bar. For example app bar color can be changed using the CSS a below,

 


.win-appbar
{
    background-color: red;
    border: 3px solid blue;
}

On running you will find that app bar color has been changed as shown below:

image

You can change the image of the icons using the CSS shown below:

 


.win-appbar .win-commandimage
{
    color: rgb(28, 160, 218);
}


On running you will find that app bar color has been changed as shown below:

clip_image002

You can apply many such style to app bar and its commands. You can attach event to the command buttons and call a function to perform a task.

I hope this post is useful. Thanks for reading.

Capture photo and save on the disk in WinJS based Windows Store App

In this post we will learn to capture a photo and save the captured photo on the disk. You can work with camera and capture a photo in the WinJS using the Windows.Media.Capture.CameraCaptureUI(). Let us start with creating the UI for the application. In the UI, we will have

  • Application bar with two buttons
  • One button to capture the photo
  • Second button is to save the photo in the Picture Library
  • Image control to preview the capture photo

Let us get it started with creating the UI. The UI mark-up will look like as follows:


<body>

    <div id="application">
        <img id="imgCaptured" />
    </div>

    <div id="AppBar" data-win-control="WinJS.UI.AppBar" data-win-options="">
        <button id="cmdSave" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdSave',label:'Save',icon:'save',section:'global',tooltip:'save'}">
        </button>
        <button id="cmdCamera" data-win-control="WinJS.UI.AppBarCommand" 
                data-win-options="{id:'cmdCamera',label:'Capture Photo',icon:'camera',section:'global',tooltip:'Capture Photo'}">
         </button>
       
    </div>
</body>


On running the application you should have a blank page with the app bar. There are two buttons to capture the photo and to save the captured photo on the disk. On the click event of the cmdCamera button we will capture a photo using following code.

 


function startCamera() {
       
            cam.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (file) {
                if (file) {

                    imgCaptured.src = URL.createObjectURL(file)
                    FileToSave = file; 

                } else {
                    
                }
            }, function (err) {
                displayError(err);
            });
       
    }


Globally we have defined three variables as below,

 


     var FileToSave; 
    var cam = new Windows.Media.Capture.CameraCaptureUI();
    var folder = Windows.Storage.KnownFolders.picturesLibrary; 


Attaching click events to both buttons as shown below:

 


args.setPromise(WinJS.UI.processAll());

            document.getElementById("cmdCamera").addEventListener("click", startCamera, false);
            document.getElementById("cmdSave").addEventListener("click", takePhoto, false);

As you see on the cmdCamera button we are calling the startCamera function which is shown above. In this function by using the Media.Capture.CameraCaptureUI capturing the photo and binding that to an image control. On the other hand on the click of cmdSave we are saving the image on the disk.


function takePhoto() {
        
       
        folder.createFileAsync("photo.jpg", Windows.Storage.CreationCollisionOption.replaceExisting)
          .then(function (file) { 
              FileToSave.copyAndReplaceAsync(file);

          });
    }

The captured photo is saved in the picture library using the instance of Windows.Storage.KnownFolders.picturesLibrary. The captured image is saved with the name photo.jpg.

This is all you need to capture an image and save it in the picture library. On running application should look like follows,

image

If you are following along then find application should look like shown above. I have also used CSS to display captured image in the centre. Used CSS is given below:

 


#imgCaptured {
    
    margin-top: 200px;
    margin-left: 100px;
    width:400px;
    height: 400px; 
    margin-right:10px;
 
}

I hope this post is useful. Thanks for reading. Happy coding.

Classes in WinJS

Even if we have heard many times about the classes in the JavaScript, it is not an object oriented language. Rather JavaScript is a prototypal language. Working with classes in JavaScript can be but cumbersome syntactically. WinJS is a JavaScript library and it reduced the syntactical complexity of working with classes. In this post we will learn to work with classes in WinJS.

Let us start with creating a class in pure JavaScript and then we will compare how easy it is to work with classes in WinJS. In JavaScript a class can be created as shown below,


    function Product(name, price) {
        this.name = name;
        this.price = price;
        this.Display = function () {
            console.log(this.name + this.price);
        }
    }

    var p = new Product("Pen", 30);
    p.Display();


If we want we can derive the class using prototype which makes working with classes’ complex in JavaScript. A class in WinJS can be created using WinJS.Class.define . It mainly contains three sections as constructor, instance members and static members.

image

You can create constructor using the function as shown below. You can pass parameters in the constructor and set the value of the private variables. A constructor with two input parameter can be created as shown below

    var Product = WinJS.Class.define(

          //constructor
          function (name, price) {
              this.name = name;
              this.price = price;

          }
          //instancemembers
          //staticmembers

        );


Next we can add instance members using the methods. To add instance members after constructor put a comma and then start a curly braces. Within this curly braces you can put all the instance members.


   {

              Display: function () {
                  return this.name + " costs " + this.price + "$";
              }
  }

You can also static member in the WinJS class. That can be added as third parameter after the comma of instance members. So let us go ahead and add a static member distributor. This can be added as follows:


//staticmembers
          {
              DistributorName : "ABC Corp"
          }

Entire Product class with constructor, instance functions and static members will look like as follows:

var Product = WinJS.Class.define(

          //constructor
          function (name, price) {
              this.name = name;
              this.price = price;

          },
          //instancemembers
          {

              Display: function () {
                  return this.name + " costs " + this.price + "$";
              }
          },
           //staticmembers
          {
              DistributorName : "ABC Corp"
          }
         

        );


Once class is created we can create instance of class and use the properties as show below.


var product1 = new Product(name, price);
                var textToDisplay = product1.Display();
                var disName = Product.DistributorName;


If you notice we are using static variable name directly with the class name. If you have any experience working with classes in JavaScript you should able to notice that working with classes in WinJS is relatively very easy syntactically.

Now let me show you a real example of working with the Product class created above. I have created a view in which user can enter name and price and on click of the button message from the Product class will get updated in the label.

<input id="txtName" type="text" />
    <input id="txtPrice" type="text" />
    <br/>
    <button id="btnDisplay">Display Product</button>
    </br/>
    <label id="lblProduct">result here </label>
    <label id="lblDis" >result here </label>

On the JS file on the click event of the button we are creating instance of the Product class by passing user input and displaying the message in the label.


document.querySelector("#btnDisplay").onclick= 
                function () {

                var name = document.querySelector("#txtName").value;
                var price = document.querySelector("#txtPrice").value;

                var product1 = new Product(name, price);
                var textToDisplay = product1.Display();
                var disName = Product.DistributorName;


                document.querySelector("#lblProduct").textContent=textToDisplay;
                document.querySelector("#lblDis").textContent = disName;

            };


Great now let us see how we can derive a class from another class.


var SportsProduct = WinJS.Class.derive(Product,
        
        function(name,price,color)
        {
            this.name = name;
            this.price = price;
            this.color = color;
        },

        {
             //instance members
        },
        {
            //static members 
         });


Derived class will have access of all the members of base class. Now we can use derive class to create new instance as show below:


       var product1 = new SportsProduct("Pen", 30,"Red");

In this way we can work with classes in WinJS and you can see that working with class syntactically very easy as compare to JavaScript.

Happy Coding.

Data Binding and Observable in WinJS

Source code on GitHub

In this post we will learn how to work with the data binding and observable class in the Windows Store application created using WinJS. We will learn to work with

  • Data binding
  • Two way data binding
  • Observable object

By default WinJS

  • Provides one way binding
  • When the data source is updated HTML element gets updated
  • Updated value of HTML element does not update the data source.

Let us start with working with a basic data binding example. So I have a JavaScript object as shown below,


var student = { name: "Dj" };

We can perform data binding in winJS using data-win-bind attribute on the HTML element.

clip_image002

In above code snippet we are using data-win-bind attribute to bind span inner text with the name property of the student object. As of now HTML is very simple and looks like as follows:


<body>
     <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
    </div>

</body>

As the last step of the data binding we need to call WinJS.Binding.processAll() by passing the data source and the target HTML element. Make sure that you call this after the execution of all the activation codes.


    var personDiv = document.querySelector('#nameSpan');
    WinJS.Binding.processAll(personDiv, student);

Essentially we are selecting the element using the document.querySelector and the in the process all function passing the target element and the data source as a data context. By now we have successfully data bind html element to the data source. On running the application you should get output as follows

clip_image002[6]

So far we have done one way binding and if data changes at the data source target element won’t get any notification. We can convert a data context to a binding context using the WinJS.Binding.as. To understand this in better way let us start looking at a problem statement. I have modified the UI as follows,


<body>
    <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerText: name">
        </span>
        <br/>
        <input type="text" id="txtInput" />
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

</body>

Now UI look like as follows and when we enter a value in the text box that should update the welcome span.

clip_image002[8]

On the click event of the button we can modify name property as follows


document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           student.name = updatedname;
        }

When run the application you will find that value of the welcome span is not getting updated. Reason behind is that when data source is getting updated it does not send any notification to the target elements bind to it. WinJS gives us a method to create notification on the data source and convert it to a binding context. You need to use WinJS.Binding.as to create binding context.

So let us modify the above code to perform two way binding,

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.name = updatedname;
        }

In above code there is only one extra added line

clip_image002[10]

Now on running the application you will find that when you change the value in text box and click on update data source value of welcome span will also be changed.

clip_image004

WinJS data bind allows us to to do binding of styles as well. Let us go ahead and add one more property to set the color of the text. Updated data source is as follows:

 


   var student = {
        name: "Dj",
        color: "red"
     };

And we can bind color to the welcome span as follows


<span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.background: color ">
        </span>

And we can update value of color as follows

var personDiv = document.querySelector('#nameSpan');
        WinJS.Binding.processAll(personDiv, student);
        var bindingSource = WinJS.Binding.as(student);
        document.querySelector("#btnUpdataDs").onclick = function () {

           var updatedname = document.querySelector('#txtInput').value;
           bindingSource.color = updatedname;
        }

Now let us see that how can we bind to a complex object. We will start with creating a complex object. Working with complex object can be summarized into following steps

  1. Create the class
  2. Add _initObservable method in the constructor of the class
  3. Make class observable by using the WinJS.Class.mix
  4. Create instance of the object
  5. Use bind methods to bind the properties
  6. Use the object in the binding

Let us start with creating a Student class

 


var Student = WinJS.Class.define(
       function()
       {

           this.name = "DJ";
           this.size = "16px";
       },
       {

           _names:
               ["foo", "loo", "koo", "too", "moo", "soo", "aoo", "too", "qoo", "coo"],
           _sizes:
               ["30px", "80px", "40px","20px","35px","67px","43px","23px","54px","12px"],

           _newName: function () {
               this["name"] = this._names[this._randomizeValue(this._names.length)];
               this["size"] = this._sizes[this._randomizeValue(this._sizes.length)];
           },
           _randomizeValue: function (max) {
               return Math.floor((Math.random() * 1000) % max);
           }

       });

In this class we have put two arrays and two functions. In the constructor of the class we are setting default value for name and the size. _newName function will return new name from the array with new size from the size array.

Next we need to add _initObservable inside the constructor. So updated constructor will look like as follows:

 


  var Student = WinJS.Class.define(
       function()
       {
           this._initObservable();
           this.name = "DJ";
           this.size = 16;
       },

Now to make the object observable we need to use WinJS.Class.mix. This can be done as follows:


    WinJS.Class.mix(Student,
    WinJS.Binding.mixin,
    WinJS.Binding.expandProperties({name: "", size: ""})
);

After this step we need to call the bind method on the instance of the Student class. Make sure to create instance in the app.onactivated event handler.

 

            var s = new Student();
            s.bind("name",onNameChange);
            s.bind("size", onSizeChange);

The bind method takes two parameters. First name of the property and second parameter as the function which will define how property will be bind. Below we have function calling on the bind.


function onNameChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.innerText = newValue;
    };

    function onSizeChange (newValue) {
        var span = document.getElementById("nameSpan");
        span.style.fontSize = newValue;
    };

On the HTML markup is bind to properties of Student and there a button. On click event of the button we will call _newName function on the student object to change the name and the font size.


   <div id="welcome">
        Welcome,
        <span id="nameSpan"
              data-win-bind="innerHTML: name;
               style.fontsize: size ">
        </span>
        <br/>
        <button id="btnUpdataDs">Update DataSource</button>
    </div>

On the click event of the button we will call _nameName function as shown below:

document.querySelector("#btnUpdataDs").onclick = function () {

            s._newName();
        }

When you run the application on the click of the button name and size of the name should change. Data binding and the observable are very important components of WinJS and you may want to use them while create app for the Windows Store.

Source code on GitHub

Happy Coding.