European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European WCF 4.5 Hosting - Amsterdam :: WCF 4.5 ChannelFactory Caching

clock October 19, 2012 10:59 by author Scott

Today I explain what ChannelFactory caching in the WCF 4.5 framework is. With the help of this new feature in .NET we can cache the service instance. Microsoft has introduced a new property for the ClientBase<T> class; the property name is CacheSetting. We can set the cachesetting with the help of the CacheSetting enum.

Here are the values of the Enum:

Name

Description

System.ServiceModel.CacheSetting.AlwaysOn

All instances of Client will use the same channel factory.

System.ServiceModel.CacheSetting.AlwaysOff

All instances of the Client would use different channel factories. This is useful when each endpoint has different security requirements and it makes no sense to cache.

System.ServiceModel.CacheSetting.Default

All instances of Client would use the same channel factory except instance #4. Instance #4 would use a channel factory that is created specifically for its use. This setting would work for scenarios where a particular endpoint needs different security settings from the other endpoints of the same ChannelFactory type (in this case IService).


Here is sample code for the Default CacheSetting:


class Program
    {
        static void Main(string[] args)
        {
             ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.Default;
             using (ServiceReference1.Service1Client client = new Service1Client()) {


             }
        }
}


Here is sample code for the AlwaysOn CacheSetting:


static void Main(string[] args)

{

  ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOn;

using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}


Here is sample code for the AlwaysOff CacheSetting:

static void Main(string[] args)
{
   ClientBase<IService1>.CacheSetting = System.ServiceModel.CacheSetting.AlwaysOff;


   using (ServiceReference1.Service1Client client = new Service1Client()) {

   }
}

 

 



European WCF 4.5 Hosting - Amsterdam :: Implementing WebSockets in WCF 4.5

clock October 15, 2012 06:59 by author Scott

Web Services have one great virtue: they're completely interoperable. They also have one great failing: in order to be interoperable, Web Services use a set of technologies that are guaranteed to give you, at best, adequate performance. Fortunately, WCF 4.5 has a solution: support for WebSockets.

Ever since Web Services appeared, developers have been trying to make them run faster. REST and JSON can be seen as a way of speeding things up by reducing the overhead in the messaging format used by Web Services. However, even with REST and JSON you're still moving and parsing text, which is the bulkiest and slowest data transfer mechanism; you'd get better performance if you could move binary data around. And REST and JSON don't tackle another reason for why Web Services give poor performance: HTTP, the network protocol used by Web Services. There are slower protocols than HTTP around, but no one is using them.


But performance isn't the only issue that using HTTP creates: HTTP in Web Services is tied to a request/response cycle. The reason Ajax applications make all their requests asynchronously is because if you call a service that takes a long time to complete, your request has to wait for that response before you can get your result.


On top of that, if your service has something else to tell your client after that initial response (an ongoing set of updates, for instance), then either your client has to make repeated polling calls to the service to get the result (another performance burden) or, in a non-Ajax application, you have to set up a complementary Web Service that the service can call with the updates.


A far better arrangement would be for the client to submit its request in a "fire and forget" kind of arrangement and then for the service to call back to the client when it has the data (and keep calling back if there are updates to send).


WebSockets addresses all of those issues, while still being an industry standard and therefore interoperable (confusions in vendor's implementations of the standard may interfere). In fact, your browser probably already supports WebSockets.


For most processing, WebSockets uses TCP to communicate, giving you the benefit of a faster protocol. WebSockets also supports sending both binary (for speed) and text (for interoperability). But in many ways, the best part of WebSockets is that it supports two-way communication: The client can call the service just to open communication; and after that, the service can call the client whenever it has information to share. And WCF 4.5 provides support for WebSockets.


So in the next few columns, I'm going to look at WebSockets in WCF 4.5. I'll look at the two ways you can implement WebSockets (one complicated and flexible, one simpler and less flexible) and create client a JavaScript client. Along the way I'll also discuss some of the issues you should consider in creating a WebSocket application.


Configuring the Server

One warning: You may not be able to use the code in this series, yet. As I write this (April 2012), WebSockets is only supported on Windows 8 (I worked on the 64-bit
beta ISO for Windows 8 Server); even then, you'll need to configure Windows 8 to support WebSockets.

To configure Windows 8, in Server Manager, from the Manage menu, run the Add Server Roles and Features wizard. In the Wizard, you'll need to add the Web Server (IIS) role. After that, under Features, select ASP.NET 4.5 (if it isn't already selected) and, under Web Services, select HTTP Activation. Finally, under Web Services (IIS)/Role Services, select WebSockets. After finishinb the Wizard, select Local Server and set IIS Enhanced Security Configuration to off.


