Quote


A good programmer is a lazy programmer, because he writes minimum code.
--Anonymous


Showing posts with label Microsoft. Show all posts
Showing posts with label Microsoft. Show all posts

Thursday, April 1, 2010

Singleton to Read Configuration

Friends,

When we first learned the basics of coding, we are told that simple code is the best code. We believed if for a long time, and went extra mile to make the code simpler. Then came the Design Patterns, the new excuse for making code complicated. Earlier we used two lines of code to instantiate an object, but now we are using four classes for the same purpose.

Having said that, design patterns are useless things? Not at all. Those are handy, when you need to solve a real problem in a standard way. Say, connecting with multiple databases or need to make sure only one instance of an object exists at any given point of time. The problem is design patterns are more abused than used. A DP used just to show cause the knowledge of the architect or programmer.

Recently, one of my friends came to me with a problem and together we solved it by using Singleton pattern.The scenario is like this. We are storing some application settings in an external XML file (don't ask me why we are not using web.config. There are many reasons). We need to read these settings from the XML file at the start of a cycle. These settings are used at different stages of the cycle. Also, one cycle is completed by calling different methods of different classes.

We have decided to use a Config class, to read from XML file. In the constructor of this class, we will write code to read from XML. We will add a few properties to this class, to expose the settings in XML. We will declare this class at class level (as private) and instantiate this class at the start of a cycle. We will need to pass this class to methods of other classes, which are called during the cycle. Good, no?

But after designing it, we didn't feel it is satisfactory. Why should it be declared as private? Why should it be carried as a baggage around different classes? Isn't there a better way?

Then the idea of Singleton came to our minds. (I don't remember who thought it first). We can make the Config class a Singleton. So no need to declare it as private. No need to carry it across classes. We can call it whenever we needed and only once the constructor will be executed. So, only once the setting will be read from XML file. Cool.

So the first step would be to make a singleton class.


namespace ConfigTest
{
    public class Config
    {
        private static Config instance;

        private Config()
        {
 
        }

        public static Config Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Config();
                }
                return instance;
            }
        }
    }
}

Please note that the constructor is private.

Now add the properties to expose the settings. For brevity, let's assume there are three settings, viz ServerName, UserName and Password. See the XML file.


<Configurations>
  <configuration>
    <ServerName>MyServer<ServerName>
    <UserName>user<UserName>
    <Password>password<Password>
  <configuration>
<Configurations>


Now we need to add three properties to expose these settings.


       public string ServerName
        {
            get
            {
                return serverName;
            }
        }

        public string UserName
        {
            get
            {
                return userName;
            }
        }

        public string Password
        {
            get
            {
                return password;
            }
        }
Three private variables serverName, userName and password are declared. What we do now is add the code in constructor to read from XML.Please find below the new constructor code.


         private Config()
        {
            XElement xml = XElement.Load("Config.xml");
           
            serverName = xml.Elements("configuration").
                        First().Element("ServerName").Value;
            userName = xml.Elements("configuration").
                        First().Element("UserName").Value;
            password = xml.Elements("configuration").
                        First().Element("Password").Value;
        }


We are done with the code. It is ready to execute. Now how can we call this Config class from our main class? It is easy. The following code shows how to display the settings from a Windows form.


            MessageBox.Show(Config.Instance.ServerName);
            MessageBox.Show(Config.Instance.UserName);
            MessageBox.Show(Config.Instance.Password);


When the first message box is executed, the details will be read from the XML file. During the consecutive executions, it just displays the property values. But what if we need to re-read from XML file? For example, before the start of next cycle, we need to refresh the settings. So we have added a new method to Config class, to refresh the settings.


        public void Refresh()
        {
            instance = new Config();
        }

That's all friends. If you interested to view the class diagram of our class, here it is.


















Hope this will help some one. You can download the entire solution here.

Thanks.

Monday, January 18, 2010

Exception Handling Blunders

When I do code review, one area I give at most care is the Exception Handling. There are two reasons for this.
  1. Exception handling is the least tested area in the code.
  2. Problems here can give you a few sleepless nights, after the application is moved to production.
If you Google, you will find thousands of links to good practices in exception handling. I am not going repeat all those. However, I will explain a few blunders found in exception handling.

One of the blunders done by the programmers is blank exception handler. See this










Whenever an exception is thrown from this code, it is simply suppressed. Remember, it is not far from now users come with a functionality is not working, and you are left clueless. No idea what happened. And if the users say, the problem happens randomly, you can be sure some thing wrong in exception handlers. What to do then? Simply replace the blank Exception handler with some code to catch and log the exception and move it to production. No other way. Then why don't you do it while you first code?

Here is the second blunder.








