Archive

Archive for April, 2008

Add an Event Handler VB VS C#

April 25, 2008 amiraryani Leave a comment

If you constantly switch between C# and VB because of working with different team, you would find some VB codes confusing in compare to C#. For me the syntax of event handling is a common case to forget in VB.

The following example is from MSDN web site for handling a Routed Event in WPF:

C# Source code:

public partial class RoutedEventAddRemoveHandler {
void MakeButton(object sender, RoutedEventArgs e)
{
Button b2 = new Button();
b2.Content = "New Button";
// Associate event handler to the button. You can remove the event
// handler using "-=" syntax rather than "+=".
<strong>b2.Click  += new RoutedEventHandler(Onb2Click);
</strong> root.Children.Insert(root.Children.Count, b2);
DockPanel.SetDock(b2, Dock.Top);
text1.Text = "Now click the second button...";
b1.IsEnabled = false;
}
void Onb2Click(object sender, RoutedEventArgs e)
{
text1.Text = "New Button (b2) Was Clicked!!";
}

VB Source Code:

Public Partial Class RoutedEventAddRemoveHandler
Public Sub MakeButton(sender As Object, e As RoutedEventArgs)
Dim b2 As Button  = New Button()
b2.Content = "New Button"
<strong>AddHandler b2.Click, AddressOf Onb2Click</strong>
root.Children.Insert(root.Children.Count, b2)
DockPanel.SetDock(b2, Dock.Top)
text1.Text = "Now click the second button..."
b1.IsEnabled = False
End Sub
Public Sub Onb2Click(sender As Object, e As RoutedEventArgs)
text1.Text = "New Button (b2) Was Clicked!!"
End Sub

Ref: http://msdn2.microsoft.com/en-us/library/ms743596(VS.85).aspx

Categories: .Net CLR, WPF

WPF: Custom Control VS User Control

April 25, 2008 amiraryani 4 comments

There are two concepts in WPF projects which are quite confusing: User Control and Custom Control. Which are available through [Add a new item] menu:

ccontrol

The best description which I found on the web is on the Martins blog:

It seems to have collection of controls which provide a combined functionality User Control is the way to go, but if you want to create a new button control or text box with new behavior you need to look at custom control.

Custom Control
1. The purpose of it is to enhance the existing control,
2. It supports theming for consumers, which means the consumers can style it in whatever way they like,
3. It is perfect to be 3rd-party control, especially because of point 2.

Whereas User Control
1. Its purpose is to compose controls into one piece,
2. It does not support theming for consumers. Therefore, the consumers can not restyle it,
3. It better stay with the consumer application in case the consumer needs to change its style somehow.

Ref:http://wangmo.wordpress.com/2007/09/28/user-controls-vs-custom-controls/

Categories: WPF

Iterates through process and their libraries

April 16, 2008 amiraryani 1 comment

Following WPF application uses System.Diagnostics namespace to get the list of all running processes. Then for each process it get the list of attached modules and show the result in a TreeView control.

Following XAML code build the content of the window. Nothing fancy.

<Window x:Class=”Processes.Window1″
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    Title=”Window1″ Height=”300″ Width=”300″>
    <DockPanel LastChildFill=”True” >
        <Button DockPanel.Dock=”Top” Name=”Button1″ Click=”Button1_Click”>
            Get All Processes
        </Button>
        <TreeView DockPanel.Dock=”Bottom” Name=”TreeView1″ >
        </TreeView>
    </DockPanel>   
</Window>

 

And the code behind is:

 

public partial class Window1 : Window
{
  public Window1()
  {
    InitializeComponent();
  }

