Archive for the ‘C#’ Category.

Extract OcxState data

At work we have recently spent effort to remove our technical debt. So far we have introduced Unicode into the native code, migrated our VB6 to VB.NET, upgraded to .NET 4.0 and now we are working on 64bit support.

However, we have used the Microsoft FlexGrid quite extensively in our VB6 (now VB.NET) components and it does not support 64bit, therefore we decided to build a compatible control which wraps the existing WinForms DataGridView control.

We discovered quite early on that the properties set through the designer of an ActiveX control does not generate designer code, but instead it is serialized as a resource and restored through the OcxState property.

Always being the one to reduce the workload I devised a way of extracting this information so that we can redo the designer set properties. I found out that I could give the control another OcxState from another ResX and I could just look at the changed properties.

In the project (download below) I created a form with the desired control on it, I hacked around with the designer generated code to allow me to override the OcxState.

private readonly AxHost.State state;

public DummyForm()
    : this(null)
{
}

public DummyForm(AxHost.State state)
{
    this.state = state;
    InitializeComponent();
}

//
// axMSFlexGrid1
//
this.axMSFlexGrid1.Location = new System.Drawing.Point(69, 75);
this.axMSFlexGrid1.Name = "axMSFlexGrid1";
if (state == null)
    this.axMSFlexGrid1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMSFlexGrid1.OcxState")));
else
    this.axMSFlexGrid1.OcxState = state;

I used the ResXResourceReader and the ResourceSet classes to get the OcxState from my desired ResX source (the project that has the state in it I want to know). Then using reflection I compared the default state of the control (using the OcxState that the designer created) to the state I desired (with my own OcxState extracted from another ResX) and I now know what properties were changed on the designer.

In this project I have referenced the Microsoft FlexGrid but in theory it could be any ActiveX control.

Download Project

How to invoke a method on a COM object in C#

Where I work we often need to invoke methods on a COM object that has been developed in VB6 or in .NET. I wrote this helper class for speed it along.

public static class ActiveX
{
    public static object Invoke(string @namespace, string @class, string method, params object[] parameters)
    {
        var progId = string.Format("{0}.{1}", @namespace, @class);
        return Invoke(progId, method, parameters);
    }

    public static object Invoke(string progId, string method, params object[] parameters)
    {
        var type = Type.GetTypeFromProgID(progId);
        var comObject = Activator.CreateInstance(type);

        return type.InvokeMember(method, BindingFlags.InvokeMethod, null, comObject, parameters);
    }
}

Composite WPF Presentation Model item template

Neat little template I designed for use at work which is an improvement over the ViewModel code snippet.

Download PresentationModel item template

How to use

It is a bit unusual the way I have written this. Instead of specifying the file name for the item, it is the view name that is to be used.

When prompted for the ViewName, specifying “MainWindow” will create:

A xaml user control called MainWindowView.xaml.

An interface called IMainWindowView.

An interface called IMainWindowViewModel.

A class called MainWindowViewModel.

(Some of this is very similar to the ViewModel code snippet)

Interface Properties

Basically rip-offs of the prop and propg code snippets you get with Visual Studio but without the scope or accessor keywords.

