Rx (Reactive Extensions)

Reactive Extensions (Rx) was added to Codeplex.com:

The project is actively developed by the Microsoft Open Technologies, inc., in collaboration with a community of open source developers.

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developersrepresent asynchronous data streams with Observables , query asynchronous data streams usingLINQ operators, and parameterize the concurrency in the asynchronous data streams usingSchedulers. Simply put, Rx = Observables + LINQ + Schedulers.

Find out more on: https://rx.codeplex.com/

Making Instant C# Viable – Visualization

A project from Ermau: Research into instant feedback in software engineering.

Check out the cool video at http://ermau.com/making-instant-csharp-viable-visualization/.

Find out more at:

C#: Save a canvas as an image

This C# code saves a Canvas as a *.PNG image:

private void CreateSaveBitmap(Canvas canvas, string filename)
     {
       RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)canvas.Width, (int)canvas.Height,
        96d, 96d, PixelFormats.Pbgra32);
      // needed otherwise the image output is black
       canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));
       canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

renderBitmap.Render(canvas);

//JpegBitmapEncoder encoder = new JpegBitmapEncoder();
       PngBitmapEncoder encoder = new PngBitmapEncoder();
       encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

using (FileStream file = File.Create(filename))
       {
         encoder.Save(file);
       }
     }

Use it like this:

CreateSaveBitmap(myCanvas, @"C:\temp\out.png");

ASP.NET Web API

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

Can’t wait for the full version of MVC 4! 🙂

[ link ]

ActiveMesa MathSharp: convert your math to code

Have you ever had to convert a formula in a Word document to code? Ever wished that it could somehow be automated? With MathSharp, this is possible!

 

MathSharp is a program for automatic conversion of math equations from MathML (produced by programs such as Word or MathType) into code in languages such as C# or F#.

[ link ]

ASP.NET MVC: place JavaScript from a View inside the head-section by using sections

When working with ASP.NET MVC, you often need some JavaScript in your views.
The most obvious way of doing this is just adding the JavaScript inside the view:

@{
     ViewBag.Title = "About Us";
 }

<script type="text/javascript">
     // some code
   </script>

<h2>About</h2>
 <p>
      Put content here.
 </p>

Your html source code will end up with a mess:

<!DOCTYPE html>
<html>
 <head>
<meta charset="utf-8" />
<title>About Us</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
 <body>
     <div>
         <header>
             <div id="title">
                 <h1>Title</h1>
             </div>
            <div id="logindisplay">
                     [ <a href="/Account/LogOn">Log On</a> ]
            </div>
             <nav>
                 <ul id="menu">
                     <li><a href="/">Home</a></li>
                     <li><a href="/Product">Products</a></li>
                     <li><a href="/Home/About">About</a></li>
                 </ul>
             </nav>
         </header>
         <section id="main">
<script type="text/javascript">
            // some code
          </script>
          <h2>About</h2>
          <p>      Put content here. </p>
</section>
        <footer>
        </footer>
     </div>
 </body>
 </html>

As you can see in the code above, the JavaScript was added where the your view was rendered.
To keep your code clean, you can use and render sections!

Open your master View _Layout.cshtml and add a RenderSection:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>@ViewBag.Title</title>
     <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
     <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
     <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
     @if (IsSectionDefined("MyOtherJavascript"))
     {
       @RenderSection("MyOtherJavascript");
     }
 </head>
 <body>

Now in your View (in my case /Home/About.cshtml) add the section:

@{
     ViewBag.Title = "About Us";
 }
@section MyOtherJavascript {
   <script type="text/javascript">
     // some code
   </script>
 }
<h2>About</h2>
 <p>
      Put content here.
 </p>

Now your JavaScript will be injected inside the header:

<!DOCTYPE html>
 <html>
 <head>
     <meta charset="utf-8" />
     <title>About Us</title>
     <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
     <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
     <script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
     // some code
   </script>
 </head>
 <body>
<!-- ... -->

That’s it! 🙂
You can add more logic to it, there is also an overload of the RenderSection in case you just want to say it is optional or not.

I demonstrated the RenderSection by injecting JavaScript into the header, but this can be used in other places (and you can also inject and render normal html code). 😉

