Sunday, January 8, 2017

C# 7 features - Local functions


A preview of C# 7.0 has been introduced with the preview release of Visual Studio 15. This should not be confused with Visual studio 2015, as it is separate.

In order to install visual studio 15, you will have to download the setup from the link here - https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-studio-15-preview-5-now-available/ and install the web and desktop development tools.

So we will start with the first feature which is the use of Local functions. Normally we create private sub-functions for code refactoring. However, these functions are exposed to other methods in the class, even though they are not required to use. But in C# 7, we can have functions within the functions. Yes, we can create a function within another function.

For example, following code is valid in C# 7.0:

        static void Main(string[] args)
        {
            var d = GetSalary();
        }
        public static Int32 GetSalary()
        {
            var s = GetSum(10, 6) * 2;

            return s;

            Int32 GetSum(Int32 a, Int32 b)
            {
                return a + b;
            }
        }

Run the code and you will get 32 as output.


Here, we have the GetSum method, which will return the sum of two numbers. The result is then multiplied by 2. Hope you enjoyed reading it. Happy coding...!!!

Saturday, January 7, 2017

SingleOrDefault vs FirstOrDefault

LINQ provides with two extension methods SingleOrDefault and FirstOrDefault. Let's see the difference between the twoAdd 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, 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...!!!