C#

Dynamic Creation Of Assemblies/Apps

The other day I was discussing code generation with a collegue and he was discussing a hyperthetical siuation where it would be possible to create source code at runtime and even compile it to create apps at runtime. Now I didnt know much about this, but I decided to have a little exploratory look into this. As ever .NET amazed me (again) and had 2 interesting namespaces to do this.

  • System.CodeDom : Which allows the generation of a CodeCompileUnit which can be then generated into a source code file for any .NET language
  • System.CodeDom.Compiler : Is able to create a Assembly/Exe at runtime from a source code file.

I have written a small demo application and an accompanying article about this over at http://www.codeproject.com, this is available right here, if you are interested. This is what it looks like anyway:

codedombig.png

The application creates a simple source code file and compiles it into an Exe and runs it, all at runtime. Cool.

Advertisements
Beginners Guide To WPF, WPF

A Beginners Guide To WPF

I have been working with WPF a little while now and have published a fair number of WPF articles over at codeproject but in one of them I was slammed for writing a intermediate article that had been mistakenly classified as a beginners article.

At first I was a bit annoyed at this, but then I started to hunt about, and there really aren’t that many beginners articles for WPF, so I decided to write a beginners WPF series. This series will be structured as follows:

Part 1 : Layout

Part 2 : XAML vs Code / Markup Extensions

Part 3 : RoutedEvents And RoutedCommands

Part 4 : Dependancy Properties

Part 5 : Databinding

Part 6 : Styles/Templates

End of series Exemplar


I hope they are useful to someone. Have a look for yourself

WPF

Amazon 3d Explorer

Today I published my latest article at http://www.codeproject.com, it is a WPF based application that uses the AWS and displays the results obtained on 3d Meshes. The 3d meshes hold interactive UIElements which in turn display a FlowDocument.

It was quite a fun article to write, and if you are interested, you can have a look at it here and it looks like the following

explorer3dbig.png

Or if you prefer you can see a video of it in action here. Hope you like it.

C#, CodeProject

Calling Method Asynchronously With A Timeout

As part of an ongoing project I am just about to finish, I had a need to use a 3rd party web service. Now I am quite an cautious sort of chap when it comes to using web services. So I generally try and ensure that I try and make my code as robust as possible when dealing with such code.

For example when calling a web service, there is no guarantee that the web server is not going to die, after all it could be a web service that is hosted on a single server. Of course if the web service is from a reputable source, its probably going to be a web farm that you’re dealing with. Never the less, it’s good to plan for problems. Such as a timeout, lack of results, remote connection denials, security issues. These call all lead into problems when dealing with a web service.

To this end I have written the following bit of code to allow me to call a method asynchronously but have a timeout. This code does not use a web service, but rather shows the pattern that could be used to call any method asynchronously with a timeout. Which of course fits well with the idea of calling a web service, call the web service asynchronously, wait for a reasonable time, then see if the results are available. If they are use them, if not alert the user in what ever manner you have opted for.

Anyway the code is fairly simple and is as follows

using System;
using System.Collections.Generic;
using System.Text;

