European Silverlight 4 & Silverlight 5 Hosting BLOG

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

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.

 



European WCF 4.0 Hosting - Amsterdam :: Creating WCF 4.0 Service and Hosting in IIS 7.5

clock May 22, 2012 11:02 by author Scott

This article will give step by step walkthrough

1. How to create a basic WCF 4.0 Service?


2. How to host WCF Service in IIS 7.5?


3. Hot to test service in a client.


Create WCF Service

Create WCF service. Open visual studio select new project and then from WCF tab select WCF Service application to create a new WCF service.




Delete the default code created by WCF from
IService1 and Service1.svc.cs

a. So delete the data contract

b. Modify the service contract as below. Just make one operation contract to return a string .

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService5
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetMessage();

    }  

}

Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService5

{
    public class Service1 : IService1
    {
        public string GetMessage()
        {
            return "Hello From WCF Service ";
        }
    }
}

Leave the default configuration created by WCF.

Web.Config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>        
          <serviceMetadata httpGetEnabled="true"/>        
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer
</configuration>

Host WCF Service in IIS 4.0

Open IIS

a. Open the command prompt in administrator mode. To do click on Start button then type RUN in search and then in Run window type inetmgr to open IIS .



Now you will have IIS open like below




b. Right click on Sites and then click Add Web Site




c. Now a window will open




Give any name of your choice as the site name. I am giving name here
HostedWcfService



Now click on
select and choose ASP.Net v4.0 from the drop down.



Now in the physical path section, we need to give physical path of the service. So to get the physical path of the service, right click on the WCF Service project in visual studio and click open project in windows explorer. Open the project in windows explorer and from address bar copy the path and paste that below. Or you can browse also. Just click on browse button and navigate to project folder of the WCF Service.




Now at the Binding section select HTTP. Give any port number. I am selecting the port as 4567




Do not give any name as host name. Leave it blank




Check the check box Start Web Site Immediately.




And now click OK on the window.


d. Now open visual studio command prompt in administrator mode. Right click and select as administrator






Type the below command


aspnet_regiis.exe /iru



You will get the message Finished Installing ASP.Net 4.0


e. Now go to
inetmgr, you would able to see the site you just created in previous step.



Publishing the WCF Service

Go back to WCF Service. Right click and select Publish




On clicking of publish a window will come.




Give a Service URL. You are free to give any Service URL here. Just make sure host name is geeting resolved. In stead of localhost you can give IP address or your machine name also.




Give the name of the site
HostedWcfService. We created this site in previous step.



Leave the credential inactive.




Now click on
Publish.



You will get the message in bottom
publish succeeded

Browsing the service hosted in IIS


Open
Inetmgr and right click on site HostedWcfService. Then from Manage Web Site select Browse option.



When you click on browse site will get open in browser




You will get the above error. Just in address bar append Service1.svc with the address to open the service in browser.


http://localhost:4567/Service1.svc


And in browser you will get the service up and running




So now you successfully created and hosted the WCF 4.0 service in IIS 7.5


Testing the Service at client

a. Create console application project




b. Right click and add the service reference.




c. Give in address the address of service hosted in IIS and click GO.




d. Call the service as below ,


Program.cs

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication1.ServiceReference1;

namespace ConsoleApplication1

{
    class Program
    {
        static void Main(string[] args)
        {
            Service1Client proxy = new Service1Client();
            Console.WriteLine(proxy.GetMessage());
            Console.Read();
        }
    }
}

Output


 

 

 

 



European Silverlight 5 Hosting - Amsterdam :: Using the ViewBox Control in Silverlight 5

clock May 14, 2012 08:40 by author Scott

This article will explore how to use the ViewBox control in Silverlight 5.

The ViewBox control allows you to place a child control such as Image within it in such a way that it will be scaled appropriately to fit the available without any distortion. It is typically used in 2D graphics.


We will begin with creating a new Silverlight 5 project.


Modify the existing XAML code of MainPage.xaml so that a Grid of 1 column and three rows is created. The code for the same is shown below:


<UserControl x:Class="SilverlightDemo.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" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
     <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
     </Grid>
 </UserControl>


Drag and drop the Viewbox control from the Toolbox into the XAML code between the <Grid></Grid> tags. Specify its row and column in the grid to be 0. The resulting code is seen below.


<UserControl x:Class="SilverlightDemo.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" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">        <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
   </controls:Viewbox> 
    </Grid>
 </UserControl>

