Friday, November 4, 2016

Getting started with Spire.Net

Recently I was thinking whether we can convert html of a website to PDF. While searching for it, I came across products from the Spire products from EIceblue. They provide these type of tools not only for the .net, but also for silverlight and wpf. Moreover, they provide API's for operating on PDF's, word documents, spreadsheets, ppt files etc. Check out the link here.

Very easy to start with. Download the package from here and start by clicking on the setup file spire.office_2.14. This will start with an installation wizard.



Accept the end user licence and click next. Select the location where you would like to extract the api dll's.

Click next, and it will ask you whether you would like to add the references to your visual studio itself. Tick the checkbox if you would like to include the tools into the Visual studio itself. Leave it unchecked if you do not want to include them in the visual studio, Click next

Select the components that you would like to install. In this case we keep the default selection. Also we can select the location where we would like to install it. Press Next to continue.


Click Install to finish. It will install the dll's on the specified location and also provides a demo applications illustrating the use of the s


You can either run the demo application or you can check the location where the dll's were installed.


Check the dll's installed on the location where we installed.

That's it. We are done with the installation. So we can no use the dll's and start using the api's. Happt coding.

Sunday, July 31, 2016

Create dynamic class in C# using CodeDom

In C#, we can create classes at run-time and compile it to generate an assembly using System.CodeDom namespace in System.dll. For this, It provides different classes and functions to create the dynamic namespace add classes, methods and properties to it.
Let's start by adding a new Console application and add the namespace using System.CodeDom to it. We will create a namespace say 'sampleNamespace' by using the CodeNamespace class. So our code will look like the following:  
  1. CodeNamespace nameSpace = new CodeNamespace("sampleNameSpace");  
Next, we will add the using's to be used in the dynamic code. This is similar to adding the namespaces which we add normally in our applications as: using System or using System.Linq. To do this, we will use the Imports function in the CodeNamespace class. So our code will look like the following: 
  1. nameSpace.Imports.Add(new CodeNamespaceImport("System"));  
  2. nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));  
  3. nameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));  
Next we will add a class named SampleClass to our namespace sampleNamespace using the CodeTypeDeclaration class. It provides different properties like Name, IsClassAttributes etc. to create class definition and add this class to our namespace sampleNamespace. So the code will look like the following: 
  1. CodeTypeDeclaration cls = new CodeTypeDeclaration();  
  2. cls.Name = "SampleClass";  
  3. cls.IsClass = true;  
  4. cls.Attributes = MemberAttributes.Public;  
  5. nameSpace.Types.Add(cls);  
Next we will use the CodeCompileUnit class, which will acts as a container for the dynamic code that we are trying to generate. This container will be used to compile and generate an assembly of our code. Let's create a physical file on our system using the CodeCompileUnit class using the StreamWriiter class. So our code will change to the following:  
  1. CodeCompileUnit compileUnit = new CodeCompileUnit();  
  2. compileUnit.Namespaces.Add(nameSpace);  
  3. CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();   
  4.   
  5. CSharpCodeProvider provider = new CSharpCodeProvider();  
  6.   
  7. using (StreamWriter sw = new StreamWriter(@"C:\SampleFile.cs"false))  
  8. {  
  9.     IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");  
  10.     provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());  
  11.     tw.Close();  
  12. }  
So our complete code will look like below: 
  1.           CodeNamespace nameSpace = new CodeNamespace("sampleNameSpace");  
  2.   
  3.           nameSpace.Imports.Add(new CodeNamespaceImport("System"));  
  4.           nameSpace.Imports.Add(new CodeNamespaceImport("System.Linq"));  
  5.           nameSpace.Imports.Add(new CodeNamespaceImport("System.Text"));  
  6.   
  7.           CodeTypeDeclaration cls = new CodeTypeDeclaration();  
  8.           cls.Name = "SampleClass";  
  9.           cls.IsClass = true;  
  10.           cls.Attributes = MemberAttributes.Public;  
  11.           nameSpace.Types.Add(cls);  
  12.   
  13.           CodeCompileUnit compileUnit = new CodeCompileUnit();  
  14.           compileUnit.Namespaces.Add(nameSpace);  
  15.           CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();   
  16.   
  17.           CSharpCodeProvider provider = new CSharpCodeProvider();  
  18.   
  19.           using (StreamWriter sw = new StreamWriter(@"D:\TestFile.cs"false))  
  20.           {  
  21.               IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");  
  22.               provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions());  
  23.               tw.Close();  
  24.           }  
