My Master's Thesis Problems and solutions encountered…

22Apr/100

External Links

Here is just a quick and small code snippet for linking to external pages from your Silverlight application.

I found quite a few potential solutions to the problem, but the first 2 or 3 just didn't compile. Most people recommended the Hyperlink with some sort of System.Diagnostics.Process.Start("http://www.link.com");attached, but I simply couldn't make it work. But finally I found a solution:

Insert a TextBlock like the one below. Notice the MouseLeftButtonDown.


            <TextBlock Grid.Column="2" Grid.Row="0"
                       VerticalAlignment="Top"
                       Text="www.aook.dk/blog"
                       TextDecorations="Underline"
                       MouseLeftButtonDown="TextBlock_MouseEnter"
                       HorizontalAlignment="Right"
             />

Next, you just need to create an EventHandler like the one below, but make sure to first add an using System.Windows.Browser; at the top.

        private void TextBlock_MouseEnter(object sender, MouseButtonEventArgs e)
        {
            HtmlPage.Window.Navigate(new Uri("http://www.aook.dk/blog"));

        }

Enjoy!

Filed under: C#, Silverlight, XAML No Comments
19Apr/100

Input validation

I needed to create a login feature, so only registered users could gain access to the Silverlight application, and I wanted to create a data validator, that would check the users' input. In the this example I just check if the user has entered an e-mail address.

Red lineError messageNo error
In the first image to the left, I have just entered my name in the E-mail address field, and entered my password. The textbox is marked with red, because there has not been registered an "@" in the field (of course, this is a very simple example. One could easily find more thorough ways of validating an e-mail address, which I will probably make a blog post about some time soon).

In the second image, the user has selected the textbox, and immediately an error message appears, explaining the user why there is a problem.

In the third image, the user has inserted a valid e-mail address and can proceed with the login feature.

So, the way to implement this feature is pretty straight-forward, especially since there is a brilliant video tutorial showing exactly how to do it. I just followed the steps on the tutorial, but I will nonetheless quickly go through the code here.

The first thing you need to know is that - as brilliant as the tutorial mentioned above may be - the code will not compile if you have the default settings on Visual Studio 2008. The tutorial does not explain that you need to make one quick settings change in order to avoid an "Arguement Exception was unhandled by User"-error message, that prevents the code from compiling.

You need to the following: Go to Visual Studio Options and then Debugging/General, and just uncheck the 'Enable Just my Code'. And that's it.

The tutorial also fails to mention a small piece of code necessary to compile, but Visual Studio helps by telling you where you need to insert the following code:

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

We'll come back to this.

How to implement the input validation:

Open your MainPage.xaml, and find the textbox whose input you want to validate. Then insert Binding statements into TextBox.Text like shown below. Notice the Path called Mail. We will use this name later.


  <TextBox width = "390" >
           <TextBox.Text>
                <Binding Mode="TwoWay"
                        Path="Mail"
                        ValidatesOnExceptions="True"
                        NotifyOnValidationError="True"
                />
          </TextBox.Text>
 </TextBox>

So, we now have a textbox that needs to be binded to a data object, so we can check when there are any changes made to it. We do this by creating a new class: Right click on your application name in the Solutions Explorer, choose Add and Class. I named my class validation.cs.

The first thing to do is to insert using System.ComponentModel; at the top, and you can delete all others system statements except the using System;. This supports the INotifyPropertyChanged, that ensures two-way binding, that is, checks if any changes are made to the object, and if there is, then the UI is updated accordingly.

Insert the following code into your validation.cs:

using System;
using System.ComponentModel;

namespace QM_v1
{
    public class validation : INotifyPropertyChanged
    {
        private string mail;

        public string Mail
        {
            get { return mail; }
            set {
                if (value.IndexOf('@') == -1)
                {
                    throw new ArgumentException("This is not a valid email address");
                }
                NotifyPropertyChanged("Mail"); // The code crashes here, if you don't change your settings, as described above.

                mail = value; }
        }

        public event PropertyChangedEventHandler propertyChanged; //mandatory event for this class. Checks the object for changes.

        private void NotifyPropertyChanged(string propertyName)
        {
                if (propertyChanged != null)
                {
                    propertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    }
}

Notice lines 33-37: This code snippet is needed for the program to compile, but is not mentioned in the tutorial mentioned above.
Lastly, open your MainPage.xaml.cs and enter the following code in your class:

  public MainPage()
        {
            InitializeComponent();

            var m = new validation();
            LayoutRoot.DataContext = m;  //LayoutRoot = name of your Grid.

        }

And that's it!

See the working example here.

Filed under: C#, Silverlight, XAML No Comments
12Apr/100

How To Get Your Silverlight Application Online

Microsoft has made it very easy to get your Silverlight Application online.

You need to retrieve two files from your application project. If your project is called "MyApp" and you're running Visual Studio 2008, the folder you are looking for is located on the following path:

Documents -> Visual Studio 2008 -> Projects -> MyApp -> MyApp -> Bin -> Debug.

Here you will find a file called 'TestPage.html and a file called 'MyApp.zap'. Open an FTP program and access your website's server, and copy-paste the two files into the root folder. Rename your 'TestPage.html' to 'index.html' (no capitals).

Enjoy!

Filed under: Silverlight No Comments
11Apr/100

Defining Styles at Application Level

When you have many subpages containing buttons, textblocks, stackpanels, etc., it is convenient to define the styles at application level. This way, all objects have the same design, and if you need to change the look and feel of your template, you only need to change it one place, like you would do with CSS when working with HTML.

In your Silverlight application, open your App.xaml , which should look something like this:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 x:Class="QM_v1.App">

    <Application.Resources>

    </Application.Resources>

</Application>

So, in this example we want to define a shared style for all textblocks, so they all have the same color, font, margin, and so forth. Inside your Application Ressource you will define a new Style, width the Setter Property and Setter Value. Like this:


 <Application.Resources>

        <Style x:Key="Normal_text" TargetType="TextBlock">
            <Setter Property="Fontsize" Value="12"/>
            <Setter Property="FontFamily" Value="Verdana"/>
            <Setter Property="Foreground" Value="#FF696969"/>
            <Setter Property="Margin" Value="5"/>
            <Setter Property="TextWrapping" Value="Wrap"/>
        </Style>

    </Application.Resources>

The Key is the unique name of the Style, while with the TargetType you define which object you want to work with. The Property and Value sets the variables. Note that Visual Studio does not auto-compete inside the Setter, so you need to be careful when writing the names of the variables.

Having defined the style, you just need to write: Style = "{Static Resource Style_name}" when defining your Textblock:


              <TextBlock Text="This text has the style that was defined in the App.xaml.  "
                Style="{StaticResource Normal_text}"
               />

Of course, this method can be used with Grids, StackPanels, buttons... everything. Very useful!

Filed under: Silverlight, XAML No Comments
11Apr/101

Grid Controls – Rows with Variable Height

When making the layout for your application you will most often use Grid Controls and/or WrapPanels. I needed a layout to be a single box that was always centered vertically and had a variable sized height, depending on the amount of text inside the box.

Initially, you need to define the basic grid layout. Open your new Silverlight project, and select the MainPage.xaml. It probably looks something like this (depending on your Visual Studio version):


<UserControl x:Class="Test.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">

  </Grid>
</UserControl>

You will need to add some measurements to the Grid definition, so it says:


<Grid x:Name="LayoutRoot" Background="White" Width="Auto" Height="Auto" ShowGridLines="True">

This only sets the color of the background and makes sure the size of the grid changes with the size of the window. Also, the ShowGridlines makes sure you can see the changes you will make next. When you are finished, you can set it to false.

With the grid control we create a 3 x 3 grid, and we need to specify the number and width/height of the columns and the rows. This is done in the Grid.RowDefinitions and Grid.ColumnDefinitions::

<UserControl x:Class="QM_v1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
  <!--Background layout-->
   <Grid x:Name="LayoutRoot" Background="White" Width="Auto" Height="auto" ShowGridLines="True">

       <!--We define the grid, ie. number of rows and number of columns-->
        <Grid.RowDefinitions>
            <RowDefinition Height="130"></RowDefinition>
            <RowDefinition Height="200"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="500"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

    </Grid>
</UserControl>

As it can be seen, we have defined three columns, where only the middle as a fixed size. The first and third column will just occupy the space left in the window. The first two rows have initially a fixed height, while the last just occupies the remaining. If you run your program, it will look something like this:

The cell in the middle is where we will place our text (and eventually the whole application). You are maybe asking yourself why we defined a fixed height to the second row, when want it to be variable... This was just to show you how the grid works, and in the following, we set the second row height to auto. But we need to insert some text into this cell, otherwise the cell height i set to 0, and can therefore not be seen.

Changes to be noted in the code below:

  • RowDefinition Height has been changed for the second row, so it's now set to auto.
  • We have added a border that defines where the textblock is to be placed ( Grid.Column="1" & Grid.Row="1">), and a StackPanel, that defines the margin.
  • The new textblock inserts the texts, and its TextWrapping = "Wrap" ensures that the text is wrapped by the border.

<UserControl x:Class="QM_v1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
  <!--Background layout-->
   <Grid x:Name="LayoutRoot" Background="White" Width="Auto" Height="auto" ShowGridLines="true">