Right click on the project name in the Solution Explorer pane and select Add Existing Item option. Choose the image "Winter.jg" from the My Documents\My Pictures\Sample Pictures folder.


Drag and drop an Image control in between the <controls:ViewBox> and </controls:ViewBox> tag and modify its code as shown below, to specify its source and size.


    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
             <Image Source="Winter.jpg" Height="40" Width="40"></Image>
         </controls:Viewbox>
     </Grid>

Drag and drop another ViewBox and then an Image control in between the second <controls:ViewBox> and </controls:ViewBox> tag.

Modify the XAML as shown below:


    <Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="200" />
         </Grid.ColumnDefinitions>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
             <RowDefinition Height="Auto" />
         </Grid.RowDefinitions>
          <controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
             <Image Source="Winter.jpg" Height="40" Width="40"></Image>
         </controls:Viewbox>
 <controls:Viewbox Grid.Row="1" Grid.Column="0" Height="70" Width="90">
     <Image Source="Winter.jpg" Height="40" Width="40"></Image></controls:Viewbox>
     </Grid>


Save the solution, build and execute it. When you see the output, you will observe that the two images show no distortion whatsoever though their height and width are not the same. This has happened because of the ViewBox.




Conclusion
: Thus, you learnt how to add and use a ViewBox control in a Silverlight application



European WCF 4.5 Hosting - Amsterdam :: Beyond Configuring Web Services in WCF 4.5

clock April 27, 2012 10:34 by author Scott

In previous post, you can see how easy it was to add a basic HTTP Web Service to a Web site in the beta of the .NET Framework 4.5 through code: Just add a shared/static method called Configure to your service and put some code in it to configure the ServiceConfiguration object passed to the method. In fact, because of the defaults that WCF 4.5 takes for a WCF service in a Web Site you don’t really need to add any code at all. In my example I did add some code to explicitly enable my service as a basic HTTP Web Service. I also chose to configure the service to return a contract and verbose error messages (both of which are turned off by default) to support testing.

But the power of WCF is in providing multiple ways of accessing the same code–as a basic Web Service or as a high performance TCP-based service. Adding TCP access requires a change in the project type: Testing a TCP-based service from Visual Studio is awkward (at best). Instead, you’ll want to create a WCF Service library where you service is hosted by WAS rather than IIS. While that makes testing your TCP access is simplified, the defaults don’t give you a service automatically and you’ll need to use a few more lines of code.


After creating your WCF Service library project add a new WCF Service to it, giving the service some meaningful name (I used “CustomerService”). Then, to demonstrate the power of configuring by code, go to your app.config file and delete the entire system.model element. You’re now ready to control your service from code.


These two lines of code make your service available as a Web Service and as a TCP-based service (which will have orders-of-magnitude better performance than the HTTP-based Web service):


PublicSharedSub Configure(sc AsServiceConfiguration)