namespace Explorer3D
{
    class AsynchMethodCall
    {
        public AsynchMethodCall()
        {
            string[] usersFetched;
            //call the delegate asychronously and wait for the results 
            //from the asynch call.
            fetchNumberOfUsersDelegate fetchUsers =
            getNumberOfUsers;
            IAsyncResult asynchResult =
            fetchNumberOfUsersDelegate.BeginInvoke(1000000, null, null);
            while (!asynchResult.AsyncWaitHandle.WaitOne(5000, false))
            {
                //waiting for result for exactly 5 seconds
            }
            //try and catch any nasty exception that may have occurred
            try
            {
                usersFetched = fetchUsers.EndInvoke(asynchResult);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// The delegate that will be called asynchronously
        /// </summary>
        internal delegate string[] fetchNumberOfUsersDelegate(int someValue);

        /// <summary>
        /// A supposedly long running method
        /// </summary>
        /// <param name="numberOfUsersToFetch">number of users to fetch</param>
        /// <returns>a string array of users fetched</returns>
        private string[] getNumberOfUsers(long numberOfUsersToFetch)
        {
            //do the long bit of work, say gather the the number of users
            //indicated by the numberOfUsersToFetch parameter from a remote
            //database
        }
    }
}

CodeProject, WPF

Styling A ScrollViewer/Scrollbar In WPF

A while back I was looking at the Infragistics WPf showcase,Tangerine and I was quite jealous about the scrollbars that they managed to use. I mean styling a Button is one thing, but the ScrollBar is made of lost of nasty different control parts, (Part_XXX elements). Incidently I wrote an article about Part_XXX elements in a WPF article over at codeproject right here if you are interested.

Anyways to cut a long story short I decided to try and have a go at Styling a bigger control such as ScrollViewer. And guess what I managed to do it. Hooray.

This is what it looks like

newstyle.png origstyle.png

My Styled ScrollViewer Original ScrollViewer

This blog entry outlines the steps I went through.

STEP 1

Lookup and copy the original ScrollViewer and ScrollBar Templates from MSDN, for example

http://msdn2.microsoft.com/en-us/library/aa970847(VS.85).aspx
http://msdn2.microsoft.com/en-us/library/ms742173(VS.85).aspx

Then I Pasted that code from MSDN into a Resources file in a WPF window.

STEP 2

I examined the control parts required for the full ScrollViewer/Scrollbar controls. This was fairly ok actually as the MSDN default Styles and pretty easy to follow.

From looking at the default styles it became clear that I needed to look at the following Style/Templates if I wished to re-style a ScrollViewer, as all of these were used in the default Style for the ScrollViewer somewhere

STEP 3

I then decided which parts I want to swap out. I chose to swap out the and proceeded to hack the default Style/Templates to acheive the look I was after.

Anyway the results ScrollViewer looks like the following image

  • RepeatButton
  • Thumb
  • ScrollBar
  • ScrollViewer

When you consider the following image, you can see why these are the Style/Templates that need to be altered

scroll.png

So basically after that, its just a question of cutting code. So withour further ado, here is the code

 


<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="ScrollViewerTemplate.Window1"
    x:Name="Window"
    Title="Window1"
    Width="200" Height="200">

  <Window.Resources>

        <!-- All the following is required to Re-Style the ScrollViewer, see 
             http://msdn2.microsoft.com/en-us/library/aa970847(VS.85).aspx
             http://msdn2.microsoft.com/en-us/library/ms742173(VS.85).aspx
             for the default Stles that the ScrollViewer has out of the box
         -->

        <!-- Brushes used in Styling of ScrollViewer -->
        <SolidColorBrush x:Key="StandardBorderBrush" Color="#888" />
        <SolidColorBrush x:Key="StandardBackgroundBrush" Color="#FFF" />
        <SolidColorBrush x:Key="HoverBorderBrush" Color="#DDD" />
        <SolidColorBrush x:Key="SelectedBackgroundBrush" Color="Gray" />
        <SolidColorBrush x:Key="SelectedForegroundBrush" Color="White" />
        <SolidColorBrush x:Key="DisabledForegroundBrush" Color="#888" />
        <SolidColorBrush x:Key="NormalBrush" Color="#888" />
        <SolidColorBrush x:Key="NormalBorderBrush" Color="#888" />
        <SolidColorBrush x:Key="HorizontalNormalBrush" Color="#888" />
        <SolidColorBrush x:Key="HorizontalNormalBorderBrush" Color="#888" />
        <LinearGradientBrush x:Key="ListBoxBackgroundBrush"
            StartPoint="0,0" EndPoint="1,0.001">
            <GradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="White" Offset="0.0" />
                    <GradientStop Color="White" Offset="0.6" />
                    <GradientStop Color="#DDDDDD" Offset="1.2"/>
                </GradientStopCollection>
            </GradientBrush.GradientStops>
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="StandardBrush"
            StartPoint="0,0" EndPoint="0,1">
            <GradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="#FFF" Offset="0.0"/>
                    <GradientStop Color="#CCC" Offset="1.0"/>
                </GradientStopCollection>
            </GradientBrush.GradientStops>
        </LinearGradientBrush>
        <SolidColorBrush x:Key="GlyphBrush" Color="#444" />
        <LinearGradientBrush x:Key="PressedBrush"
            StartPoint="0,0" EndPoint="0,1">
            <GradientBrush.GradientStops>
                <GradientStopCollection>
                    <GradientStop Color="#BBB" Offset="0.0"/>
                    <GradientStop Color="#EEE" Offset="0.1"/>
                    <GradientStop Color="#EEE" Offset="0.9"/>
                    <GradientStop Color="#FFF" Offset="1.0"/>
                </GradientStopCollection>
            </GradientBrush.GradientStops>
        </LinearGradientBrush>

