Contents tagged with C#

  • Generate C# Classes from a JSON String Easily Using Visual Studio

    As developers, we are often faced with certain tasks that are very repetitive in nature, which can also be time consuming to solve it. For example, whenever we need to reserialize a complex JSON string to classes we may need to write a lot of code. Until recently, whenever I needed to do such task I invariably create the classes manually and if it's a complex string, I was spending way too much time on that.

    When the instances like these began to happen every now and then, I decided to search for online options which can spit out classes from a JSON string. After some googling, I found out this site json2csharp.com which can do what I was looking for. You only need to paste the JSON in the input box and click on the Generate button to get the classes in C#.

    Categories: C#, Visual Studio 2015 Tips & Tricks, Windows 10

  • AutoMapper - NullSubstitution

    Sometimes you may want to provide default values if there are null values for a member in the source. Automapper has got a NullSubstitute method in configuration to specify a value for a memeber having null value.

    Syntax

    NullSubstitute("<provide default value for null>"

    Usage

    var config = new MapperConfiguration(cfg =>
                    {
    
                        cfg.CreateMap<ModelData, ViewModel>()
    						.ForMember(dest => dest.Name, opt => opt.NullSubstitute("Default Name"));
                    });
    

    Categories: C#, AutoMapper

  • AutoMapper - Dynamic & ExpandoObjects

    Automapper supports dynamic and ExpandoObjects and will map to/from without any additional configuration. In the example given below, mapping is done from a ExpandoObject(viewModel) to an instance of ModelData class(model)

    The members for the source are dynamically created and AutoMapper maps it properly without any explicit configuration. You can see that which create the configuration object have an empty lambda expression.

    using System;
    using AutoMapper;
    using System.Dynamic;
    
    namespace AutoMapperSamples.Configuration
    {
        namespace AutoMapperSample
        {
    
            public class ModelData
            {
                public string Name { get; set; }
                public DateTime StartedOn { get; set; }
    
    
            }
            
            public class TestAutoMapper
            {
    
                public static void Main()
                {
    
                    dynamic viewModel = new ExpandoObject();
                    viewModel.Name = "Bridge Construction";
                    viewModel.StartedOn = DateTime.Now;
                    var config = new MapperConfiguration(cfg => { });
    
                    config.AssertConfigurationIsValid();
    
    
                    var model = new ModelData { StartedOn = DateTime.Now, Name = "Bridge Construction" };
    
                    model = config.CreateMapper().Map<modeldata>(viewModel);
                    Console.WriteLine("\nName " + model.Name);
                    Console.WriteLine("\nStart Date " + model.StartedOn);
    
    
    
                    Console.ReadKey();
                }
            }
        }
    }
    

    Output

    Categories: C#, AutoMapper

  • AutoMapper - Property/Field Filtering

    By default Automapper will try to map not only public properties but also public fields found in source and destination.

    using System;
    using AutoMapper;
    
    namespace AutoMapperSamples.Configuration
    {
        namespace AutoMapperSample
        {
            
            public class ModelData
            {
                public string Name { get; set; }
                public DateTime StartedOn { get; set; }
    
                public string Location;
            }
    
    
    
            public class ViewModel
            {
                public string Name { get; set; }
                public DateTime StartedOn { get; set; }
    
                public string Location;
            }
    
    
            public class TestAutoMapper
            {
    
                public static void Main()
                {
                    var config = new MapperConfiguration(cfg =>
                    {
                        cfg.CreateMap<ModelData, ViewModel>();
                    });
    
                    config.AssertConfigurationIsValid();
    
                    var model = new ModelData { StartedOn = DateTime.Now, Name = "Bridge Construction", Location = "India" };
    
                    var viewModel = config.CreateMapper().Map<viewmodel>(model);
                    Console.WriteLine("\nName " + viewModel.Name);
                    Console.WriteLine("\nStart Date " + viewModel.StartedOn);
                    Console.WriteLine("\nLocation " + viewModel.Location);
    
    
                    Console.ReadKey();
                }
            }
        }
    }
    

    In this example Location is a public field and it will also get mapped automatically.

    Output

    Categories: C#, AutoMapper

  • AutoMapper - Working with prefix and postfix

    Another configuration option we have is for recognizing prefixes or postfixes in the member names. In some scenarios we may have a prefix or postfix for all the properties in the source model and it's not there in the destination model. This cannot be handled by the default mapping rules in AutoMapper. For that we have RecognizePrefixes and RecognizePostfixes method in the MapperConfiguration class where we can specify postfix or prefix. If AutoMapper finds the prefix/postfix in the members in source instanace then it will be discarded and if it found a match in the destination instance then maps correctly.

    Syntax - Prefix

    RecognizePrefixes("<prefix name>");

    Syntax - Postfix

    RecognizePrefixes("<postfix name>");

     

    Sample Code - Prefix

    var config = new MapperConfiguration(cfg =>
    {
         cfg.RecognizePrefixes("Work");
         cfg.CreateMap<ModelData, ViewModel>();
    });
    

    Sample Code - Postfix

    var config = new MapperConfiguration(cfg =>
    {

    cfg.RecognizePostfixes("Work");
    cfg.CreateMap<ModelData, ViewModel>();
    });

    Categories: C#, AutoMapper

  • AutoMapper - Replacing Member Names

    Another feature available in AutoMapper is the ability to replace characters or the complete name in the source member name while doing the mapping. This will become helpful when you deal with member names having different spelling or some special characters in it. It's normally done during the configuration for mapping and needs to do only once.

    Syntax 

    ReplaceMemberName("<orignial member name>","<matching property name>");

     var config = new MapperConfiguration(cfg =>
    {
    cfg.ReplaceMemberName("StartedOn", "Started_On");
    cfg.ReplaceMemberName("Name", "FirstName");

    cfg.CreateMap<ModelData, ViewModel>();
    });

    Here we are doing couple of replacements, one for adding a underscore to Started_On property and second one for completely using a new name for the property. One thing to note here is that you should specify the replacements before the CreateMap statement otherwise it will you invalid mapping exception at runtime.

    Categories: C#, AutoMapper

  • AutoMapper - Profiles

    Profiles is another great feature from AutoMapper which helps you to mappings and it comes in handy when we need to apply different mapping rules for the same object. Let's take the case of a DateTime field being mapped to a String field and the requirements can be different based on the business requirements .

    In the below example I have a source model which has got a DateTime field and the destination model with a string property. In one instance I needs to show the data in mm/dd/yyyy format and another case I need to show only month and year.

    using System;
    using AutoMapper;
    
    namespace AutoMapperSamples.Configuration
    {
        namespace Profiles
        {
            public class DateTimeProfile1 : Profile
            {
                protected override void Configure()
                {
                    CreateMap<DateTime, String>().ConvertUsing<DateTimeToString1TypeConverter>();
                }
            }
    
            public class DateTimeProfile2 : Profile
            {
                protected override void Configure()
                {
                    CreateMap<DateTime, String>().ConvertUsing<DateTimeToString2TypeConverter>();
                }
    
            }
    
            public class DateTimeToString1TypeConverter : ITypeConverter<DateTime, String>
            {
                public string Convert(ResolutionContext context)
                {
                    return DateTime.Parse(((object)context.SourceValue).ToString()).ToString("dd/MMM/yyyy");
                }
            }
    
            public class DateTimeToString2TypeConverter : ITypeConverter<DateTime, String>
            {
                public string Convert(ResolutionContext context)
                {
                    return DateTime.Parse(((object)context.SourceValue).ToString()).ToString("MMMM - yyyy");
                }
            }
    
            public class Model1
            {
                public DateTime StartedOn { get; set; }
            }
    
            
    
            public class ViewModel
            {
                public String StartedOn { get; set; }
            }
    
    
            public class TestProfile
            {
    
                public static void Main()
                {
                    var config1 = new MapperConfiguration(cfg =>
                    {
                        cfg.AddProfile<DateTimeProfile1>();
                        cfg.CreateMap<Model1, ViewModel>();
                    });
    
                    var config2 = new MapperConfiguration(cfg1 =>
                    {
                        cfg1.AddProfile<DateTimeProfile2>();
                        cfg1.CreateMap<Model1, ViewModel>();
                    });
    
                    var model1 = new Model1{ StartedOn = DateTime.Now};
                    
                    var viewModel1 = config1.CreateMapper().Map<ViewModel>(model1);
                    Console.WriteLine(viewModel1.StartedOn);
                    viewModel2 = config2.CreateMapper().Map< ViewModel>(model1);
                    Console.WriteLine(viewModel2.StartedOn);
    
                    
                    Console.WriteLine(viewModel2.StartedOn);
                    Console.ReadKey();
                }
            }
        }
    }

    Categories: C#, AutoMapper

  • AutoMapper - Custom Type Converters

    Another scenario where AutoMapper cannot do default mapping is when the types of the properties in both source and destination classes are different. Even though the names are same, there is no way AutoMapper can proceed in cases such as from String to Int32 or DateTime. If try to do mapping then AutoMapper will throw exception at the time of configuration or at the time of mapping itself.

    This problem can be solved using the Custom Type Converters available in AutoMapper. We can create custom type converters by extending the ITypeConverter interface and provide the logic needed for converting the source to the destination

    Categories: C#, AutoMapper

  • AutoMapper - Updating Instances

    So far in this series we were dealing with mappings only with new instances of the source and destination classes. Automapper can also be used to do mapping for existing instances also, meaning instances that have data already in it before mapping. Typical example of this sceanario happens when we edit information, at that time our source will be the edited data and the destination data will be one stored in the data store.

    Categories: C#, AutoMapper

  • AutoMapper - Projections

    So far we saw how to do mapping between simple objects that have same name and same type using AutoMapper. In the last post, I have explained the use of MapFrom method to do a custom mapping by concatnating values from two properties. In some case we may need to map properties between two fields with different property names and AutoMapper will be unable to do the mapping by default. Here also we are going to use the MapFrom method to determin which field needs to be picked up from the source for mapping the value in the destination object.

    Categories: C#, AutoMapper

  • AutoMapper - Conditional Mapping

    Automapper has got another feature called conditional mapping which provides you to do mapping based on conditions. For example if you have a custom mapping for FullName property which uses FirstName and properties of source instance. In that case you want to make sure that these two fields are not null or whitespace, otherwise it will produce some undesirable results as shown in the example below.

     

    Categories: C#, AutoMapper

  • AutoMapper - Custom Mapping

    Up untill now we have gone various examples using AutoMapper that was doing one-to-one mapping. But there may arise some scenarios where we need to apply some custom logic for doing the mapping. We can do that in AutoMapper in multiple ways, one way of doing that is using ResolveUsing method while creating a map

    Categories: C#, AutoMapper

  • AutoMapper - Ignoring Properties

    In this post I will show you how to ignore properties from getting mapped automatically by AutoMapper. Suppose if both the source and destination has got a property with same name, but is used for representing different information, in that case we definitly not want the property to be mapped automatically. We can configure this while creating the mapping in AutoMapper as follows.

    Syntax 

    var config = new MapperConfiguration(cfg => { 
        cfg.CreateMap<Source, Destination>().ForMember(x =>x.DestinationPropertyName, opt => opt.Ignore());
    });
    
    

    Example

    var config = new MapperConfiguration(cfg => { 
        cfg.CreateMap<Person, PersonVM>().ForMember(x =>x.Name, opt => opt.Ignore());
    });
    

    Since AutoMapper supports FluentAPI, you will be able to call ForMember methods multiple time if you ignore more than one property

    var config = new MapperConfiguration(cfg => { 
    cfg.CreateMap<Foo, FooCopy>()
    .ForMember(x =>x.Name, opt => opt.Ignore())
    .ForMember(x => x.Age , opt => opt.Ignore() );
    });
    
    

    In this example, while creating the mapping I have added the ForMember method to ignore the Name property while doing the mapping. If you look at the output window you can see that the value for Name is empty even though the property in the source instance has value in it

    It will be a tedious procedure if we want to ignore a significant amount of properties from getting mapped automatically. So if you ever face that scenario do consider creating an extention class like the one below which ignores the properties based on data attribute specified in the model

    Categories: C#, AutoMapper

  • Getting Started With AutoMapper

    Automapper is an utility library designed for object-to-object mapping. Let's take the case of mapping columns in a data table to its equivalent business entity, we will have to manually write code for mapping each of these columns and assume if there are a lot of entities, it's quite boring as well as creates redundant code. Some bright minds in the industry took note of it and set to solve the problem by automating it and thus AutoMapper was born. 

    First of all you need to install AutoMapper package, which can be done from the Package Manager Console using the following statement

    PM> Install-Package AutoMapper

    Let's create a simple program to do a basic mapping procedure.

    1. Create a map which indicates the mapping flow for automapper.

    var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Source type, Destination type>();
    });

    IMapper mapper = config.CreateMapper(); 

      Suppose if you want to convert from class A to class B, then your mapping statement will be like 

    var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<A, B>();
    });

    IMapper mapper = config.CreateMapper();

    2. The actual mapping happens when we call the Mapper.Map function

    var destinationObj =  mapper.Map<Source type>(Source instance);

    Eg: var bObj = mapper.Map<A>(aObj);

    Categories: C#, AutoMapper

  • Introduction to AutoMapper

    In our daily life as developers, we sometimes do some sort of repetitive coding that can be avoided by some sort of automation. Automapper is one such utility which helps developers to mapping of properties from one object to another. Typical examples for this scenario includes mapping of Domain entity to a DTO(Data Transfer Objects) , Model to a ViewModel. Normally this sort of mapping occurs at the boundary between the layers where we need to transfer data, say from Data Layer to Business Layer or from Business Layer to Presentation Layer. 

    In this example we have a class called Product which is a domain entity and we have another class called ProductViewModel which is a subset of the domain entity. So to transfer the data from the domain entity to the view model class we are manually mapping the properties one by one in line #17. The major drawbacks of these apporach are

    Categories: C#, AutoMapper

  • Using static statement in C# 6.0

    The using static is another neat little feature introduced in C# 6.0 which helps you to make your code more readable as well as helps to avoid some redundancy in your code.

    We all know that we can import a namespace with using which helps us to use the type name without using the fully qualified name. For example, in most of the programs the first statement will be using System and if we want to call the WriteLine method using the statement given below,

     

    using System;

    public class Program
    {
        public static void Main()

        {

            Console.WriteLine("This is a test");

         }

    }

    Suppose if we didn't imported the namepsace then, instead of Console.WriteLine() we need to call the method with the fully qualified name. ie System.Console.WriteLine() 

    public class Program
    {
        public static void Main()

        {

            System.Console.WriteLine("This is a test");

         }

    }

    Imagine a class with a large number of calls to the WriteLine method and we will be having a lot of redundant 

    code for the owner class, in this case System

    Let's take the below code as an example

    Categories: C#, C# 6.0 New Features

  • nameof Expression in C# 6.0

    This function is one of the useful addtion to the language in C# 6.0 and will see a widespread adoption. We as developers have written many times the below code numerous times in our life.

    In this basically we are checking whether the parameters are properly set according the business rules and if it's not then throws the ArgumentNull exception with the message saying that this particular property is not set.

    Suppose after some time we decided to change the name of the properties, went ahead with using the refactoring options available in Visual Studio. In the example I removed the term Product from all the properties using the refactoring option, but the messages for the ArgumentNull exception won't change since it's inside string literals.

    Now when the exception occurs there is a mismatch between the actual property name and the name in the message. Imagine if this occurs in a class containing a lot of properties then it take some time to make the corrections and also there's a possiblity of missing out on some.

    Categories: C#, C# 6.0 New Features

  • Auto Properties in C# 6.0

    C# 6.0 brings the ability to initialize an auto-properties pretty much like the way we do for a field. This helps you to intialize the backing field without woking through the setter of the auto property or making using of a local variable. It's executed in the order as written and not at the time when the object is initialized. It means that we cannot reference it using this keyword since the property iniitialization happens before the object intialization.

    In the earlier versions, suppose if we want to initialize the properties to some default values we were doing that at the time of instantiating an object as shown below

    In C# 6.0, now it's possible to initialize the values for the properties at the time of declaration itself.

    Many of you may be wondering why I am using a $ symbol in front of the string and how can I use the C# syntax inside the string which is later transformed into the correct message during execution of the code. It's the new String interpolation feature in C# 6.0 and you read more about it here.

    And you can mix and match the defaults with the ones you want as shown below. In this example, I have modified the default values at the time of instantiation for FirstName and LastName properties and left the Email property untouched

    Also we can initialize it without a setter also.

    Categories: C#, C# 6.0 New Features

  • Dictionary Initializers in C# 6.0

    Dictionary initialization was first introduced with C# 3.0 and the syntax for the same remained same since then.

    In C# 6.0 the syntax was tweaked little bit to make it more friendly to maintain. As we all know in a dictionary object, information is stored as key value pairs and if you look at the above syntax a lot of curly brackets and punctuation marks are used. This makes it pretty ugly and doesn’t reflect the data structure which is holding the data.

    The new syntax reduces the number of keystrokes and the code is now more elegant and readable by omitting some curly braces and the syntax now uses the equals sign which helps you to recognize the info in a key value pair format

    Even though they have introduced a new way on initializing dictionary objects, the old way of writing is still valid and it’s up to you developers to use which one.

    Categories: C#, C# 6.0 New Features

  • String Interpolation in C# 6.0

    Up untill now we are using various options for formatting strings using String.Format or by concatenating string values using + operator or String.Concat function. 

    In the case of using + operator , as the number of items that needs to concatenated increases it becomes very hard to maintain and to understand what we are doing and some times it may result in incorrect string ouput too.

    This can be solved to some extent by using the String.Format function by using the literals as placeholders so that we will get to know what the output be in advance by looking at the text part. But here we may find problems if we don't give the parameter values in the same order as in the string text part. Also if the number of placeholders and the values in the parameter list are not in sync an exception will be thrown at runtime.

    In C# 6.0, Microsoft added a new feature to make our life easier by allowing us to put the expressions directly in the string literal. Now we can inject the values into a string using curly bracket enclosed expressions.

    Categories: C#, C# 6.0 New Features

  • 1
  • 2