sc.EnableProtocol(
New BasicHttpBinding
sc.EnableProtocol(
New NetTcpBinding)

While that (in theory) makes your service accessible, it doesn’t make the information about the service (the metadata) available. As a result, you won’t be able to either use Visual Studio’s WCF Test Client or be able add a service reference for your service to another project by using the Add Service Reference dialog’s Discover button. To enable the metadata you use the same code that I had in my previous post but with one extra line of code that specifies the address where the metadata is available. In that line you create a System.URI object specifying the address (the address must reference your computer name but the port and service name are up to you) and use it to set the HttpGetUrl property:


Dim behavior As New Description.ServiceMetadataBehavior

behavior.HttpGetEnabled =
True
behavior.HttpGetUrl = New System.Uri("http://localhost:1868/Customers")

sc.Description.Behaviors.Add(behavior)

You also need to add endpoints for HTTP and TCP access to your service. For that, you use the AddServiceEndpoint method on the ServiceConfiguration object passed to your Configure method. The first parameter to the AddServiceEndpoint is the type of the interface that your service implements (“ICustomers” in this example), the second parameter is the binding class for the endpoint, and the final parameter is the address itself (make sure that you use different addresses for each endpoint):


sc.AddServiceEndpoint(GetType(ICustomerService),

         New BasicHttpBinding(),
         "http://localhost:1868/Customers")
sc.AddServiceEndpoint(GetType(ICustomer),

         New NetTcpBinding(),  
         "net.tcp://localhost:1867/Customers")

There is an annoyance when you go to test your service: In a Service Library, in the absence of any entries in the config file, the test client can’t retrieve the information about the service. You’ll first get a dialog that the “WCF Service Host cannot find any service metadata”–just click the No button to continue. When the Test Client appears, it won’t display any services. You’ll need to go to the Test Client’s File menu and select Add Service to display the Add Service dialog box. In the box, enter the URL you used to set the HttpGetUrl property followed by “?wsdl” (e.g. “http://localhost:1868/Customers?wsdl”—and make sure you type the URL exactly the way it appears in your code). When you click the OK button, the Test Client will finally grab the service information and you’ll be able to test your service. The good news here is that, once you enter the URL with ?wsdl successfully, you won’t have to enter it again (you will still need to go through all the dialogs, though).

And there you go: With less than a dozen lines of code you’ve configured a service as both a basic HTTP service and TCP-based service. Adding additional access methods (e.g. named pipes, advanced web services, https) should just consist of enabling the protocol with the EnableProtocol method and adding a compatible endpoint.

 



European WCF Hosting - Amsterdam :: How to Solve - The type provided as the Service attribute could not be found

clock April 25, 2012 07:08 by author Scott

This had me stumped for a little while today. Whilst trying to host a WCF service in IIS we got this message when we tried to access the .svc file:

The type 'YourType, YourAssembly', provided as the Service attribute value in the ServiceHost directive could not be found.


At first the message seemed to be very specific about not being able to find the
type - almost as though it had found the assembly so I changed the YourAssembly to utter nonsense to see if the error changed. Alas no, so it was possible that the assembly couldn't be 'found', let alone the type.

Everything seemed to be in order as far as the assembly was concerned. He was in the bin folder and security was setup appropriately. The type, namespace and assembly were quadruple checked and
definitely correct. We even hooked up WinDbg and used the sxe ld YourAssembly command in the hope that we'd see the module attempt to load and fail. But nothing.

So I did what I always do in these situations and reverted to my ol' skool
Response.Write-ASP-classic-style debugging techniques. First step was to drop in an aspx page that used the Activator to create the type dynamically. Here's the ASPX page (no .aspx.cs required):

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Runtime.Remoting" %>

<%
ObjectHandle oh = Activator.CreateInstance("YourAssembly", "YourType");
Response.Write(oh.Unwrap().ToString() + " loaded OK");
%>

Just drop this page next to your .svc file and navigate to it in the browser. If it works and you can see the name of your type then you have a different problem to ours. I got an error that looked like this:


Could not load file or assembly 'SomeOtherAssembly' or one of its dependencies. The system cannot find the file specified.

Aha! So we could find the type specified in the Service attribute but we couldn't find some of its dependences. That's better - turns out I was missing an assembly that had to be GAC'd for this to work.



European Silverlight 5 Hosting - Amsterdam :: Client-side Collections Silverlight 5

clock April 24, 2012 06:33 by author Scott

With the release of Silverlight 5 just around the corner, I thought I would start a series on the new PivotViewer and how to get up and running with it. We will start the series off by exploring how to create a client side collection.

One of the most anticipated features of the new PivotViewer is the ability to create client-side collections. PivotViewer accomplishes this by utilizing the traditional ItemsSource property for data and a form of XAML data templates to define the trading card. It is interesting to note that the fundamental core of PivotViewer is still using the DeepZoom technology. If you are thinking that DeepZoom only handles images and not XAML, you would be correct. Under the hood, PivotViewer is rendering the data templates to images and then adding those images to DeepZoom. Remembering that little tidbit will help later down the road.


The Basics


First things first, let’s get a PivotViewer control into our application. One of the great changes in the PivotViewer is that instead of 4 libraries we are down to one. So to include the PivotViewer in your application, you simple need to add a reference to System.Windows.Controls.Pivot.


Now we can add a PivotViewer to our application like this:


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

    <pivot:PivotViewer x:Name="pViewer"/>
</Grid>


Doesn’t get much simpler than that, now does it?


Getting your Data


In order to focus in our demo, we are going to generate some dummy data on the client. Of course, you are most likely going to be pulling in more meaningful data (let’s hope anyway) and you can still do that in the traditional ways.


public class DemoItem : INotifyPropertyChanged

{

    public string ShortName { get; set; }

    private string _color;
    public string Color
    {
        get { return _color; }
        set
        {
            _color = value;
            NotifyProperty("Color");
        }
    }

    private int _value;
    public int Value

    {
        get { return _value; }
        set
        {
            _value = value;
            NotifyProperty("Value");
        }
    }

    private string _data1;
    public string Data1
    {
        get { return _data1; }
        set
        {
            _data1 = value;
            NotifyProperty("Data1");
        }
    }

    private DateTime _stamp;
    public DateTime Stamp
    {
        get { return _stamp; }
        set
        {
            _stamp = value;
            NotifyProperty("Stamp");
        }
    }

    public static ObservableCollection<DemoItem> BuildData()
    {
        var data = new ObservableCollection<DemoItem>();

        for (int i = 0; i < 100; i++)
        {
            var itm = new DemoItem()
             { ShortName = i.ToString("000") };

            var mod = i % 3;

            switch (mod)
            {
                case 0:
                    itm.Color = "Blue";
                    break;
                case 1:
                    itm.Color = "Red";
                    break;
                case 2:
                    itm.Color = "Green";
                    break;
            }

            itm.Data1 = i % 2 == 0 ? "Even" : "Odd";
            itm.Stamp = DateTime.Now.AddDays(-1*i);
            data.Add(itm);
        }

        return data;
    }

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyProperty(string propName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this,
              new PropertyChangedEventArgs(propName));
    }

    #endregion

}

As you can see there isn’t a whole lot going on here. The BuildData() method knocks out some data that will let us see PivotViewer in action. I used a string for the color property so it would map to a PivotViewer property cleanly.


Now that we can generate our data, how do we get it into PivotViewer? It’s as simple as using the ItemsSource property (yep just like a normal Silverlight control).

pViewer.ItemsSource = DemoItem.BuildData();

Setting up your PivotProperties

In the original PivotViewer properties were defined as facets. In the new version we now have PivotProperties. There hasn’t been any changes to the number or types of properties. The four available types are :

1. PivotViewerStringProperty
2. PivotViewerNumericProperty
3. PivotViewerDateTimeProperty
4. PivotViewerLinkProperty

PivotViewer has a PivotProperties property (try saying that 3 times fast) that you can set via code or in XAML. For completeness sake, let’s take a look how each would look. Both of these examples yield the same result.

PivotViewer Properties in XAML:

<pivot:PivotViewer x:Name="pViewer">

    <pivot:PivotViewer.PivotProperties>
        <pivot:PivotViewerNumericProperty
            Id="Value"
            Options="None"
            Binding="{Binding Value}"/>
        <pivot:PivotViewerStringProperty
            Id="Data1"
            Options="CanFilter,CanSearchText"
            Binding="{Binding Data1}"/>
        <pivot:PivotViewerStringProperty
            Id="Color"
            Options="CanFilter,CanSearchText"
            Binding="{Binding Color}"/>
        <pivot:PivotViewerDateTimeProperty
            Id="Stamp"
            Options="CanFilter"
            Binding="{Binding Stamp}"/>
    </pivot:PivotViewer.PivotProperties>
</pivot:PivotViewer>


PivotViewer Properties in code behind:


pViewer.PivotProperties = new List<PivotViewerProperty>()

        {
            new PivotViewerNumericProperty()
                {
                    Binding = new Binding("Value"),
                    Id = "Value",
                    Options = PivotViewerPropertyOptions.None
                },
            new PivotViewerStringProperty()
                {
                    Binding = new Binding("Data1"),
                    Id = "Data1",
                    Options = PivotViewerPropertyOptions.CanFilter
                    | PivotViewerPropertyOptions.CanSearchText
                },
            new PivotViewerStringProperty()
                {
                    Binding = new Binding("Color"),
                    Id = "Color",
                    Options = PivotViewerPropertyOptions.CanFilter
                    | PivotViewerPropertyOptions.CanSearchText
                },
            new PivotViewerDateTimeProperty()
                {
                    Binding = new Binding("Stamp"),
                    Id = "Stamp",
                    Options = PivotViewerPropertyOptions.CanFilter
                }

        };

There are only a few options for a PivotProperty, so I thought it would be worth listing them. Here is a break down of each property and how it effects how the PivotProperty is used inside of PivotViewer

PivotProperty Options

None

No options are set

Private

If set, it will not display property in detail pane

CanFilter

Shows the property in the filter pane and the sort drop down box

CanSearchText

The search box will search for this property for matches

Wrapping Text

Will wrap the text within the detail pane


Trading Cards

Now we have our data and have mapped the data to the a collection of PivotProperties, what’s next? The last set it to define what the trading card is going to look like. For this post we are going to look at a basic solution which we will expand upon in the next post.


XAML data templates in PivotViewer take the shape of a PivotViewerItemTemplate. PivotViewer has a ItemTemplates property that is used to map one or more templates for your trading cards. For our case we are going to create a simple trading card that consists of a Border that is filled with the card’s Color property and put a ShortName property in the middle of the Border. The template will look something like this:

<pivot:PivotViewerItemTemplate x:Key="DemoTemplate">
    <Border Width="300" Height="300"
            Background="{Binding Color,
                    Converter={StaticResource colorConverter}}">
        <TextBlock Text="{Binding ShortName}" FontSize="20"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center" />
    </Border>
