Naveen's Weblog

Bridge to future

2010 in review

Posted by codingsense on January 2, 2011

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

About 3 million people visit the Taj Mahal every year. This blog was viewed about 52,000 times in 2010. If it were the Taj Mahal, it would take about 6 days for that many people to see it.

 

In 2010, there were 15 new posts, growing the total archive of this blog to 63 posts. There were 10 pictures uploaded, taking up a total of 166kb. That’s about a picture per month.

The busiest day of the year was December 14th with 282 views. The most popular post that day was Left Join, Right Join Using LINQ.

 

Where did they come from?

The top referring sites in 2010 were google.com, google.co.in, codeproject.com, yandex.ru, and social.msdn.microsoft.com.

Some visitors came searching, mostly for linq left join, left join linq, linq join, left join in linq, and linq join example.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Left Join, Right Join Using LINQ March 2009
16 comments

2

Customize a slider in WPF, Step by Step Tutorial February 2010
1 comment

3

Difference between Select and SelectMany in LINQ September 2008
7 comments

4

MSSQL Output in XML using For XML December 2008

5

Bulk Insert and Update MSSQL December 2008
14 comments

Posted in Uncategorized | 1 Comment »

The designer cannot process the code at line

Posted by codingsense on December 5, 2010

From somedays back I was getting a weird problem while opening the design of windows form. The error message looked like the below one

The designer cannot process the code at line 37: this.comboBox1.Items.AddRange(new []{ “one”, “two”, “three”, “four”}); The code within the method ‘InitializeComponent’ is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again.

If I commented the AddRange line it was working fine or It was pointing at the next line those had AddRange method. I quickly googled for the solution and found many but none of the fix was useful. By careful observation I found that something was missing the line. See if you can observe what’s missing the below line ;)

 this.comboBox1.Items.AddRange(new []{
“one”,
“two”,
“three”,
“four”});

Just adding the type of the array that I was creating solved my problem, for above problem I added new object[] and then all worked fine.

this.comboBox1.Items.AddRange(new object[]{
“one”,
“two”,
“three”,
“four”});

After fixing the issue I started searching for the person who had removed it, I wanted to show him the issue so that he will not do the same next time. After searching for hours I found that it was Mr. ReSharper who had removed the type. From then I started carefully using Resharper instead of just clicking on what it suggests.

Happy coding :)
Codingsense

Posted in Uncategorized | 2 Comments »

Zip/Unzip using System.IO.Package in .Net

Posted by codingsense on December 5, 2010

I was working on a project where it was required to zip and unzip files, these days we were using Cabarc.exe and all was working fine. Now we planned to give unicode support and booom!! cabarc.exe failed to zip the folder, since it does not support unicode characters. I found that there are many open source projects like SharpZipLib, DotNetZip etc. But we did not wanted to use the available open source projects to implement it. So I decided to search for some other option and what I found is System.IO.Package in WindowsBase.dll. It exposes a class called Package which will help to pack and unpack files and folders.

Download Source code (13 Kb)

I have made a separate dll (CustomPackage.dll) that you can use for zipping and unzipping of folders. I have also created a dummy project PackageWrapper to help you understand how to make calls to the dll.

Features:

  • The project supports Unicode characters in folder or files (Limitation with Cabarc.exe)
  • Zipping is done also for all sub directories . While unzipping the same directory structure will be maintained.

Improvements for you to do:
I have used Mime Type as MediaTypeNames.Application.Octet to make it generic and support all kind of files and have used the compression option CompressionOption.NotCompressed since the mime type will not compress. If you know that you will have only similar type of files to zip or unzip then you can select proper Mime type and compression option as CompressionOption.Maximum to compress the files to maximum extent.

For any kind of improvements or clarifications please feel free to comment.

Happy Coding :)
Codingsense

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

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 | Leave a 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 »

 
Follow

Get every new post delivered to your Inbox.