  private void Button1_Click(object sender, RoutedEventArgs e)
  {
    foreach (Process process in Process.GetProcesses())
    {
      TreeViewItem head = new TreeViewItem();
      head.Header = process.ProcessName;
      TreeViewItem files = new TreeViewItem();
      files.Header = “Modules”;
      try
      {
        foreach (ProcessModule module in process.Modules)
        {
          files.Items.Add(new TreeViewItem
          {
            Header = module.ModuleName + “:”
              + module.FileName + “(“
              + module.FileVersionInfo.FileVersion + “)”
          });
        }
      }
      catch (Exception)
      {
        files.Items.Add(new TreeViewItem { Header = “Access denied” });
      }

      head.Items.Add(files); 
      TreeView1.Items.Add(head);    
    }
  }
}

 

The running result would be a simple window with only one button. Pressing the button loads the list of all process into the treeview:

image

 
To project is created in VS 2008 Professional Edition: Download Souce Code

Categories: Diagnostics, WPF

WPF: sample of loading an icon to an image control

April 14, 2008 amiraryani 4 comments

The following sample codes shows how to load an icon in to a image control. It use URI package to load the embed icon from the current assembly. For more information about URI refer to my previous post or following MSDN articles:

 

Image image1 = new Image();
Uri iconUri = new Uri(“pack://application:,,,/MyIcon.ico”, UriKind.Absolute);      
try
{
  Stream iconStream = System.Windows.Application.GetResourceStream(iconUri).Stream;
  IconBitmapDecoder decoder = new IconBitmapDecoder(iconStream,
     BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
  image1.Source = decoder.Frames[0] ;  
}
catch (System.IO.IOException)
{
  MessageBox.Show(“Icon file not found”);         
}

Categories: WPF

URIs in Windows Presentation Foundation

April 14, 2008 amiraryani Leave a comment

It seems that understanding and using uniform resource identifiers (URI) is essential in WPF. After searching web and MSDN help I found following articles useful:

 

With a bit of simplification, I can describe the URI as a new method for identifying the relative or absolute location of a file.

The key element of the URI is the package scheme.  which represent the logical path of a content. It contains two parts Authority and Path.

pack://authority/path

WPF supports two authorities:

  • application:///
  • siteoforigin:///

 

MSDN: “The application:/// authority identifies application data files that are known at compile time, including resource and content files. The siteoforigin:/// authority identifies site of origin files.”

I found that Application authority is adequate in majority of cases including  accessing a file or a resource from the local or referenced assembly.

Important: to conform to RFC 2396, the “/” character must be replaced with the “,” character and other reserved characters must be escaped including “%” and “?”

Following examples shows pack URI for different scenarios:

Resource file – local assembly

“pack://application:,,,/ResourceFile.xaml”

 

Resource file in subfolder – local assembly

“pack://application:,,,/Subfolder/ResourceFile.xaml”

 

Resource file – referenced assembly

“pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml”

 

Resource file in subfolder of referenced assembly

“pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml”

 

Resource file in versioned referenced assembly

“pack://application:,,,/ReferencedAssembly;v1.0.0.0;component/ResourceFile.xaml”

 

Content file

“pack://application:,,,/ContentFile.xaml”

 

Content file in subfolder

“pack://application:,,,/Subfolder/ContentFile.xaml”

 

Site of origin file

“pack://siteoforigin:,,,/SOOFile.xaml”

 

Site of origin file in subfolder

“pack://siteoforigin:,,,/Subfolder/SOOFile.xaml”

Categories: WPF

Application Exeption Handling in WPF

April 11, 2008 amiraryani Leave a comment

DispatcherUnhandledException in Application.XAML.CS can be used to catch all unhandled exceptions. The following is a sample source codes:

private void App_DispatcherUnhandledException(object sender,
DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(“An unhandled ” + e.Exception.GetType().ToString() +
” exception was caught and ignored.”);
e.Handled = true;
}

And the event can be wired up as:

<Application x:Class=”PreventSessionEnd.App”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
StartupUri=”Window1.xaml”
DispatcherUnhandledException=”App_DispatcherUnhandledException”>
</Application>

Categories: WPF

Stop debugger from step through

April 10, 2008 amiraryani Leave a comment

Debugging projects can be difficult when the code step through lots of classes or functions that is not necessary to debug. The following attribute make debugger to step over any decorated source code.

[SerializableAttribute]
[ComVisibleAttribute(true)]
[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Struct|
AttributeTargets.Constructor|AttributeTargets.Method, Inherited = false)]
public sealed class DebuggerStepThroughAttribute: Attribute

 

Also these are other useful attributes to know:

-DebuggerBrowsableAttribute:
Determines if and how a member is displayed in the debugger variable windows.

-DebuggerDisplayAttribute:
Determines how a class or field is displayed in the debugger variable windows.

-DebuggerHiddenAttribute:
Debugger does not stop in a method marked with this attribute and does not allow a breakpoint to be set in the method.

-DebuggerNonUserCodeAttribute:
This attribute suppresses the display of these adjunct types and members in the debugger window and automatically steps through, rather than into, designer provided code.

-DebuggerStepperBoundaryAttribute:
When executing within the boundaries of the DebuggerNonUserCodeAttribute, designer-provided code is executed as a step-through until the next user supplied code is encountered.

-DebuggerTypeProxyAttribute:
It allow to overwrite how a given type is shown in debugger.

-DebuggerVisualizerAttribute:
Associate a Visualizer for a given class. For more information refer to http://msdn2.microsoft.com/en-us/library/e2zc529c.aspx

 

Related link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.aspx

Categories: .Net CLR