        <!-- SrollViewer ScrollBar Repeat Buttons (at each end) -->
        <Style x:Key="ScrollBarLineButton" TargetType="{x:Type RepeatButton}">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="Focusable" Value="false"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RepeatButton}">
                        <Border
          Name="Border"
          Margin="1"
          CornerRadius="2"
          Background="{StaticResource NormalBrush}"
          BorderBrush="{StaticResource NormalBorderBrush}"
          BorderThickness="1">
                            <Path
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Fill="{StaticResource GlyphBrush}"
            Data="{Binding Path=Content,
                RelativeSource={RelativeSource TemplatedParent}}" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter TargetName="Border" Property="Background"
                                Value="{StaticResource PressedBrush}" />
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Foreground"
                                Value="{StaticResource DisabledForegroundBrush}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <!-- SrollViewer ScrollBar Repeat Buttons (The part in the middle, 
             not the thumb the long area between the buttons ) -->
        <Style x:Key="ScrollBarPageButton" TargetType="{x:Type RepeatButton}">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="IsTabStop" Value="false"/>
            <Setter Property="Focusable" Value="false"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RepeatButton}">
                        <Border Background="Transparent" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <!-- ScrollViewer ScrollBar Thumb, that part that can be dragged
            up/down or left/right Buttons -->
        <Style x:Key="ScrollBarThumb" TargetType="{x:Type Thumb}">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="IsTabStop" Value="false"/>
            <Setter Property="Focusable" Value="false"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Border
          CornerRadius="2"
          Background="{TemplateBinding Background}"
          BorderBrush="{TemplateBinding BorderBrush}"
          BorderThickness="1" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <ControlTemplate x:Key="VerticalScrollBar"
            TargetType="{x:Type ScrollBar}">
            <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition MaxHeight="18"/>
                    <RowDefinition Height="0.00001*"/>
                    <RowDefinition MaxHeight="18"/>
                </Grid.RowDefinitions>
                <Border
      Grid.RowSpan="3"
      CornerRadius="2"
      Background="#F0F0F0" />
                <RepeatButton
      Grid.Row="0"
      Style="{StaticResource ScrollBarLineButton}"
      Height="18"
      Command="ScrollBar.LineUpCommand"
      Content="M 0 4 L 8 4 L 4 0 Z" />
                <Track
      Name="PART_Track"
      Grid.Row="1"
      IsDirectionReversed="true">
                    <Track.DecreaseRepeatButton>
                        <RepeatButton
          Style="{StaticResource ScrollBarPageButton}"
          Command="ScrollBar.PageUpCommand" />
                    </Track.DecreaseRepeatButton>
                    <Track.Thumb>
                        <Thumb
          Style="{StaticResource ScrollBarThumb}"
          Margin="1,0,1,0"
          Background="{StaticResource HorizontalNormalBrush}"
          BorderBrush="{StaticResource HorizontalNormalBorderBrush}" />
                    </Track.Thumb>
                    <Track.IncreaseRepeatButton>
                        <RepeatButton
          Style="{StaticResource ScrollBarPageButton}"
          Command="ScrollBar.PageDownCommand" />
                    </Track.IncreaseRepeatButton>
                </Track>
                <RepeatButton
      Grid.Row="3"
      Style="{StaticResource ScrollBarLineButton}"
      Height="18"
      Command="ScrollBar.LineDownCommand"
      Content="M 0 0 L 4 4 L 8 0 Z"/>
            </Grid>
        </ControlTemplate>
        <!-- HorizontalScrollBar Template using the previously created Templates -->
        <ControlTemplate x:Key="HorizontalScrollBar"
            TargetType="{x:Type ScrollBar}">
            <Grid >
                <Grid.ColumnDefinitions>
                    <ColumnDefinition MaxWidth="18"/>
                    <ColumnDefinition Width="0.00001*"/>
                    <ColumnDefinition MaxWidth="18"/>
                </Grid.ColumnDefinitions>
                <Border
      Grid.ColumnSpan="3"
      CornerRadius="2"
      Background="#F0F0F0" />
                <RepeatButton
      Grid.Column="0"
      Style="{StaticResource ScrollBarLineButton}"
      Width="18"
      Command="ScrollBar.LineLeftCommand"
      Content="M 4 0 L 4 8 L 0 4 Z" />
                <Track
      Name="PART_Track"
      Grid.Column="1"
      IsDirectionReversed="False">
                    <Track.DecreaseRepeatButton>
                        <RepeatButton
          Style="{StaticResource ScrollBarPageButton}"
          Command="ScrollBar.PageLeftCommand" />
                    </Track.DecreaseRepeatButton>
                    <Track.Thumb>
                        <Thumb
          Style="{StaticResource ScrollBarThumb}"
          Margin="0,1,0,1"
          Background="{StaticResource NormalBrush}"
          BorderBrush="{StaticResource NormalBorderBrush}" />
                    </Track.Thumb>
                    <Track.IncreaseRepeatButton>
                        <RepeatButton
          Style="{StaticResource ScrollBarPageButton}"
          Command="ScrollBar.PageRightCommand" />
                    </Track.IncreaseRepeatButton>
                </Track>
                <RepeatButton
      Grid.Column="3"
      Style="{StaticResource ScrollBarLineButton}"
      Width="18"
      Command="ScrollBar.LineRightCommand"
      Content="M 0 0 L 4 4 L 0 8 Z"/>
            </Grid>
        </ControlTemplate>
        <!-- Style for overall  ScrollBar -->
        <Style x:Key="{x:Type ScrollBar}" TargetType="{x:Type ScrollBar}">
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Style.Triggers>
                <Trigger Property="Orientation" Value="Horizontal">
                    <Setter Property="Width" Value="Auto"/>
                    <Setter Property="Height" Value="18" />
                    <Setter Property="Template"
                        Value="{StaticResource HorizontalScrollBar}" />
                </Trigger>
                <Trigger Property="Orientation" Value="Vertical">
                    <Setter Property="Width" Value="18"/>
                    <Setter Property="Height" Value="Auto" />
                    <Setter Property="Template"
                        Value="{StaticResource VerticalScrollBar}" />
                </Trigger>
            </Style.Triggers>
        </Style>

        <!-- Style for overall  ScrollViewer -->
        <Style x:Key="FavsScrollViewer" TargetType="{x:Type ScrollViewer}">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ScrollViewer}">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>

                            <ScrollContentPresenter Grid.Column="1"/>

                            <ScrollBar Name="PART_VerticalScrollBar"
            Value="{TemplateBinding VerticalOffset}"
            Maximum="{TemplateBinding ScrollableHeight}"
            ViewportSize="{TemplateBinding ViewportHeight}"
            Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/>
                            <ScrollBar Name="PART_HorizontalScrollBar"
            Orientation="Horizontal"
            Grid.Row="1"
            Grid.Column="1"
            Value="{TemplateBinding HorizontalOffset}"
            Maximum="{TemplateBinding ScrollableWidth}"
            ViewportSize="{TemplateBinding ViewportWidth}"
            Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>

                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

  </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <ScrollViewer     RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Stretch"
                        Margin="0,0,0,0"
                        Width="Auto" HorizontalScrollBarVisibility="Visible"
                        Style="{StaticResource FavsScrollViewer}">
         </ScrollViewer>
    </Grid>
