CoreCLR's Blog

Archive for the ‘.NET’ Category

Display a messagebox from the ViewModel using Prism’s InteractionRequests

Posted by coreclr on January 5, 2011

Prism has a nice feature called InteractionRequests. We can use this when the view-model needs to initiate an interaction, like displaying a messagebox.

Below is a simple example:

XAML:

In XAML I define the PopupChildWindowAction to display the dialog to the user.  The visuals of this dialog is defined in the SaveWindowsTemplate.
The magic here is the InteractionRequestTrigger from Prism. I set the SourceObject to the SaveRequest that is defined in the ViewModel.

SaveRequest is a InteractionRequest that define a Raise method, that we can use to raise the event.

I then use a interaction trigger to call the Cancel method in the viewmodel.  See Preview post.

ViewModel:

And the result look like this:

Advertisements

Posted in .NET, Silverlight | Leave a Comment »

Using interaction triggers in MVVM

Posted by coreclr on January 5, 2011

Commands are ofter to limited when using the MVVM pattern. Instead we can use interaction triggers.

Here is a simple example of handling the MouseEnter event for a button in a viewModel.

XAML:

ViewModel:

The key point here is the CallMethodAction object. CallMethodAction is a TriggerAction defined in the Microsoft.Expression.Interactivity.Core namespace. In this example I set TargetObject to the DataContext (the viewModel) and MethodName to the method we want to call in the ViewModel.

If you need to send parameters to the method, you just expose those as properties in the viewModel and use standard DataBinding.

Remember to reference Microsoft.Expression.Interactions.dll

Posted in .NET, Silverlight | Leave a Comment »

Executing Unit Tests on the Build server only

Posted by coreclr on November 18, 2010

We often have some Unit Tests/Integration Tests that we only want to execute when the tests are running on the TFS build server.
One solution is to put these tests in a separate solution, but this is annoying when doing refactoring. Having a separate solution is also a bad choice when we want to see our total code coverage results.
Another solution is to use the Test List feature in Visual Studio, but these Test Lists are just pure pain!

I would like to put an attribute on the TestMethod instead. As far as I know, this is not possible today.

So currently we have an environment variable on the build server, and then we use this method from our tests:

public static class TestUtils
{
	public static bool IsTestRunningOnBuildServer()
	{
		if (Environment.GetEnvironmentVariable("IS_TFS_SERVER", EnvironmentVariableTarget.Machine) != null)
		{
			return true;
		}
	   return false;
	}
}

Very simple, but it works.

Another solution is to use Test Categories in TFS2010:

http://www.edsquared.com/2009/09/25/Test+Categories+And+Running+A+Subset+Of+Tests+In+Team+Foundation+Server+2010.aspx

 

Posted in .NET | Tagged: | Leave a Comment »

Overriding Equals for Reference and Value Types

Posted by coreclr on February 7, 2010

In different programming forums, there are always questions about how, why and when to override Equals and GetHashCode for .NET types.

Its actually relative simple to do, so in this post we will look at overriding Equals for Reference and Value Types.

For reference types, we want to override Equals when we want to check for equality and not identity.

We will use this simple Car class as example:

public class Car
    {
        private readonly string serialNumber;

        public string SerialNumber
        {
            get { return serialNumber; }
        }

        public Car(string serial)
        {
            serialNumber = serial;
        }
    }

Comparing two Car instances will return false, since Equals checks identity. That is, the two references does not point to the same object.

Car car1 = new Car("12345");
Car car2 = new Car("12345");
Console.WriteLine(car1.Equals(car2));

But lets say that we want to check for equality instead. So two Car’s are Equal, if the SerialNumber on the car’s are equal. Lets override the Equals method: 


public override bool Equals(object obj)
{
  if (obj == null)
      return false;

  if (Object.ReferenceEquals(this, obj))
      return true;

  if (this.GetType() != obj.GetType())
      return false;

  return ((Car)obj).SerialNumber == this.SerialNumber;
}

Now Equals will return true for two types with the same SerialNumber.

