Showing posts from 2010


How many times did we want to know the size of a folder and all its sub-folders?

For me it has been always the case whenever I clean up my hard drive. It is just too tiring to right-click and check out the properties.

TreeSize (free) lets you do just that. The interface is a tree view which shows the sub-folders with their sizes.

Unpackage .msi file

A quick tip to unpackage the .msi file without installing the application:

MSIEXEC /a "msi file path" targetdir="install location"

The argument that works is "/a" which is for admin mode.

WPF: How to disable controls?

How do I disable a Button in WPF?
Use - IsEnable property.

Using a WinForms user control in WPF

During WPF application development we are bound to face situation where we cannot port the WinForms user control to WPF, and will be forced to use the control in WPF window.
The steps below help us achieve that:
1) Add <WindowsFormsHost> control to the window
If needed remove the Height, Width and Margin property and use 'Stretch' for HorizontalAlignment and VerticalAlignment - to simulate the Dock=Fill.
2) Now we can add any WinForms control to the WindowsFormsHost.
For example if we have WinForms user control named UserControl1, we can write this code: UserControl1 uc1 = new UserControl1(); winHost.Child = uc1;
- cheers HTH

Moving from WinForms to WPF

1) TabControl:
- How to set the title on the TabItem control?
In WinForms we used the Text property, in WPF we have the Header property. The header property is of type object, so basically we can put 'anything' in the header - not just text.
2) TextBox:
- How to add scrollbar to TextBox?
Add these properties: HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Auto"

3) Button:

- How to write a multi-line text on the button?

As expected this doesn't work
<Button.Content> Hello\rthere<Button.Content/>

We need to use a TextBlock as Content, and use a <LineBreak /> in the text.

For e.g.:
<TextBlock>Test<LineBreak/> button</TextBlock>

WinForms Dock=Fill in WPF

Today while designing a WPF form, I was using a TabControl and wanted to fill it entirely on the window.
In WinForms we would reach out to the Dock property of TabControl and select 'Fill'. However we do not have Dock property in WPF controls.
Solution: We can use the alignment properties to achieve the same effect:
<TabControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />

You will need to remove Height, Width and Margin properties of the control to make it fill.

Important Links:

What To Know Before Debating Type Systems:

Internet explorer has restricted this webpage from running scripts...

When we open an XML file from local computer, I get the following error message: "In order to protect your security, Internet explorer has restricted this webpage from running scripts or ActiveX controls that could access your computer"
Which could be quite irritating if it is a large document or if you use the '+' often.
Solution: To resolve this go to Tools>Internet Options>Advanced and check the following: Allow active content to run files in my Computer Allow active content from CDs to run on my Computer.

Royal TS - remote desktop tool

I had been using RDC available in Windows for a long time and didn't actually found a problem with it until the day when I had to connect to half a dozen virtual machines - all of them having long, hard to remember auto generated passwords.
Enter Royal TS. It's just the first day of using it and I am already thanking my stars. (Got to know about this tool just by chance on of the manager's computer).
The current version are shareware with limited features, but the version 1.5 is full featured free version:

LINQ – fetching controls on the WinForm

Let us take a simple example, but a useful one. We start with a form, having 3 text boxes and a button. The button validates whether all the text boxes are filled up or not (a common business case).We want to color background of the textboxes Red if they are empty:

var textBoxes = from tBox inthis.Controls.OfType<TextBox>()
where tBox.Text.Trim() == ""
select tBox;
foreach (TextBox tbox in textBoxes)
tbox.BackColor = Color.Red;

We get the same result as before. Building upon this, right now we get all the text boxes but what if we want to check only the visible text boxes? We should be able to achieve it by adding ‘tBox.Visible == true’ in the LINQ query. Which brings us to the question, how do we add AND condition in LINQ? (along the way let’s add Enabled condition as well)

var textBoxes =
from tBox inthis.Controls.OfType<TextBox>()
where tBox.Text.Trim() == "" &&
tBox.Visible == true &&
tBox.Enabled == true
select tBo…

Checking from Live writer

Testing..1..2..3!Image check…

WPF Commands

Q. What happens if we define both the Command for a button and also provide handler for its click event?
A. The click event's handler fires first, and then the command.
Q. Can we assign add a command twice to the CommandBindings collection with different execute event handler?
A. Through testing it looks only one execute handler is fired. The first binding which is added to the collection gets invoked.
Q. Can we do something additional when the built-in commands are fired? For example we want to do something more when a copy command is invoked. Adding a new binding for Application.Copy does not work. (refer previous question) Or if we can't extend can override the Application.Cut behavior?

Binding to ListData (with IsSynchronizedWithCurrentItem)

