Tag Archives: Visual Studio

C# – Constraining Type Parameters

Sometimes it can be useful to constrain what types can be passed to generic classes. Say for example that you were building a generic binary tree, then you might what to ensure that only types that implemented IComparable can be used.

The where keyword is used to specify constraints.

public class BinaryTree<T> where T : IComparable<T>

As detailed on MSDN the full list of constraints is listed below.

where T: struct
The type argument must be a value type. Any value type except Nullable can be specified.

where T : class
The type argument must be a reference type, including any class, interface, delegate, or array type.

where T : new()
The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T :
The type argument must be or derive from the specified base class.

where T :
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U
The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

Entity Framework – The Basics

Entity Framework makes creating and accessing databases easier and removes the need to write lots of data access code.

Getting Started

Add the NuGet packege listed below to your project – searching the NuGet package manager for “Entity Framework” should bring it up.

Creating a Model

Firstly we need a create a model that will represent our data, this can just be a simple C# class with a couple of properties. Below is a simple customer model.

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Creating a Context

Now we need to create a context which will handle the communication with the database.

public class CustomerContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

Putting It All Together

Finally we just need to add some code that will save a customer instance into our database.

using( CustomerContext ctx = new CustomerContext() )
{
    Customer customer = new Customer() { Name = "Bob Smith" };
    ctx.Customers.Add( customer );
    ctx.SaveChanges();
}

Finally

You may wonder why the code above works as we didn’t create a database, the beauty of Entity Framework is that it does all of this for us. If you check Sql Server Management Studio you should notice that a database has been created along with a table for our customers.

Using Graphs and Charts In WinRT Apps – The Basics

Visual Studio does not provide a chart control by default for use in WinRT apps but we can get around this by using the ones provided in the WinRT XAML Toolkit.

Getting Started

Create a new blank Windows Store project in Visual Studio and then add the two NuGet packages listed below – searching in the NuGet package manager for “WinRT XAML Toolkit” should bring them both up.

Creating an empty chart

In MainPage.xaml add the following XAML namespace reference.

xmlns:Charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"

Now lets add an empty chart that we’ll use to hold the chart type that we are interested in.

<Charting:Chart Name="MyChart" Width="500" Height="500" Title="My Chart" Margin="0">
</Charting:Chart>

Adding a Pie Chart

There are many different types of chart that can be created but for the sake of simplicity we will just create a pie chart in this tutorial.

<Charting:Chart Name="MyChart" Width="500" Height="500" Title="Chart" Margin="0">
    <Charting:PieSeries Margin="0" IndependentValuePath="Item1" DependentValuePath="Item2" IsSelectionEnabled="True" />
</Charting:Chart>

Note that IndependentValuePath determines what we want to show on each pie segment like its name and DependentValuePath determines the size of each pie segment. I’ve set them to “Item1” and “Item2” as we are using a Tuple to pair the values together as you will see below.

Populating the pie chart

Open the code behind file for MainPage.xaml and add the following code which will create three segments in the pie chart.

public MainPage()
{
    this.InitializeComponent();

    this.Loaded += MainPage_Loaded;
}

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    List<Tuple<string, int>> myList = new List<Tuple<string,int>>()
    {
        new Tuple<string, int>("Item 1", 20),
        new Tuple<string, int>("Item 2", 30),
        new Tuple<string, int>("Item 3", 50)
    };

    (MyChart.Series[0] as PieSeries).ItemsSource = myList;
}

If you build you application you should see a pie chart with three segments shown onscreen. That’s all for this tutorial but stay tuned for more on the WinRT XAML Toolkit.

C# is Keyword

The ‘is’ keyword in C# can be used to test whether an object is compatible with a certain type.

CODE

if (obj is MyObject)

The above code would determine if obj is an instance of the MyObject type, or a type that derives from MyObject.

NOTES

An ‘is’ expression evaluates to true if the provided object is not null and can be cast to the provided type without causing an exception to be thrown.

C# as Keyword

The ‘as’ keyword in C# can be used to cast an object to a different type.

CODE

MyClass myObject = obj as MyClass;

In essence it achieves the same as below, but if the cast fails it returns null rather than throwing an InvalidCastException.

MyClass myObject = (MyClass) obj;

NOTES

As this method returns null if the cast fails, you could end up with a NullReferenceException further down the line if you do not check to ensure that the resultant object is not null.

StringFormat for WinRT and Phone 8.1 Apps

Windows RT and Phone 8.1 are missing the StringFormat property used in databinding, but this behaviour can be implemented quite easily using a converter class.

To being with create a new class and call it StringFormatConverter, then add the code shown below.

INCLUDES

using System;
using Windows.UI.Xaml.Data

CONVERTER CODE

public class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

USAGE

<TextBlock Text="{Binding Text, Converter={StaticResource StringFormatConverter}, ConverterParameter='{}{0:C}'}" />

NOTES