Run the code and open the location to see the code file got generated with your code:
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated by a tool.  
  4. //     Runtime Version:4.0.30319.42000  
  5. //  
  6. //     Changes to this file may cause incorrect behavior and will be lost if  
  7. //     the code is regenerated.  
  8. // </auto-generated>  
  9. //------------------------------------------------------------------------------  
  10.   
  11. namespace sampleNameSpace {  
  12.     using System;  
  13.     using System.Linq;  
  14.     using System.Text;  
  15.       
  16.       
  17.     public class SampleClass {  
  18.     }  
  19. }  
So this was about how we can generate dynamic class with namespace using CodeDom classes. In next article we will see how we can add methods to these classes. Hope you enjoyed reading it. Happy coding...!!! 

Saturday, June 4, 2016

Abstract class vs Interface

This is one of the most common questions which is being asked in interviews - what is the difference between the abstract class and and interface. And different answers include the use related to multiple inheritance, abstract/non-abstract methods, no instance creation for abstract class etc. These are fine, but one of the most important answer which I feel is the real difference i.e. which one should be used when, is normally not answered properly. In this article we will try to see what is should be.

An abstract class is aimed at
  1. Providing the functionality of a base class with some functionality which we want to force the derived classes to use.
  2. Provide abstract methods, which the derived classes can implement as per their own requirement.
The first point here is the important one. It is not necessary that we use the abstract class to have abstract methods. It's just optional. However, the point whether we should use abstract class or an interface, can be decided by considering both the points above.

For ex. we can have an abstract class with an abstract method say SaveData and a non abstract method named CreateDatabaseConnection, which is used for database connectivity. Two classes ClassA and ClassB derive from this abstract class and must provide their own implementations of the SaveData. However, they must use the same CreateDatabaseConnection method. This is where we should use the abstract class rather then the interface.

So, an abstract class provides the functionality of a base class as well as contain abstract methods, which must be implemented by the derived classes. However, this is not the case with the Interfaces. They can only have method definitions and no method with complete definition.

So I guess this should be the main point to be considered while deciding whether to use an abstract class or an interface.

Hope you enjoyed reading it. Happy coding...!!!

Saturday, May 21, 2016

Wcf Service Name attribute

Concept of using services as an api, are very common, providing the advantage for different components/systems, to interact with each other in a loosely coupled manner. For this purpose, we can use asp.net web api or wcf services or wcf rest based services. So a service may have different methods as part of your system, which include methods like GetProductId, UpdateOrderById etc.

However, sharing the names of the methods will expose some kind of basic information of your system entities, as well. For example, like GetProductById clearly states that the there is an entity like Product in your system. Moreover, any method like GetCategoryProducts can be interpreted that there are two entities Product and Category in your system. Wouldn't it be nice to expose these methods using a different name. 

In wcf, we can do this through the use of the Name property, in the OperationContract attribute. Let's see how we can do this.
We will start by creating a wcf service with a method named GetData, which returns some data. So it will be like following:

   [ServiceContract]    
   public interface IService1    
   {    
       [OperationContract]    
       string GetData(int value);     
   }    
       
   public class Service1 : IService1    
   {    
      public string GetData(int value)    
      {    
          return string.Format("You entered: {0}", value);    
      }    
  }    

Next, we add a client application, add the reference to this project and call this method. So the code will look like the following:

   ServiceReference1.Service1Client _client = new ServiceReference1.Service1Client();  
   var _data = _client.GetData(2); 

Now in order to make this method to be called with another name, say GetMyData, we will add the Name property on the OperationContract attribute. So the code will change to following:

  [ServiceContract]  
    public interface IService1  
    {  
         [OperationContract(Name="GetMyData")]  
         string GetData(int value);  
    }  

Update the service reference and see that we cannot access the method with the same name again.

wcf service name attribute, Name attribute in Wcf Service

Similarly, we can add the Name property on the ServiceContract, DataContract and DataMember attributes.

Happy coding...!!! 

Saturday, May 7, 2016

ng-model in angular-js

Displaying data in the applications is a very basic need. To do so, angularcjs provides two main directives, apart from other directives. These are ng-model and ng-bindIn this article we will try to understand how ng-model can be used and why it is useful over ng-bind.