To work with WCF 4.5, you'll need
Visual Studio 11 (again, in beta, as I write this). The first time you run it, Visual Studio 11 will probably offer to download an update; if so, take the update (I took the update and I won't guarantee that the following code will work without it).

Second warning: This may be a frustrating set of columns if you're reading them as soon as I post them. I've got a fair amount of ground to cover so, in this column, I'll only be setting up to write the code that a WebSocket service requires. But hang tough; the next column will have the code and subsequent columns will show you how to build the clients and provide an alternative way to build a WebSocket service.


Building the Service

I did my testing with a WCF Service Application Project. To take advantage of IIS's support for WebSockets that I'd just finished configuring, I went to the Web tab of my Project Properties and unchecked the Use IIS Express option so that I was testing with the "real" IIS.


Once you've set up your server and project, the first step in creating your WebSocket service is to define two interfaces: one with a single method that accepts requests from clients and another interface with a single method to send results.


For the first interface, I'll define a method that accepts an Order Id (I call the method OrderStatusById method and the interface IRequestOrderStatusUpdates). In the ServiceContract attribute on the interface that accepts requests, you need to use the attribute's CallbackContract to specify the second interface (the one with the method used to send data back to the client is ISendOrderStatus in this example). The method must accept a Message as its only input parameter and the method's OperationContract attribute must set its IsOneWay property to True and its Action property to an asterisk.


The result for my Order status example looks like this:


<ServiceContract(CallbackContract:=GetType(ISendOrderStatus))>
Public Interface IRequestOrderStatusUpdate

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub OrderStatusByID(OrderStatusMessage  As Channels.Message)

End Interface


The definition for the return method is similar, except that you don't need any special specifications for the ServiceContract attribute. I've called my method SendOrderStatus:


<ServiceContract()>
Public Interface ISendOrderStatus

  <OperationContract(IsOneWay:=True, Action:="*")>
  Sub SendOrderStatus(OrderStatusMessage  As Channels.Message)

End Interface


At this point you're ready to write the code for these methods, which I'll look at in my next column (the column after that will look at building a client).

 



HostForLIFE.eu now supports Windows Server 2012 Hosting Platform in European Data Center

clock October 1, 2012 08:06 by author Scott

Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.

“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”


With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see
http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.

For more information about our service, please visit
http://www.hostforlife.eu.

About HostForLIFE.eu:


HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.


Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European Silverlight 5 Hosting - Amsterdam :: Markup Extensions in Silverlight 5

clock September 28, 2012 09:03 by author Scott

Another cool feature available in Silverlight 5 is markup extensions. The idea behind the feature is ability to allow developers to supply values to XAML parser at the time it parses visual tree. In other words, once parser finds a markup extension in XAML, it will create an instance of it, set any properties that the extension might have, then call ProvideValue method that will return a value of the type that the property that markup extension supports expects. For example, I am writing a markup extension to supply an ICommand to the button, my XAML would looks like the following:

      <Button Content="Save" HorizontalAlignment="Left"  
             Grid.Row="4" Grid.Column="0"
             Command="{ext:CommandMarkupExtension
                 ViewModel={Binding ElementName=LayoutRoot, Path=DataContext},
                 ExecuteMethodName=Run,
                 CanExecuteMethodName=CanRun}"/>


So, in this example for markup extension I am writing a command extension. As you can see in the XAML above, my extension takes three parameters: ViewModel to invoke, execute and can execute method names. This way I can de-clutter my view model by removing all the command instantiation code, and just write the two methods I need. The code in this extension is very easy – just a handful of dependency properties and interface implementation for IMarkupExtension:

using System;

using System.Windows;

using System.Windows.Input;

using System.Xaml;


namespace SL5Features.Extensions

{

  public class CommandMarkupExtension : FrameworkElement, IMarkupExtension<ICommand>
  {