FYI: I’m using ASP.NET MVC 3 with Razor engine.

msdn ]

BugAid for Visual Studio: Enhance your debugging experience

BugAid is an extension for Visual Studio that can help you whenever you debug C# code. Using our unique features you can debug faster than ever before and have more time for writing quality code!

P.S.: If you buy BugAid, I would appreciate it if you leave them a message that you got the news from this blog 😉

[ link ]

UnicornManager: Prism 4, MEF, WPF, EF 4.1 code first, NuGet, MVVM, DataValidation, …

This blog post is an attempt to learn and discover Prism 4 together with MEF, EF 4.1 code first and by trying to use concepts like a repository, data validation and Unit of Work.

The reason why I post this here is to (1) learn from your comments and (2) create a basic guided tutorial for beginners.

I hope you don’t mind that I’ve chosen unicorns for this example 😉

Go!

Let’s start Visual Studio 2010 Service Pack 1 and create a new WPF Application called UnicornManager:

The solution will contain 3 projects at the end:

  • UnicornManager
  • UnicornManager.Core
  • UnicornManager.Data

UnicornManager.Core will be our core module, hence the name.
The first thing that we are going to do is preparing our UnicornManager project so that it can import other modules via MEF.

First we are going to add some references.
Right-click UnicornManager and select [Add Reference…] and search for System.ComponentModel.Composition in the [.NET] tabpage.

Next we need to install Prism with MEF. Make sure the UnicornManager project is selected and in Visual Studio click [Tools] > [Library Package Manager] > [Manage NuGet Packages…]
Click [Online] on the left and in the [Search Online] textbox type in: Prism.
Select Prism.MEFExtensions and click [Install].
(This will automatically also install Prism, because it depends on it)

Now rename MainWindow.xaml to Shell.xaml by right-clicking it and [Rename].
Open the Shell codebehind file (Shell.xaml.cs) and also rename MainWindow to Shell.

Above the partial Shell class add the [Export] attribute.

The codebehind for Shell should look like this now:

namespace UnicornManager
{
/// <summary>
/// Interaction logic for Shell.xaml
/// </summary>
[Export]
public partial class Shell : Window
{
public Shell()
{
InitializeComponent();
}
}
}

Now in the Shell xaml code we will create a very basic layout. We have a region to show our content and on the left a region for the sidebar. I have called these two regions MainRegion and SidebarRegion where our Views (UserControls) will be made visible. For the regions I’m using two ContentControls, but don’t forget that an ItemsControl also exists to host multiple UserControls in it.

This is the XAML:

<Window x:Class="UnicornManager.Shell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Regions="http://www.codeplex.com/prism">http://www.codeplex.com/prism"
Title="Shell" Height="600" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<ContentControl x:Name="MainRegion"
Regions:RegionManager.RegionName="MainRegion"
Grid.Column="1" />

<ContentControl x:Name="SidebarRegion"
Regions:RegionManager.RegionName="SidebarRegion"
Grid.Column="0" />
</Grid>
</Window>

Add a new class to the UnicornManager project and name it CoreBootstrapper.cs.
This class will be the starting point of our application.

Make the class public and let it inherit from MefBootstrapper.
The other methods are being used to tell our application which is our main Window to start up and where our other Views and objects  are located.

The bootstrapper code looks like this:

namespace UnicornManager
{
public class CoreBootstrapper : MefBootstrapper
{
protected override System.Windows.DependencyObject CreateShell()
{
return this.Container.GetExportedValue<Shell>();
}

protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (Window)this.Shell;
Application.Current.MainWindow.Show();
}

protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreBootstrapper).Assembly));
}
}
}

Now if you try to run the project you will receive an IOException that the resource ‘mainwindow.xaml’ cannot be located. Don’t worry, we just forgot to remove the startup path from the App.xaml code:

<em> </em>StartupUri="MainWindow.xaml"

Now in the App codebehind tell the application that it should use our bootstrapper instead:

public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

CoreBootstrapper bootstrapper = new CoreBootstrapper();
bootstrapper.Run();
}
}

If everything went fine, you should be able to run the application. 😀