Will can also implement the IEquatable interface, so we get a type safe Equals method. So we will move the logic to the generic method, and let the non-generic method call the generic method:

public override bool Equals(object obj)
   {
       Car car = obj as Car;
       if (car != null)
       {
           return Equals(car);
       }
       else
       {
           return false;
       }
   }

   public bool Equals(Car other)
   {
       if (other == null)
           return false;

       if (Object.ReferenceEquals(this, other))
           return true;

       if (this.GetType() != other.GetType())
           return false;

       return ((Car)other).SerialNumber == this.SerialNumber;
   }

The last thing we should do, is overriding GetHashCode. The doc says, that Types that override Equals must also override GetHashCode. That is, if two types are equal, the must return the same HashCode. So lets override GetHashCode as well.

Here is the complete class:

public class Car : System.IEquatable<Car>
{
   private readonly string serialNumber;

   public string SerialNumber
   {
       get { return serialNumber; }
   }

   public Car(string serial)
   {
       serialNumber = serial;
   }

   public override bool Equals(object obj)
   {
       Car car = obj as Car;
       if (car != null)
       {
           return Equals(car);
       }
       else
       {
           return false;
       }
   }

   public bool Equals(Car other)
   {
       if (other == null)
           return false;

       if (Object.ReferenceEquals(this, other))
           return true;

       if (this.GetType() != other.GetType())
           return false;

       return ((Car)other).SerialNumber == this.SerialNumber;
   }

   public override int GetHashCode()
   {
       return SerialNumber.GetHashCode();
   }
}

This completes the override of Equals for a reference type. Now lets look at Value Types.

By default the Equal method for value types actually checks for equality and not identity. This is implemented in the System.ValueType that overrides Equals. Its implemented something like this:

public override bool Equals(object obj)
{
if (obj == null)
{
   return false;
}
RuntimeType type = (RuntimeType) base.GetType();
RuntimeType type2 = (RuntimeType) obj.GetType();
if (type2 != type)
{
   return false;
}
object a = this;
if (CanCompareBits(this))
{
   return FastEqualsCheck(a, obj);
}
FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic 
| BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < fields.Length; i++)
{
   object obj3 = ((RtFieldInfo) fields[i]).InternalGetValue(a, false);
   object obj4 = ((RtFieldInfo) fields[i]).InternalGetValue(obj, false);
   if (obj3 == null)
   {
       if (obj4 != null)
       {
           return false;
       }
   }
   else if (!obj3.Equals(obj4))
   {
       return false;
   }
}
return true;
}

We can see that is uses reflection.

The implementation is pretty much the same as the implementation for a reference type.

Here is the complete code for the value type:

public struct Car : System.IEquatable<Car>
{
   private readonly string serialNumber;

   public string SerialNumber
   {
       get { return serialNumber; }
   }

   public Car(string serial)
   {
       serialNumber = serial;
   }

   public override bool Equals(object obj)
   {
       if (obj is Car)
       {
           return ((Car)obj).Equals(this);
       }
       else
       {
           return false;
       }
   }

   public bool Equals(Car other)
   {
       if (other == null)
           return false;

       if (Object.ReferenceEquals(this, other))
           return true;

       if (this.GetType() != other.GetType())
           return false;

       return ((Car)other).SerialNumber == this.SerialNumber;
   }

   public override int GetHashCode()
   {
       return SerialNumber.GetHashCode();
   }

   public static bool operator ==(Car a, Car b)
   {
       return a.Equals(b);
   }

   public static bool operator !=(Car a, Car b)
   {
       return !(a.Equals(b));
   }
}


I you want all the details, go directly to the source – MSDN.

Posted in .NET | Leave a Comment »

Silverlight Feature Request: Allow Network Communication on Application Exit

Posted by coreclr on December 6, 2009

If you would like native .NET access to calling Web Services on Application Exit, then vote here:
http://silverlight.uservoice.com/pages/4325-runtime-feature-suggestions/suggestions/310806-allow-the-app-to-hit-a-web-service-on-exit?ref=title

