Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts
Sunday, December 28, 2014

C# 6.0–Auto implemented property initializer

This blog post is part of C# 6.0 Features Series.
As we all know C# 6.0 is there in preview mode and Microsoft has added few small features to C# 6.0 which helps  lot while you develop application. In today’s blog post we are going to learn one more small feature called “Auto implemented property initializers”.

Developers working on C# used a automatic properties a lot and there has been lot of demands from developers that automatic properties should a have initializers and Microsoft has listened to that feedback and with C# 6.0 it has been introduced. So now we don’t have to use constructors to initialize automatic properties and there will be less and much cleaner code for Automatic property initializations.

Share:
Friday, December 26, 2014

C# 6.0–nameof Operator

This blog post is part of C# 6.0 Features Series.
Microsoft announced the new version of C# 6.0 at the day of visual studio connect event on November. They have not added any big features to C# 6.0 but they have listened to community and added few small features which comes really handy. One of the that is nameof operator.  In this blog post we learn why nameof operator is very useful.

Let’s create a class Employee with few properties.
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Now what I want to do here is to create a object with object initializer and print values of properties with print method.

Share:
Saturday, July 26, 2014

Different way of mapping with EFCodeFirst

Recently I have been working Entity Framework Code First 6.0 and it’s awesome. I am in love with it. It has got great fluent API and we can do anything with that. It’s also promotes Convention over configuration which I love so far.

I have seen people are more confused about how we can map table to class via Entity framework via code first. So this post is going to be in same series. In this post I’m going to write about different ways to mapping table to class. I have already written two post about in details.

Entity Framework code first and Inheritance–Table per hierarchy
Entity framework code first and inheritance- Table Per Type

In this blog post I will give you tips and tricks to map class(type) with database table.

Share:
Thursday, July 24, 2014

HashSet in C#

In this blog post we are going to learn about HashSet collection in C#. It is a cool collection available from C# 3.5. Like any other collection it can be used for representing a set of value. It is an optimized set collection. It helps eliminating duplicate string or elements in collection. Whenever an Item is added in collection it will check whether this items are already there in collection If not then only it will add items.

Let’s take an example for the same.
using System;
using System.Collections.Generic;

