Saturday, January 7, 2017

SingleOrDefault vs FirstOrDefault

LINQ provides with two extension methods SingleOrDefault and FirstOrDefault. Let's see the difference between the two. Add a new class clsTest and add two properties Id and Name. Create a List clsTest type, add some data. So we have the following code:  
  1. static void Main(string[] args)  
  2.        {  
  3.            List<clsTest> lstTest = new List<clsTest>();  
  4.   
  5.            lstTest.Add(new clsTest  
  6.            {  
  7.                Id = 1,  
  8.                Name = "A"  
  9.            });  
  10.            lstTest.Add(new clsTest  
  11.            {  
  12.                Id = 2,  
  13.                Name = "B"  
  14.            });  
  15.            lstTest.Add(new clsTest  
  16.            {  
  17.                Id = 3,  
  18.                Name = "C"  
  19.            });  
  20.   
  21.   
  22.            var fod = lstTest.Where(l => l.Name == "D").FirstOrDefault();  
  23.            var sod = lstTest.Where(l => l.Name == "D").SingleOrDefault();  
  24.        }  
Here, we are access an element which does not exist in the list. Run the application and we get null. So both of these methods handle the null condition. Now let's add duplicate records and search the record. So the code changes to: 
  1. static void Main(string[] args)  
  2.         {  
  3.             List<clsTest> lstTest = new List<clsTest>();  
  4.   
  5.             lstTest.Add(new clsTest  
  6.             {  
  7.                 Id = 1,  
  8.                 Name = "A"  
  9.             });  
  10.             lstTest.Add(new clsTest  
  11.             {  
  12.                 Id = 2,  
  13.                 Name = "B"  
  14.             });  
  15.             lstTest.Add(new clsTest  
  16.             {  
  17.                 Id = 3,  
  18.                 Name = "C"  
  19.             });  
  20.             lstTest.Add(new clsTest  
  21.             {  
  22.                 Id = 4,  
  23.                 Name = "C"  
  24.             });  
  25.   
  26.             var fod = lstTest.Where(l => l.Name == "C").FirstOrDefault();  
  27.             var sod = lstTest.Where(l => l.Name == "C").SingleOrDefault();  
  28.         }  
Now run the application. We get the exception Sequence contains more than one element for SingleOrDefault. FirstOrDefault returns the first matching record i.e. the record with Id=3. However, This is because, SingleOrDefault cannot handle the situation if there are multiple elements with the same name. However, FirstOrDefault will return the first matching record from the list. Happy coding...!!!

Module ' ' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

While learning angular-js, I came across the following error:

Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

The error seems to be straightforward that the module is not loaded. However, I cross-checked and found that module was there in the script and should have been loaded. My code looked like below:

  <table ng-app="myApp" ng-controller="testController">
        <tr ng-repeat="x in lstStrings">
            <td>{{ x }}</td>
        </tr>
    </table>

    <script type="text/javascript">
        var angApp = angular.module('myApp');
        angApp.controller('testController', function ($scope, $http) {
            $http.get('http://localhost:57964/api/test/getstringslist')
                  .then(function (response) {
                      $scope.lstStrings = response.data;
                  });
        });
    </script>

Then while comparing the code with some of the samples, I found that a very minor but very effective mistake which was causing the issues. The issue was that I was missing the second parameter of the angular.module function, So the missing part was the one highlighted below:

 <script type="text/javascript">
        var angApp = angular.module('myApp', []);
        angApp.controller('testController', function ($scope, $http) {
            $http.get('http://localhost:57964/api/test/getstringslist')
                  .then(function (response) {
                      $scope.lstStrings = response.data;
                  });
        });
    </script>

See how small the issue was, but it was the one that was breaking the application. As per official angular documentation, the second parameter is:

 This array is the list of modules myApp depends on.

This is a required parameter and can be specified as blank, if there is no dependency of other modules, on this one. Hope this helps somebody else also...!!! Happy coding.

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, IsClass, Attributes 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-bind. In 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...!!!