       <!--We define the grid, ie. number of rows and number of columns-->
        <Grid.RowDefinitions>
            <RowDefinition Height="130"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="500"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>

<!--the border-->
        <Border BorderThickness="2"
                    BorderBrush="#D1CACA"
                    Margin="10"
                    CornerRadius="10"
                    Background="#E8E8E8"
                    Grid.Column="1"
                    Grid.Row="1">
            <!--The text-->
            <StackPanel Margin="10">
                <TextBlock Text="The height of this row depends on the amount of text to be wrapped. Make sure you have your middle row set to 'auto' and the TextWrapping set to 'Wrap'."
                           Margin="5"
                           TextWrapping="Wrap"
                 /><!--Important to wrap the text!-->
            </StackPanel>
        </Border>
    </Grid>
</UserControl>

If you run this code, you'll see something like this:

Grid, variable row size

As said before, you can just set the ShowGridlines to false when you are finished.

So, by using the code above you have created a grid, where the middle cells has fixed width, but the height depends on the amount of text you have inserted into the Textblock.

Filed under: Silverlight, XAML 1 Comment
8Apr/102

How to insert XAML code into WordPress

Initially, I had difficulties inserting XAML into the WordPress blog, as the characters < and > are used in XAML, which conflicted with the WordPress HTML. As the XAML code didn't show properly, I went looking for plugins to use, and found what I was looking for:

With the SyntaxHighlighter Evolved you can insert code into WordPress that looks like this:


(...)

<ScrollViewer VerticalScrollBarVisibility ="Auto">
    <Grid x:Name="LayoutRoot" Background="#00000000" Width="Auto" Height="Auto">
  <!--Comment-->

            <Grid.RowDefinitions>
            <RowDefinition Height="130"></RowDefinition>
            <RowDefinition Height="auto"></RowDefinition>
(...)

All you need to do is the following:

  1. Go to this page and download the WordPress plugin
  2. Open an FTP program and access your website's server
  3. Copy and paste the plugin-folder to the wp-content/plugins folder
  4. Go to your WordPress admin page and click on Plugins in the administration panel
  5. Activate your SyntaxHighlighter plugin

That's it!

On your post, you need to insert the following code snippet:

[-sourcecode language="XML"]
... your code ...
[-/sourcecode]

OBS!! You need to remove the two "-". I had to put them there, so the code wouldn't be interpreted.

The SyntaxHighlighter supports many laguages, including Java, Perl, C# (csharp), Python, Ruby, Scala, SQL, VB... and XML. Not XAML, but close enough. Just replace language = XML above with for example language = java or language = csharp.

On this page you can read more about posting source code in WordPress. There are many extensions. For example:

  • Disable the URLs in your posted code: Insert autolinks = false
  • Collapse the code box when the page loads, requiring the visitor to click to expand it. Insert collapse= true
  • Remove the line numbering. Insert gutter = false.
  • Highlight specific lines of code. Insert highlight = "11, 12" if you want lines 11 and 12 to be highlighted.
  • When posting only one or two lines of code, you can simplify the code highlighting. Insert light = true.

The code snippet below has been made by writing [-sourcecode language="XML" autolinks="false" collapse="true" highlight="3,4"] (again, without the first "-").

   <UserControl x:Class="Smuk.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
  >  <ScrollViewer VerticalScrollBarVisibility ="Auto">

Enjoy!

Filed under: Wordpress 2 Comments
4Apr/100

Beautiful LaTeX table

The trouble with writing your Thesis in LaTex is that it's someties difficult to make things beautiful, because it's so relatively hard to change formats, colors and such. Making a table can also be a bit time-consuming, but it's really not _that_ difficult.

I needed a table for my chapter on Requirements, and I wanted something special: I wanted that every second row was a different color and that the top and bottom line where thicker that the others. Below you can see a picture of the table:

Beautiful LaTeX table

First, you have to add the following code in your Preamble.tex:

 \usepackage[table]{xcolor}

The code for the table is as follows:


\begin{center}
\rowcolors{1}{white}{gray}
\begin{tabular}{  p{3cm}  |  p{8cm} }
\bottomrule
\textbf{Name} &amp; \textbf{Description}\\  \hline

        Text & Text  \\ \hline
        Text & Text  \\ \hline
        Text & Text  \\ \hline
        Text & Text  \\ \hline
        Text & Text. \\ \hline
        Text & Text  \\ \hline

\bottomrule
\end{tabular}
\end{center}

And that's it!

Short explanation.

You have to notice two things: First,

\rowcolors{1}{white}{gray}



is what adds color to every second row. Second, it's the

 \bottomrule


that makes the first and the last line thicker.

Also, you'll notice that the rows in the picture are not gray. This is because I have defined a new color and used instead, as I really didn't like any of the deafult colors. New colors are defined it the Preable.tex like this:

\definecolor{orange}{RGB}{253,245,230}

As you can see, you can define a color by knowing the RGB-values. In this example, I have named the color "orange", which I then write in the table code: It will say

\rowcolors{1}{white}{orange}

instead of

\rowcolors{1}{white}{gray}

Adding new colors is not at all necessary. You can always use the deafult colors, so the last part is completely optional.

Filed under: LaTeX No Comments