namespace CSharpHashSet
{
    class Program
    {
        static void Main(string[] args)
        { 
            HashSet<string> nameHashSet=
                new HashSet<string>
                {
                    "Jalpesh", "Vishal", "Tushar", "Jalpesh"
                };
            foreach (var item in nameHashSet)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}
Now if you see the code carefully I have created HashSet of name(string type) with duplicate name like “Jalpesh” and then enumerate that collection with for loop and print items of collection with Console.WriteLine.

Share:
Sunday, July 20, 2014

Entity Framework Code First migrations

In this blog post we are going to learn about entity code first migrations. Entity Framework code first approach will allow you to define model classes as per the domain requirements via POCOs. Hence you have complete control over classes are written. But as application grows and there are some new features to be added and  your classes will change. Entity Framework Code Migrations allows you to handle this migrations.

As we all now that Entity Framework Code First approach allows you to create database based on your classes created. It’s provide you three types of initializers.

CreateDatabaseIfNotExist: This is the default initializer which will create classes if database not exists.

DropCreateDatabasesWhenModelChanges: This initializer is only good when you don’t concern about your database records. If there is any change in class then it will match database will classes and if there is any difference then it will drop and create a new database.

DropCreateDatabaseAlways: This initializer will always create new database whether database exist or not. If database exist then it will drop that database and create it again.

Share:
Thursday, July 17, 2014

How to convert PSD into image file in c# with Magick.NET

Recently in one of project we had a requirement of converting a Adobe Photoshop file (PSD) into image file(.png) file. After digging while on internet I have found a great library which has so many features in can easily convert PSD files into any time of image file.

The Library is Magick.NET. It’s a open source project you can find more information about it from the following codeplex link.
https://magick.codeplex.com/

There are lots of example available for image conversion and other image editing functions. You can find that about that on documentation.
https://magick.codeplex.com/wikipage?title=Convert%20image

There are lots of NuGet package are available also. Following is a one of them.

Share:
Friday, July 4, 2014

Entity Framework code first and Inheritance–Table per hierarchy

Before some day I have posted a blog about Entity Framework code first and Inheritance – Table per type and this post in next in series with that.

In previous post we have learned about how entity framework code first handles inheritance and in this part we are going to extend this and modify some of code of the code of data context to see how its creates a “Table per Hierarchy”.

We’re going to use same code as previous post just going to change EDataContext code like below.

public class EDataContext : DbContext
{
    public EDataContext() : base("MyConnectionString") 
    { 
    }
    public IDbSet<Customer> Customers { get; set; }
    public IDbSet<Employee> Employees { get; set; }
    public IDbSet<Person> Persons { get; set; }
}

If you see this code carefully and compare is with previous post. The only difference is persons property. That will force Entity Framework to create a single table for inheritance hierarchy. Now we are going to run this application again and see how it creates table. It will create only one table like this.

Share:
Saturday, June 21, 2014

Entity framework code first and inheritance- Table Per Type

Also see part-2 of this blog post- Entity Framework code first and Inheritance–Table per hierarchy
Recently I am using Entity Framework a lot. So I tried some of advance scenario and this post related to it only. In this post we will learn how entity framework handles inheritance.

In object oriented world, We all use Inheritance for reusability. We create some base classes and inherit those in child classes to facilitate code reuse and we don’t have to write again and again. In this post we will also have same kind of methodology. We are going to create a “Person” class and inherit this in to Employee and Customer class and we are going to see how entity framework code first handles this kind of inheritance by default. I’m going to use entity framework version 6.0 and Visual Studio 2013.

So what we are waiting for. Let’s get started. So create a console application from file menu new project.

New-project-entity-framework-inheritance

Once you are done with creating a application. It’s time to add entity framework via nuget package.

adding-entityframework-nuget-inheritance

Share:
Thursday, May 22, 2014

.NET Framework 4.5.2 released by Microsoft

Microsoft has released .NET Framework 4.5.2 before some time see the announcement from It’s .NET Framework team blog. It’s a compatible, in-place update for Microsoft.NET Framework 4.0,4.5 and 4.5.1.  This framework also run side by side with earlier version of .NET framework.

From where I can download .NET Framework 4.5.2?


Following are link from where you can download .NET framework 4.5.2.

.NET framework web installer- Internet required at the time installation. It will download required file runtime.A Boots trapper that pulls in components based on the target OS/platform specs on which the .NET Framework is being deployed.

Share:
Wednesday, May 21, 2014

Fun with Angela Smith library by James Chambers for C#

AngelaSmith is an awesome library created by James Chambers. This library is used to generate realistic test data. You can find more information about it from the following link.

https://github.com/MisterJames/AngelaSmith

As per documentation on the github, it is.
AngelaSmith is a library you can use to generate realistic test data. It is composed of several property fillers that can populate commonly named properties through reflection using an internal database of values or randomly created data. You can override any of the fillers, give AngelaSmith hints on how to fill them, or easily extend the property fillers using extension methods or MEF.
It’s an awesome realistic data generator library. You can generate object data as well list also. She can fill anything that you throw it to her.You can use it’s static methods to create objects for testing, design time data or seeding a database.

Share:
Thursday, April 10, 2014

How to convert C# object into JSON string with JSON.NET

Before some time I have written a blog post – Converting a C# object into JSON string in that post one of reader Thomas Levesque commented that mostly people are using JSON.NET a popular high performance JSON for creating for .NET Created by James Newton- King. I agree with him if we are using .NET Framework 4.0 or higher version for earlier version still JavaScriptSerializer is good. So in this post we are going to learn How we can convert C# object into JSON string with JSON.NET framework.

Share:

Dapper Micro ORM Series

Recently before some time I have created a blog post about list of blog post I have written about Petapoco Micro ORM. So one of the friend suggested I should write same kind of series post about Dapper Micro ORM so that reader of my blog can find the all the posts on same page. So that’s why I writing this blog post.

What is dapper:

Dapper is Micro ORM developed by Sam Saffron few years ago while he was working as lead developer at stack exchange. This ORM was developed specially for Stack Exchange QA sites like stackoverflow.com and superuser.com for the performance improvement. It has got a single file where all the code has been written. You can download dapper Micro ORM from the following location.

http://code.google.com/p/dapper-dot-net/

Dapper Micro ORM related posts on dotnetjalps.com:

Following is a list of post related to dapper Micro ORM that I have written on this blog.

Playing with dapper Micro ORM and ASP.NET MVC 3.0
Insert with Dapper Micro ORM and ASP.NET MVC 3
Edit/Update with dapper ORM and ASP.NET MVC 3
Delete with Dapper ORM and ASP.NET MVC 3

If I write blog post about dapper then I will keep adding into this list. That’s it.

Hope you like it. Stay tuned for more!!
Share:
Saturday, April 5, 2014

Converting a C# Object into JSON string

Some people might think why I am writing so much about basics but the things but in reality  I got lot of questions through email and other communities about very basic things. So I thought instead of replying them into single thread. It is a good idea to write blog post about it and as a result I am writing this blog post.

In this post we are going to learn how we can convert a object into JSON string It is very simple. Let’s first see how we can convert C# Object into JSON string.

Converting a C# object into JSON string:


So to demo this, I have created a employee class like following.

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now let’s create object of this class and assign some value like following.

Employee employee=new Employee
                    {FirstName = "Jalpesh",
                    LastName = "Vadgama"};

For this demo we are using console application so we have to add System.Web and System.Web.Extensions  reference to access the JavaScript Searilizer class through which we are going to convert this object into JSON string. We are going to add reference like following.

add-reference-serializtion-web-convert-chsarp-object-into-json

Now with JavaScript Searilizer class which belongs to System.Web.Script.Serialization namespace we can easily convert C# object into JSON string. Following is a code for that.

var javaScriptSerializer = new 
    System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(employee);
Console.WriteLine(jsonString);

Now when run this console application. Following is a output as expected.

convert-c#-object-to-json-string-javascriptsearializer

Here its serialize object into JSON string. Same you can desterilize the JSON string into C# object with Deserialize function.

That’s it. It’s very easy. Hope you like it. Stay tuned for more..
Share:
Saturday, March 22, 2014

Explicit Keyword in C#

Yesterday, I have written a blog post about Implicit Keyword in C#. In today’s post we are going to learn about Explicit keyword in C#. Like Implicit keyword explicit keyword is also used for typecasting one class into another class. It is also a type conversion operator but rather then directly invoking it will invoke by cast.

As per MSDN, The Explicit keyword declares a user defined type conversation operator that must be invoked with cast.

Usage of explicit operator in C#:

Let’s take a simple example. Following is a code for that.

using System;

namespace ExplicitOperatorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            User user=new User
            {
                    FirstName = "Jalpesh",
                    LastName = "Vadgama"
            };

