Naveen's Weblog

Bridge to future

Get all controls on a windows form without recursion

Posted by codingsense on July 22, 2010

Hi,

Its given in microsoft patterns and practices to consider replacing recursion with looping because each recursive call adds data to the stack. Examine your code and see if your recursive calls can be converted to a looping equivalent.

I was wondering if all the solutions that uses recursion can be replaced without using recursion.
So I took the first step in looking into my project and found a piece of code that was using recursion, a function that would give me all the controls on a windows form. So I decided trying to convert that code without the use of recursive call.

Here is what I came up with,



static IList getControls(Control ParentControl)
{
List<Control> ListOfControls = new List<Control>();
List<Control> ContainerControls = new List<Control>();
ContainerControls.Add(ParentControl);

while (ContainerControls.Count > 0)
{
foreach (Control control in ContainerControls[0].Controls)
{
if (control.Controls.Count > 0)
{
ContainerControls.Add(control);
}
ListOfControls.Add(control);
}
ContainerControls.Remove(ContainerControls[0]);
}
return ListOfControls;
}

Great, the method gave me proper result as compared with the recursive function, what next I wanted to see how it has increased in performance and I used stopwatch to determine the time taken by both of the methods on the same form which was heavily loaded with controls and containers, it had 82 controls on it. The time taken by recursive function was double the time taken by the new method.

So I concluded that replacing recursive method with looping will enhance performance and also helps in consuming less memory.

If you get a better way to overcome recursion then please feel free to comment, till then I will continue my search for more recursive calls in my code.

Happy Learning :)
Codingsense

Posted in C# | Tagged: , | Leave a Comment »

The module “D:\..\support files\..\abc.dll” was loaded but the call to DllRegisterServer failed with error code 0×80020009.

Posted by codingsense on July 1, 2010


Hi,

While registering a com dll using RegSvr32 I encountered the following problem in Windows 7

Problem:
The moduleThe module “D:\..\support files\..\abc.dll” was loaded but the call to DllRegisterServer failed with error code 0×80020009.
For more information about this problem, search online using the error code as a search term.

Solution:
1) I opened command prompt in administrator mode. ( Always open the cmd.exe in administrator mode while registring a dll in Vista or Win 7, Steps – Type cmd in search box, when cmd is listed in the above list, right click it and click open as administrator)
2) The folder “Support files” was having a space so it failed to locate it. I navigated to the support files and then used regsvr32 command and all worked fine :)

Happy Learning,
CodingSense

Posted in Errors | 1 Comment »

Writing Custom FxCop Rules

Posted by codingsense on May 23, 2010

FxCop is a static analysis tool that you can use to write custom rules those need to be followed by the developers. Writing custom rules in FxCop is very easy, in the beginning you will feel it bit complex since there are no much help available on web but once if you have written a rule you will be preety much confident that you can write any rule you desire.

Download FxCop

SInce FxCop analyses IL code from your assemblies, we should know about some of the keywords of IL to write complex rules. Use this sheet as a reference while seeing your IL code through ILDASM.

I have created a template project for Custom FxCop Rules for you which you can use and add your rules. So that you can concentrate more on Custom Rules rather than creating the project.

Download CustomFxCopRules template

If you want to add any new rule you have to follow these steps using the above template.

  1. Create a class and name it with the rule.
  2. Create a new node of that of the classname (not necessary but only for easier reference) in CustomRules.xml with desired settings
  3. Create a constant with the same name and value in Constants.resx file
  4. Write your logic in that class

And to debug the rules that you have written here is a post
http://social.msdn.microsoft.com/forums/en-US/vstscode/thread/b92a0416-bf20-40c1-88a0-8fcff07133dc/

More References:
http://www.binarycoder.net/fxcop/pdf/fxcop.pdfhttp://www.binarycoder.net/fxcop/pdf/fxcop.pdf
http://www.nmentor.com/Blog/Tutorials/1.%20How%20to%20Write%20Custom%20FxCop%20Rule.pdf

I will put some of the custom rules in coming post which willl cover all the required topics to make you understand FxCop better. If you want any specific rule, then feel free to post a comment to me and I will help you out :)

Happy Learning
Codingsense :)

Posted in C# | Tagged: | Leave a Comment »

Why and how use comments effectively

Posted by codingsense on May 22, 2010