    public Object ViewModel
    {
      get { return (Object)GetValue(ViewModelProperty); }
      set { SetValue(ViewModelProperty, value); }
    }

    public static readonly DependencyProperty ViewModelProperty =
        DependencyProperty.Register(
        "ViewModel", typeof(Object),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public string ExecuteMethodName
    {
      get { return (string)GetValue(ExecuteMethodNameProperty); }
      set { SetValue(ExecuteMethodNameProperty, value); }
    }
    public static readonly DependencyProperty ExecuteMethodNameProperty =
        DependencyProperty.Register(
        "ExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));


    public string CanExecuteMethodName
    {
      get { return (string)GetValue(CanExecuteMethodNameProperty); }
      set { SetValue(CanExecuteMethodNameProperty, value); }
    }

    public static readonly DependencyProperty CanExecuteMethodNameProperty =
        DependencyProperty.Register(
        "CanExecuteMethodName",
        typeof(string),
        typeof(CommandMarkupExtension),
        new PropertyMetadata(null));

    public ICommand ProvideValue(IServiceProvider serviceProvider)
    {
      ReflectionCommand command =
        new ReflectionCommand(ViewModel, ExecuteMethodName, CanExecuteMethodName);
      return command;
    }
  }
}

To support the extension I need to write a command object that would actually implement ICommand. This class is pretty trivial, so I am not commenting it much:


using System;

using System.Reflection;

using System.Windows;

using System.Windows.Input;  


namespace SL5Features.Extensions

{

  public class ReflectionCommand : ICommand
  {

    private MethodInfo canExecuteMethod = null;
    private MethodInfo executeMethod = null;
    private object viewModel = null;

    private ReflectionCommand() {


    public ReflectionCommand(
      object viewModel,
      string executeMethodName,
      string canExecuteMethodName)
    {
      this.viewModel = viewModel;
      Type type = viewModel.GetType();
      if (!string.IsNullOrEmpty(canExecuteMethodName))
      {
        this.canExecuteMethod = type.GetMethod(canExecuteMethodName);
      }
      this.executeMethod = type.GetMethod(executeMethodName);
    }

    public void Execute(object parameter)
    {
      executeMethod.Invoke(viewModel, new[] { parameter });
    }

    public bool CanExecute(object parameter)
    {
      if (viewModel != null && canExecuteMethod != null)
      {
        return (bool)canExecuteMethod.Invoke(viewModel, new[] { parameter });
      }
      else
      {
        return true;
      }
    }



    public event EventHandler CanExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
      if (CanExecuteChanged != null)
      {
        CanExecuteChanged(this, EventArgs.Empty);
      }
    }

  }
}

So, far it is pretty easy. Now, all I have to do is add Run and CanRun method on my view model that my command will invoke:

using SL5Features.Models;
using System.Windows;

namespace SL5Features.ViewModels

{
  public class PersonViewModel : ViewModelBase<Person
  {
    public PersonViewModel()
    {
      Model = new Person() { FirstName = "Sergey", LastName = "Barskiy" };
    }

    public void Run(object parameter)
    {
      MessageBox.Show("Run")
    }
    public bool CanRun(object parameter
    {
      return true;
    }
  }
}


Hopefully, I demonstrated the power of markup extension for you. The goal of using them to me is reduction of the amount of code elsewhere in the system, since you will obviously have to write more XAML. Of course, I am sure Blend 5 will support mark up extensions, so potentially you can just drag my extension on top of the button and setup a few properties in properties window. You will also see a number of demos where an extension is used to support localization, which seems pretty intuitive use of the feature. Bottom line is: I love getting new features that make my job easier by allowing me to write less code and re-use more of the code written.

 



European WCF 4.5 Hosting - Amsterdam :: IntelliSense for WCF Config file .NET 4.5

clock September 4, 2012 07:09 by author Scott

Now Visual studio 2011 is giving IntelliSense for WCF config files (App.config, Web.config). It is really good for .NET developer, previously when we developed WCF application; Application development is easy rather than configuration. Now in VS 2011 gives us IntelliSense in the Config file. Even we can also map contract.

In previous version of Visual Studio we did configuration via "
Edit WCF Configuration" wizard

In the below image we can set endpoint binding.




In the below image we can set service contract.


 



European Silverlight 5 Hosting - Amsterdam :: Creating a Silverlight 5 Static Markup Extension

clock August 28, 2012 10:00 by author Scott

If you have done any WPF application development I am sure you have used and fallen in love with the Static markup extension. If you’re are not familiar with it, the Static markup extension allows you to reference static fields and properties in your XAML markup.

For example; let’s assume we have a class with the following static field defined:


public class Common