            Employee employee = (Employee) user;

            Console.WriteLine(employee.FirstName);
            Console.WriteLine(employee.LastName);
            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public static explicit operator Employee(User user)
        {
            Employee employee=new Employee
            {
                    FirstName = user.FirstName, 
                    LastName = user.LastName
            };
            return employee;

        }
    }
}

I have written almost same code as we have written for implicit operator. Same two classes “Emplyee” and “User” with first name and last name operator. The only difference is I have written explicit keyword instead of implicit. And same way I have used casting in main function of console application.

In main function I have initialized class “User” with first name and last name and then type cast that in Employee class object.  Following is out put as expected.












That’s it. It is very easy. Hope you like it. Stay tuned for more..
Share:
Friday, March 21, 2014

Implicit Keyword in C#

In today’s post we are going to learn about implicit operator in C#. Implicit keyword is used for conversation in C#. It is used to declare an implicit user-defined type conversation operator. So with the help of implicit keyword you can convert one class into another class without writing any other syntax.

You can find more information about Implicit from following MSDN link.
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx

Usage of Implicit Keyword in C#:


Sounds interesting!! Let’s take a example of implicit operator in so that it will be much clear. Following is a code for that.

using System;

namespace ImplicitOpeartorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            User user=new User
            {
                    FirstName = "Jalpesh",
                    LastName = "Vadgama"
            };

            Employee employee = user;

            Console.WriteLine(employee.FirstName);
            Console.WriteLine(employee.LastName);
            Console.ReadKey();
        }
    }

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class User
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public static implicit operator Employee(User user)
        {
            Employee employee=new Employee
            {
                    FirstName = user.FirstName, 
                    LastName = user.LastName
            };
            return employee;

        }
    }
}

