C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets
 C# Code Snippets  C# Code Snippets

Thursday, December 27, 2007

How To Use Hierarchical DataTemplate in WPF



Hi all

I am going to show you a simple example of how to use Hierarchical DataTemplates in a tree view for an easy display of hierarchical Data. The Example shows the links in a WebPage recursively. First we will create the data model that we want to show, note that we have two seperate models, one for the root element and one for the acctual data.

    public class WebPage
{
public string Href { get; set; }
public string PageTitle { get; set; }
public List<WebPage> LinksInPage { get; set; }
}

public class Root
{
public string Title { get; set; }
public string Url { get; set; }
public List<WebPage> WebPages { get; set; }
}
We have to create a root object and the accrual data object as separate classes. the data template for each one will look like this:
        <HierarchicalDataTemplate DataType="{x:Type data:Root}"
ItemsSource="{Binding Path=WebPages}">
<
Border BorderBrush="Black"
BorderThickness="2"
CornerRadius="10">
<
StackPanel>
<
TextBlock Margin="10,0,0,0"
Text="{Binding Title}"></TextBlock>
</
StackPanel>
</
Border>
</
HierarchicalDataTemplate>

<
HierarchicalDataTemplate DataType="{x:Type data:WebPage}"
ItemsSource="{Binding Path=LinksInPage}">
<
Border BorderBrush="Black"
BorderThickness="2"
CornerRadius="10">
<
StackPanel>
<
TextBlock Margin="10,0,0,0"
Text="{Binding PageTitle}"></TextBlock>
<
TextBlock Margin="10,0,0,0"
Text="{Binding Href}"></TextBlock>
</
StackPanel>
</
Border>
</
HierarchicalDataTemplate>
In the constructor of the window we will create the hierarchy of the data in code and provide the tree view with the  DataContext
public Window1()
{
InitializeComponent();
Root r = new Root();
r.WebPages = new List<WebPage>();
r.Title = "HomePage";
r.Url = @"http://www.HomePage.com";

WebPage link1 = new WebPage();
link1.Href = @"http://www.HomePage.com/link1";
link1.PageTitle = "link1";
r.WebPages.Add(link1);

WebPage Link2 = new WebPage();
Link2.Href = @"http://www.HomePage.com/Link2";
Link2.PageTitle = "Link2";
r.WebPages.Add(Link2);

WebPage Link3 = new WebPage();
Link3.Href = @"http://www.HomePage.com/Link2/Link3";
Link3.PageTitle = "Link3";
Link2.LinksInPage = new List<WebPage>();
Link2.LinksInPage.Add(Link3);

WebPage Link4 = new WebPage();
Link4.Href = @"http://www.HomePage.com/Link2/Link4";
Link4.PageTitle = "Link4";
Link2.LinksInPage.Add(Link4);

WebPage Link5 = new WebPage();
Link5.Href = @"http://www.HomePage.com/link1/Link5";
Link5.PageTitle = "Link5";
link1.LinksInPage = new List<WebPage>();
link1.LinksInPage.Add(Link5);

WebPage Link6 = new WebPage();
Link6.Href = @"http://www.HomePage.com/link2/Link3/Link6";
Link6.PageTitle = "Link6";
Link3.LinksInPage = new List<WebPage>();
Link3.LinksInPage.Add(Link6);

treeView1.DataContext = r;
}
To finish we will define the TreeView in Xaml:
    <Grid Background="LightSkyBlue">
<
TreeView Margin="0,0,15,0" Name="treeView1" Background="LightSkyBlue">
<
TreeViewItem ItemsSource="{Binding Path=WebPages}"
Header="{Binding Title}"></TreeViewItem>
</
TreeView>
</
Grid>
Notice that we provide the TreeView with one TreeViewItem, thats the root The result is this display:
Hierarchical Data Template 
You can download the Source code here:
http://www.filefactory.com/file/2e5dfd/
Enjoy
Amit

AddThis Social Bookmark Button

Saturday, December 22, 2007

How to Suppress / Disable Script Errors in WebBrowser Control

Hi all

I am currently writing an application that uses the WebBrowser control to perform operations on web pages. Unfortunately I stumbled upon a very annoying problem, sometimes an Internet explorer script error window pops up and stops all execution until you click the OK button. I've searched the web for hours and the same answer came up:

it's easy (so easy, yeah...) just do this:

WebBrowser.Silent = true;

the problem is that WebBrowser does not have a property named silent!!!!!! Maybe it did, but no more! if you don't believe me take a a look at the MSDN.

What you should do is use

WebBrowser.ScriptErrorsSuppressed = true;

which does exists...

Hope this helps some frustrated people (like me).

Happy holidays

Amit

AddThis Social Bookmark Button

How To Use Microsoft Expression Blend to Modify a Control

Hi all

Say you absolutely have to change the Button of a Combobox to a circle instead of an arrow - you just have to!!!!

Here comes Microsoft Expression Blend to the rescue, If you code in WPF and don't have it yet, you can get it here:

http://www.microsoft.com/expression/products/download.aspx?key=blend2preview

Its the beta of blend 2 but believe me when I say it feels like no beta.

Ill wait here while you download and install...

Done? Great let's start:

Open up a new project and throw in a combobox. Right click on the combobox, you should get the following context menu:

untitled

We want to press on edit a copy (picture above), which will open the next menu:

untitled 

This is Microsoft Blend's way of saying: I am going to create a new style, where would you like me to put it?

Press ok if you want it in the window's resources or select a resource dictionary if you want it to be placed there, for the sake of the example lets press OK. Now we have created a custom Combobox style. Lets right click on the Combobox toggle button, this menu pops:

untitled

We are going to select the edit template option (picture above) and that's it: we can now do whatever we want to the toggle button, like put in a red circle instead of the arrow. To do that, select the arrow by using the Direct select option from the toolbar on the left (second from top) and delete it. Insert an ellipse where the arrow used to be, and paint it red. The result is this beautiful Combobox that function exactly like the original, except it has a red circle and not an arrow:

untitled

In the same manner you can do whatever you want to any control. If you wish to see the code that Microsoft Blend wrote for you, just check out Window1.xaml or the resource dictionary you specified before

Please comment if you are experiencing problems I'll be happy to help

Enjoy

Amit

AddThis Social Bookmark Button

Wednesday, December 19, 2007

Expresso - a Great Regular Expression Tool

Hi All

This one is for all you guys who are tired of pressing F5 over and over in Visual studio just to see if you got the Regular expression right, I know got tired of it and that's how i found this tool.

Introducing Expresso the "Visual Studio of Regular Expression":

You can Download it free of charge from here:

http://www.ultrapico.com/ExpressoDownload.htm

After you install it and run check the help section, there's a very useful tutorial there. basically your screen is split into four: Top left corner is where you type in the pattern you are looking for, top right is the analyzer which compiles the pattern on the left as you type it, bottom left is the actual text you are parsing and on the bottom right are the matches your pattern turned out. In order to check for matches you just have to click "Run Mach" which is located just above the top left window. you can try and use my other example for regular expressions (http://dev102.blogspot.com/2007/12/regular-expressions.html) on Expresso to check how it works.

The most important thing is that after you are satisfied with the results click on Tools->View Code and Viola, on the bottom right you get the actual C# code for your application

untitled

Comment if you have any questions

Enjoy

Amit

AddThis Social Bookmark Button

Internet Explorer 7 Ultimate Plugin

Hi all.

Do you envy the Mozilla ad blocker and customizations options?
Well, no more!!!

Introducing IE7Pro the perfect add-in that give you great customization options and much much more!
Check it out here:

http://www.ie7pro.com/

Enjoy

Amit

AddThis Social Bookmark Button

Monday, December 17, 2007

How to Compile from Windows Explorer / Total Commander

Hi all

Are you dreaming of compiling/building binaries without waiting hours for Visual Studio to open up ?
Now you can !

You can download a Registry fix File from here :

http://www.filefactory.com/file/eefa52/

Just double click it and your there...

The result is this:

Example

Notes:
1. It's build debug only version.
1. Will not work for unmanaged (win32 types) projects.

