Get rid of the “Manager” syndrome.

February 1, 2010 by codingcraft

Are you one of those coders who often find themselves stuck on deciding a meaningful, explanatory name for their newly created classes? Do you frequently end up creating some “Manager” or “Master” class? If so, then beware! There is something wrong going in there with the vision and perception of your classes. Perhaps, you are asking your nice little classes to do too many things for you; they probably are losing their focus and are perplexed about their existance. Perhaps, you burden these poor fellows with too many responsibilities.

Is anything wrong about having a class to do more than one thing? Well, the Single Responsibility Principle (SRP) says “Yes” there is.

Consider the following class:

  GiveMeName
{
public void Save(Employee emp){…}
public List Get(){…}
public double CalculateGross(double basic){…}
public void NotifyEmployee(Employee emp){…}
}
 

This is the what the class does for you:

1. Saves the newly created employee object to the database,

2. gets the list of employees in the database,

3. calculates the Gross from the basic using the business rule,

4. Sends email Notifications to the employees.

Now if you were to give a meaningful, unambiguous and self-explanatory name to the class GiveMeName, what would you name it? Well, confusing … isn’t it?  The confusion is a very good indicator of the fact that we are doing something unfair to the class here. We are making the poor guy cater to too many responsibilities.  I bet the best name you can think (like me) would be Employee or EmployeeManager. This is where we lose the trick.

Try breaking the GiveMeName class into three small classes:

  EmployeeDb
{
public void Save(Employee emp){…}
public List Get(){…}
}
 
  EmployeeGrossCalculator
{
double Calculate(double basic);
}
 
  EmployeeNotifier
{
public void Notify();
}
 

These classes are much more focused and their names are beautifully self-explanatory and suggestive of their purpose and meaning of existence. They tell you why were they born and why do they exist. Thus there would be one and only reason for any of these classes to change, for, there is one and only one responsibility these classes cater. This will ensure Orthogonal code and hence maintainability of your code. It will help your code to stay closer to universal principle of programming - Tight Cohesion and Loose Coupleing.

So next time when you create a class and find that it’s name doesn’t come obviously to you, and you have to satisfy yourself with some “Manager” kind of name with your class, think twice, think if you have taken a leaf out of the book of SRP.

Test Driven Development

February 1, 2010 by codingcraft

As a software developer I always found it very embarrassing to face the truth that my code is also entitled to have its share of bugs. I would find it so very irritating when I have worked passionately for hours to build something and a tester would walk-in with a sheet in hand and suggest “hey bro! You missed out”. I might argue with him but deep down inside I would know the fact that I have indeed “missed out” on something. This is one embarrassment we developers go through all the time but it is only us who could be blamed for this. We don’t think enough before jumping into the code.

There have been so many instances where I have felt like rewriting a piece of code which has become ugly over a period. These code would smell. But my boss would silence my itch with a question that “why would you want to finger something which is up and running?”.

While these problems had become a way of life for me, I came across a refreshing way of software development – Test Driven Development (TDD). TDD is a process pattern for constructing iterations of development projects that employ unit testing. It is a core tenet of “Agile Development”, specifically the Extreme Programming (XP) camp. Unlike the conventional approach to software development where coding is followed by testing, TDD requires to have the tests in place before writing any code. These test-cases serve as the specification and scope for the functionality to be provided.

TDD Life cycle

Add a test: Add a new test. The test must fail for the first time as because the test must be created before any the functionality itself.

Run the test: The test must fail for the first time.

Write code: Write code to develop the functionality.

Run the test again: All the test written for the functionality must pass indicating that all specifications have been met. If not, refactor the code until all the tests pass.

TDD requires developers to think and think hard about specification and scope of the functionality to be developed before writing any code. This ensures that a good deal of brain storming going into understanding the problem before making any efforts to solve it.
Refactoring code is a risky affair because you can always run into this risk of “breaking something while making something”. Having unit-tests in place gives developers the cushion to refactor code confidently. After making the code change the developer can simply run the automated test and to ensure that everything is alright.

Coding for testability demands a much more civilized design to be in place. The code must have “Separation of Concerns” clearly defined. It must be orthogonal. It must follow “Dependency Inversion” Principal. A code not easily testable simply suggests a flaw in the design.

As a newbie, I found writing TDD a little time consuming and cumbersome. But as I get more and more used to it I can really see an increase in my productivity and improvement in the quality of code that I write. The benefit that I reap by investing a little extra time is huge. It’s definitely worth a shot.

Parse Shapefile using SharpMap

December 2, 2009 by codingcraft

Our current project required us to read Shapefile and import the shape (from .shp file) and data (from .dbf file) from the same. We investigated into quite a few tools having the ability to parse a shape file and import the shape (also called Geometries) along with the data into the database. These tools were either not up to the mark or pretty costly. This is when I came across SharpMap which did the trick for us.  

SharpMap is an easy-to-use mapping library for use in web and desktop applications. It is an open source under GNU Lesser General license.  

Download and import the SharpMap dll  

 You can download the SharpMap dll from here. Import the compiled dll into the application by browsing downloaded location.  