ng-Model and two way data binding:

ng-model supports two way data binding while ng-bind does not. Two way data binding means that when ng-model is used for any property/variable, and, when any change is made in it's value, it get's reflected, where-ever it is being used.

For example, suppose we have a property named "DefaultText", with any default value. This property is bind with an input control(to get input from user) and span tag(to display the value to the user), using the angular expression or ng-bind

When the page first loads, the input control will display the default value. The value flows from the variable in the controller to the input type control and also in the span tag with which it is being bind with. When value is changed in the input type control, it updates the underlined model property i.e. "DefaultText" and updated value is displayed in the span tag, as it is attached to it. 

Let's try this by creating a controller named ngModelBindController:

   var mainApp = angular.module('mainApp', []);

        mainApp.controller('ngModelBindController', function ($scope) {
            $scope.DefaultText = 'Enter a Value';
        });


Next, we bind the controller with a div in the html and use the ng-model directive to bind the DefaultText property to an input control of type text. Also we bind this property to the span tag using the angular expressions, to display the value of this variable. So our html will look like the following:


  <div ng-app="mainApp" ng-controller="ngModelBindController">
        <fieldset>
            <legend>ng-model in angular-js</legend>
            <p>
                Enter a value:
                <input type="text" ng-model="DefaultText" />
            </p>
            <span>You have entered: {{ DefaultText }}
            </span>
         </fieldset>
    </div>


Now run the application and we can see that the default value i.e. "Enter a Value" is displayed in the input control. Change the input control value and it will get's updated in the span tag.


ng-model in angular js



That's it, this is the basic working of ng-model. Hope you enjoyed reading it. Happy coding...!!!

Saturday, April 30, 2016

CRUD Operations using AngularJS

Recently I started exploring the angular js. So i decided to try with basic crud operations and create a new application. So let's see how we can do this. For our purpose, we will be using javascript arrays rather then any database. So let's start by adding 
Remove the web.config file and add an html page. To use angular js, we will add reference to online angular js script file on the following link.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js">

To start with our sample, we will add data into a javascript array. For this, add two input type controls and and buttons to save data. Also, add a new angular module and define a model named EmpModel in it, having three properties called Id, Name and Salary. Bind this model with our input controls, by our angular module named mainApp and a controller named CRUDController. So our code will look like the following:

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title></title>  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>  
</head>  
<body>  
  
    <div ng-app="mainApp" data-ng-controller="CRUDController">  
  
        <table>  
            <tr>  
                <td>EmpId: </td>  
                <td>  
                    <span>{{ EmpModel.Id }}</span></td>  
            </tr>  
            <tr>  
                <td>Name:</td>  
                <td>  
                    <input type="text" data-ng-model="EmpModel.Name" /></td>  
            </tr>  
            <tr>  
                <td>Salary:</td>  
                <td>  
                    <input type="number" data-ng-model="EmpModel.Salary" /></td>  
            </tr>  
            <tr>  
                <td></td>  
                <td>  
                    <input type="button" value="Save Data"/></td>  
            </tr>  
        </table>  
    </div>  
  
    <script type="text/javascript">  
        var app = angular.module("mainApp", []);  
  
        app.controller('CRUDController', function ($scope) {  
            $scope.EmpModel = {  
                Id: 0,  
                Salary: 0,  
                Name: '',  
            };   
        });  
    </script>  
</body>  
</html> 

To add data into our javascript array, let's add a method named AddData. This method will receive the data from $scope and add it to the array. So our controller will change to: 

var app = angular.module("mainApp", []);  
       app.controller('CRUDController', function ($scope) {  
  
           $scope.EmpModel = {  
               Id: 0,  
               Salary: 0,  
               Name: '',  
           };  
  
           $scope.EmpList = [];  
           $scope.AddData = function () {  
               var _emp = {  
                   Id: $scope.EmpList.length + 1,  
                   Name: $scope.EmpModel.Name,  
                   Salary: $scope.EmpModel.Salary  
               };  
               $scope.EmpList.push(_emp);  
               ClearModel();  
           }  
  
           function ClearModel() {  
               $scope.EmpModel.Id = 0;  
               $scope.EmpModel.Name = '';  
               $scope.EmpModel.Salary = 0;  
           }  
       });  