 {
     public static string StaticText = "This is text from a static property";
 }

We can use this field in our WPF application as follows:

<Grid>

     <TextBlock Text="{x:Static ext:Common.StaticText}" />
 </Grid>



NOTE: “ext” is a namespace that has been defined to instruct the XAML parser where to find our static field.

Pretty cool right? Unfortunately if you are also doing any Silverlight development you will soon find that this wonderful and useful extension does NOT exist in Silverlight. Luckily for us in Silverlight 5 we were given the ability to write our own custom markup extensions. This can be done using either the
IMarkupExtension or the abstract MarkupExtension class.

Now it’s time to create our own Static markup extension. I want to point out that there is a naming convention when creating custom markup extensions. The convention is as follows; ExtensionNameExtension. The name of the extension is followed by Extension. This is very similar to how you create attributes. You won’t actually be using the suffix when define them in XAML.

Let’s start by creating a new class called StaticExtension. The StaticExtension class should derive from the MarkupExtension abstract class. You will need to implement the abstract ProvideValue method. The code I used for the Static markup extension is as follows.

/// <summary>
 ///  Class for Xaml markup extension for static field and property references.
 /// </summary>
public class StaticExtension : MarkupExtension
 {
     /// <summary>
     ///  The static field or property represented by a string.  This string is
     ///  of the format Prefix:ClassName.FieldOrPropertyName.  The Prefix is
    ///  optional, and refers to the XML prefix in a Xaml file.
     /// </summary>
    private string _member;
     public string Member
     {
         get { return _member; }
         set
         {
             if (value == null)
             {
                 throw new ArgumentNullException("Member");
             }
             _member = value;
         }
     }

    /// <summary>
     ///  Return an object that should be set on the targetObject's targetProperty
    ///  for this markup extension.  For a StaticExtension this is a static field
    ///  or property value.
     /// </summary>
    /// <param name="serviceProvider">Object that can provide services for the markup extension.
     /// <returns>
     ///  The object to set on this property.
     /// </returns>
    public override object ProvideValue(IServiceProvider serviceProvider)
     {
         if (_member == null)
             throw new InvalidOperationException("member cannot be null");

        // Validate the _member
        int dotIndex = _member.IndexOf('.');
         if (dotIndex < 0)
             throw new ArgumentException("dotIndex");

        // Pull out the type substring (this will include any XML prefix, e.g. "av:Button")
        string typeString = _member.Substring(0, dotIndex);
         if (typeString == string.Empty)
             throw new ArgumentException("typeString");

        // Get the IXamlTypeResolver from the service provider
         IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
         if (xamlTypeResolver == null)
             throw new ArgumentException("xamlTypeResolver");

        // Use the type resolver to get a Type instance
        Type type = xamlTypeResolver.Resolve(typeString);

        // Get the member name substring
         string fieldString = _member.Substring(dotIndex + 1, _member.Length – dotIndex – 1);
         if (fieldString == string.Empty)
             throw new ArgumentException("fieldString");

        // Use the built-in parser for enum types
         if (type.IsEnum)
         {
             return Enum.Parse(type, fieldString, true);
         }

        // For other types, reflect
        bool found = false;
         object value = null;

        object fieldOrProp = type.GetField(fieldString, BindingFlags.Public |                                                         BindingFlags.FlattenHierarchy | BindingFlags.Static);
         if (fieldOrProp == null)
         {
             fieldOrProp = type.GetProperty(fieldString, BindingFlags.Public
|                                                         BindingFlags.FlattenHierarchy | BindingFlags.Static);
             if (fieldOrProp is PropertyInfo)
             {
                 value = ((PropertyInfo)fieldOrProp).GetValue(null, null);
                 found = true;
             }
         }
         else if (fieldOrProp is FieldInfo)
         {
             value = ((FieldInfo)fieldOrProp).GetValue(null);
             found = true;
         }

        if (found)
             return value;
         else
             throw new ArgumentException("not found");
     }
 }

Now all I need to do is add a namespace to my Silverlight view and then use it in XAML as follows:

<Grid x:Name="LayoutRoot" Background="White">