iprop

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>iprop</Title>
			<Shortcut>iprop</Shortcut>
			<Description>Code snippet for an automatically implemented property on an interface</Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[$type$ $property$ { get; set; }$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

ipropg

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>ipropg</Title>
			<Shortcut>ipropg</Shortcut>
			<Description>Code snippet for an automatically implemented property with a 'get' accessor for interfaces</Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[$type$ $property$ { get; }$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

View model property

Because I am so lazy :P

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>View model property snippet</Title>
			<Shortcut>vmprop</Shortcut>
			<Description></Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
        <Literal>
          <ID>name</ID>
          <ToolTip>Property name</ToolTip>
          <Default>Field</Default>
        </Literal>
        <Literal>
          <ID>field</ID>
          <ToolTip>Field name</ToolTip>
          <Default>field</Default>
        </Literal>
        <Literal>
          <ID>type</ID>
          <ToolTip>Type</ToolTip>
          <Default>object</Default>
        </Literal>
			</Declarations>
			<Code Language="csharp">
        <![CDATA[
    $type$ $field$;
    public $type$ $name$
    {
        get { return $field$; }
        set
        {
            if ($field$ == value)
                return;

            $field$ = value;
            SendPropertyChanged("$name$");
        }
    }
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Closeable TabItems using CompositeWPF

On a project I am working on at the moment, I needed to allow the user to open and close views. As I was using the Composite Application Block injecting views into a tab control was really easy. Closing them was not.

To remove a view from a region you need two things, the RegionName and the View.

This article helped me a lot when engineering this approach:

http://blogs.infosupport.com/blogs/willemm/archive/2008/07/31/Creating-closeable-tabitems-for-use-in-CompositeWPF.aspx

However the RegionManager.GetRegionName did not work against the TabItem. I always got null, I am assuming this is a change that was made during the time the article was posted. Using the TabControl however worked.

But you cannot easily bind to two things (the TabControl and the TabItem).

To achieve my goal I used the XAML from the article and changed it little

<DataTemplate x:Key="CustomTabHeader">
<StackPanel Orientation="Horizontal">
<ContentPresenter>
<ContentPresenter.Content>
<Binding Path="Content.Model.HeaderText">
<Binding.RelativeSource>
<RelativeSource Mode="FindAncestor"
AncestorType="{x:Type TabItem}"/>
</Binding.RelativeSource>
</Binding>
</ContentPresenter.Content>
</ContentPresenter>
<Button Margin="8,0,0,0"
Command="{Binding Path=Model.CloseTabCommand.Command, ElementName=ThisControl}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type TabItem}}}"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">
<Grid>
<Canvas Width="8" Height="8">
<Line X1="2" X2="6" Y1="2" Y2="6" Stroke="Black" StrokeThickness="1"/>
<Line X1="6" X2="2" Y1="2" Y2="6" Stroke="Black" StrokeThickness="1"/>
</Canvas>
</Grid>
</Button>
</StackPanel>
</DataTemplate>

<Style TargetType="TabItem">
<Style.Setters>
<Setter Property="HeaderTemplate"
Value="{StaticResource CustomTabHeader}"/>
</Style.Setters>
</Style>

The only difference is where I go for my commands and header text. In my project I have an interface that describes a headed content item.

The change really is in the code for closing the view:

class CloseTabCommand : CommandModelBase
{
private readonly IRegionManager regionManager;

public CloseTabCommand(IRegionManager regionManager)
{
this.regionManager = regionManager;
}

public override void OnExecute(object sender, ExecutedRoutedEventArgs e)
{
var tabItem = (TabItem)e.Parameter;
var tabControl = (TabControl) e.Source;

var regionName = RegionManager.GetRegionName(tabControl);

regionManager.Regions[regionName].Remove(tabItem.Content);
}
}

In the end the solution boiled down to being really simple. You still bind to the tab item but the source is the tab control.

There will be some drawbacks to this approach. If a key binding is setup for this command then the source could change, so care should be taken.

But this works and it will do for the time being until I think of a better solution.

Project Validator

As an idea that compliments the previous validator I built, this msbuild task will search for all the projects in a given path and check that they are all building to the correct path.

Download source

To use just define two properties: SearchPath, which is the parent folder to start looking in. It will search all subfolders as well by default. And BuildFolder, which is the desired target for building to.

All it does is very simple substring matching to check that it is valid.

For example, if I build a project to ..\bin\Debug and ..\bin\Release and the specify my build folder is ..\bin then both paths are valid. But if one of the build targets was set to something like ..\foo then it would be invalid

Again, this validator could be extended to check other parts of the project files.

Assembly Validator

Due to a really subtle problem with our build scripts and project settings at work, we were releasing a debug assembly.

So I built this MSBuild task to validate the assemblies after they have been built.

Download Source

It is very simple to use.

Create a property called ExpectedConfiguration that has the configuration.

Create inclusion and exclusion item groups called AssemblyInclusions and AssemblyExceptions.

Then use the ValidateAssemblies target.

It will then look for all assemblies and validate each ones configuration attribute.

This could be extended to validate assemblies much more extensively, like checking publisher and copyrigth details etc

Generic WeakReference

I always felt that I wanted to use the WeakReference class a lot like the Nullable<T> class.


internal class WrappedWeakReference<T> : WeakReference
 {
 public WrappedWeakReference(T target)
 : base(target)
 {
 }

 public new T Target
 {
 get { return (T) base.Target; }
 set { base.Target = value; }
 }

 public static implicit operator WrappedWeakReference<T>(T item)
 {
 return new WrappedWeakReference<T>(item);
 }
 }

This allows you to write things like:

 private WrappedWeakReference<MyObject> weakMyObject;

 public void Foo()
 {
 weakMyObject = new MyObject();
 }

 public void Bar()
 {
 weakMyObject.Target.SomeProperty....etc
 }
}

I think its nice idea.

However never did actually use this, I implemented the solution in a different manner where I did not need a weakreference, so this never got tested. I am not sure if it would work.

Empty object code snippet pattern

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>Empty pattern snippet</Title>
			<Shortcut>empty</Shortcut>
			<Description>Creates an empty static property and nested null object </Description>
			<Author>Alex Boyne-Aitken</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Class type</ToolTip>
					<Default>Class</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[
			private static readonly $type$ empty = new NullObject();
public static $type$ Empty { get { return empty; } }

private class NullObject : $type$
{
}
			$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

Download