If you are suspicious :)  Just create a text file and name it <whatever>.reg and Copy what's written below in blue into it and just double click it to integrate it into the registry

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Build]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Build\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:build /v:m /p:Configuration=Debug;Platform=\"x86\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Clean]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Clean\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:clean /v:n /p:Configuration=Debug;Platform=\"x86\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Rebuild]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.sln\shell\Rebuild\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:rebuild /v:n /p:Configuration=Debug;Platform=\"x86\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Build]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Build\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:build /v:m /p:Configuration=Debug;Platform=\"AnyCPU\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Clean]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Clean\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:clean /v:n /p:Configuration=Debug;Platform=\"AnyCPU\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Rebuild]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.csproj\shell\Rebuild\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:rebuild /v:n /p:Configuration=Debug;Platform=\"AnyCPU\"\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Build]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Build\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:build /v:m /p:Configuration=Debug\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Clean]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Clean\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:clean /v:n /p:Configuration=Debug\""

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Rebuild]

[HKEY_CLASSES_ROOT\SystemFileAssociations\.proj\shell\Rebuild\command]
@="cmd.exe /K \"\"%%windir%%\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild.exe\" \"%1\" /t:rebuild /v:n /p:Configuration=Debug\""

Have fun

AddThis Social Bookmark Button

Friday, December 14, 2007

How To Create Code Snippets Easily

Hi all

Whenever I want to create a code snippet I usually take an already created one and change the XML file to suit my needs, well NO MORE!!!!

introducing Snippy the Code snippet editor, creating code snippets was never so Easy!!!

let's check out the tool with a snippet I wrote for a class with one variable including a constructor and a property for that variable.

snippy

It's so easy, you just give it a shortcut to use in Visual Studio, add the literals you want to use and then write the code you need using the literals. When you are done just save it in your Visual Studio Custom Snippets folder, which is usually : "C:\Documents and Settings\<USERNAME>\My Documents\Visual Studio 2008\Code Snippets\Visual C#\My Code Snippets", and that's it. Next time you run Visual Studio type in the shortcut and let the magic begin... :)

the out put of this snippet is this:

<?xml version="1.0" encoding="utf-8"?>
<
CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<
CodeSnippet Format="1.0.0">
<
Header>
<
SnippetTypes>
<
SnippetType>Expansion</SnippetType>
</
SnippetTypes>
<
Title>Class_1</Title>
<
Shortcut>Cls1</Shortcut>
<
Description>template for class with one variable</Description>
<
Author>Amit Raz</Author>
</
Header>
<
Snippet>
<
Declarations>
<
Literal Editable="true">
<
ID>Member1</ID>
<
ToolTip>First member</ToolTip>
<
Default>member</Default>
<
Function>
</
Function>
</
Literal>
<
Literal Editable="true">
<
ID>Type1</ID>
<
ToolTip>type 1</ToolTip>
<
Default>int</Default>
<
Function>
</
Function>
</
Literal>
<
Literal Editable="true">
<
ID>MemberPropName</ID>
<
ToolTip>
</
ToolTip>
<
Default>propname</Default>
<
Function>
</
Function>
</
Literal>
<
Object Editable="true">
<
ID>ClassName</ID>
<
ToolTip>Class name</ToolTip>
<
Default>class1</Default>
<
Function>
</
Function>
</
Object>
</
Declarations>
<
Code Language="csharp"><![CDATA[public class $ClassName$
{
private $Type1$ $Member1$;

public $Type1$ $MemberPropName$
{
get
{
return $Member1$;
}
}

public $ClassName$($Type1$ newMember)
{
$Member1$ = newMember;
}
}
]]></Code>
</
Snippet>
</
CodeSnippet>
</
CodeSnippets>


Not very friendly right? let's just have snippy do all the work...



You can download it here:



http://www.gotdotnet.com/codegallery/codegallery.aspx?id=b0813ae7-466a-43c2-b2ad-f87e4ee6bc39



hope you Enjoy this



Amit

AddThis Social Bookmark Button

Thursday, December 13, 2007

Google Toolbar 5 Beta is out!!!

Google has just released the new Beta version of Google toolbar 5 which has some new features:

  • Support for goggle Gadgets.
  • One click registration form filling.
  • Synchronizing Toolbar from another computer.
  • Fixing of broken Links.
  • New bookmarks management system and many more!!!
  • Integration with YouTube.
  • Find out weather forecast in your area.

The new toolbar also has the Google Notebook in it.

download it from here:

http://toolbar.google.com/T5/intl/en/index.html

Enjoy!!!