     <TextBlock Text="{ext:Static Member=ext:Common.StaticText}" />
 </Grid>



That’s it! I will definitely be using this quite often. I would like to mention that unlike in WPF where you don’t have to specify the “Member” property explicitly, in Silveright you have to explicitly set the Member property. This is because there is not a
ConstructorArgument attribute in Silverlight. So until then you will need to have a little extra text in your markup syntax.



European Silverlight 5 Hosting - Amsterdam :: Breakpoints on Xaml in Silverlight 5

clock July 13, 2012 09:45 by author Scott

Silverlight 5 Beta brings the enormously useful ability to set a break point in your Xaml where you have a data binding. This can greatly simplify debugging and fixing binding issues.



To see this, create a new Silverlight 5 project and set up the Xaml to have 5 rows and 2 columns. Place the title in the first row (spanning both columns) and prompts in the next 4 rows. The prompts are


- FullName

- Address
- Phone
- Email

Add four TextBlocks in the second column to display the values that will correspond to these prompts. The Xaml for the four prompts looks like this:


<TextBlock
    Grid.Column="1"
    Grid.Row="1"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding FullName}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="2"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Address}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="3"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding PhoneNumber}" />
<TextBlock
    Grid.Column="1"
    Grid.Row="4"
    Margin="5"
    HorizontalAlignment="Left"
    VerticalAlignment="Center"
    Text="{Binding Email}" />

To make this work, of course, we need a class and an instance to bind to. Begin by creating a new class, Person,


public class Person

{

    public string FullName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

In MainPage.xaml.cs create an instance of Person, and set that instance to be the data context for the bindings,


public MainPage()
{
    InitializeComponent();
    var per = new Person()
    {
        FullName = "Jesse Liberty",
        Address = "100 Main Street, Boston, MA",
        Email = "[email protected]",
        Phone = "617-555-1212"
    };
    this.DataContext = per;
}

When you run this you’ll find that three of the four bindings work well, but the phone number is not displayed. Set a break point in the Xaml folder on the binding for the PhoneNumber and run the application. When you hit the break point examine the locals window as shown in the illustration to the below.



Note that there is an error message. By clicking on the message you can open a text reader for the entire error message, as shown in the next figure to the below.




The error message indicates that there is no property PhoneNumber in the type Person, and sure enough, a quick check of the code shows that the property is just
Phone.

Change the binding from PhoneNumber to Phone and the program works as expected.



European Silverlight 5 Hosting - Amsterdam :: How to Design RichTextBox in Silverlight 5

clock June 29, 2012 08:54 by author Scott

In this article, I am going to explain how to design a RichTextBox in Silverlight. This example also demonstrates the RichTextBox control as well. It is easy to formatt a Silverlight RichTextBox at design time through XAML. In this example I have used an image to illustrate the example clearly.

<UserControl x:Class="SilverlightApplication3.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:DesignHeight="300" d:DesignWidth="400" DataContext="{Binding}">