Well, here you are showing a user friendly message to the user. No need to worry about security aspects. Your password will not be shown to the user. Neither the database object names. But what happens when you need to fix this issue? What are you going to do with "Functionality not working"? Is it network issue or some one stopped the database? No way to find out.

Why programmers make such mistakes? After all, IT companies hire best people for their work. The answer is simple. The programmers are overconfident that their code will never break. So, they don't give much importance to the exception handlers. It is just done for the sake of coding standards.

Here is the third blunder.












(I have even seen Throw New Exception(ex.Message). But that is a different story). What's wrong here? You are just throwing the exception you got. The code will work the same way if the Exception handler were non existing. That's all? No.

Imagine, Inside SomeMethod another method is called (Say Method1). From this Method, another method, Method2, is called. Method1 and Method2 don't have exception handlers. Then one exception is thrown from Method2. It will be cascaded to the Exception handler in MyMethod (shown above). Then from catch block, a new exception is thrown. Remember the actual exception is happened in Method2, but in the logs you will find that it happened in MyMethod. Just remember this simple piece of misinformation can delay a problem fix for a few days, if it happened in an area you have least access, that is in production.

Here is the last one.










Wondering what's wrong here? I accept this the most intelligent one among the exception handlers listed so far. But here also we can improve.
  1. The message is shown to the user. Are you expecting the users to call you and inform you each time such a message is seen? Or will they keep a notepad to write down every strange messages they see? Oh! they have more important things to do. So, add a logging to the Exception Handlers. Use log4net, Enterprise Library or whatever you like, but add logging.
  2. What if you get a message "Object reference not set to an instance of an object."? No idea where it happened, among thousands of lines of code. You need to log the Exception.StackTrace as well. You need to log Exception.Message and Exception.StackTrace. There is an easy way. You can log Exception.ToString, which encompasses Message, StackTrace and even details of inner exceptions.
  3. Showing the actual exception message to the user may be risky at times. Who knows the message contains your credit card numbers or passwords? There is a high possibility error message contains database object names, which can make a hackers job easy. So, my advice is log the entire exception details and show the user a friendly message.
So, how can be the right one here? See below.


That's all for time being. Hope this will help some one to fix the production issues faster.

Thanks.


Friday, October 9, 2009

Minimize to save memory

Does Minimizing a Windows application reduce memory usage? So says this blog. An interesting piece of information. "In any multitasking system, minimizing an application means that it won't be utilized by the user right now. Therefore, the OS automatically makes the application use virtual memory and keeps bare minimum amounts of the code in physical RAM.". Wondering how I missed this information so far. But I don't think the OS is doing the trick. A few applications (for example, Mozilla Firefox) exhibited no change in memory usage when minimized. So it would be the application, which is playing the trick.

Thanks man.


Tuesday, September 22, 2009

Microsoft Comes To Your Town

Hi Friends,

Microsoft Community Techdays are back. It is a great way to get updates on latest technology. For registration goto http://www.communitytechdays.com/

Thanks.


Sunday, September 13, 2009

Microsoft Excel 2003 to Excel 2007 mapper

Hi Friends,

Recently our company upgraded to Excel 2007 in all its machines. While we enjoyed the cool new look and features, it has a downside. People who were experts till yesterday, became novices today. Most of the time spent for searching menus or toolbar shortcuts, which we already know in Excel 2003.

But Microsoft didn't let us down. They have come up with a Reference guide for Excel 2003 users. Here it covers most popular commands. If you need full list of commands, you can download an excel sheet here.

Interesting? Enjoy.


Thursday, September 3, 2009

Open source is bug free?

I was thinking that Microsoft programs are buggy and open source programs are bug free, Until I read this blog by Steve Bellovin, one of the pioneers of Internet security.

Especially, read the last paragraph. Kudos to Microsoft, for making their programs more robust.

Thanks,


Sunday, August 30, 2009

Power Toys!!

Hi Friends,

I don't remember exactly when I heard about Microsoft Power Toys for Windows XP. I remember it was during work. If I come across interesting links or freewares at work, I will forward those links to my personal email, so that I can try those at home. When I checked my email today I found the link to Power Toys.

What I liked most is the Alt-Tab Replacement. Install this tool, and then if you press Alt+Tab, instead of usual boring switch tasks screen, you will get a more elegant window with preview of windows to switch. Try it, you will sure like it.

There are other interesting tools, too. A power calculator, Image Resizer, CD slide show creator, etc. I haven't tried all. I have installed the Virtual Desktop manager, but not sure how to use it. Still trying it.

Here is the link to download Power Toys - http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx

See a screenshot of Alt-Tab Replacement.



Download and enjoy.