In above code I have created two classes “User” and “Employee”. Both contains two properties FirstName and LastName. Also in user class I have defined implicit operator Employee which convert user object into employee object.

In main function I have created object of user with first name as “Jalpesh” and last name as “Vadgama” and then assign it to Employee class. So when you assign object to employee class it will call Employee operator with implicit keyword and convert that user object into employee object.

At the end I have printed first name and last name property of Employee class and following is output as expected.

implicit-operator-c#

That’s it. It’s very easy. Hope you like it. Stay tuned for more.. Happy programming.
Share:
Thursday, March 20, 2014

Enhanced debugging with DebuggerDisplay in C#

We all need to debug our projects and for that we need to some visualization to see values of debug data C# has a attribute called ‘DebuggerDisplay’ which helps developers to visualize data in the way developer wants .

As per MSDN, DebuggerDisplay attributes allows developers of the type, who specifies and best understands the runtime behaviour of that type, to also specify what that type will look like when it is display in debugger.

How to use DebuggerDisplay attribute:


Display attribute constructor has one argument, a string will displayed in the value column for instances of type. This string will contain {} braces and this text between {} will evaluate as expression. So what we are waiting for lets try it in Visual Studio. I have written following code for that.
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var employee =new Employee();
        }
    }

    public class Employee
    {

        [DebuggerDisplay("Id={EmployeeId}")]
        public int EmployeeId = 1;

        [DebuggerDisplay("Name={Name}")]
        public string Name = "Jalpesh Vadgama";
    }
}

Here you can see I have created a class called “Employee” with two variable with DebuggerDisplay Attribute and from main method I have created a object of employee class. Now let’s create debug the code via pressing F5 and see how its works.

DisplayDeubggerAttribute

As you can see its display data as defined in argument. So now you can format your debugger visualizer screen as per your requirement. That’s it. Hope you like it. Stay tuned for more.
Share:
Saturday, November 30, 2013

How to find days in year except Saturday and Sunday in C#

Before 2 years I have written a blog post to find Saturday and Sunday in given date range.  It has gain a lot of popularity and on that blog post one user ask about how we can find days in year except Saturday and Sunday in C#. This post is a in reply for that. Following is a code for that.
using System;

namespace DatimeApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startDate = new DateTime(2013, 1, 1);
            DateTime endDate = new DateTime(2013, 12, 31);

            TimeSpan diff = endDate - startDate;
            int days = diff.Days;
            int j=0;
            for (var i = 0; i <= days; i++)
            {
                var testDate = startDate.AddDays(i);
                if (testDate.DayOfWeek != DayOfWeek.Saturday && testDate.DayOfWeek != DayOfWeek.Sunday)
                {
                    j = j + 1;
                    Console.WriteLine(testDate.ToShortDateString());
                }
            }
            Console.WriteLine(string.Format("Total Days:{0}",j));
            Console.ReadLine();
        }
    }
}

If you see above code,  Its very easy to find all days except Saturday and Sunday in a year. I have created two dates with Start date and end date and then I found a difference between those two days. And then in for loop I have checked whether they are weekdays then I have printed a date for that. I have calculated all days except Saturday and Sunday for year 2013. At the end I have printed total days also.

Once you run the code following is a output as expected.

FindDaysExceptSatudaySundayInCsharp

That’s it. Hope you like it. Stay tuned for more…
Share:
Sunday, October 27, 2013

All about Virtual,Override and New in C#


I have seen that lots of people get confused with Virtual, Override and new keyword in C#. So I thought it will be a good idea to write a blog post about it. In this blog post we will learn what is virtual, override and new keyword in C# and what’s difference between override and new in C#.

Virtual and Override in C#:


Virtual keyword allows class member to override in derived class. Let’s take simple example. I have class A which contains Print Method method as virtual method and I have another class B which is derived from class A which overrides Print method. Following is a code for that.

