Thursday, May 12, 2016

How to Change Internet Explorer Document Mode of Web Browser Control

In your Windows Forms or WPF application, you may need to change document mode of your WebBrowser  Control.  One way  to do this  is  that  adding a registry record under


Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION


Here is the C# code,




public MainForm()
{
   WriteRegistry();
}
private void WriteRegistry()
{
   const string IERegPath = @"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
   const string IEVersion = "11001";
   const string AppName = "MyTestApp.exe";

    RegistryKey Regkey = null;

     try
     {
          Regkey = Registry.CurrentUser.OpenSubKey(IERegPath, true);
          Regkey.SetValue(AppName,IEVersion, RegistryValueKind.DWord);
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.ToString());
     }
}        



Here we set IE Version  value as  11001 which means ; Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks.

You can find IE Version values here;
https://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx

The reason that we added this register under CURRENT_USER instead of  LOCAL_MACHINE is that  writing a registery to LOCAL_MACHINE requires admin rights and the user who is using your application may not be administrator on the computer. That's why it is safer to add registry for only current user.

After running your application, you can see the registry value  as ;




Regards,


Saturday, April 16, 2016

C# Mapping Properties; FastMapper , Automapper performance Comparision

Nowadays, almost in all n-tier  projects you need property  mapping. In an MVC project,  mapping might be needed from view model to domain model  or vice versa, or  you might need property mapping from entity class to a DTO class.

You can achieve mapping by  manual mapping ( mapping each property by writing code ) or you can use a third party  library.   Actually ,  manual mapping ( mapping each property by writing code ) is the safest way.  As in performance terms, it is the fastest way to achieve mapping   moreover  code  is easy to understand and easy to maintain.  As disadvantage your code gets bloated as following;



customerDto.Balance = customer.Balance;
customerDto.BirthDate = customer.BirthDate;
customerDto.City = customer.Address.City;
customerDto.District = customer.Address.District;
customerDto.DoorNo = customer.Address.DoorNo;
...
...


If your project requires massive property mapping  ,  a third party might ease up your development stage and you can do mapping by writing  a few lines of code.  This is basically the advantage you get.  You achieve mapping by writing a few lines of code ( suppose both destination and source class has same properties).

There are  a few disadvantages such as performance and maintenance. First of all, adding a third party library makes maintenance more difficult since you will probably add some custom mapping rules and the library you use might have bugs that are hard to maintain. Secondly, as expected,  it will work slower than manual mapping.

So far in my projects  I've used  Automapper  I can tell, I am not really pleased with it.  Firstly, its usage has changed a lot as they published new versions. Secondly , its performance is really poor.

Recently , I've seen another mapping library Fastmapper.  Which is quite easy to use with its fluent api design  and its performance is very close to manual mapping. In terms of feature , it is not as rich as Automapper , but it works fine for simple property mapping. And in most of the applications, that is all you need.

 I've created a performance benchmark project to  see the result myself;

Here is the result ;



Actually,  you will probably never  map 100.000 objects from one  to another in an enterprise application. It is a very rare case.  Yet still, you should be aware of performance  of the tool/API/framework/library you are using.

Here's  the  source code of  the performance test project ;



//Customer Class
public class Customer
{
   public int Id { get; set; }
   public decimal Balance { get; set; }
   public string Name { get; set; }
   public string Surname { get; set; }
   public DateTime BirthDate { get; set; }
   public AddressInfo Address { get; set; }
   public List Accounts { get; set; }

   public Customer()
   {
      this.Address = new AddressInfo();
   }
}
public struct Account
{
   public int BankCode { get; set; }
   public int BranchCode { get; set; }
   public int Number { get; set; }
   public int AccountPostFix { get; set; }

   public override string ToString()
   {
      return string.Format("{0}-{1}-{2}-{3}", BankCode, BranchCode,
      Number, AccountPostFix);
   }
}
public class AddressInfo
{
   public string City { get; set; }
   public string District { get; set; }
   public string Street { get; set; }
   public int DoorNo { get; set; }
   public int ZipCode { get; set; }
}
//CustomerDTO Class
public class CustomerDto
{
   public int Id { get; set; }
   public decimal Balance { get; set; }
   public string Name { get; set; }
   public string Surname { get; set; }
   public DateTime BirthDate { get; set; }
   public string City { get; set; }
   public string District { get; set; }
   public string Street { get; set; }
   public int DoorNo { get; set; }
   public int ZipCode { get; set; }

   public List Accounts { get; set; }

   public static implicit operator CustomerDto(Customer customer)
   {
      CustomerDto customerDto = new CustomerDto();
      customerDto.Accounts = new List();

      foreach (Account account in customer.Accounts)
      customerDto.Accounts.Add(account.ToString());
      customerDto.Balance = customer.Balance;
      customerDto.BirthDate = customer.BirthDate;
      customerDto.City = customer.Address.City;
      customerDto.District = customer.Address.District;
      customerDto.DoorNo = customer.Address.DoorNo;
      customerDto.Id = customer.Id;
      customerDto.Name = customer.Name;
      customerDto.Street = customer.Address.Street;
      customerDto.Surname = customer.Surname;
      customerDto.ZipCode = customer.Address.ZipCode;

      return customerDto;
   }
}
...
...
//Manual Mapping
CustomerDto customerDto = new CustomerDto();
customerDto.Accounts = new List();

foreach (Account account in customer.Accounts)
customerDto.Accounts.Add(account.ToString());
customerDto.Balance = customer.Balance;
customerDto.BirthDate = customer.BirthDate;
customerDto.City = customer.Address.City;
customerDto.District = customer.Address.District;
customerDto.DoorNo = customer.Address.DoorNo;
customerDto.Id = customer.Id;
customerDto.Name = customer.Name;
customerDto.Street = customer.Address.Street;
customerDto.Surname = customer.Surname;
customerDto.ZipCode = customer.Address.ZipCode;

//Using Automapper
var config = new MapperConfiguration(cfg => cfg.CreateMap()
          .ForMember(dest => dest.City, opt => opt.MapFrom(src => src.Address.City))
          .ForMember(dest => dest.District, opt => opt.MapFrom(src => src.Address.District))
          .ForMember(dest => dest.DoorNo, opt => opt.MapFrom(src => src.Address.DoorNo))
          .ForMember(dest => dest.ZipCode, opt => opt.MapFrom(src => src.Address.ZipCode))
          .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street)));

var mapper = config.CreateMapper();
...
...
CustomerDto customerDto = mapper.Map(customer);
...
//Using FastMapper
TypeAdapterConfig
   .NewConfig()
   .MapFrom(dest => dest.City, src => src.Address.City)
   .MapFrom(dest => dest.District, src => src.Address.District)
   .MapFrom(dest => dest.DoorNo, src => src.Address.DoorNo)
   .MapFrom(dest => dest.ZipCode, src => src.Address.ZipCode)
   .MapFrom(dest => dest.Street, src => src.Address.Street);
...
...
CustomerDto customerDto = TypeAdapter.Adapt(customer);
...
..



Regards,

Monday, April 4, 2016

Executing MySql stored procedure by using Enterprise Library

Once I needed a simple data access layer class to execute simple db commands. And I've come up with a class that wraps  Enterprise Library  Data Application classes and makes it even easier to call for me. This is my implementation ;



/// 
/// Facade interface to data access class 
/// 
public interface IDatabaseFacade
{
   int ExecuteNonQuery(string spName, List<object> parameters);
}
...
...

public class DatabaseFacade : IDatabaseFacade
{
   private Database database;

   public DatabaseFacade()
   {
      DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(),false);
      this.database = DatabaseFactory.CreateDatabase();
   }

   public int ExecuteNonQuery(string spName, List<object>parameters)
   {
      using (DbCommand command = this.database.GetStoredProcCommand(spName, parameters.ToArray()))
      {
         return this.database.ExecuteNonQuery(command);
      }
   }
}

It is pretty straightforward. Sure it may have some design issues, i just implemented in hurry and used it right away and once it worked fine i didn't return back to it and checked my design. I've added this implementation to my tiny toolkit  to use it further.

This is just a simple class to execute a non-query store procedure.  Simple use is ;



DatabaseFacade dbFacade = new DatabaseFacade();
List<object> parameters = new List<object>()
{
   "Test",
   123,
   null,
   DateTime.Now,
   "Tester"
};
int result = dbFacade.ExecuteNonQuery("DbCommand_INS", parameters);


No need parameter name definition. You can just pass  stored procedure name with  parameters as a list of object. It worked fine. However, it turns out , this only works on Sql Server.  When i tried to execute mysql  stored procedure it produced following exception ;



System.NotSupportedException : Parameter discovery is not supported for connections using GenericDatabase. You must specify the parameters explicitly, or configure the connection to use a type deriving from Database that supports parameter discovery.

It seems that we cannot call MySql stored procedure without parameters.We have to pass them with names. So I had to pass parameters with their names. However, I didn't want to change my interface because the purpose of this implementation was to make data access as  simple as possible. So  I have changed the implementation of concrete class as following ;



public class DatabaseFacade : IDatabaseFacade
{
   private Database database;

   public DatabaseFacade()
   {
      DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);
      this.database = DatabaseFactory.CreateDatabase();
   }

   public int ExecuteNonQuery(string spName, List<object> parameters)
   {         
     if (database.DbProviderFactory is MySqlClientFactory)
     {
        string spStr = this.BuildMysqlSpString(spName, parameters);

        using (DbCommand command = this.database.GetSqlStringCommand(spStr))
        {
            DbCommand commandWithParameters = this.AddParameters(command, parameters);

            return this.database.ExecuteNonQuery(commandWithParameters);
        }
    }
    else {
       using (DbCommand command = this.database.GetStoredProcCommand(spName, parameters.ToArray()))
       {
          return this.database.ExecuteNonQuery(command);
       }
    }
   }
   #region MySql Functions
   private DbCommand AddParameters(DbCommand dbCommand, List<object> parameters)
   {
      for (int i = 0; i < parameters.Count; i++)
      {
         DbParameter parameter = dbCommand.CreateParameter();
         parameter.ParameterName = string.Format("@parameter{0}", i + 1);
         parameter.Value = parameters[i];

         dbCommand.Parameters.Add(parameter);
      }
      return dbCommand;
   }
   private string BuildMysqlSpString(string spName, List<object> parameters)
   {
      StringBuilder spBuilder = new StringBuilder();
      spBuilder.AppendFormat("call {0}(", spName);
      List dbParameters = new List();

      for (int i = 0; i < parameters.Count; i++)
      {
         spBuilder.AppendFormat("@parameter{0},", i + 1);
      }

      if (parameters.Count != 0)
         spBuilder.Length--;
      spBuilder.Append(")");

      return spBuilder.ToString();
   }
   #endregion
}


Design may look a bit ugly, yet it works for both MySql and Sql Server database ( haven't tested for others) , and you got the idea. To make it work for mysql , you have to build stored procedure call string and pass parameters with names.



Happy Coding!

Saturday, April 2, 2016

NLog Custom Target With Constructor Dependency Injection by using Autofac

Recently, I have decided to switch to NLog from log4net. Personally, I do prefer to implement my own  class(  appender/target  or whatever you call it) to  do the actual logging  and  i prefer to log to database with some session variables. After switching to NLog  I've implemented my own custom target as below;



[Target("AS.Custom.NLogTarget")]
public class NLogCustomTarget : Target
{
   private readonly ISessionContext _sessionContext;
   private readonly IDbContext _dbContext;

   public NLogCustomTarget(ISessionContext sessionContext, IDbContext dbContext)
   {
      this._sessionContext = sessionContext;
      this._dbContext = dbContext;
   }
   protected override void Write(LogEventInfo logEvent)
   {
      AppLog log = new AppLog();
      log.AppDomain = AppDomain.CurrentDomain.FriendlyName;
      log.ClientIP = this._sessionContext.ClientIP;
      log.Level = logEvent.Level.Name;
      log.LoggerName = logEvent.LoggerName;
      log.MachineName = Environment.MachineName;
      log.Message = logEvent.FormattedMessage;
      log.Username = this._sessionContext.UserName;

      this._dbContext.Set().Add(log);
      this._dbContext.SaveChanges();
   }
}

Here the registration ;


IContainer _container;
ContainerBuilder builder = new ContainerBuilder();
_container = builder.Build();
builder = new ContainerBuilder();
builder.RegisterType()
       .As()
       .InstancePerRequest();
builder.RegisterType()
       .As()
       .InstancePerRequest();
builder.RegisterType()
       .AsSelf()
       .InstancePerLifetimeScope();
builder.Update(_container);
....
As you can guess ISessionContext    is an interface to current HttpContext wrapper and IDbContext is interface to my current EntityFramework DbContext class. I will not get in detail to those since it is not the subject of this post.


Unfortunately , this configuration is not enough to get constructor injection working on  custom NLog target. The reason is , target class is created by NLog factory which has no information about the type registrations you have done or any information about your container. Luckily , NLog provides a delegate to setup your own instance creating method.

With  a simple dependency resolver interface and implementation over the great Autofac   IOC, i got it working.
Here is  my implementation ;


IDependencyResolver :



/// 
/// Simple interface to create a dependency resolver
/// 
public interface IDependencyResolver
{
    object GetService(Type serviceType);
}

My Custom Dependency Resolver Class:



public class ASAutofacDependencyResolver : IDependencyResolver
{
   private readonly IContainer _container;

   public ASAutofacDependencyResolver(IContainer container)
   {
      this._container = container;
   }

   public object GetService(Type serviceType)
   {
      return this.Scope().Resolve(serviceType);
   }
   private ILifetimeScope Scope()
   {
      try
      {
         if (HttpContext.Current != null)
            return AutofacDependencyResolver.Current.RequestLifetimeScope;
         return _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
      }
      catch (Exception)
      {
         return _container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
      }
   }
}

Configuration of logger:



public static class LoggingConfigurator
{
   private static readonly string NLogDefaultFileName = "NLog.config";
   private static IDependencyResolver _resolver;

   public static void SetResolver(IDependencyResolver resolver)
   {
      _resolver = resolver;
   }
   public static void ConfigureNLog()
   {
       ConfigurationItemFactory.Default.CreateInstance = (Type type) => _resolver.GetService(type);
       string path = AppDomain.CurrentDomain.BaseDirectory + NLogDefaultFileName;
       LogManager.Configuration = new XmlLoggingConfiguration(path, false);
   }
}
And we setup up the dependency resolver as below;


LoggingConfigurator.SetResolver(new ASAutofacDependencyResolver(_container));


That is it!

Monday, March 28, 2016

Problems With Abstraction over DI Container. a.k.a : Conforming Container

Recently , I've started to build a project by using onion architecture. And  I have followed  one of the basic principle of software  designing  that says  ;


 "Program to an interface, not an implementation"
which is quite accurate. However , I've lost at some point when i was designing my infrastructure layer. I came up with the idea of putting an abstraction over DI framework and designing top layers without them knowing which DI framework is used in application. Aim was in case i want to swap my DI framework , I could do it easily at Infrastucture layer by adding a concrete container implementation and activate it on runtime. One common container abstraction to rule them all!

At first it appeared quite logical to me , so I've made a researched on github if someone already done it and  I've found ;  LAN.Core.DependencyInjection .

This implementation was exactly  what i was looking for except that they didnt implement container for  Autofac  which i am currently using in my project. I added source codes to my project and made Autofac implementation myself. Everthing was great, so abstract!

Well, not really. Problems occured as your needs in your project grow. Autofac is quite rich framework in terms of functionality and it was so wrong to restrict it to a common abstract container. I ended up adding those functions up to the abstract container.It slowly turned into Autofac container itself!

As a result, I just removed that abstraction because it was going to be an abstraction on another abstraction which is not really good. And i was recently reading  Mark Seemanns  blog and I have seen my faul design there , which is described as an anti-pattern :  Conforming-Container

In summary ;  do not put abstraction over your DI framework and make it more complicated. It will create more problems than it solves. Just use DI framework as itself!

Regards,

Sunday, March 20, 2016

Internet Explorer Performance Tips

Recently at work,  I  was asked to develop an HTML Grid  to be replaced  with current Grid we do use in our web application. The reason was, the grid  we use was simply insufficent in terms of usability ( has lack of features )  , visuality ( had some visual problems in same cases and at some IE versions )  and extendability . Source code of  the existing  grid component  was poorly documented, badly coded and hard to understand. So I've decided  not to maintain existing grid component , develop a new one instead.
Long story short  ; I've found the amazing Datatables which is a jquery plugin that provides awesome, extendable and easy to use  html grid. After finished  developing the required grid ( that has custom filters, customized css , customized sorting and paging ...etc)  started to test it. It was working great on Chrome. However, it was extremely slow on Internet Explorer.
In my test ,  1.500 records of json data was bound to the HTML grid. It was taking 3-4 seconds for Chrome to render, while Internet Explorer was rendering it in about 50-55 seconds.
It was unacceptable.I knew IE's rendering performance was shit, but still  I wasn't expecting this kind of slow rendering.Since , in our company we use Internet Explorer as browser for our application, i had to work on the grid and optimize it for IE.

After searching performance killer function calls by using profiler , we made some fixes and could manage to make our grid render 1.500 records in 9-10 seconds on IE. It was still bad performance comparing to Chrome , but it was kinda acceptable.


TL DR; Here are tips

  • use  table-layout: fixed; If you rendering table , use  : 
    
    table-layout: fixed;
    
  • Avoid using  css class selector :    Class selector is an optimization killer for IE. Especially if the page is crowded in terms of DOM.  Better  select element by id , or  narrow down the element set.
For instance; 


$('.filter-row');// Bad performance 
$('#myTable .filter-row') ; //Better performance
$('#myTable #filterRow') ; // Much better performance
  • Use pure javascript instead of jquery functions :  No doubt, jquery is great. Makes javascript much easier and readable. However, this comes with a performance cost. Each jquery call is extra CPU cost for us. It is nothing big , but if you need to call a jquery function like 1500 times ( as in my tests) ,things get slow. If your priority is performance  better use pure javascript functions.
You can see it by yourself by using  IE Profiler.  In my case, i had function calls such as ;  html()  , wrapInner , addClass  and removeClass. After converting them to pure javascript calls , i got huge performance boost.

I would be glad to hear advices, tips or questions from you as well. Waiting for comments...