Today while testing out data binding in WPF to list controls, I learnt something new.
On the window, I created two list boxes, and a textblock control all have data context of an xml static resource.
For the ItemsSource in listbox I was using: {Binding XPath=@name} [the xml resource contains a Color element with attribute 'name]. I used IsSynchronizedWithCurrentItem on both the listboxes and bound the TextBlock Text to {Binding XPath=@Name}.
On testing the app I found, the controls are not synchronized. After referring to MSDN and some testing with different bindings - I found that to enable synchronization between all the controls to the CurrentItem of the collection, it is important to bind the list boxes to the whole collection. and not to a member or attribute (in this example).
So for listboxes it should be ItemsSource={Binding}, for display purposes we can use DisplayMemberPath or DataTemplate.

Tool to download complete web site

Use this to copy a complete web site locally.
[TIP: You can use this to download channel9 videos of your interest]

Debug XAML

Important links

Events, Delegate and Multithreading
MSDN's canonical technique for using Control.Invoke is lame

Send a message to a Windows Forms message loop

SlickRun custom magic words

[msdn] Filename="$W$" Notes="Searches MSDN using Google" GUID={2F9AC37E-9BD9-486D-9168-D7C2FF0D0750} StartMode=5 UseRunAs=0 Disable32BitRedir=0 [msdngo] Filename="$W$" Notes="Goes to the first Google search item on MSDN site" GUID={E82C1293-A5C3-4D18-BBD7-BAFC543AC6EE} StartMode=5 UseRunAs=0 Disable32BitRedir=0 [n] Filename="notepad.exe" Params="$W$" GUID={B3DADC2D-B5EA-4186-B165-CDCF7F6BEF2F} StartMode=5 UseRunAs=0 Disable32BitRedir=0 [stack] Filename="" GUID={28BF5F9B-CAE3-48E9-A66E-440135239B96} StartMode=5 UseRunAs=0 Disable32BitRedir=0 [times] Filename="" Notes="The New York Times" GUID={6791C0B1-91B9-4946-BC16-07B58AEFF9DF} StartMode=5 UseRunAs=0 Disable32BitRedir=0 [wi] Filename="http://frer0342:8080/WorkItemTracking…

Dev Tools

- Slickrun:
- Process explorer:
- RocketDoc:
- Fences:
- LINQPad: (Code snippet execution)
- mTail:

Using Attributes

I just realised that we have two ways to use an attribute.
For example the attribute - AttributeUsage - is implemented in the class AttributeUsageAttribute. And we can use either AttributeUsage or AttributeUsageAttribute in our code.
In fact if you create a custom attribute in class named "TestAttribute":
public class TestAttribute : Attribute { }
and define another custom attribute named "Test":
public class Test : Attribute { }
and then try using the attribute in a class:
[Test()] public class MyClass { }
This will give compilation error: 'Test' is ambiguous between 'Test' and 'TestAttribute'; use either '@Test' or 'TestAttribute'
The code intellisense as well displays only the "Test" pointing to TestAttribute in its list, it doesn't show the other "Test".
I believe C# creates an alias of TestAttribute somewhere for the attribute. It actually makes sense to use aliased-name of attribute. It would be unwieldy to write…

Links to training kits

Comparing assembly versions in C#

Found a nice little trick to compare version strings in .NET:

Version version1 = new Version("2.4.1");
Version version2 = new Version("2.5");

if (version1 <= version2)
// in this case true

No need to rely on string.Compare() method !!

Virtual Desktop Manager - cool tool

Just found a virutal desktop manager tool (free):

How to set the default encoding in windows

Go to -> Control Panel - Regional and Language Options; Advanced tab
This impacts the entire computer.

Web links discussing encoding in Windows

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Characters Vs. Bytes
How to Use Special Characters in Windows Documents
Windows-1252 (so called ANSI) (The above links says: ANSI does not necessarily have to map to CP1252. It does, however, always refer to the legacy codepage set for the system. This may be CP1252 on western European or US systems but don't count on that)

Encoding to use while reading/writing files in .NET

"Digging deep into encoding"
While performing File I/O, it is important to keep in mind whether the files being processed can contain special characters or not. If it is so, then check the encoding you are using.

Encoding used in:
StreamReader: it uses UTF-8 encoding by default unless otherwise specified.

StreamWriter: Uses the default encoding of the system unless otherwise specified.

If we do a check on the default encoding - we get "Windows-1252" [which is ANSI]. So while development if we don't specify encoding (and use defaults) then the files created by applications will use ANSI encoding, and applications reading them will use UTF-8!!!

This will give error, and we will see square characters/questions marks in place of the special characters.
- We can use encoding "Windows-1252" when reading the file or
- use encoding UTF-8 while writing /reading the files (better approach)

Ironically: You will get error (if no encoding is specified) only if you …

Invalid characters (square boxes) while reading a text file (encoding issue)

While reading a text file we get square symbols in .NET for special symbols. For e.g ° . However if the file is created\saved as Unicode then the file is read correctly.
- tried encoding.UTF-8 but still get the error string - notepad opens up the file correctly with the special characters
Use encoding "Windows-1252".
Sample code -
using (StreamReader reader = new StreamReader(filePath, System.Text.Encoding.GetEncoding("Windows-1252"))) { string content = reader.ReadToEnd(); reader.Close(); return content; }

Delete from a table which requires lookup in another table

Problem: To delete rows from TableA based on filter condition which requires a lookup on another table TableB.
Solution 1)
DELETE FROM TableA FROM TableA as A INNER JOIN TableB as B on A.ID = b.ID WHERE B.COL2 = ''someval' and B.COL3 = 'someval'
Solution 2)
DELETE FROM TableA WHERE ID IN (SELECT ID FROM TableB where COL2 = ''someval' and COL3 = 'someval')

Get distinct rows from DataTable

Found a method in data table object to get distinct rows:
DataTable dtTest = dtProduct.DefaultView.ToTable(true, new string[] { "PRODUCT", "NATURE", "TYPE" });
The first parameter has to be 'true' to get distinct rows, the second is the list of columns to return.