A code is said to be good by the quality of comments it contains. A code with good quality of comments will save a lot of time and help to understand the code quick and better and while maintaining software and avoid regression bugs. Many products and companies do not strictly follow writing of comments in the product. So if your product has no comments or little then start writing the proper comments.

We should have Comments for

  1. Classes
    • What does the class do?
    • Which other classes are used by it?
  2. Methods
    • What does the method do?
    • What are the inputs and return type?
    • What changes to the system is done by that method (if it is updating a database or xml file or a static variable of some other class etc)
  3. Comment Complex lines
    • Emphasis more on why the below line is required than what the below line does (e.g. assume the scenario in which we are iterating a list and we are incrementing the List index by one, instead of writing the obvious “Increment the index by one” write “move to the next element in the list by incrementing the index by one”)
    • Write comments to only the lines which are not obvious. Comments will be required majorly for algorithms or if it’s changing the behavior of a system.
  4. Give appropriate names to variables and Methods
    • Giving proper names to variables and methods for what it does help to understand the obvious lines much better, avoid comments for such lines. Like if I have a variable named hasOperationFailed, by just looking it I can be sure that it’s a Boolean fields and while checking the conditions like If(hasOperationFailed) makes me understand what condition am I checking.
  5. Read the comment twice after writing
    • This may seem to waste time but trust me, after reading the written comment again we tend to re write the lines many times. Since the value of comments can only be said by the reader who uses it. So if the lines are simple to understand and appropriate then your efforts will be considered.

There are software’s that fetches the comments from your code and gives the output in different formats so that you can verify your comments and it can be used as a guide for what your classes and methods does.
Here are the list of some

Other references:
http://www.codeproject.com/KB/XML/csharpcodedocumentation.aspx?msg=1679454

Happy learning,
Codingsense :)

Posted in Solutions | Tagged: | 1 Comment »

Steps to improve maintainability of your code

Posted by codingsense on May 13, 2010

Hi,

I have seen people always telling that maintaining a product is harder. All people want to go into the product or module where its building from the scratch and pass the older code to our juniors. Why?? Is it that we want to learn new things or we don’t want to waste time in the product where we have put lots of effort to ruin it or are we afraid??

Is there any easy way to convert bad code to good code. Its not like moving a magic wand and all code is straight. First of all we should accept that its our mistake, unless we accept our mistake we keep giving hundreds of reasons to run away from it. We should have interest in making it good, plan properly and execute with determination. Here’s my story wherein I have gone through phases from good to bad and bad to good.

Two years back in Feb 2008 I started a product and was playing a role of tech lead. There were lots of eyes and concerns on that product that it will be a game changer for our company. There was a long list of feature given by our functional team, plan to combine 2 existing product functionality into one, easy navigation, and the old saying was repeated “URGENT REQUIREMENT” we were given 1 year for the first product release. So it began, planning of modules, prioritizing the features, coding standards was revisited, right features were assigned to right persons etc etc. Full team was motivated to work in the upcoming successful product.

Days passed… somewhere after 6 months an internal release was planned for the functional team and for the stakeholders. Great all were happy, I and my team got many awards, good recognition in the company and got some suggestions (also known as changes) in the software. All changes were incorporated successfully with the new features parallel development.

All was going great, until after some 5 months (1 month left for delivery) some expert gave (very late) a very good suggestion to the management for future perspective. When we received the document of changes they were huge, major changes had to be done in many of the key classes. All teammates were sort of disappointed that their feature which was done with lot of hard work and interest would be corrupted. They started blaming the management, for such changes. But all cooperated since we were the experts and it would be shame to go against the changes expected.

Now started the actual impact, changes were planned, one change would affects other flow, dependency between the classes was more, poor commented code, testers started doing stress testing on the bug tracking tool by putting more and more bugs in it.All team was under stress, daily pig meetings were started to know the status. Day by day the deadlines were nearing and the features and bugs were poured more on us.

Finally we ended up not giving the full product in the expected deadline. The days of the awards and recognition were gone. For next week I and some senior members were very busy in answering what went wrong and why we dint reach the target. Since there was intense pressure from the marketing team the product was shipped to the customers who were waiting for it. There were still more changes pitching in and we were very much tensed how to incorporate those without creating regression bugs in our product. Many bugs were reported by the customer and fixing them was a huge task for us.