Posted in .NET, Silverlight, Threading | Leave a Comment »

How to expand TreeViewItems from right to left in Silverlight

Posted by coreclr on November 28, 2009

In this post I am going to show how we can change the Silverlight TreeView Template to support expanding TreeViewItems from right to left.
The text on the items should still be left-to-right and the text should be right alligned.

First we will build a normal TreeView with some data.

We define a HierarchicalDataTemplate:

<UserControl.Resources>
      <common:HierarchicalDataTemplate x:Key="MyHierarchicalTemplate" ItemsSource="{Binding Items}" >
          <TextBlock Text="{Binding Title}" />
      </common:HierarchicalDataTemplate>
  </UserControl.Resources>

And this is the TreeView that will use the HierarchicalDataTemplate:

<controls:TreeView VerticalAlignment="Stretch" 
          x:Name="treeView"                                                                  
          ItemTemplate="{StaticResource MyHierarchicalTemplate /> 

Then we define a simple class to hold the data:

public class DataItem
    {
      public string Title { get; set; }
      public ObservableCollection<DataItem> Items { get; set; }

      public DataItem(string title, params DataItem[] items)
      {
          this.Title = title;
          ObservableCollection<DataItem> itemsObservableCollection =
              new ObservableCollection<DataItem>();

          foreach (var item in items)
            itemsObservableCollection.Add(item);

         Items = itemsObservableCollection;
      }
    }


And in our MainPage we populate the TreeView with some data:

public partial class MainPage : UserControl
    {
        ObservableCollection<DataItem> itemsSource;
        public MainPage()
        {
            InitializeComponent();
            AddData();
            treeView.ItemsSource = itemsSource;
        }

        private void AddData()
        {
            itemsSource = new ObservableCollection<DataItem>()
            {
                 new DataItem("Europe",
                    new DataItem("Denmark"),
                    new DataItem("Norway"),
                    new DataItem("Sweden")),
                  new DataItem("USA",
                    new DataItem("New York",
                        new DataItem("Albany"))),
            };
        }
    }

When we run this, we get a simple TreeView like this:

image

So far, so good. Now lets change the Template so we can get the TreeView to display the items from Right to Left.

We open Blend and edit the ItemContainerStyle Template:

image

First set HorizontalContentAlignment and HorizontalAlignment to right:

<Setter Property="HorizontalContentAlignment" Value="Right"/>
<Setter Property="HorizontalAlignment" Value="Right"/>


Now locate the Grid element, and change the definition to this:

<Grid.ColumnDefinitions>
   <ColumnDefinition Width="Auto"/>
   <ColumnDefinition Width="15"/>
   <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="*"/>
</Grid.RowDefinitions>

Now located the Selection Rectangle element and set these two properties:

Grid.Column="0"
HorizontalAlignment="Right"


Now located the Header Button element and set these properties:

Margin="0,0,10,0"
Grid.ColumnSpan="2"
HorizontalAlignment="Right"

Next locate the ContentPresenter and set HorizontalAlignment:

HorizontalAlignment="Right"

Then locate the ItemsPresenter element and set these properties:

Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Margin="0,0,10,0"
HorizontalAlignment="Right"
Visibility="Collapsed"

Now Locate the ExpanderButton and set these properties:

VerticalAlignment="Stretch" 
HorizontalAlignment="Right" 
RenderTransformOrigin="0.5,0.5" 
Grid.Column="1"

Now we will use a RotateTransform to rotate the ExpanderButton. Add this:

<ToggleButton.RenderTransform>
           <TransformGroup>
              <ScaleTransform/>
              <SkewTransform/>
              <RotateTransform Angle="-180"/>
              <TranslateTransform/>
           </TransformGroup>
</ToggleButton.RenderTransform>

Now add a RotateTransform to the CheckedVisual Path element. We rotate that –90.

<Path.RenderTransform>
  <TransformGroup>
     <ScaleTransform/>
     <SkewTransform/>
     <RotateTransform Angle="-90"/>
     <TranslateTransform/>
  </TransformGroup>