Now add a new Class Library project called UnicornManager.Data to the solution. This project will contain our models by using the Entity Framework 4.1 code first.

Delete Class1.cs from the project and create two folders: DAL and Models.
(DAL = Data Access Layer)

Make sure you have the Data project selected and install EntityFramework via NuGet:

Add also the System.ComponentModel.Composition reference to the project.

Lets create our simple model by adding a new Unicorn class to the Models folder. Here is the code:

namespace UnicornManager.Data.Models
{
public class Unicorn
{
public int UnicornId { get; set; }

public string LastName { get; set; }
public string FirstName { get; set; }
}
}

In the DAL folder we are going to add some repositories, UnitOfWork and code necessary for EF 4.1 code first. I’m not posting the code here, you can download this and check the DAL folder in the UnicornManager.Data project.

Because this is just a basic demo application with one class, we would not need a UnitOfWork because it is just an extra wrapper around the UnicornRepository. However if you have more models you will have some extra Repositories, which can be placed in the UnitOfWork.

Our last step is to create our Core module. Add a new Class Library project to the solution called UnicornManager.Core. This will contain our ViewModels and Views.

Delete Class1.cs and add a new class called CoreModule.cs.
Remember we also need to add Prism here by getting the Prism.MEFExtensions from NuGet and a reference to System.ComponentModel.Composition and System.Xaml.

The CoreModule is the entry point for our Bootstrapper. Here we Export our module and register our Views with the regions of our Shell.
This is the code:

[Module(ModuleName = "CoreModule")]
[ModuleExport(typeof(CoreModule))]
public class CoreModule : IModule
{
private IRegionManager _RegionManager;

[ImportingConstructor]
public CoreModule(IRegionManager regionManager)
{
this._RegionManager = regionManager;
}

#region IModule Members

public void Initialize()
{
_RegionManager.RegisterViewWithRegion("MainRegion", typeof(Views.MainView));
_RegionManager.RegisterViewWithRegion("SidebarRegion", typeof(Views.SidebarView));
}

#endregion
}

In the Initialize method, we register two views, but we didn’t create them yet, time to do this first.

Add two folders in the Core project: ViewModels and Views.
In the ViewModels folder add two classed called: MainViewModel.cs and SidebarViewModel.cs.

Code for MainViewModel:

namespace UnicornManager.Core.ViewModels
{
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MainViewModel : NotificationObject
{
private IUnitOfWork _UnitOfWork;

[ImportingConstructor]
public MainViewModel(IUnitOfWork unitOfWork)
{
this._UnitOfWork = unitOfWork;
Init();
}

public ObservableCollection<Unicorn> Unicorns { get; set; }

private void Init()
{
this.Unicorns = _UnitOfWork.UnicornRepository.GetSyncedEntityItems();
}
}
}

Don’t forget to add a reference from the Core to the Data project. Here we see that we get our UnitOfWork object via MEF by using the [ImportingConstructor] attribute.

We also inherit from NotificationObject, this way we don’t have to implement the INotifyPropertyChanged ourselves. Thank you Prism for adding this already to the ViewModels base class.

Code for the SidebarViewModel:

namespace UnicornManager.Core.ViewModels
{
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SidebarViewModel : NotificationObject, IDataErrorInfo
{
private IUnitOfWork _UnitOfWork;
private DelegateCommand<object> _AddUnicornCommand;

private string _FirstName;
private string _LastName;

[ImportingConstructor]
public SidebarViewModel(IUnitOfWork unitOfWork)
{
_UnitOfWork = unitOfWork;
_AddUnicornCommand = new DelegateCommand<object>(AddUnicornExecute,
(o) => { return !string.IsNullOrEmpty(FName) && !string.IsNullOrEmpty(LName); });
PropertyChanged += new PropertyChangedEventHandler(SidebarViewModel_PropertyChanged);
}

public DelegateCommand<object> AddUnicornCommand
{
get { return _AddUnicornCommand; }
}

public string FName
{
get { return _FirstName; }
set
{
if (_FirstName != value)
{
_FirstName = value;
RaisePropertyChanged(() => FName);
}
}
}

public string LName
{
get { return _LastName; }
set
{
if (_LastName != value)
{
_LastName = value;
RaisePropertyChanged(() => LName);
}
}
}

private void SidebarViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "FName":
case "LName":
AddUnicornCommand.RaiseCanExecuteChanged();
break;
}
}

