TimeSpans cann't be serialized. The best workaround I've found is to serialize the TimeSpan Ticks property instead. This can be done as follows:

private TimeSpan _sampleRate = new TimeSpan(0, 0, 0, 1, 0);
[XmlIgnore]
public TimeSpan SampleRate
{
	get { return _sampleRate; }
	set { _sampleRate = value; }
}
[XmlElement("SampleRate"), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public long SampleRateTicks
{
	get { return SampleRate.Ticks; }
	set { SampleRate = new TimeSpan(value); }
}

As always, feel free to comment, or ask.


Layers in XAML

Published 7/13/2013 by Christian
Tags: ,

This took me some time to figure out how to do. But as always, as soon as you figure it out, its actually quite simple.

I had two images I, in some cases, wanted to place on top of each other. It turns out, that if you put a given number objects into the same grid cell, they will be placed in layers.

<Grid>
	<Grid Grid.Column="0" Grid.Row="0"> 
		<Image Source="{Binding Path=Image}" />
	</Grid>
	<Grid Grid.Column="0" Grid.Row="0">
		<Image Source="{Binding Path=HoverImage}" />
	</Grid>
</Grid>

As always, feel free to comment, or ask.


OK this is not rocket science, but I keep forgetting.

To get the current mouse position relative to a control, System.Windows.Forms.Control has a static MousePosition property

System.Windows.Forms.Control.MousePosition

and a PointToClient method, which will take the screen coordinats as a Point as agument, and return a the client coordinates.

Eg. in a TreeView, this can be used to get the node the mouse is pointing at, as:

TreeNode editNode = treeView.GetNodeAt(treeView.PointToClient(System.Windows.Forms.Control.MousePosition));

As always, feel free to comment, or ask.


To ensure thread safety where Invoke is not implemented, can be done with a System.Windows.Threading.Dispatcher.

 

The Dispatcher should of course run on same thread as the thread safe instance, hence the Dispatcher instance should be created when the thread safe instance is constructed.

 

A little example is in order here, I guess.

Say that we have a object Foo accessed by object Bar, in Bar’ backgroundworker. This would cause a cross-thread exception

public class Foo
{
    private Object _fooBar;
    public Object FooBar
    {
        get { return _fooBar; }
        set { _fooBar = value; }
    }
    
    public Foo()
    {
    }
}

public class Bar
{
    private Foo _foo;
    public Foo Foo
    {
        get { return _foo; }
        set { _foo = value; }
    }
    
    public Bar()
    {
        this.Foo = new Foo();

        BackgroundWorker backgroundWorker = new BackgroundWorker();
        backgroundWorker.DoWork += backgroundWorker_DoWork;
    }

    void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        Foo.FooBar = NextFooBar();
    }

    private object NextFooBar()
    {
        return new Object();
    }
}

Since Foo don’t implement Invoke (or inherit from a object that does), one way to get about this would be to use a System.Windows.Threading.Dispatcher.

public class Foo
{
    private System.Windows.Threading.Dispatcher _dispatcher = null;
    private Object _fooBar;
    public Object FooBar
    {
        get { return _fooBar; }
        set { _dispatcher.Invoke(((Action<Object>))delegate(v) { internalSetFooBar(v); }, new object[] { value }); }
    }
    private void internalSetFooBar(object value)
    {
        _fooBar = value;
    }
    
    public Foo()
    {
        _dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
    }
}

public class Bar
{
    private Foo _foo;
    public Foo Foo
    {
        get { return _foo; }
        set { _foo = value; }
    }
    
    public Bar()
    {
        this.Foo = new Foo();

        BackgroundWorker backgroundWorker = new BackgroundWorker();
        backgroundWorker.DoWork += backgroundWorker_DoWork;
    }

    void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        Foo.FooBar = NextFooBar();
    }

    private object NextFooBar()
    {
        return new Object();
    }
}

As always, feel free to comment, or ask.

 


In Visual Studio 2012, tracking the open/focused file in the Solution Explore can be done in

Options -> Projects and Solutions

 

As always, feel free to comment, or ask.


Implementering IEnumerable

Published 5/24/2013 by Christian in Code

Implementering IEnumerable<T> can be done as follows:

#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
    foreach (var item in List)
    {
        if (item == null)
        {
            break;
        }
        yield return item;
    }
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}
#endregion

Static Events

Published 1/7/2013 by Christian in Code