</Window>

And if you want to try this for yourself, here is a VS2008 demo project scrollviewertemplate.zip


 
WPF

Meeting Josh Smith

I have just returned home after a very wonderful trip to New York. Whilst there I had a chance to meet/drink and chat with one of my codeproject heros, A.K.A Mr Josh Smith (A.K.A the Bach loving one. Just check this MP3 as played by Josh)

He was really cool, he is what we would call “A Smashing Chap” over here in England. I had a great time being shown the best watering holes/eateries by Josh. Though I did manage to show the local, one bar with excellent views of Manhattan that he had never been to. So that good.

Josh also blogged about this, at the following URL and even put up some pictures, if you fancy a peek.

http://joshsmithonwpf.wordpress.com/2008/01/09/meeting-sacha-barber/

As I say Josh showed me and my girlfriend Sarah a great time, so thanks Josh. All the best to you. Hope to do it again some time.

CodeProject, WPF

WPF Flow Document For Beginners

As part of an article that I am creating for www.codeproject.com I decided to look into using the System.Windows.Documents namespace and have a look at seeing if I could make a semi-cool’ish looking document.

Now when you use FlowDocuments, there are several container WPF container controls which you may host a FlowDocument in. These WPF container controls vary in what they provide. Lets see the difference shall we

  • FlowDocumentScrollViewer : Simply displays the entire document and provides a scroll bar. Like a web page
  • FlowDocumentPageViewer : Shows document as individual pages, and allows user to adjust zoom level.
  • FlowDocumentReader : Combines FlowDocumentScrollViewer and FlowDocumentPageViewer into a single control, and exposes text search facilities.