              <Grid x:Name="LayoutRoot" Background="White" Height="450" Width="550">
                      <RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" Name="contentBox" VerticalAlignment="Top" Height="330" Width="390" IsReadOnly="True" Background="#FFFFFF69">
                    <Paragraph FontFamily="Arial" FontSize="12" TextAlignment="Justify">
                   This photograph shows a
                <Run Text=" blue hills " FontStyle="Italic" FontWeight="ExtraBold" /> belongs to the
                <Run Text=" high " Foreground="blue" FontWeight="ExtraBold"/> graphic photography. High graphic photography requires a     great deal of precision.
                <LineBreak/>
                <InlineUIContainer>
                    <Image Height="143" HorizontalAlignment="Left" Margin="144,82,0,0" Name="images" Stretch="Uniform" VerticalAlignment="Top" Width="196" Source="/SilverlightApplication3;component/Images/Blue%20hills.jpg" />
                </InlineUIContainer>
                <LineBreak/>
                <LineBreak/> |
          </Paragraph>
        </RichTextBox>
    </Grid>
</UserControl>

Now I am going to explain the code so that it can be easily understood. It creates a RichTextBox, with some text and an image. To place and format the text, I first use the Paragraph element, then the Run element. Note that the Paragraph element also has a Foreground property but which I have not used here. In this I use the Run element which is useful to format text. The RichTextBox control also allows you to add elements of type Bold, Underline etc.The Run element derives from the Inline element, an Inline cannot be used directly within a RichTextBox control, however, you can use the Run element.


The LineBreak element is used to introduce line breaks.

The Image is placed inside the InlineUIContainer.

InlineUIContainer: A mandatory child element that is used to place an Image in the RichTextBox control.

You can have as many Paragraph and Run elements as you want, in a RichTextBox control. Using a combination of Paragraph and Run elements, you can format the text in various ways.

The output of the above application is shown below:



European Silverlight 5 Hosting - Amsterdam :: Platform Invocation Services in Silverlight 5

clock June 13, 2012 08:26 by author Scott

One of the new features included with the Silverlight 5 RC is the ability to interact with Platform Invocation Services, or PInvoke for short. This functionality allows managed code, like your Silverlight application, to make calls to unmanaged code like the C++ code that exists in DLLs on your system. PInvoke can be quite complex and covers a lot of different scenarios, so I've focused on a simple scenario to help you get started. You can learn more about PInvoke by reading this MSDN tutorial.

In this post, I will show you how to build a Silverlight Out-of-Browser (OOB) application that uses the native DLLs on your machine to play "beeps." With modern versions of Windows 7, the beeps have evolved into complex sounds that you can assign to various functions. Create a new Silverlight application called "PInvoke," set it to run out of browser and be sure to check the box that indicates it requires elevated trust.


Take a look at the MessageBeep function. It is documented
here. The first thing you'll notice is that the type of beep or sound to play is not very friendly as it is passed in as an unsigned integer. Based on the documentation, you can create the following enumeration to simplify things and expose a few key types:

1 public enum BeepTypes : uint
2 { 
3     Ok = 0x00000000, 
4     Error = 0x00000010, 
5     Warning = 0x00000030, 
6     Information = 0x00000040 
7 }

To make it easy to take a string and cast it to the enumeration value, add this extension method as well:


01 public static class BeepTypeExtensions 
02 { 
03     public static BeepTypes AsBeepTypeEnum(this string beepType) 
04     { 
05         BeepTypes beepTypeEnum; 
06         return Enum.TryParse(beepType, true, out beepTypeEnum) 
07                     ? beepTypeEnum 
08                     : BeepTypes.Error; 
09     } 
10 }


It is always good practice to encapsulate your calls to unmanaged code in a managed class. This limits the exposure and dependency on PInvoke. It also allows you to write more portable code because you can implement the calls in managed code or simply stub out empty methods for targets that don't support the PInvoke implementation. Here is a simple contract to play a sound:


1 public interface ISoundPlayer 
2 { 
3     void PlaySound(BeepTypes type); 
4 }


Now for the implementation. Create a class called
SoundPlayer. The documentation gives you the message signature and the DLL that the method is located in. Bridging to the method in this example is very easy. First, include a using statement for System.Runtime.InteropServices. This is where the PInvoke bridge lives. Next, simply define the message signature as a static extern and import the DLL:

1 [DllImport("User32.dll")] 
2 private static extern Boolean MessageBeep(UInt32 beepType);

Implement the contract and call the method you just imported using PInvoke:


1 public void PlaySound(BeepTypes type) 
2 { 
3     if (!MessageBeep((UInt32) type)) 
4     { 
5         throw new Exception("Beep failed!"); 
6     } 
7 }

That's all there is to it! Now wire up some Xaml in the main page to host four buttons:

01 <Grid x:Name="LayoutRoot" Background="White"> 
02     <Grid.RowDefinitions> 
03         <RowDefinition Height="1*"/> 
04         <RowDefinition Height="1*"/> 
05     </Grid.RowDefinitions> 
06     <Grid.ColumnDefinitions> 
07         <ColumnDefinition Width="1*"/> 
08         <ColumnDefinition Width="1*"/> 
09     </Grid.ColumnDefinitions> 
10     <Button x:Name="Ok" Content="OK" Grid.Row="0" Grid.Column="0"  Click="Button_Click"/> 
11     <Button x:Name="Error" Content="Error" Grid.Row="0" Grid.Column="1"  Click="Button_Click"/> 
12     <Button x:Name="Warning" Content="Warning" Grid.Row="1" Grid.Column="0"  Click="Button_Click"/> 
13     <Button x:Name="Information" Content="Information" Grid.Row="1" Grid.Column="1"  Click="Button_Click"/> 
14 </Grid>

Make sure that the name of the button matches the name of the enum. In the code-behind for the main page, create an instance of the sound player:

1 private readonly ISoundPlayer _soundPlayer = new SoundPlayer();

Now you can implement the button click event. Simply cast the name of the button to the enumeration and call the method on your managed class:


1 private void Button_Click(object sender, RoutedEventArgs e) 
2 { 
3     var button = sender as Button; 
4     if (button == null) 
5     { 
6         return; 
7     } 
8     _soundPlayer.PlaySound(button.Name.AsBeepTypeEnum()); 
9 }

That's it! Run the application in OOB mode and you will be able to press the buttons and hear your default Windows sounds play. If you change your theme or override the sounds, the application will play the correct sounds because it is bridging to the unmanaged code and asking the operating system to play the sound rather than trying to play it from a resource embedded within the Silverlight application.


Hopefully this light example will help you get started. PInvoke has a number of uses from interfacing directly with USB ports to enumerating drives and devices on the host system. It certainly opens the door to a new realm of possibilities with Silverlight.

 



European Silverlight 5 Hosting - Amsterdam :: Implicit Data Templates in Silverlight 5

clock May 29, 2012 08:43 by author Scott

One of the powerful new features around templating in the Silverlight 5 beta is the ability to produce a DataTemplate that will be implicitly associated with a particular data type.

For example, if I have these 2 simple types Person and Vehicle;


public class Person  
{  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public int Age { get; set; }  
}  
public class Vehicle  
{  
  public string Type { get; set; }  
  public int Wheels { get; set; }  
}
 

then I can define implicit templates for them by writing templates such as these;


<UserControl.Resources> 
    <DataTemplate 
      DataType="local:Person"> 
      <StackPanel> 
        <TextBlock 
          Text="{Binding FirstName}" /> 
        <TextBlock 
          Text="{Binding LastName}" /> 
        <TextBlock 
          Text="{Binding Age}" /> 
      </StackPanel> 
    </DataTemplate> 
    <DataTemplate 
      DataType="local:Vehicle"> 
      <StackPanel> 
        <TextBlock 
          Text="{Binding Type}" /> 
        <TextBlock 
          Text="{Binding Wheels}" /> 
      </StackPanel> 
    </DataTemplate> 
  </UserControl.Resources>
 

where I have not specified a
Key for these resources but have, instead, specified a DataType and that’s enough for Silverlight to figure it out.

If I have a scenario like this one where I have a
ListBox bound to a set of Items;

<Grid>  
  <Grid.RowDefinitions>  
    <RowDefinition />  
    <RowDefinition  
      Height="Auto" />  
    <RowDefinition  
      Height="Auto" />  
  </Grid.RowDefinitions>  
  <ListBox  
    ItemsSource="{Binding Items}">  
  </ListBox>  
  <Button  
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" />  
  <Button  
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" />  
</Grid> 


with a
DataContext providing a view model like this one;

public class ViewModel  
{  
  public ViewModel()  
  {  
    this.Items = new ObservableCollection<object>();  
    this.AddPerson = new SimpleCommand(() =>  
      {  
        this.Items.Add(  
          new Person()  
          {  
            FirstName = "TestFirst",  
            LastName = "TestLast",  
            Age = 22  
          });  
      });  
    this.AddVehicle = new SimpleCommand(() =>  
      {  
        this.Items.Add(  
          new Vehicle()  
          {  
            Type = "Car",  
            Wheels = 4  
          });  
      });  
  }  
  public ObservableCollection<object> Items { get; set; }  
  public ICommand AddPerson { get; set; }  
  public ICommand AddVehicle { get; set; }  
}
 

then whenever I add a
Person to the ListBox the runtime will find the right implicit template to display the Person and if I add a Vehicle to the ListBox then the runtime will do the right thing there too;



and, if for example I was to make my ViewModel implement property change notification and then bind up a new property called
SelectedItem to my ListBox then I can bring in a ContentPresenter and it will also make use of the implicit template as in;

<UserControl.Resources>  