Amit

AddThis Social Bookmark Button

How to use Regular Expressions

Hi

Ever needed to parse a web page and get all the Links in it (href's)? the easy way is to use this regular expression to get the href:

Regex r = new Regex("href.*)";

for those of you who don't know this means get me something that starts with -href- and then: whatever... that's what the -.*- is for. The problem is that now we have to work on the results in order to get the actual link.

Extra work? I don't think so...

We want to use groups, so the regular expression will look like this:

"href.*?"(?<HREF>.*?)"

Or in code: (we need to add \ for some escape characters)

Regex MyRegex = new Regex("href.*?\"(?<href>.*?)\"",RegexOptions.Multiline);


The RegexOptions.Multiline means that we can provide a multiline string as the input of the Regular expression


lets break it down:


href.*?"(?<HREF>.*?)"



The beginning is the same -href.*- get everything that starts with href now comes the twist.



the -?"- means stop on the first " you find, if we drop the -?- he will stop on the last -"- he finds (greedy!!!). Now comes the definition of the group: -(?<HREF>.*?) the syntax for defining a group is :



(?<GroupName><Rule>)



What comes after the Group name is the regular expression for the group, in our case the end looks like this:



.*?)"



which means get everything until the first " you see.



that way we will get the "clean" URL inside the HREF group!



To use the groups use this code:



public static void GetMatches(string s)
{
Regex MyRegex = new Regex("href.*?\"(?<href>.*?)\"", RegexOptions.Multiline);
MatchCollection mc1 = MyRegex.Matches(s);
Console.WriteLine(MyRegex.ToString());
foreach (Match m1 in mc1)
{
Console.WriteLine("URL: {0}", m1.Groups["href"].Value);
}
}

Credit to Shahar A.

Have fun!!

Amit

AddThis Social Bookmark Button

Wednesday, December 12, 2007

How to add a new XML node to file

Need to open an XML file and add a node?

Here's how:

Sample XML file:

<?xml version="1.0"?>
<
HelpData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<
helpButtonUrls>
<
HelpButtonUrl>
<
buttonName>BugReport</buttonName>
<
url>C:\BugRep.exe</url>
</
HelpButtonUrl>
</
helpButtonUrls>
</
HelpData>

We want to add another HelpButtonNode:

private void AddNodeToXMLFile(string XmlFilePath, string NodeNameToAddTo)
{
//create new instance of XmlDocument
XmlDocument doc = new XmlDocument();

//load from file
doc.Load(XmlFilePath);

//create main node
XmlNode node = doc.CreateNode(XmlNodeType.Element, "HelpButtonUrl", null);

//create the nodes first child
XmlNode ButtonName = doc.CreateElement("buttonName");
//set the value
ButtonName.InnerText = "Video Help";

//create the nodes second child
XmlNode url = doc.CreateElement("url");
//set the value
url.InnerText = "D:\\RunHelp.exe";

// add childes to father
node.AppendChild(ButtonName);
node.AppendChild(url);

// find the node we want to add the new node to
XmlNodeList l = doc.GetElementsByTagName(NodeNameToAddTo);
// append the new node
l[0].AppendChild(node);
// save the file
doc.Save(XmlFilePath);
}


XML file after:


<?xml version="1.0"?>
<
HelpData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<
helpButtonUrls>
<
HelpButtonUrl>
<
buttonName>BugReport</buttonName>
<
url>C:\BugRep.exe</url>
</
HelpButtonUrl>
<
HelpButtonUrl>
<
buttonName>Video Help</buttonName>
<
url>D:\RunHelp.exe</url>
</
HelpButtonUrl>
</
helpButtonUrls>
</
HelpData>




And thats all there is to it!



AddThis Social Bookmark Button

Sunday, December 9, 2007

Learn Visual Studio .Net

Hi Everyone!!!

This is my new blog in which i will Share all I know/hear about/find interesting about Application Development.

For starters i would like to introduce you to http://www.learnvisualstudio.net/ which is a web site that has over 500 Video tutorials about almost enything you can think of that is related to application development, C#, VB, ASP.NET, SQL, Visual Studio and much much more .
it's only 140$ for a lifetime subscription!!!

so check it out, they have some freebees that change from time to time.

Amit

AddThis Social Bookmark Button