On one evening was not feeling to go home so stayed till night I thougth that I and my team were responsible for the bad code and we are the one going to fix those and show our potential. I started recollecting all the mistakes that were done by me and my team and started documenting it, further found some tips across the web and added those. After analyzing the entire problem I found angle of deviation that we had been from our actual goal and plans and listed all the faults that we had done. Made up my mind to speak to the management in the early morning regarding it and get some time to refactor and restructure the code. The following steps were planned to be executed with intense care.

  • Put proper comments
  • Fix coding standards and project conventions
  • Remove unnecessary code
  • Identifying and breaking up big classes
  • Breaking up big methods
  • Refactor existing code
  • Remove memory leaks
  • Restructuring
  • Write automated unit tests

After following each step properly with collecting the daily status from the team, sharing the problems and discussing some new solutions, finally it took around 7 months to complete the product.
Even though we were late by 8 months we had reached the goal properly and were ready to accept any further changes. From last year the product was sent to the market and there was very good response from our customers and the days of awards had begun again.
From next posts I am planning to go in depth of execution of each of the steps followed.

For any clarification please revert back.

Happy Coding
Naveen Prabhu :)

Posted in C#, Solutions | Tagged: , , | Leave a Comment »

Why Avoid Exception

Posted by codingsense on March 16, 2010

Hi,

Last week I was optimizing a module, as I was working I found that if exceptions are avoided then we can save lot of fruitful time. So made the below sample to see how much time we can save by avoiding an exception.

In below sample a method just iterates and another method throws an exception.




using System;

namespace ConsoleApplication1
{
class Program    
{
static void Main(string[] args)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

sw.Start();
loopProper();
sw.Stop();
Console.WriteLine("Looping Time : " + sw.ElapsedMilliseconds);

sw.Reset();
sw.Start();
ThrowException();
sw.Stop();
Console.WriteLine("Exception not hanlded Time : " + sw.ElapsedMilliseconds);

Console.Read();
}

static void loopProper()
{
for (long Index = 0; Index < 350000; Index++)
{

}
}

static void ThrowException()
{
long Temp = 0;
long Zero = 0;

try            
{
Temp = Temp / Zero;
}
catch (ArithmeticException ex)
{

}
}
}
}



After running the above sample we can find that an time taken by just one exception is approx around time taken by 3,50,000 iterations. So if we can avoid exceptions then we can do more fruitful work in the same time.

I dont mean that exception handling should not be used, but try to avoid it to maximum. If you can use some if conditions where you know the line might give an exception, and see how the performance increases.

Any about my output, the module had a algorithm that would take 80-85 sec to complete and after optimization its taking 2 sec to complete. Changes in logic of the algorithm and exception handling increased the performance drastically.

Happy learning,
Codingsense :)

Posted in C# | Leave a Comment »

Aborting a suspended thread

Posted by codingsense on March 16, 2010

Hi,

I was working on a multithreading application and found an interesting thing on resuming a thread, so planned to share with you.

When a thread is running if we abort it, it gets stopped. But if a suspended thread is aborted then it gives an exception “Thread is suspended; attempting to abort”.

The below sample demonstrates it, first the thread is started, then suspended and then aborted. Run the application and check the error.




using System;
using System.Threading;

namespace ConsoleApplication1
{
class Program    
{
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(DoSomething));
thread.Start();

for (int Index = 0; Index < 10; Index++)
{
switch (Index)
{
case 4:
thread.Suspend();
Console.WriteLine("Thread suspended");
break;

case 6:
thread.Abort();
Console.WriteLine("Thread aborted");
break;

}

//Main Thread is made to sleep                
Thread.Sleep(300);
}

Console.Read();
}

private static void DoSomething()
{
while (true)
{
Thread.Sleep(300);
Console.WriteLine("I am busy doing work");
}
}
}
}


To overcome this exception we can use Resume to invoke the suspended thread and then abort.
Replace the case 6 with below code snippet.




case 6:
try                        
{
thread.Abort();
}
catch (ThreadStateException)
{
thread.Resume();
}
Console.WriteLine("Thread aborted");
break;


now running the application aborts the thread as expected.
From this sample we can learn that if we use resume on a suspended thread then it starts again, but if we have signalled for abort on that thread and try resume then it will stop the thread in proper manner.

Happy Learning
Codingsense :)

Posted in C# | Tagged: | Leave a Comment »

Grouped RadioButton for WPF Datagrid

Posted by codingsense on February 9, 2010

Hi,

One of my friend was having a problem in implementing the radio button in datagrid, if implemented he wanted to know how to group them so that in 2 different columns radio button will be grouped as one. So after few attempts I found the following method and explained him the implementation.