</pivot:PivotViewerItemTemplate>

You might notice that I added a value converter to the background. Since we are storing the color as a string, we need to map it to a SolidColorBrush. SL doesn’t expose all of the Color methods you find in .NET, so we have to be a bit clever in getting the color mapped. Here is the value converter that I am using:

public class TextToSolidColorConverter : IValueConverter

{


    public object Convert(object value,
                        Type targetType,
                        object parameter,
                        CultureInfo culture)
    {
        var xaml = "<SolidColorBrush " +
            "xmlns='http://schemas.microsoft.com/client/2007' " +
            "Color=\"" + value.ToString() + "\"/>";
        return XamlReader.Load(xaml);
    }

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

With our template added as a resource, we can set the template in code with the following:


pViewer.ItemTemplates = new PivotViewerItemTemplateCollection()
    {
        (PivotViewerItemTemplate) Resources["DemoTemplate"]
    };

And that is really all there is to it. If we run our solution, we should get something like this:



Press Release – HostForLIFE.eu Proudly Announces SQL 2012 Hosting for European Market

clock April 23, 2012 07:41 by author Scott

HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. We proudly announces the availability of the SQL 2012 hosting in our entire servers environment. HostForLife customer can choose SQL 2012 when creating a database from inside HostForLife hosting control panel.

The first new option is Windows SQL Server 2012, which is available to customers from today. With the public release just last week of Microsoft’s latest version of their premier database product, HostForLife has been quick to respond with updated their shared server configurations. SQL Server 2012 Web Edition is available for the same low monthly rental price as the previous SQL 2008, as well as Express Edition, which is a basic version of Microsoft’s SQL Database product, available for free.


“We’re proud to be at the cutting edge for new technologies. With these additions, customers have the option to explore these new products in the safe environment of their own shared server. Developers and IT Managers can research the potential impact of next-generation software without risking current infrastructure. With Microsoft’s announcement of the general availability of their new SQL server, we are proud to launch SQL 2012 hosting along with a suite of SQL 2012 management tools." Said John Curtis, VP Marketing and Business Development at HostForLIFE.eu.


John added, “It’s very important to our customers that we support their current deployments; we want to make sure that our customers have their good opportunity to test this new technology."


“HostForLIFE customers can now take advantage of SQL Server 2012’s advanced BI capabilities, We’re excited to see the benefits of this release add value to the energy management and manufacturing arena. Ensuring compatibility with Microsoft’s new SQL Server 2012 demonstrates how HostForLife and Microsoft remain committed together to providing leading edge technology for the benefit of our shared customers." Said CEO of HostForLIFE.eu, Anthony Johnson.


For more information about this new product, please visit
http://www.hostforlife.eu/SQL-2012-European-Hosting.aspx.

About us:


We are European Windows Hosting Provider which FOCUS in Windows Platform ONLY. We support Microsoft technology, such as the latest ASP.NET 4, ASP.NET MVC 3, SQL 2008/2008 R2, and much more.


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 it's 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 :: Silverlight 5 Pivot Viewer Control

clock April 16, 2012 09:24 by author Scott

In this article we will learn about creating a Pivot Viewer control in Silverlight .

Lets get started with a short description of what a PivotViewer Control is.


For this example I have used the Silverlight 5 PivotViewer, since most of us would have Silverlight 5 right now .


The Silverlight PivotViewer Control does not come by default with the Silverlight 4 toolkit. It has to be downloaded and installed separately .


With Silverlight 5 one would get the PivotViewer by default .


For Silverlight 4 it must be downloaded from the link shown below :


http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=17747


Once installed , the PivotViewer gets installed in the path as shown below :


C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\PivotViewer\Aug10


Hence forth I am using Silverlight 5 but similar steps needs to be followed for Silverlight 4.


Add a reference to the below DLL as shown below :




Let's start coding then . PivotViewer uses a special type of Collection called as Collection XML .


We need to understand Collection XML in order to effectively work with PivotViewer .


Collection XML (CXML) is the schema used to describe structured data to be displayed in the PivotViewer collection experience.


We make use of a class called CxmlCollectionSource to bind to the ItemSource of the PivotViewer


More Information on the CxmlCollectionSource can be found in the link below :


http://msdn.microsoft.com/en-us/library/system.windows.controls.pivot.cxmlcollectionsource(v=vs.96).aspx


Shown below is how the data is bound to the ItemSource property of the PivotViewer Control .




The final code is below :