Write code to import Shapefile data 

    
ShapeFileProvider sf = null;
sf = new ShapeFileProvider(filePath);
sf.Open(false);
BoundingBox ext = sf.GetExtents();
FeatureDataSet ds = new FeatureDataSet();
sf.ExecuteIntersectionQuery(ext, ds);
FeatureDataTable<uint> table = ds.Tables[0]
as FeatureDataTable<uint>//TODO:
//Read the .dbf data from the row.

foreach (FeatureDataRow row in table.Rows)
{
   Polygon polygon = row.Geometry
          as SharpMap.Geometries.Polygon;
   if(polygon != null)
  {
     foreach (var vertex in polygon.ExteriorRing.Vertices)
     {
        double latitude = vertex.Y;
        double longitude = vertex.X;

        //TODO:
        //Import to to the database.
     }
   }
}

 

 

You can write a program which would run once and import all the shapefile data into your database schema. You will, thus, have all the data to play at will. Try it out.

Draggable Popup with Silverlight 3

December 1, 2009 by codingcraft

As an Asp.net developer, I always liked the AJAX Modal Popup Extenders and used it extensively. As I move into RIA technologies with Silverlight 3, I find that the out-of-the-box popup control does not have the drag feature. To me, this is not good because more often than not we would like such Popups to be drag-enabled. A little bit of work around was all it took to make this popup drag-enabled. Thought it is worth sharing …

XAML:


<Popup Name="pop" Width="150" Height="200" >
   <StackPanel
       Name="stkPopup"
       Width="150"
       Height="200"
       Background="Gray"
       MouseLeftButtonDown="MouseDown"
       MouseMove="MouseMove"
       MouseLeftButtonUp="MouseUp">
          <StackPanel
             Width="150"
             Height="18"
             Background="Blue" >
              <TextBlock
                 FontSize="14"
                 Width="100" >
                    Infomation
              </TextBlock>
          </StackPanel>
          <TextBlock>
             DATA: my data.
          </TextBlock>
          <Button
             x:Name="btnClose"
             Click="btnClose_Click"
             Height="15"
             Width="15"/>
   </StackPanel>
</Popup
>

C# Code:


private void MouseDown(object sender, MouseButtonEventArgs e)
{
   Popup item = (sender as StackPanel).Parent as Popup;
   mouseY = e.GetPosition(null).Y;
   mouseX = e.GetPosition(null).X;
   isMouseCaptured = true;
   (item.Child as StackPanel).CaptureMouse();
}

private void MouseMove(object sender, MouseEventArgs e)
{
   Popup item = (sender as StackPanel).Parent as Popup;
   if (isMouseCaptured)
   {
      double deltaV = e.GetPosition(null).Y - mouseY;
      double deltaH = e.GetPosition(null).X - mouseX;
      double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
      double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);
      item.SetValue(Canvas.TopProperty, newTop);
      item.SetValue(Canvas.LeftProperty, newLeft);
      mouseY = e.GetPosition(null).Y;
      mouseX = e.GetPosition(null).X;
   }
}

private void MouseUp(object sender, MouseButtonEventArgs e)
{
   Popup item = (sender as StackPanel).Parent as Popup;
   isMouseCaptured = false;
   (item.Child as StackPanel).ReleaseMouseCapture();
   mouseY = -1;
   mouseX = -1;
}

This sufficed my need for now. But going ahead, I am planning to make it truly “Modal” and package into a reusable user control. But that’s for the next post. Till then … happy coding.

Bing Map Silverlight Control Released

November 23, 2009 by codingcraft

I had been playing around with the Bing Map Silverlight Control CPT for quite sometime now and was really thrilled to find out that it has finally been released. Great news for all the MS developers who wanted to get rid of the pain of coding JavaScript to integrate Maps to their application. The control leverages the power and richness of Silverlight technology. The interactive SDK looks really cool. Microsoft can really make a big impact on the GIS front with the Bing Map Silverlight Control.

There is, however, a point concern. Microsoft has altered the Terms and conditions for usage. Here is a list of some of the features in the Bing Maps Silverlight Control v1.0:

• Silverlight 3 enabled,
• Position Silverlight UIElements on the Map,
• Data Binding with the MapItemsControl,
Bing Maps Web Services support,
• World Wrap / infinite pan across the dateline,
• Design-time integration with Expression Blend,
• Scripting interface for coding with JavaScript,
• cool Online Interactive SDK.

Here are some useful links to try out the new Bing Maps Silverlight Control:

Download Bing Maps Silverlight Control
Bing Maps Silverlight Control Interactive SDK
Bing Maps Silverlight Control SDK
Bing Maps Account Center

Hope this was useful.

The page you are requesting cannot be served because of the extension configuration

October 23, 2009 by codingcraft

Recently, I migrated to Windows 7 and ended up installing all my software’s again. I had a project which involved hosting a WCF service on IIS. The service used a .svc file extension and IIS 7 on my machine was not aware how to handle these files.

The error I got looked something like this:

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Detailed Error InformationModule StaticFileModule.

There were more errors related to local machine below these errors.I looked up the net and after some digging figured out the solution to the problem:

1. Run Visual Studio 2008 Command Prompt as “Administrator”.
2. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation.
3. Run this command servicemodelreg –i.
The servicemodelreg is a command line tool which provides the ability to manage the registration on ServiceModel on a machine.

Hope this hepls. Happy programming.