To implement a radio button you have to use the DataGridTemplateColumn, where you can create your custom column for datagrid.

Download Code(5.7Kb)

The radio button was quite easily implemented as the following code




<dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>





After the implementation of the radio button we faced a challenge to group it up and we came with a very beautiful idea of giving a group name to both of them and here is what we did, we gave a groupname as “RadioGroup” to both of the radio button as




<dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="RadioGroup" IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="RadioGroup" IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>





Oops we were again into a problem, now all the cells were grouped together so we could select only one out of whole group.
Think Think Think is what we did, then we got a idea to have a group name that is unique for each row that is created. So we created a property called index which will be unique across each person, and we binded our column with the index, so that for each person instance the index will be same but not for 2 persons in the collection.
And this gave us the final solution of grouped radio button. Here is what we did.




 <dg:DataGridTemplateColumn
					Header="Male">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="{Binding Index}" IsChecked="{Binding Male}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>                
<dg:DataGridTemplateColumn
					Header="Female">                    
<dg:DataGridTemplateColumn.CellTemplate>                        
<DataTemplate>                            
<RadioButton GroupName="{Binding Index}" IsChecked="{Binding Female}" />                        
</DataTemplate>                    
</dg:DataGridTemplateColumn.CellTemplate>                
</dg:DataGridTemplateColumn>




So the main thing that has to be noted is, we should have a property that will remain unique accross the collection. If we have such property just bind it with the groupname and radio button will work absolutely fine.

Hope you found it useful. For any clarification or any better suggestions please revert back.

Happy Learning,
Codingsense :)

Posted in WPF | Tagged: , | 6 Comments »

Find row count of all tables in given database

Posted by codingsense on February 4, 2010

Hi,
Last week I wanted to know which tables in my database are having records and it was quite big database and would take a lot of time opening all tables and check. So I planned to write a query and find out. And here is what I wrote.

Select rows, OBJECT_NAME(id)
from sysindexes where id in
(select Object_ID(TABLE_NAME) from INFORMATION_SCHEMA.TABLES)
and indid < 2 and rows > 0

And this fetched me the exact result i wanted. There are lot of metadata tables in MSSQL which can be handy.
For more information on metadata information in MSSQL click here

Happy Learning
Codingsense :)

Posted in MSSQL | Tagged: , | Leave a Comment »

Rounding off to nearest in C#

Posted by codingsense on February 4, 2010

Hi,

Here I am posting a simple post but its very useful and I saw lot of questions arising on the same. So made a sample to share with you.
There are 2 types of rounding off in the following sample
1) Rounding off to nearest 10, 100, 1000 and other multiples of 10
2) Rounding off to nearest decimal place

Rounding off to nearest 10, 100, 1000 and other multiples of 10



public static double RoundToNearest(double Amount, double RoundTo)
{
double ExcessAmount = Amount % RoundTo;
if (ExcessAmount < (RoundTo / 2))
{
Amount -= ExcessAmount;
}
else            
{
Amount += (RoundTo - ExcessAmount);
}

return Amount;
}


Rounding off to nearest decimal place




public static decimal RoundToNearestDecimal(decimal Amount, int DigitsToRound)
{
return Math.Round(Amount, DigitsToRound, MidpointRounding.AwayFromZero);
}


Sample usage of the above code





Console.WriteLine("Amount = 123456789");
Console.WriteLine(RoundToNearest(12345678, 10));
Console.WriteLine(RoundToNearest(12345678, 100));
Console.WriteLine(RoundToNearest(12345678, 1000));
Console.WriteLine(RoundToNearest(12345678, 10000));
Console.WriteLine(RoundToNearest(12345678, 100000));

Console.WriteLine();

decimal deci = Convert.ToDecimal(123.456789);
Console.WriteLine("Amount = 123.456789");
Console.WriteLine(RoundToNearestDecimal(deci, 1));
Console.WriteLine(RoundToNearestDecimal(deci, 2));
Console.WriteLine(RoundToNearestDecimal(deci, 3));
Console.WriteLine(RoundToNearestDecimal(deci, 4));
Console.WriteLine(RoundToNearestDecimal(deci, 5));


Sample output for the above code

Happy Learning
Codingsense :)

Posted in C# | Tagged: , | 3 Comments »

 
Follow

Get every new post delivered to your Inbox.