            _cxml = new CxmlCollectionSource(new Uri("http://www.xpert360.net/PDC2010/PDC2010.cxml", UriKind.Absolute));

            pv1.PivotProperties = _cxml.ItemProperties.ToList();
            pv1.ItemTemplates = _cxml.ItemTemplates;
            pv1.ItemsSource = _cxml.Items;

Let's give it a run.




Cheers





European WCF 4.5 Hosting - Amsterdam :: One Line of Code to Configure WCF 4.5

clock April 10, 2012 11:47 by author Scott

The WCF 4.5 beta simplifies configuring WCF, provides better support for code-based configuration, and makes it easier to do code-based configuration in Web sites. Don’t get me wrong: I like the WCF configuration files but, I gather, I may be in a minority. Many developers prefer to configure their WCF services from code where possible. Unfortunately, one of the places where that isn’t possible is the most common place to host WCF services: in a Web application (well, I’m told it was possible but only in the sense that it’s possible to remove your own appendix).

WCF 4.5 (at least, in the beta) provides a simple solution: Add a static/shared method called Configure to your service class and fill it with the code required to configure your service. WCF will call that Configure method at the appropriate moment and pass the method an instance of the ServiceHost class. In your Configure method, you can work with that ServiceHost to configure your service.


What’s especially impressive is how simple it is. The default settings alone mean that if you add an svc file to your Web site then you have a Web Service. You can make that explicit, however, with a single line of code. This example makes the service containing this method available as a Web Service with no WCF-related tags required in the config file at all:


Public Shared Sub Configure(sc AsServiceConfiguration)