</Path.RenderTransform>

That’s it!

Set the ItemContainerStyle on the TreeView to our new Template:

ItemContainerStyle="{StaticResource RightToLeftViewItemStyle}"

Run and you should see the Items expanding from right to left with the text alligned to the right:

image

Get the code here.

(rename it to .zip)

Posted in .NET, Silverlight | Leave a Comment »

Async chain of service calls in Silverlight

Posted by coreclr on November 26, 2009

A colleague of mine asked me how to chain service calls in a Silverlight async model.

Lets say you have these two operations:

string GetId()
void Calculate(string id)

And you must call GetId first and then use the result of that operation to call the Calculate operation.

The solution is pretty simple. We can use our old friend; the AutoResetEvent class. Luckly this exist in Silverlight as well.

First we put the task on the ThreadPool so we don’t block the UI Thread:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(StartWork);
}

And here is the StartWork method:

public void StartWork(object state)
{
    var dataService = new DataServiceClient();
    var personService = new PersonServiceClient();

           string id = string.Empty;
           dataService.GetIdCompleted += (s, e) =>
           {
               id = e.Result;

               //signal the event, so the thread can continue
               autoResetEvent.Set();
           };

           //call GetIdAsync
           dataService.GetIdAsync();

           //pause the thread
           autoResetEvent.WaitOne();

           //call CalculateAsync with the id
           personService.CalculateAsync(id);
}

Thats it. Pretty simple.

Posted in .NET, Silverlight, Threading | Leave a Comment »

Silverlight 4 Beta

Posted by coreclr on November 18, 2009

Today we can download a beta version of Silverlight 4.

The tools are here and Expression Blend are here.

Silverlight 4 has a lot of nice features. If you have done any LOB WPF development, you will be very happy to see these new features in Silverlight 4:

– Trusted applications (COM Interop, file-access, network)
– Printing Support
– Right-click context menu
– Clipboard access Support
– Better Data Binding support (grouping/editing, StringFormat)
– Implicit Styling
– RichTextbox support
– IDataErrorInfo support
– Build-in mouse wheel support
– Webcam and microphone support
– Network credentials support (authentication)
– WCF NetTcp Binding
– UDP Multicast Support
– Profiler and Profiler API
– Out of browser Window settings (position, size, chrome)
– Notification windows (toast)
– Embedding HTML (WebBrowser control)
– Same compiled code to be run on the desktop and Silverlight

and off course WCF RIA Services

This page describe all the new features and this page describe known bugs in Silverlight 4.

And finally this page describe a Technical Feature Overview.

Posted in .NET, Silverlight, WPF | Leave a Comment »

RelativeSource Binding in Silverlight 3

Posted by coreclr on November 9, 2009

Silverlight 3 introduced the RelativeSource Binding that we know from WPF.

As the name indicates, RelativeSource  is used when setting up a relative Data Binding.

Lets look at an example. If we want to bind the ToolTip to  Content property on the same element, we can say:

<Button Content="Button" Height="25" Width="75"
    ToolTipService.ToolTip="{Binding Content, 
RelativeSource={RelativeSource Self}}" />

As you can see, when binding to ourself, we don’t need any name on the element.

Another option is to use TemplatedParent.

Lets say that we want to change a Slider template to include a TextBox. And that TextBox should always display the same value as the slider.

Here is the full code:

<Slider Height="84" Margin="229,151,200,0" VerticalAlignment="Top">
    <Slider.Template>
        <ControlTemplate>
            <Grid x:Name="Root">
                <Grid.Resources>
                    <ControlTemplate x:Key="RepeatButtonTemplate">
                        <Grid x:Name="Root" Opacity="0" 
                              Background="Transparent"/>
                    </ControlTemplate>
                </Grid.Resources>
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="CommonStates">
                        <VisualState x:Name="Normal"/>
                        <VisualState x:Name="MouseOver"/>
                        <VisualState x:Name="Disabled"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
                <StackPanel>
                    <Grid x:Name="HorizontalTemplate" 
                          Background="{TemplateBinding Background}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Rectangle x:Name="TrackRectangle" 
                                   Fill="#FFE6EFF7" Stroke="#FFA3AEB9" 
                                   StrokeThickness="{TemplateBinding BorderThickness}" 
                                   RadiusX="1" RadiusY="1" Height="3" Margin="5,0,5,0" 
                                   Grid.Column="0" Grid.ColumnSpan="3"/>
                        <Rectangle x:Name="HorizontalTrackRectangleDisabledOverlay" 
                                   Fill="White" RadiusX="1" RadiusY="1" Height="3" 
                                   Margin="5,0,5,0" Opacity=".55" Visibility="Collapsed" 
                                   Grid.Column="0" Grid.ColumnSpan="3"/>
                        <RepeatButton x:Name="HorizontalTrackLargeChangeDecreaseRepeatButton" 
                                      Height="18" IsTabStop="False" Template="{StaticResource 
                            RepeatButtonTemplate}" Grid.Column="0"/>
                        <Thumb x:Name="HorizontalThumb" Height="18" Width="11" IsTabStop="True" 
                               Grid.Column="1"/>
                        <Rectangle x:Name="ThumbDisabledOverlay" Fill="White" RadiusX="2" 
                                   RadiusY="2" Width="11" Opacity=".55" Visibility="Collapsed" 
                                   Grid.Column="1"/>
                        <RepeatButton x:Name="HorizontalTrackLargeChangeIncreaseRepeatButton" 
                                      Height="18" IsTabStop="False" 
                                      Template="{StaticResource RepeatButtonTemplate}" 
                                      Grid.Column="2"/>
                    </Grid>
                    <TextBox Width="200" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                        Path=Value}"/>
                </StackPanel>
            </Grid>
        </ControlTemplate>
    </Slider.Template>
</Slider>

The line that we are interested in is this:

<TextBox Width="200"
        Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
        Path=Value}"/>

The TextBox is inside the Slider Template. We use TemplatedParent to bind the Text Property of the TextBox to it’s parent’s Value property (the slider is the parent).

There is a important difference between using a Binding with RelativeSource like this, and using the normal TemplateBinding.

The TemplateBinding is a one-way binding. From the templated parent to a element inside the template. If you need binding both ways, then you should use a Binding with RelativeSource as above.

WPF has two other options that Silverlight don’t: PreviousData and FindAncestor.

With PreviousData we can bind the previous data item in the list of data items being displayed. And FindAncestor refers to the ancestor in the parent chain of the data-bound element

Posted in .NET, Silverlight, WPF | Leave a Comment »

Debugging Release Builds

Posted by coreclr on October 30, 2009

This is a nice little trick you might not know.

Lets say you have an application build in release
mode (/debug:pdbonly /optimize+) and you want to attach the debugger directly to a running instance.

To keep it simple, this is our app:

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

          private void button1_Click(object sender, RoutedEventArgs e)
          {
              Cal(100);
          }

          int Cal(int x)
          {
              return x * x;
          }
      }

We set a break point in this line and attach to the process:

return x * x;

But the debugger will never break in our code!

The reason is that the JIT compiler has inlined the method call (remember that will compiled with /optimize+)

This is indeed a good thing. In most cases, we want the JIT compiler to have the option to inline our production code.

We can see that the module is optimized in the modules window in VS:

 image

Disable JIT Optimization

For debugging purposes, we can actually disable JIT Optimization without rebuilding the code.

Put an ini file (yes ini) in the same folder as the exe file. The filename should match the exe filename, just with ini as extension. In this case WpfApplication1.exe and WpfApplication1.ini.

The ini file should contain these 3 lines:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

This will tell the JIT compiler not to optimized the code, so the method-call won’t be inlined.

We can now see that the loaded module is not optimized:

image

Remember to disable “Enter Just My Code” in VS.NET (Tools –> Options –> Debugger)

Posted in .NET, Debugging, Visual Studio, WPF | Leave a Comment »