  <DataTemplate  
    DataType="local:Person">  
    <StackPanel>  
      <TextBlock  
        Text="{Binding FirstName}" />  
      <TextBlock  
        Text="{Binding LastName}" />  
      <TextBlock  
        Text="{Binding Age}" />  
    </StackPanel>  
  </DataTemplate>  
  <DataTemplate  
    DataType="local:Vehicle">  
    <StackPanel>  
      <TextBlock  
        Text="{Binding Type}" />  
      <TextBlock  
        Text="{Binding Wheels}" />  
    </StackPanel>  
  </DataTemplate>  
</UserControl.Resources>  

<UserControl.DataContext>  

  <local:ViewModel />  
</UserControl.DataContext>  

<Grid>  

  <Grid.ColumnDefinitions>  
    <ColumnDefinition />  
    <ColumnDefinition />  
  </Grid.ColumnDefinitions>  
  <Grid.RowDefinitions>  
    <RowDefinition />  
    <RowDefinition  
      Height="Auto" />  
    <RowDefinition  
      Height="Auto" />  
  </Grid.RowDefinitions>  
  <ListBox  
    ItemsSource="{Binding Items}" 
    SelectedValue="{Binding SelectedItem,Mode=TwoWay}" />  
  <Button  
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" />  
  <Button  
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" />  
  <ContentPresenter  
    Grid.Column="1" 
    Content="{Binding SelectedItem}" />  
</Grid> 


and so then both the ListBox on the left and the ContentPresenter on the right are using implicit templates to display content;




(as an aside, I also tried this with a
ContentPresenter inside a Tooltip and it didn’t work for me so far in the beta).

Naturally, you can override these implicit templates so if I want a different template for my
ContentPresenter I can simply add an implicit template that is nearer to the ContentPresenter in the hierarchy of resource resolution as in;

<UserControl.Resources> 