 sc.EnableProtocol(NewBasicHttpBinding())
End Sub

You can configure these services by instantiating behavior classes, configuring them, and adding them to the ServiceConfiguration’s Description property’s Behaviors collection. That’s a good thing because, while my previous example was all the code you need (in fact one more line than you needed), it’s probably not all the code you want, for two reasons.


Configuring the Service

First, with just that code you won’t be able to retrieve the WSDL contract for this service (what WCF refers to as service’s “metadata”) so you won’t be able to use Visual Studio’s WCF test client (you also won’t be able to use the Discover button in Visual Studio’s Add Service Reference dialog). For testing purposes, and until you can save to a separate file the WSDL contract that you can give to the developers building the clients/consumers for this service, you’ll want to configure your service to return a WSDL contract. To tell your service to make its metadata available you add code like the following to your Configure method. This code creates a ServiceMetadataBehavior object, sets its HttpGetEnabled property to True (that actually turns on the feature), and add the configured behavior to the Behaviors collection:

Dim behavior As New Description.ServiceMetadataBehavior
behavior.HttpGetEnabled = True
sc.Description.Behaviors.Add(behavior)


Second, by default, WCF services don’t return a lot of information in their exception messages. That’s a good thing: While that information is very useful in debugging, it probably isn’t something you want to share with the general public. However, in testing, you probably do want that those chattier error messages and you can enable the with this code in the Configure method:

Dim debugBehavior As New Description.ServiceDebugBehavior
debugBehavior.IncludeExceptionDetailInFaults = True
sc.Description.Behaviors.Add(debugBehavior)

But both of these changes highlight an issue with code-based configuration. In production, you probably don’t want your service freely giving up its contract to whoever asks for it. Instead you probably want to control access to your service’s contracts so that you have some idea who’s using your service and can contact those users when you’re making changes to your service. And you certainly don’t want to send out those verbose error messages from your production system. So, before moving your service to production you’re going to want to change the values used in this code.

The problem is that, with the code I’ve used here, there’s no simple way to inspect the assembly you’re deploying to production to determine if the settings are correct: the code is compiled and is unreadable. One of the nice features of the config files is that you could inspect them (and even change them) with Notepad. The right answer is probably to move settings that will change from one installation to another (e.g. test and production) into your AppSettings where you’ll still have visibility to them.

Please visit our site at
http://www.hostforlife.eu if you need Silverlight 5 WCF RIA hosting. Starts from only €2.45/month.

 



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