public class A
{
    public virtual void Print()
    {
        System.Console.WriteLine("Virtual Print method from a");
    }
}

public class B:A
{
    public override void Print()
    {
        System.Console.WriteLine("Override Print method from b");
    }
}
Now If I create a object of class A like following and run the code Print method run as normal method. Following is code for for that.
class Program
   {
       static void Main(string[] args)
       {
          A a=new A();
          a.Print();
       }
   }

Once you run this it will have following output.

VirutalAsNormalMethodinCsharp

But when you create a object of class B like following it will completely override the functionality of class A. That is called method Method Overriding. Following is a code for that.

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now, if you run this code it will completely override the code and following will be output as expected.

OverrideMethodinCsharp

How to call base class method with override:


In some scenario, we need base class functionality also while overriding the method of that class. C# provides that functionality with ‘base’ keyword. For that I have changed code of class B like following.
public class B:A
{
public override void Print()
{
    System.Console.WriteLine("Override Print method from b");
    base.Print();
}
}

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now if you run the code you will see output of both method as expected.

BaseKeywordwithoverridecsharp

What is difference between new and override in C#:


After looking into above example some people will argue that this functionality will be achieved by new keyword also. This is call Method Hiding where with new keyword you can hide functionality of base class.  But wait there is a difference. Both are slightly different let’s take some simple example to show difference following is a code for that.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public override void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

In this code, same A class Print method is override by B class Print method and I have created two object of class B. One with reference to base class A and another B itself. Now let’s run this example and following is a output.

OverridewithInheritancedifferencebetweenoverideandnew

Here you see both time it will override class A’s Print Method. Now let’s change above code with new keyword like following.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public new void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

Now you run this code. Following is output.

OverridewithInheritanceDifferenceBetweenoverrideandnew

If you see both output carefully then you will notice a difference. With override keyword it will override Print method in both scenarios. While with new keyword it will only hide print method and both method exist as separate method so if you create a class A object with B then it will class A’s Print method without hiding it and If you create class B object with B then it will hide the base class method and print from class B’s method. So that was the difference.

That’s it. Hope you like it. Stay tuned for more..
Share:
Tuesday, October 22, 2013

Linq- AddRange Method in C#

In this post I’m going to explain you about Linq AddRange method. This method is quite useful when you want to add multiple elements to a end of list. Following is a method signature for this.
public void AddRange(
    IEnumerable<T> collection
)
To Understand let’s take simple example like following.

using System.Collections.Generic;
using System;
namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            foreach (var newname in newnames)
            {
                names.Add(newname);
            }
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I am adding content of array to a already created list via foreach loop. You can use AddRange method instead of for loop like following.It will same output as above.
using System;
using System.Collections.Generic;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames);
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Now when you run that example output is like following.

AddRangeLinqCsharp

Add Range in more complex scenario:

You can also use add range to more complex scenarios also like following.You can use other operator with add range as following.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames.Where(nn=>nn.StartsWith("Vi")));
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I have created array with string and filter it with where operator while adding it to an existing list. Following is output as expected.

AddRangeLinqCsharpAdvanceScneario

That’s it. Hope you like it. Stay tuned for more..
Share:
Monday, October 21, 2013

throw new exception- C#

This post will be in response to my older post about throw exception best practice. where one of user asked that I should include throw new exception.So I thought it will be good idea to write a whole blog post for it. This blog post explains what's wrong with throw new exception.

What’s wrong with throw new exception:


Throw new exception is even worse, It will create a new exception and will erase all the earlier exception data. So it will erase stack trace also.Please go through following code. It’s same earlier post the only difference is throw new exception.

using System;

namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DevideByZero(10);
            }
            catch (Exception exception)
            {
                throw new Exception
                (string.Format(
                    "Brand new Exception-Old Message:{0}",
                     exception.Message));
            }
        }

        public  static void DevideByZero(int i)
        {
           int j = 0;
           int k = i/j;
           Console.WriteLine(k);
          
        }
    }
}

Now once you run this example. You will get following output as expected.

Throw new exception C#

Hope you like it. Stay tuned for more..
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews