Naveen's Weblog

Bridge to future

Posts Tagged ‘Tips and Tricks’

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 »

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 »

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: , | 4 Comments »

Customize a slider in WPF, Step by Step Tutorial

Posted by codingsense on February 1, 2010

Hi,

Today let us explore how to customize a slider control in WPF. I have seen a lot of explanation and looked many articles on net about the slider, but i got the the better idea about it only when I implemented it in my own way.
Let me share the same step by step method with you all.

Download Source (7.8 Kb)

So lets begin, First create a WpfApplication in VS2008 and insert a slider control in the grid layout.Open the designer and click on the XAML view. You will see the below code.

<Grid>
<Slider Name="CusomSlider" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />····
 </Grid>


Now we have to override the Style property of the slider to give it the look we want. We will name the style as MyCustomStyleForSlider and override the style method as below code,

<Slider Name="CusomSlider" Style="{StaticResource MyCustomStyleForSlider}" Height="25" VerticalAlignment="Top" Margin="46,65,37,0" />


Slider control is made up of many subcontrols, those include Track which inturn include Track.IncreaseRepeatButton, Track.DecreaseRepeatButton, Track.Thumb.
Thumb is the main sub control that makes the rectangle shape that moves left and right. The same thumb can also be found in horizontal and verticle scrollbars. So lets insert the following default template of all the controls that all together make the slider control.

<Style x:Key="MyCustomStyleForSlider" TargetType="{x:Type Slider}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TickBar x:Name="TopTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Top" Height="4" Grid.Row="0"/>
<TickBar x:Name="BottomTick" Visibility="Collapsed" Fill="{TemplateBinding Foreground}" Placement="Bottom" Height="4" Grid.Row="0"/>
<Border x:Name="TrackBackground"  
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >
<Canvas Margin="-6,-1">
<Rectangle Visibility="Hidden" x:Name="PART_SelectionRange" Height="4.0"
 Fill="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"
 Stroke="{DynamicResource {x:Static SystemColors.ControlDarkDarkBrushKey}}"
 StrokeThickness="1.0"/>
</Canvas>
</Border>
<Track x:Name="PART_Track" Grid.Row="1">
<Track.DecreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.DecreaseLarge}"/>
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="{x:Static Slider.IncreaseLarge}"/>
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb x:Name="Thumb" Background="Black"/>                                        
</Track.Thumb>
</Track>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


Now run the application and check how it looks and works, click on its right and left and a small dot i.e Thumb without any style moves right and left.


Now lets apply style to the thumb and name it as CustomThumbForSlider, below is the implementation.

·<Style x:Key="CustomThumbForSlider" TargetType="{x:Type Thumb}">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Ellipse Fill="#FF8F4040" Stroke="#FF000000" Height="15" Width="15"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


and override the above style to the thumb.

<Thumb x:Name="Thumb" Style="{StaticResource CustomThumbForSlider}" Background="Black"/>


After overriding the Thumb style lets have a look of the slider control,

Great, i.e The important thing that makes the slider control is the IncreaseRepeatButton and DecreaseRepeatButton, when clicked on ends they decrease in the size to the amount of the Tickbar value making the other button grow in size and that gives us the illusion that the thumb is moving. Nice move right ok lets get furthur.

Now we need to hide the Increase and decrease repeat buttons so lets create their styles.

<Style x:Key="SliderRepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="IsTabStop" Value="false"/>
<Setter Property="Focusable" Value="false"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RepeatButton}">
<Rectangle Fill="Transparent"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


Ok apply the styles to the repeat buttons and run the application, you will see that we have only the thumb that moves left and right on clicking but we dont see any track. So now we shall give border control a proper background and brush so that we get a good look at the starting and ending of the slider control. Lets create a style for both of these properties and apply them to the border.

<SolidColorBrush x:Key="HorizontalSliderTrackNormalBackground" Color="#FFE7EAEA"/>
<LinearGradientBrush x:Key="HorizontalSliderTrackNormalBorder" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FFAEB1AF" Offset="0.1"/>
<GradientStop Color="White" Offset=".9"/>
</LinearGradientBrush>
<Border x:Name="TrackBackground" 
 Background="{StaticResource HorizontalSliderTrackNormalBackground}"
 BorderBrush="{StaticResource HorizontalSliderTrackNormalBorder}"                                        
 BorderThickness="1" CornerRadius="1"
 Margin="5,0" VerticalAlignment="Center" Height="4.0" Grid.Row="1" >


Now run the application, you can see that we have customized the design of our slider control.

Change the ellipse control or the border styles to whatever you desire and you will be able to create your own design for the slider control.
Change some of the properties of tickbar, thumb and repeat buttons and see how they behave, which will give you more hands on with slider controller.

References:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.tickbar.aspx

Happy Learning,
Codingsense :)

Posted in C#, WPF | Tagged: , , , | 16 Comments »

Clone fields and properties in a abstract class

Posted by codingsense on March 15, 2009

Hi Friends,

In this post we shall see how we can clone the properties of a abstract class.

If there is a normal class and we need to clone it, then we will use the simple method of cloning
1) Create a new object
2) Copy all the properties of this object to the newly created object
3) Return the object

But assume a condition when we have a abstract class in which lot of properties are been defined and it has lot of derived classes. Now if we want all the derived classes to implement clone and clone all the properties of the base class then we need to write clone method in each derived classes. Since we know that we cannot create a instance method in abstract class becuase its instance cannot be created.

What would you do in the following case, here is the solution for it, Its simple and a generic method that can be used in any class that needs to implement clone. Here it goes.

Clone Properties:

abstract class CloneProperties: ICloneable    
{
public int fldi = 0;

int propi = 0;
public int Propi
{
get { return propi; }
set { propi = value; }
}

int propj = 0;
public int Propj
{
get { return propj; }
set { propj = value; }
}

        #region ICloneable Members

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
PropertyInfo[] properties = newInstance.GetType().GetProperties();

int i = 0;

foreach (PropertyInfo pi in this.GetType().GetProperties())
{
properties[i].SetValue(newInstance, pi.GetValue(this, null), null);
i++;
}

return newInstance;
}
        #endregion    
}

To check the output we shall create a dummy class and inherit it from cloneProperties class

class Prop : CloneProperties    
{
}

And in the Main function we shall call the clone and check

class Program    
{
static void Main(string[] args)
{
CloneProperties cloneProp1 = new Prop();
cloneProp1.fldi = 1;
cloneProp1.Propi = 2;
cloneProp1.Propj = 3;
CloneProperties cloneProp2 = (CloneProperties)cloneProp1.Clone();

Console.WriteLine("Cloning Properties");
Console.WriteLine("fldi = {0} , Propi = {1}, Propj = {2}", cloneProp2.fldi, cloneProp2.Propi,cloneProp2.Propj);

Console.Read();
}
}

Output:

Output after cloning Properties

Output after cloning Properties


Well it has worked fine, we can see that only the properties are succesfully cloned so they have got the values 2 and 3 and for fields it dint clone and it has value 0.

Clone Fields:

If you need to clone only the fields then you can replace the above clone function with the below one

public object Clone()
{
//we create a new instance of this specific type.            
object newInstance = Activator.CreateInstance(this.GetType());

//We get the array of properties for the new type instance.            
FieldInfo[] fields = newInstance.GetType().GetFields();

int i = 0;

foreach (FieldInfo fi in this.GetType().GetFields())
{
fields[i].SetValue(newInstance, fi.GetValue(this));
i++;
}

return newInstance;
}

Output:
cloneflieds

Here you can see that only fields are cloned and properties are set to the default vaule.

Happy Learning :)

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

Search metadata

Posted by codingsense on December 23, 2008


Many times we may want to see the information of our MSSQL objects. Here are some list of searches i have come across and found useful to share with you all.

  • SYSOBJECTS:

    The below query gives the list of keys associated with a table

    
    select name, xtype from sysobjects where parent_obj = object_id(N'[dbo].TableName')

    You can further filter it out by adding where clause to get only Primary Key( Xtype = ‘PK’) and foreign key (Xtype = ‘F’) and so on

    XType List :
    C: Check constraint
    D: Default constraint
    F: Foreign Key constraint
    L: Log
    P: Stored procedure
    PK: Primary Key constraint
    RF: Replication Filter stored procedure
    S: System table
    TR: Trigger
    U: User table
    UQ: Unique constraint
    V: View
    X: Extended stored procedure

  • INFORMATION_SCHEMA:

    To List the Tables in the database with thier properites use

    
    select * from INFORMATION_SCHEMA.TABLES

    To see the list of stored procedures in the database with thier properites use

    
    SELECT * FROM INFORMATION_SCHEMA.ROUTINES

    Information schema to find foreign keys associated with a table
    More Information_Schema

  • SYSINDEXES:

    Many people use count(*) to get the number of rows in a table, for this operation the MSSQL server recounts the rows thus leading to slower process. The table properties will have its rowcount at any point of time. The best way is to access from sysindexes as follows

    
    select rows from SYSINDEXES WHERE ID = OBJECT_ID('TableName') and indid < 2

Happy Learning :)

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

Guidelines, Tips and Tricks MSSQL

Posted by codingsense on December 23, 2008

Here are some of the Tips and Tricks to imporve the performance of MSSQL.

  • Minimize the use of nulls.Because they incur more complexity in queries and updates. ISNULL and COALESCE functions are helpful in dealing with NULL values.
  • Use TRUNCATE TABLE statement instead of DELETE clause if you want to delete all rows from a table
  • Do not use reserved words for naming database objects, as that can lead to some unpredictable situations
  • Avoid using the new bigint data type unless you really need its additional storage capacity. The bigint data type uses 8 bytes of memory verses 4 bytes for the int data type
  • Don’t use “sp_“ as your prefix for stored procedures – it is a reserved prefix in MS SQL server!
  • The Union All statement is much faster than Union, because Union All statement does not look for duplicate rows, and Union statement does look for duplicate rows, whether or not they exist.
  • Always put the Declare statements at the starting of the code in the stored procedure. This will make the query optimizer to reuse query plans.
  • Do not call functions repeatedly in stored procedures, triggers, functions and batches, instead call the function once and store the result in a variable, for later use.
  • To avoid trips from application to SQL server, we should retrieve multiple resultset from single Stored procedure instead of using output param.
  • If stored procedure always returns single row result set, then consider returning the result set using OUTPUT parameters instead of SELECT statement, as ADO handles OUTPUT parameters faster than result set returned by SELECT statements.
  • Avoid (*), Try to restrict the queries result set by returning only the particular columns from the table, not all table’s columns.
  • Use SET NOCOUNT ON statement in your stored procedures to reduce network traffic.
  • Call stored procedure using its fully qualified name.The complete name of an object consists of four identifiers: the server name, database name, owner name, and object name. An object name that specifies all four parts is known as a fully qualified name. Using fully qualified names eliminates any confusion about which stored procedure you want to run and can boost performance because SQL Server has a better chance to reuse the stored procedures execution plans if they were executed using fully qualified names.
  • Do not query/manipulate the data directly in your front end application, instead create stored procedures, and let your applications to access stored procedure
  • Except or Not Exist clause can be used in place of Left Join or Not In for better performance.

If any more additional tips or guidelines then please post a comment.

Happy Learning :)

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

 
Follow

Get every new post delivered to your Inbox.