The ConverterParameter is whatever format you would like your text to be in, in the above example it converts it to a currency. More information about converters can be found on the msdn page here.

Sending HTTP Get Requests

Sometimes you may need to retrieve data from a webserver, one of the ways to do this is by using HTTP Get. C# offers the HTTPClient class to make this process relatively simple.

INCLUDES

using System.Net.Http;

GET CODE

public async void GetData()
{
    using (var client = new HttpClient())
    {
        var response = await client.GetAsync(url);

        var responseString = await response.Content.ReadAsStringAsync();
    }
}

NOTES

The HTTPClient class is not available for all version of Visual Studio or the .Net framework. It should work natively in Visual Studio 12 and 13 for the .Net framework versions 4.5 and above. A portable version is available on NuGet for other platforms such as Windows phone 7.1 and 8.0.

Sometimes caching of requests can mean that calls using HTTP Get result in the same data being returned each time, even though the data that is being requested has changed. This is particularly evident on the Windows Phone but can be fixed by setting the IfModifiedSince Property on the HTTPClient. The code below simply says that any data modified up to the current time should be returned.

client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;

Sending HTTP Post Requests

Sometimes you may need to send data to a webserver, one of the ways to do this is by using HTTP Post. C# offers the HTTPClient class to make this process relatively simple.

Data is encoded as a series of key-value-pairs and then sent to the supplied url after which a response is waited for.

INCLUDES

using System.Net.Http;

POST CODE

public async void PostData()
{
    using (var client = new HttpClient())
    {
        var values = new List<KeyValuePair<string, string>>();
        values.Add(new KeyValuePair<string, string>("thing1", "hello"));
        values.Add(new KeyValuePair<string, string>("thing2 ", "world"));

        var content = new FormUrlEncodedContent(values);

        var response = await client.PostAsync("http://www.mydomain.com/recepticle.aspx", content);

        var responseString = await response.Content.ReadAsStringAsync();
    }
}

NOTES

The HTTPClient class is not available for all version of Visual Studio or the .Net framework. It should work natively in Visual Studio 12 and 13 for the .Net framework versions 4.5 and above. A portable version is available on NuGet for other platforms such as Windows phone 7.1 and 8.0.

Caliburn Micro Part 5: WinRT and Phone 8.1

Welcome to the next part of this blog series on Caliburn Micro, in the previous part we saw how the Event Aggregator can be used to pass messages between different View Models. In this next part we will see how Caliburn Micro can be used in a Windows RT or Windows Phone 8.1 application.

It should be noted that Visual Studio 13 or higher and Windows 8.1 are required to develop Windows Phone 8.1 and Window Store 8.1 apps.

In the following examples a Windows Phone 8.1 one app is used but the procedure should be similar if not the same for Windows Store apps.

Step 1: Getting Started

First off create a new Windows Phone 8.1 or a Windows Store project and grab the Caliburn Micro nugget package from the Library Package Manager in Visual Studio.

Step 2: Adding Caliburn Micro Support

If you have used Caliburn Micro in other applications you will probably have created a bootstrapper to set up all the Caliburn Micro related stuff and start your application. Windows Phone 8.1 and Windows Store apps work in a slightly different way so a bootstrapper is not required. If you look in the solution explorer there should be a file called App.xaml, we will start by editing this.

Edit the file so that it looks like the code below, note that x:Class is unique to the name of your application and so should be left as it is.

<caliburn:CaliburnApplication
    x:Class="YourAppName.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:caliburn="using:Caliburn.Micro">

</caliburn:CaliburnApplication>

Next we need to edit App.xaml.cs to add code that will setup and start our application. Change App.xaml.cs so that it looks as below.

public sealed partial class App : CaliburnApplication
{
    private WinRTContainer container;

    public App()
    {
        InitializeComponent();
    }

    protected override void Configure()
    {
        container = new WinRTContainer();

        container.RegisterWinRTServices();

        container.PerRequest<ShellViewModel>();
    }

    protected override void PrepareViewFirst(Frame rootFrame)
    {
        container.RegisterNavigationService(rootFrame);
    }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        DisplayRootViewFor<ShellViewModel>();
    }

    protected override object GetInstance(Type service, string key)
    {
        return container.GetInstance(service, key);
    }

    protected override IEnumerable<object> GetAllInstances(Type service)
    {
        return container.GetAllInstances(service);
    }

    protected override void BuildUp(object instance)
    {
        container.BuildUp(instance);
    }
}

Things to take note of here are that you need to add a new entry for every View Model that you create, so in the Configure function you would add a new container.PerRequest with the name of your View Model. Also of note is the DisplayRootViewFor in the OnLaunched function, this needs to be changed to whichever View Model you want displayed when your app starts up.

Step 3: Develop Your Application

That’s about all you need to know about setting up the application, if you need help on how the rest of Caliburn Micro works please see the previous blog posts in this series.

That’s it for this tutorial join us next time for a look at using the Window Manager.