private void AddUnicornExecute(object parameter)
{
Unicorn unicorn = new Unicorn() { FirstName = FName, LastName = LName };
_UnitOfWork.UnicornRepository.Insert(unicorn);
_UnitOfWork.Save();
}

#region IDataErrorInfo Members

public string Error
{
get
{
// no single error for the entire object
return null;
}
}

public string this[string columnName]
{
get
{
string errorMessage = null;
switch (columnName)
{
case "FName":
if (validateNameString(FName))
errorMessage = "Not valid this";
break;
case "LName":
if (validateNameString(LName))
errorMessage = "May not be empty";
break;
}

return errorMessage;
}
}

#endregion

// some basic input checks
private Func<string, bool> validateNameString = x => string.IsNullOrEmpty(x) || x.Length > 50;
}
}

Keep in mind that we save our object via the UnitOfWork and not directly via the UnicornRepository. IDataErrorInfo was also implemented.

It is time to add two Views to the Views folder. Start by adding a new User Control (WPF) called MainView.xaml to the project.

XAML code:

<UserControl x:Class="UnicornManager.Core.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBlock Text="Hello From MainView (Core Module)"
Grid.Row="0"/>
<ListBox ItemsSource="{Binding Unicorns, Mode=TwoWay}"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>

MainView codebehind:

namespace UnicornManager.Core.Views
{
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MainView : UserControl
{
public MainView()
{
InitializeComponent();
}

[Import]
public MainViewModel ViewModel
{
set { DataContext = value; }
}
}
}

Here we Export our view and we Import our ViewModel. Just some basic MEF importing and exporting.

Add another User Control (WPF) called SidebarView.xaml to the Views folder:

<UserControl x:Class="UnicornManager.Core.Views.SidebarView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">http://schemas.microsoft.com/expression/blend/2008"
xmlns:prism="http://www.codeplex.com/prism">http://www.codeplex.com/prism"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<StackPanel>
<Label Content="First Name:" />
<TextBox Text="{Binding FName, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"/>
<Label Content="Last Name:" />
<TextBox Text="{Binding LName, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"/>

<Button Height="30"
Content="Add Unicorn"
Command="{Binding AddUnicornCommand}"/>
</StackPanel>
</Grid>
</UserControl>

Codebehind for the SidebarView:

namespace UnicornManager.Core.Views
{
/// <summary>
/// Interaction logic for SidebarView.xaml
/// </summary>
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class SidebarView : UserControl
{
public SidebarViews()
{
InitializeComponent();
}

[Import]
public SidebarViewModel ViewModel
{
set { DataContext = value; }
}
}
}

If we now run our application we still see the same empty window. This is because we forgot our Bootstrapper to tell that it can also search in our Module!

Select the UnicornManager project and add a reference to our Core project.
Next in the ConfigureAggregateCatalog method in our CoreBootstrapper add new AssemblyCatalogs for the Data and Core projects:

protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreBootstrapper).Assembly));
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Data.Models.Unicorn).Assembly));
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreModule).Assembly));
}

Now run the project and have fun! 😉

What I like to hear from you (and if possible with code examples or a link to the adjusted solution)

  • Is the structure for this project ok?
  • There is no need to configure a ModuleCatalog in the bootstrapper when working with Prism and MEF or is that not true?
  • The Entity Framework has also some validation of its Entities (see UnitOfWork class: DbEntityValidationException). Is there a way to work with DataAnnotations on the Entity Frame Model classes instead of implementing the IDataErrorInfo on the ViewModel. Because this feels like writing double code. How do you show Entity (validation) exceptions on the UI directly?
  • How would you implement a Ribbon + add and merge tabpages when having multiple Modules?
  • MVVM: Do the Models also require INotifyPropertyChanged or only the ViewModels?

Download the project source here. (It is UnicornManager.zip)

Links:

(Maybe somebody can extend the solution so that others (and myself!) can learn from it)