Thursday, October 28, 2010

A cool tool to rename your .Net project

Have you ever tried to rename your solution, project, namespace? If you have ten projects in your solution and you try to rename all projects and solutions, it will be nightmare for you. It’s a totally boring work. Once, I faced this scenario. My solution had 21 projects. Instead of renaming the projects , namespaces manually, I built a tool which did the work for me.

clip_image002

This tool is easy to use. Say, you have projects named; MyProject.DAL, MyProject.Buiness, MyProject.Common, MyProject.Model etc. You want to rename MyProject into HelloProject. In order to do this, write “HelloProject” onto new solution Name text box, “MyProject” onto Old Solution Name text box and locate the folder of your project.

Consider the following things while using this tool:

  • · Keep a backup project.
  • · You might get an error if you don’t have permission to rename each file and folder. In spite of getting error, you can open the rename solution. The tool should change the necessary files and folders.
  • · After opening the solution, clean it and rebuild it.

You can download the source code from here.

Happy Programming!

Wednesday, October 6, 2010

A generic Data Access Layer using ADO.Net entity framework for N-Tier application

If you work with ADO.Net, you know object context is mainly responsible to track changes of entity in an object graph. So, ADO.Net entity framework works fine as long as your entity is connected to object context. However, in N-Tier application/web application, the entity has to be disconnected from object context. In order to work with disconnected entity, entity framework doesn’t have any straight forward way before the entity framework team introduces self-tracking entities.

I have created a simple data access layer for disconnected entities using the self-tracking feature of Entity framework. The following code snippet shows generic implementation for CRUD operations:

public class MallInteractiveMapEntities2 : MallInteractiveMapEntities
    {
        private static Dictionary<string, Action<MallInteractiveMapEntities2, object>>
            _AddToMethodCache =
                new Dictionary<string, Action<MallInteractiveMapEntities2, object>>();

        public MallInteractiveMapEntities2():base()
        {
            if(_AddToMethodCache.Count == 0)
            {
                lock(_AddToMethodCache)
                {
                    _AddToMethodCache.Add(typeof (Mall).Name,
                                          (context, entity) => context.Malls.ApplyChanges(entity as Mall));
                    _AddToMethodCache.Add(typeof(Floor).Name,
                                          (context, entity) => context.Floors.ApplyChanges(entity as Floor));
                }
            }
        }

        public void AddTo<TEntity>(TEntity entity)
        {
            _AddToMethodCache[typeof(TEntity).Name](this, entity);
        }

        public bool ApplyChangesToEntity<TEntity>(TEntity entity) where TEntity : IObjectWithChangeTracker
        {
            try
            {
                AddTo<TEntity>(entity);
                SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }

public bool ApplyChangesToEntityList<TEntity>(IEnumerable<TEntity> entities) where TEntity : IObjectWithChangeTracker
        {
            try
            {
                entities.AsParallel().ForAll(AddTo);
                SaveChanges();
            }
            catch
            {
                return false;
            }
            return true;
        }
      
    }

MallInteractiveMapEntities class is generated from Entity framework designer for a specific database. MallInteractiveMapEntities2 class which is inherited from MallInteractiveMapEntities has some methods to perform the CRUD operations.

To illustrate the use of the above class, consider we have two entities named “Map” and “Floor”. “Floor” is the child of “Map” and the relation is one to many. In order to create(C) Map and Floor, use the following pseudo code.

  Mall mall = new Mall();
  mall.Name = "American Shopping Mall";

            Floor floor1 = new Floor();
            floor1.Name = "Ground Floor";
            mall.Floors.Add(floor1);

            Floor floor2 = new Floor();
            floor2.Name = "First Floor";
            mall.Floors.Add(floor2);


            using (MallInteractiveMapEntities2 context = new MallInteractiveMapEntities2())
            {
                context.ApplyChangesToEntity<Mall>(mall);
            }

When you instantiate an entity, it will be marked as an added state.

To update an entity with child entities, use the following pseudo code:

      Mall mall = new Mall();
      mall.Id = 1;
      mall.Name = "American Shopping Mall";
      mall.MarkAsModified();
 
      Floor floor1 = new Floor();
      floor1.Name = "Ground Floor";
      floor1.MallId = mall.Id;
      floor1.MarkAsModified();
      mall.Floors.Add(floor1);

      Floor floor2 = new Floor();
      Floor2.MallId = mall.Id;
      Floor2.MarkAsModified();
      floor2.Name = "First Floor";
      mall.Floors.Add(floor2);


      using (MallInteractiveMapEntities2 context = new MallInteractiveMapEntities2())
            {
                context.ApplyChangesToEntity<Mall>(mall);
            }


Here, you have to mark the entity as a modified state. You also have to set the parent id to a child entity.

To delete (D) an entity, simply mark each entity as a deleted by using the “MarkAsDeleted()” method.

Self tracking is a promising feature of Entity framework. By using this feature, you can create a data access layer for disconnected entity of ADO.Net entity framework.

Hope this help!

Be careful about using Session state of ASP.NET

As an ASP.NET developer, we always use session state whenever we need to keep something related to user. Usually, session’s data stays in memory. Now a day, memory is not very expensive. Since memory is not expensive, we like to keep something into session without thinking much about it. This thinking leads to a dangerous state of an asp.net project.

Recently, our team was profiling one of our asp.net applications. At the time of profiling, we figured out some CPU intensive operations. Among the CPU intensive operations, session serialization was very costly.

We are using ASP.NET state server for our session state. In order to keep an object into state server, the object has to be serialized. As mentioned before, serialization is very costly operation. The following are the thumb rules for me while using state server:

  • Always run and use state server at the time of development. In other words, never use InProc.
  • Until or unless you need anything to keep in session, don’t keep it.
  • If you need any user specific data which is costly to get and doesn’t change during the session time, keep that data in the static field. Keep in mind that for a web farm environment, each process has to initialize the static field.
  • Never use default serialization of .Net for large and heavy object. .Net default serialization uses reflection which is expensive. Implement custom serialization for such a scenario.
  • Don’t keep large object using a single key. If you don’t need the entire object at a time, splits the object. It will reduce the size of the object and reduce the de-serialization cost.

Happy Programming!

Tuesday, August 17, 2010

WPF calendar control for touch screen application

If you are looking for WPF calendar control, you will get many over the internet. However, none of the calendar control is friendly for touch screen application. If you use any third party touch application framework such as “breezmultitouch”, you will not be able to get all the complex event of WPF built-in controls. For this reason, WPF built-in calendar control is not suitable for touch screen application.

The following screen shot shows a calendar control which is totally touches friendly. Its basic behavior is similar to Windows OS’s calendar control. All features of calendar control are managed by Button and RadionButton control. Both of these controls are very friendly for touch screen application.


There is nothing complicated in the implementation of the calendar control. Most of the implementation is easy to read. You can easily use this control by just referencing the WpfCustomControlCalendar project or you can copy the source of the control to any of your own project.

You can download the complete source code from here.

Hope this Help!


Monday, August 2, 2010

PhotoViewer Application in WPF

For one of my touch applications, I was looking for a photo viewer control. After googling sometime, I got a few photo viewers. However, none of the viewer seems good for touch application. Eventually, I tried to develop a photo viewer control by myself. The control will work with non-touch application too. I am uploading the non-touch version here.

The photo viewer control will load a collection of photos as a thumbnail and will display a photo depending on the selection from thumbnail. The user can navigate in collection by two buttons. The following image shows the appearance of the photo viewer control.



The development of the control is plain and simple. You can use this control by minimum effort. You need to set the path of the photo directory in the load event of PhotoStack class.

You can download the source code from here.

Hope this help!

Sunday, May 9, 2010

Set ValidationGroup for DateTimeControl of Sharepoint

Sharepoint has enough built-in controls to develop custom application for it. It is wise to use sharepoint’s controls for sharepoint application. It gives you the flexibility to get same look and feel of sharepoint.

Once I needed a date time picker for one my sharepoint application. I looked for it into sharepoint control library and immediately got it. The date time picker of sharepoint is intuitive to use.

However, it has limitation. It has a built-in required field validation control. Unfortunately, you cannot set the ValidationGroup for the built-in validation control what is really annoying. Most of our real life scenarios, we had to set the validationGroup. The following code snippet shows a way to set validationGroup:

public class CusDateTimeControl : DateTimeControl
{
public CusDateTimeControl (string validationGroup)
{
ValidationGroup = validationGroup;
}
private string ValidationGroup { get; set; }

protected override void CreateChildControls()
{
base.CreateChildControls();
//Set validationgroup name.
m_validatorRequired.ValidationGroup = ValidationGroup;
}

}
The above code snippet is very plain and simple. It just inherits from DateTimeControl . The DateTimeControl class has a protected member (m_validatorRequired) for required field validation. Set the validationGroup of "m_validatorRequired" inside "CreateChildControl" method.

Hope this help!