Bind the AddData method to our button using ng-click angular directive. To display the data, we use the ng-repeat directive which will read the data from the array and generate an html table. So our html form will look like the following:

 <table>  
           <thead>  
               <th>Id</th>  
               <th>Name</th>  
               <th>Salary</th>  
           </thead>  
           <tr data-ng-repeat="Emp in EmpList">  
               <td>{{ Emp.Id }}</td>  
               <td>{{ Emp.Name }}</td>  
               <td>{{ Emp.Salary }}</td>  
           </tr>  
       </table>  

Now, run the application and see the data get's added.


Now let's delete the record from the table. Add a function for deletion in the controller. So our controller code will change to the following:

$scope.DeleteData = function (emp) {  
               var _index = $scope.EmpList.indexOf(emp);  
               $scope.EmpList.splice(_index, 1);  
           }  

The argument of this function is of type EmpModel and will contain the data of the record which we are going to delete. We will find index of the record and remove it from the array. Next bind the delete button click event with our delete function using ng-click and pass the EmpModel instance as the parameter. See the code below: 

 <table border="1" style="width: 300px">  
          <thead>  
              <th>Id</th>  
              <th>Name</th>  
              <th>Salary</th>  
          </thead>  
          <tr data-ng-repeat="Emp in EmpList">  
              <td>{{ Emp.Id }}</td>  
              <td>{{ Emp.Name }}</td>  
              <td>{{ Emp.Salary }}</td>  
              <td>  
                  <input type="button" value="Delete" data-ng-click="DeleteData(Emp)" /></td>  
          </tr>  
      </table>  

Run the code, add new records and try to delete them.


Now, let's perform the update. First will display the data to be updated, in our input controls. Add a new method named BindSelectedData in our controller, which will pass the data to the input controls, using the $scope.EmpModel. Our function will look like the following:


$scope.BindSelectedData = function (emp) {  
    $scope.EmpModel.Id = emp.Id;  
    $scope.EmpModel.Name = emp.Name;  
    $scope.EmpModel.Salary = emp.Salary;  
}  

To use the above method, bind it to the table row click using ng-click directive. Our html will change to:  

<table border="1" style="width: 300px">  
          <thead>  
              <th>Id</th>  
              <th>Name</th>  
              <th>Salary</th>  
          </thead>  
          <tr data-ng-repeat="Emp in EmpList" data-ng-click="BindSelectedData(Emp)">  
              <td>{{ Emp.Id }}</td>  
              <td>{{ Emp.Name }}</td>  
              <td>{{ Emp.Salary }}</td>  
              <td>  
                  <input type="button" value="Delete" data-ng-click="DeleteData(Emp)" /></td>  
          </tr>  
      </table>  

Select rows from the table and see that the data get's bind to the input controls through the $scope.EmpModel, which get;s the data from the emp object(argument of the BindSelectedData method). See the screenshot below:

Finally we will add the update button to perform the data updation. Add a method called UpdateData in the controller. So our controller will change to the following:

$scope.UpdateData = function () {  
    $.grep($scope.EmpList, function (e) {  
        if (e.Id == $scope.EmpModel.Id) {  
            e.Name = $scope.EmpModel.Name;  
            e.Salary = $scope.EmpModel.Salary;  
        }  
    });  
    ClearModel();  
}  

Our method will find the record in our array and perform it's updation. Attach our method with the click event of our update button by using the ng-click directive. So html mark-up will change to: 

<table>  
          <tr>  
              <td>EmpId: </td>  
              <td>  
                  <span>{{ EmpModel.Id }}</span></td>  
          </tr>  
          <tr>  
              <td>Name:</td>  
              <td>  
                  <input type="text" data-ng-model="EmpModel.Name" /></td>  
          </tr>  
          <tr>  
              <td>Salary:</td>  
              <td>  
                  <input type="number" data-ng-model="EmpModel.Salary" /></td>  
          </tr>  
          <tr>  
              <td>  
                  <input type="button" value="Save Data" data-ng-click="AddData()" /></td>  
              <td>  
                  <input type="button" value="Update Data" data-ng-click="UpdateData()" /></td>  
          </tr>  
      </table>  

Run the application, edit and record and click the Update button..

That's it, our basic application is ready to use. Hope you enjoyed reading this article. Happy coding...!!!