  <DataTemplate 
    DataType="local:Person"> 
    <StackPanel> 
      <TextBlock 
        Text="{Binding FirstName}" /> 
      <TextBlock 
        Text="{Binding LastName}" /> 
      <TextBlock 
        Text="{Binding Age}" /> 
    </StackPanel> 
  </DataTemplate> 
  <DataTemplate 
    DataType="local:Vehicle"> 
    <StackPanel> 
      <TextBlock 
        Text="{Binding Type}" /> 
      <TextBlock 
        Text="{Binding Wheels}" /> 
    </StackPanel> 
  </DataTemplate> 
</UserControl.Resources> 

<UserControl.DataContext> 

  <local:ViewModel /> 
</UserControl.DataContext> 

<Grid> 

  <Grid.ColumnDefinitions> 
    <ColumnDefinition /> 
    <ColumnDefinition /> 
  </Grid.ColumnDefinitions> 
  <Grid.RowDefinitions> 
    <RowDefinition /> 
    <RowDefinition 
      Height="Auto" /> 
    <RowDefinition 
      Height="Auto" /> 
  </Grid.RowDefinitions> 
  <ListBox 
    ItemsSource="{Binding Items}" 
    SelectedValue="{Binding SelectedItem,Mode=TwoWay}" /> 
  <Button 
    Command="{Binding AddPerson}" 
    Content="Add Person" 
    Grid.Row="1" /> 
  <Button 
    Command="{Binding AddVehicle}" 
    Content="Add Vehicle" 
    Grid.Row="2" /> 
  <Grid 
    Grid.Column="1"> 
    <Grid.Resources> 
      <DataTemplate 
        DataType="local:Vehicle"> 
        <StackPanel 
          Orientation="Horizontal"> 
          <TextBlock 
            Text="{Binding Type}" /> 
          <TextBlock 
            Text="{Binding Wheels}" /> 
        </StackPanel> 
      </DataTemplate> 
    </Grid.Resources> 
    <ContentPresenter 
        Grid.Column="1" 
        Content="{Binding SelectedItem}"/> 
  </Grid> 
</Grid> 

and, naturally, you can also mix/match this implicit approach with the explicit approach that you’d use in Silverlight 4 today.


I think this is a pretty powerful addition to the Silverlight 5 binding/templating abilities and it’ll be interesting to see what other folks and frameworks do with it.

 



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in