For example a FlowDocumentPageViewer is as shown below

flowdocumentpageviewer.png

For those of who have not come across the FlowDocument, here is a list of some of the things that can be done with it

  • Allow paragraphing
  • Allow anchoring of images
  • Allow hyperlinks
  • Allow text blocks
  • Allow tables
  • Allow subscript/superscript text
  • Allow UIElements (such as Button etc etc)
  • Allow text effects

Think of FlowDocument(s) as a mini desktop publishing type interface. Though I’m sure things like Quark are going to yield more flexability. Never the less, the results of FlowDocument(s) could be thought as be able to create that sort of page publishing type layout.

What I’m going to do now is show you how to create a few of the various FlowDocument elements both in XAML and in code as they are little different actually.

PARAGRAPH

In XAML

<!-- FLOW DOCUMENT VIEWER START -->    
<FlowDocumentPageViewer x:Name="flowDocViewer"  Margin="0,0,0,0" Background="#FF414141" Zoom="80" >         
<!-- FLOW DOCUMENT START -->
<FlowDocument x:Name="flowDoc" Foreground="White" FontFamily="Arial"  >
<Paragraph x:Name="para1" FontSize="11">
The following details have been obtained from Amazon to match your initial query.
Some of the returned values may have been empty, so have been ommitted from theresults shown here.
Also where there have been more than one value returned viathe Amazon Details, these to have been
omitted for the sake of keeping things simplefor this small demo application. Simple is good,
when trying to show how something works
</Paragraph>
</FlowDocument>
</FlowDocumentPageViewer>


In C# code behind

Paragraph paraHeader = new Paragraph();
paraHeader.FontSize = 12;
paraHeader.Foreground = headerBrsh;
paraHeader.FontWeight = FontWeights.Bold;
paraHeader.Inlines.Add(new Run("Paragraph Text"));
flowDoc.Blocks.Add(paraHeader);




HYPERLINKS

In XAML

<Paragraph FontSize=”11″>

     <Hyperlink  Click="hl_Click" NavigateUri="www.google.com">Click Here</Hyperlink>
</Paragraph>



In C# code behind

Paragraph paraValue = new Paragraph();Hyperlink hl = new Hyperlink(new Run("Click Here To View The Link Data"));

hl.FontSize = 11;hl.NavigateUri = new Uri(nonNullprop.PropertyValue);

hl.Click += new RoutedEventHandler(hl_Click);paraValue.Inlines.Add(hl);
flowDoc.Blocks.Add(paraValue);




EMBEDDING UI ELEMENTS

In XAML

 

<BlockUIContainer>

    <Button Width="60" Height="60" Click="Button_Click">

        Click me

    </Button>

</BlockUIContainer>


In C# code behind

 

BlockUIContainer uiCont = new BlockUIContainer();

Button b = new Button();

b.Width = b.Height = 60;

b.Click += new RoutedEventHandler(Button_Click);

b.Content = "Click me";

flowDoc.Blocks.Add(uiCont);

Of course this is only touching the surface of what can be done with FlowDocuments. But it gives you an idea of how flexable the formatting of documents is with WPF.

The screen shot below shows an example with some Paragraphs/Tables/Hyperlinks and UIElements in place

flowdocumentexample.png