Using Static Events should be done with care, if you are subscribing to such an event from instances, as a race condition could occur, when subscribing and null-checking the event.
The trick here is to subscribe a trivial handler to the static event, when declaring it, eg.:

//Added a trivial handler to avoid race condition;
public static event EventHandler DataChangedEvent = delegate { };

Then you can use it without the null check.

//No need to null check. A trivial event handler has been subscribed to event.
DataChangedEvent(ToolTip, EventArgs.Empty);

Oh by the way - this trick naturally also applies to instance events.

As always, feel free to comment, or ask.

 

Edit

In C# 6.0 this can actually be done much more nicely, using the 'Null-conditional operators'.

 

DataChangedEvent?.Invoke(ToolTip, EventArgs.Empty);

 

This way you don't need to subscribe the trivial handler to the static event. So declaring it will just look like this - even for a static event:

public static event EventHandler DataChangedEvent;

You can watch Mads Torgersen brief video on C# 6.0 here:

http://channel9.msdn.com/Events/Visual-Studio/Connect-event-2014/116


XAML

Published 12/10/2012 by Christian in Code
Tags:

Doing a new Modern UI/Metro style UI to our application, recently I’ve been fortunate enough to begin working in WPF.
To get a quick overview of XAML, I found these IMO rather good tutorials:


http://www.youtube.com/watch?v=0qE5hyuU9hE&feature=g-hist


http://www.youtube.com/watch?v=qPDNgN2mEeA


As of yet, I haven’t had time to watch the rest in the series, but I would guess that, if one would need more explanation, it would be worth watching them.

 

As always, feel free to comment, or ask.


Sometimes, and as far as I have been able to determine after I have cancelled a build, the “Find in Files” function in Visual Studio (2010 and 2012) isn’t working. It wouldn’t search all the files in my solution.
According to the below, the solution is, amoun other, to press <Ctrl + Scroll lock>. This key combination however is the only one I’ve tried.


Quote
Hi all,

Thank you for your continued interest in this bug. We have been able to reproduce the issue intermittently in several versions of Visual Studio running on several versions of Windows and have identified the root cause as external to VS. The Windows team unfortunately did not have time to fix this for their current release, but we are working with them to hopefully have this bug fixed for a future version of Windows. At present, the workaround (as many of you noted) is to press Ctrl+Scroll Lock, Ctrl+Break, or the Break key alone.

Again, thanks for all of the details you provided about this bug. If you have any further questions or comments, please feel free to post again here; although this issue was closed quite a while ago, I'll make sure it stays on our radar.

Thanks, Brittany Behrens Program Manager, VS Platform - Editor
End Quote

Unfortunately I haven’t been able to find the link to this post.


As always, feel free to comment, or ask.


Did you know that
Event -= new EventHandler(yourEventHandler)
wouldn’t unsubscribe the event handler from the event. This means that the object that contains the event still holds a reference to the object containing the event handler and visa versa. And if you try to dispose one of the object, the GarbageCollector wouldn’t collect it. It will remain in memory until both object are disposed.

The way to resolve this is to make an instance of the delegate you want to subscribe to the event, and unsubscribe this instance from the event.

An example might be in order here:

public class Foo : IDisposable
{
    public event System.EventHandler AnEvent;

    private void RaiseEvent()
    {
        if (AnEvent != null)
        {
            AnEvent(this, new System.EventArgs());
        }
    }

    void IDisposable.Dispose()
    {
        AnEvent = null;
    }
}

public class Bar : IDisposable
{
    private System.EventHandler _eventHandler = null;
    public System.EventHandler EventHandler
    {
        get
        {
            //If no instance of _eventHandler exist, create a new one
            if (_eventHandler == null)
            {
                _eventHandler = new System.EventHandler(theEventHandler);
            }
            return _eventHandler;
        }
    }

    private Foo _foo;

    public Bar()
    {
        _foo = new Foo();
        _foo.AnEvent += EventHandler; //Subscribe to AnEvent
    }

    private void theEventHandler(object sender, System.EventArgs e)
    {
        //Do the handling stuff
    }

    void IDisposable.Dispose()
    {
        _foo.AnEvent -= EventHandler; //UnSubscribe from AnEvent
        _foo = null;
    }
}


Notice that I have created an instance of the event handler delegate in the

public EventHandler EventHandler


property.
This instance (_eventHandler) is the instance that I subscribe to the event

_foo.AnEvent += EventHandler;


and unsubscribe again in Dispose

 

_foo.AnEvent -= EventHandler;

 


As always, feel free to comment or ask.