European Silverlight 4 & Silverlight 5 Hosting BLOG

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

Silverlight Hosting - HostForLIFE.eu :: Linking your Silverlight apps to data and web services (WebClient)

clock July 29, 2026 14:55 by author Peter

As any ASP.NET application silverlight can connect to any of the web or data services like

  • WebClient (simple HTTP request )
  • WebRequest/WebResponse classes (to more complex HTTP requests )
  • WCF Web Services (through proxy classes )
  • ADO.NET Data Services

In this section we'll find how to create a WebClient in silverlight.

Using WebClient in Silverlight
In this article explain the step by step creation of a Web client application in Silverlight 2.0.

Create simple POX (Plain Old XML) Service

Step 1: Silverlight Application

  • Create a new silverlight application WebClientAccessApp
  • Add a new Class, called Employee.cs to the Web site part of your solution.
  • Add member variables for EmployeeName, EmpID and Salary.

Step 2: XML Service
In this task you'll add a generic handler and have it return XML data back to the caller.

Add a new Generic handler to your Web application and call it EmployeeDataHandler.ashx
Create an instance of employee list 'empList' to which Employee object get added
The Generic handler will process an incoming request using the code declared in the ProcessRequest function.
In this function, some new instances of Employee are added into the empList.
Next, you'll write code that serializes the List<T> into XML and writes it back as a response to the caller. Here's the code:

XmlSerializer ser = new XmlSerializer(typeof(List<Employee>));
using (XmlWriter writer = XmlWriter.Create(context.Response.OutputStream))
   {
       context.Response.ContentType = "text/xml";
       ser.Serialize(writer, empList);
               }


You may notice that the ArrayOfEmployee node has been generated for you by the XmlWriter. It has also been given a default namespace and XSD.

Step3: XAML to bind
The XAML (Page.xaml)

  • add a ListBox
  • ItemsControl allows you to define how to render bound data according to a DataTemplate
  • Add a single TextBlock that binds to the each property. 

<ItemsControl x:Name="_employees">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <TextBlock FontSize="14" Height="30" Text="{Binding EmployeeName}" />
       <TextBlock FontSize="14" Height="30" Text="{Binding EmpID}" />
        <TextBlock FontSize="14" Height="30" Text="{Binding Salary}" />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>


Step 4: WebClient
To set a static port for your Web project to run on,

  • select the Web project in Solution Explorer, and press F4 to call up the properties window.
  • 'Use Dynamic Ports' entry and set it to 'False'. Save everything
  • then find the 'Port Number' setting and make it '8001'.

Step 5: In the client
In Page.xaml.cs

Call a POX Service
Add new code in Page() (constructor) that creates a new instance of the WebClient class, and then instructs it to download a string from the above URI, as well as wiring up a completed event handler callback.
      public Page()

{

  InitializeComponent();

  WebClient wc = new WebClient();

  wc.DownloadStringAsync(new  Uri("http://localhost:8001/WebClientAccessApp/EmployeeDataHandler.ashx

"));

  wc.DownloadStringCompleted += new

      DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);

 }


Binding the Data on the Callback
When you specified the DownloadStringCompleted callback Visual Studio should have created a boiler plate event handler for you.
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
}


The string data will be stored in DownloadStringCompletedEventArgs Result property, so you can load it into an XDocument using
XDocument xReturn = XDocument.Parse(e.Result);

One of the new language features in .NET, and in Silverlight is LINQ, which brings some functional programming to Silverlight.

So here's how you can use it to create an IEnumerable of Employee from the returned XML. As ItemsControl requires an IEnumerable to bind data

IEnumerable<Employee> employees = from employee in xReturn.Descendants("Employee")
  select new Employee
  {
    EmployeeName = employee.Element("EmployeeName").Value,
    EmpID = Convert.ToDouble(employee.Element("EmpID").Value),
    Salary = Convert.ToDouble(employee.Element("Salary").Value)
  };

To bind to ItemsControl set the ItemSource
_employees.ItemsSource = employees;

Here you are. After a long runyou have a result

You have seen some of these,

  • WebClient which is used for simple asynchronous HTTP requests.
  • XDocument, XmlWriter and XmlSerializer for managing XML Data
  • The XML ItemsControl for data binding

For more complex HttpRequest, we'll find how in my following articles
Happy Coding. 



Silverlight Hosting - HostForLIFE.eu :: Silverlight's Graphics Path

clock July 23, 2026 11:58 by author Peter

Using Silverlight's Path
A collection of linked lines, curves, and other basic graphics elements is called a graphics route. This article shows how to utilize XAML and C# to provide Path control in Silverlight.

Introduction
A graphics path is a set of connected lines, curves, and other simple graphics objects, including rectangles, ellipses, and text. A path works as a single graphics object, so an effect applied to the graphics path will be applied to all the components of the path. For example, if a graphics path contains a line, a rectangle, and an ellipse and we draw the path using a red stroke, all three components (line, rectangle, and ellipse) of the graphics path will be drawn with the red stroke.
 
The Path object represents a path shape and draws a path. The Path object draws both closed and open paths. A closed path is a shape that has the same start and endpoints and an open path is a shape that has different start and endpoints.
 
The Fill property fills the interior of an ellipse. The Stroke property sets the color and StrokeThickness represents the width of the outer line of an ellipse.
 
The Data property of the Path object defines a shape or a collection of shapes in form of Geometry.
 
The Path element represents a Silverlight Path control in XAML
    <Path/>  

The code snippet in Listing 1 creates a Path and draws an arc by settings its Data property.
    <Path Stroke="Black" StrokeThickness="4"   
            Data="M 80,200 A 100,50 45 1 0 100,50" />  


The output looks like

The Path Syntaxes
Let us take a look at the Data attribute of the Path code used in the previous section.
    <Path Stroke="Black" StrokeThickness="4"   
            Data="M 80,200 A 100,50 45 1 0 100,50" />  

As you may see from the above code snippet, the Data attribute has the letter M followed by two comma-separated numbers, letter A is followed by two comma-separated numbers, and letter O is also followed by two comma-separated numbers.

  • The letter M represents a move action and moves to the given point from the current point. For example, M 80,200 command moves from the current point to the point (80, 200).
  • The letter L draws a line from the current point to the specified point. For example, the L 100,200 command draws a line from the current point to the point (100, 200).
  • The letter H draws a horizontal line from the current point to the specified point towards the x-axis.
  • The letter V draws a vertical line from the current point to the specified point towards the y-axis.
  • The letter C draws a cubic Bezier curve from the current point to the third point and two points in between are used as the control points.
  • The letter S draws a smooth cubic Bezier curve from the current point to the second point and the first point is used as the control point.
  • The letter Q draws a quadratic Bezier curve from the first point to the second point and the first point is used as the control point.
  • The letter T draws a smooth quadratic Bezier curve from the first point to the second point and the first point is used as the control point.
  • The letter A draws an elliptical arc. It takes five parameters -  Size, IsLargeArc, Rotation Angle, Sweep Direction, and Endpoint.
  •  The letter Z closes the current path by drawing a line from the current point to the starting point.

Using Geometries within a Path
The LineGeometry class represents the geometry of a line. The StartPoint and EndPoint properties of the LineGeometry class define the start and endpoints of a line. The following code snippet creates the geometry of a line.
    <LineGeometry StartPoint="20,50" EndPoint="200,50" />  

The RectangleGeometry class represents the geometry of a rectangle. The Rect property of the RectangleGeometry defines the starting points, width, and height of a rectangle. The following code snippet creates the geometry of a rectangle.
    <RectangleGeometry Rect="80,167 150 30"/>  

The EllipseGeometry class represents the geometry of an ellipse. The Center property of the EllipseGeometry defines the center of an ellipse. The RadiusX and RadiusY define the width and height of an ellipse. The following code snippet creates the geometry of an ellipse.
    <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  

The GeometryGroup creates a composite geometry that is a combination of multiple Geometry objects.
 
The code listed in Listing 2 creates a GeometryGroup with three geometry shapes - a line, an ellipse, and a rectangle and sets the Data property of a path.
    <Path Stroke="Black" StrokeThickness="3" Fill="Blue" >  
        <Path.Data>  
            <GeometryGroup >  
                <LineGeometry StartPoint="20,200" EndPoint="300,200" />  
                <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
                <RectangleGeometry Rect="80,167 150 30"/>  
            </GeometryGroup>  
        </Path.Data>  
    </Path>  

 
The output of Listing 2 looks like

The FillRule property of the GeometryGroup class specifies how the intersecting areas of geometry objects in a GeometryGroup are combined. It has two values – EvenOdd and NonZero.  The default value of the FillRule is EvenOdd. In this case, the intersecting area of two shapes is not filled. In the case of NonZero, the interesting area of two shapes is filled. By setting the FillRule to NonZero generates Figure 3.

Create a Path Dynamically
The code listed in Listing 3 creates Figure 2 dynamically. As you can see from Listing 3, we create a LineGeometry, an EllipseGeometry, and a RectangleGeometry and then we create a GroupGeometry and add all three geometries to the GroupGeometry. After that, we simply set the Data property of Path to the GroupGeometry.
    /// <summary>  
    /// Creates a blue path with black stroke  
    /// </summary>  
    public void CreateAPath() {  
        // Create a blue and a black Brush  
        SolidColorBrush blueBrush = new SolidColorBrush();  
        blueBrush.Color = Colors.Blue;  
        SolidColorBrush blackBrush = new SolidColorBrush();  
        blackBrush.Color = Colors.Black;  
      
        // Create a Path with black brush and blue fill  
        Path bluePath = new Path();  
        bluePath.Stroke = blackBrush;  
        bluePath.StrokeThickness = 3;  
        bluePath.Fill = blueBrush;  
      
        // Create a line geometry  
        LineGeometry blackLineGeometry = new LineGeometry();  
        blackLineGeometry.StartPoint = new Point(20, 200);  
        blackLineGeometry.EndPoint = new Point(300, 200);  
      
        // Create an ellipse geometry  
        EllipseGeometry blackEllipseGeometry = new EllipseGeometry();  
        blackEllipseGeometry.Center = new Point(80, 150);  
        blackEllipseGeometry.RadiusX = 50;  
        blackEllipseGeometry.RadiusY = 50;  
      
        // Create a rectangle geometry  
        RectangleGeometry blackRectGeometry = new RectangleGeometry();  
        Rect rct = new Rect();  
        rct.X = 80;  
        rct.Y = 167;  
        rct.Width = 150;  
        rct.Height = 30;  
        blackRectGeometry.Rect = rct;  
      
        // Add all the geometries to a GeometryGroup.  
        GeometryGroup blueGeometryGroup = new GeometryGroup();  
        blueGeometryGroup.Children.Add(blackLineGeometry);  
        blueGeometryGroup.Children.Add(blackEllipseGeometry);  
        blueGeometryGroup.Children.Add(blackRectGeometry);  
      
        // Set Path.Data  
        bluePath.Data = blueGeometryGroup;  
      
        LayoutRoot.Children.Add(bluePath);  
    }  

If we need to generate a single geometry, we do not need to use a GeometryGroup. We can simply set geometry as the Data of the Path. The following code snippet sets an EllipseGeometry as the Data property of a Path.
    <Path Stroke="Black" StrokeThickness="3" Fill="Blue" >  
        <Path.Data>              
                <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
       </Path.Data>  
    </Path>  


Formatting a Path
We can use the Fill property of the Path to draw a Path with any kind of brush including a solid brush, linear gradient brush, radial-gradient brush, or an image brush. The code in Listing 4 uses linear gradient brushes to draw the background and foreground of a Path.
    <Path Stroke="Black" StrokeThickness="3">  
        <Path.Data>  
            <GeometryGroup>  
                <LineGeometry StartPoint="20,200" EndPoint="300,200" />  
                <EllipseGeometry Center="80,150" RadiusX="50" RadiusY="50" />  
                <RectangleGeometry Rect="80,167 150 30" />  
            </GeometryGroup>  
        </Path.Data>  
        <Path.Fill>  
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">  
                <GradientStop Color="Blue" Offset="0.25" />  
                <GradientStop Color="Orange" Offset="0.50" />  
                <GradientStop Color="Green" Offset="0.65" />  
                <GradientStop Color="Red" Offset="0.80" />  
            </LinearGradientBrush>  
        </Path.Fill>  
    </Path>  

 
The new Path looks like Figure 4.

Setting Image as Background of a Path
 
To set an image as the background of a Path, we can set an image brush as the Fill of the Path. The code in Listing 5 sets fills the Path with an image.   
    <Path.Fill >  
        <ImageBrush ImageSource="dock.jpg" />  
    </Path.Fill >  

The new output looks like Figure 5.

Drawing a Semi-transparent Path
The Opacity property represents the transparency of a Path. The value of Opacity is between 0 and 1, where 0 is fully transparent and 1 is fully opaque. The code listed in Listing 6 generates a semi-transparent shape.
    <Path Stroke="Black" StrokeThickness="3" Opacity="0.5" />  
 
The new output looks like Figure 5.

Summary
In this article, I discussed how we can create a Path control in Silverlight at design-time using XAML and at run-time using C#.  We also saw how we can format a Path by setting its fill property. After that, we saw you set an image as the background of a Path. In the end, we saw how to draw a semi-transparent Path.

HostForLIFE.eu Silverlight 5 Hosting
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 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.



Silverlight Hosting - HostForLIFE.eu :: How to Handle Double-Click in Silverlight 5?

clock September 12, 2025 08:25 by author Peter

We will talk about how to handle a double-click in Silverlight 5 in this article. Silverlight 5 has a new functionality that handles double-click. In Silverlight 5, the idea of a click count was added. You can utilize the ClickCount property of the MouseButtonEventArgs class to simply count the number of clicks without of creating special double, triple, or many click events. Both the left and right mouse buttons are affected by this.

Setup the Solution:
Create a Silverlight Application project with the name "HandlingDoubleClickInSL" as shown below.

As we are going to demonstrate in Silverlight 5 just ensure that we have selected Silverlight 5 in the project's options when creating the project.

Setting up the XAML:
Open the MainPage.xaml to design our screen. Here are the steps to create our UI.
Divide the LayoutRoot grid into two columns as in the following figure.

Add two StackPanels to the Grid; one for Grid column 0 and another one for Grid column 1.
In the first StackPanel Add 5 Borders with Height as 100.
In the second StackPanel add a TextBlock with the following properties.

Adding Mouse Click Event to Border:
Now just add the "MouseLeftButtonDown" in the Border's property with Event name like as shown in the figure.

Complete Xaml:
The given howfollowing figure shows the complete code for our UI.

ClickCount Event:
We have defined the Event as in the figure shown.

Here the bdr.Tag.ToString () is used to get the border that we clicked. The e.ClickCount is the Property of MouseButtonEventArgs class which is of type integer.

The e.ClickCount == 2 handles the double click condition.

The ClickCount Property maintains the Clicks count for us.

How ClickCount Calculated:
The count is calculated based on the time between first click and the second click.

Consider if you are trying to click 5 times. After 3rd click, if you give 200 milliseconds gab between the 3rd and 4th click then the 4th click will be treated as the 1st click. It will reset the ClickCount property if the time between the first click and second click is greater the 200 milliseconds.

Application in Action:
The logic in this demo is when you are clicking on various colour boxes with various clicks it will display the colour box name with the clicks you have clicked.

Let see the Demo.

In this figure above the single click is captured.

The above figure shows the double-click on the Red color box. You can see the Multiple clicks displayed in the following figure.



Summary
In this article, we have seen how to handle single, double and multiple clicks in Silverlight 5. We can handle multiple clicks but not multiple times. Thanks for spending your precious time here. Please provide your valuable feedbacks and comments, which enables me to give a better article the next time. 

HostForLIFE.eu Silverlight 5 Hosting
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 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 Sorting and Grouping Feature

clock June 28, 2013 07:56 by author Scott

Using Silverlight and XAML, you can bind to a collection of data. Once that is done, you can then sort, filter, or group the data using a collection view. A collection view is similar to a layer on a binding source collection. It enables you to navigate and display the source collection based on queries to sort, filter, and group data, without having to change the underlying source collection itself. If a source collection implements the INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are transmitted to the views. A single source collection can have multiple views associated with it.

 

I will show brief tutorial about sorting and grouping functionally through the PagedCollectionView class. Consider an example that demonstrates how to sort and group bound data in a collection using an
PagedCollectionView object.

Create a Silverlight application named CollectionsDemo.

Add the following markup to MainPage.xaml.

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    x:Class="CollectionsDemo.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"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=System.Windows"
xmlns:dat="clr-namespace:System.Windows.Data;assembly=System.Windows"
xmlns:local="clr-namespace:CollectionsDemo"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400"

<Grid x:Name="LayoutRoot">
    <sdk:DataGrid Name="dgridMovies" ItemsSource="{Binding}" >
            <sdk:DataGrid.RowGroupHeaderStyles>
                <Style TargetType="sdk:DataGridRowGroupHeader">
                    <Setter Property="PropertyNameVisibility" Value="Collapsed" />
                    <Setter Property="Background" Value="PaleGreen"/>
                    <Setter Property="SublevelIndent" Value="25" />
                </Style>
            </sdk:DataGrid.RowGroupHeaderStyles>
        </sdk:DataGrid>
</Grid>
</UserControl>

The above markup creates a DataGrid and sets its ItemsSource property. The markup also sets style for the DataGrid rows.

Add the following code to MainPage.xaml.cs to create the Movies and Movie classes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.ComponentModel;

namespace CollectionsDemo
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            Movies movies = new Movies();
            InitializeComponent();

            // For sorting
            PagedCollectionView pg = new PagedCollectionView(movies);
            pg.SortDescriptions.Add(new SortDescription("Title", ListSortDirection.Ascending));
            dgridMovies.DataContext = pg;

            // For grouping
            pg.GroupDescriptions.Add(new PropertyGroupDescription("Year"));
            dgridMovies.DataContext = pg;
        }
    }

    // Represents a collection of movies
    public class Movies : ObservableCollection<Movie>
    {
        public Movies()
            : base()
        {
         Add(new Movie() { Title = "Sherlock Holmes - Game of Shadows", Year = "2011" });
         Add(new Movie() { Title = "ParaNormal Activity", Year = "2010" });
         Add(new Movie() { Title = "Michael Clayton", Year = "2010" });
         Add(new Movie() { Title = "A Separation", Year = "2011" });
         Add(new Movie() { Title = "Lost", Year = "2009" });
        }
    }

// Represents a Movie entity having two properties, Title and Year
    public class Movie
    {
        public string Title { get; set; }
        public string Year { get; set; }
    }
}

You will first create a PropertyGroupDescription object and pass the name of the property based on which sorting or grouping will take place. Then, add the PropertyGroupDescription to the SortDescriptions or GroupDescriptions collection of PagedCollectionView depending on which operation is to be performed.

These actions are done using the above code.

On executing, the output will be similar to Figure below. As you can see, the movie details are grouped by year and sorted according to title.


 



European WCF Hosting - Amsterdam :: How to Create WCF Service with SOAP/REST Endpoints

clock June 10, 2013 08:35 by author Scott

In this post I am going to describe a solution to the following problem.  I would like to create a single WCF Service and expose it via a standard SOAP endpoint and REST endpoint using Entity Framework, WCF and WCF REST.  Then I would like to consume it from WinRT from two different view models working against the same view.  This is an exercise of research into data options in WinRT.

First of, let’s create a service.  I am going to use the following data class:

    public class Session
    {
        public int SessionID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Speaker { get; set; }
        public DateTime When { get; set; }
    }

My data context for EF Code First is just as simple:

    public class Context : DbContext
    {
        public Context() :
            base("Name=VSLive")
        {
        }
        public DbSet<Session> Sessions { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Session>().Property(p => p.Title).HasMaxLength(100).IsRequired();
            modelBuilder.Entity<Session>().Property(p => p.Speaker).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<Session>().Property(p => p.Description).IsRequired();
            modelBuilder.Entity<Session>().Property(p => p.When).IsRequired();
        }
    }

Now, the service.  I am just going to perform basis CRUD opertions.  The key to the service is my interface that I am going to decorate with both SOAP(OperationContract) and REST(WebGet or WebInvoke) attributes.

    [ServiceContract]

    public interface IVSLiveService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/GetList", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Session[] GetList();

        [OperationContract]
        [WebInvoke(UriTemplate = "/Create", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Session Create(Session session);


        [OperationContract]
        [WebInvoke(UriTemplate = "/Update", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Session Update(Session session);

        [OperationContract]
        [WebInvoke(UriTemplate = "/Delete?sessionId={sessionId}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        void Delete(int sessionId);

    }

The implementation is not quite as interesting, but for the same of completeness of this post, here it goes:

using System.Data.Entity;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using WinRT.Data;
using WinRT.DataAccess;

namespace WcfService
{
    [AspNetCompatibilityRequirements(
      RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class VSLiveService : IVSLiveService
    {
        public VSLiveService()
        {
            Database.SetInitializer(new Initializer());
        }

        public Session[] GetList()
        {
            using (var context = new Context())
            {
                context.Configuration.LazyLoadingEnabled = false;
                context.Configuration.ProxyCreationEnabled = false;
                return context.Sessions.ToArray();
            }
        }

        public Session Create(Session session)
        {
            using (var context = new Context())
            {
                context.Sessions.Add(session);
                context.SaveChanges();
            }
            return session;
        }


        public Session Update(Session session)
        {
            using (var context = new Context())
            {
                context.Entry(session).State = System.Data.EntityState.Modified;
                context.SaveChanges();
            }
            return session;
        }

        public void Delete(int sessionID)
        {
            using (var context = new Context())
            {
                var session = new Session { SessionID = sessionID };
                context.Entry(session).State = System.Data.EntityState.Deleted;
                context.SaveChanges();
            }
        }
    }
}

Now, the part that took me the longest to figure out: web.config.

I have single service node, and I have two endpoints for it, using the same contract, but two different bindings and behaviors.  I am putting entire web.config:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add
          name="VSLive"
          connectionString="Server=.;Database=VSLive;Trusted_Connection=True;"
          providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>    
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!—To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding
          name="VSLiveService_BasicHttpBinding"
          maxBufferSize="1000000"
          maxReceivedMessageSize="1000000">
          <readerQuotas
            maxBytesPerRead="1000000"
            maxArrayLength="1000000"
            maxDepth="1024"
            maxStringContentLength="1000000"/>
        </binding>
      </basicHttpBinding>
      <webHttpBinding>
        <binding
           name="VSLiveService_WebHttpBinding"
           maxBufferSize="1000000"
           maxReceivedMessageSize="1000000">
          <readerQuotas
            maxBytesPerRead="1000000"
            maxArrayLength="1000000"
            maxDepth="1024"
            maxStringContentLength="1000000"/>
        </binding>
      </webHttpBinding>

    </bindings>
    <services>
      <service name="WcfService.VSLiveService">
        <endpoint
          address="soap"
          binding="basicHttpBinding"
          bindingConfiguration="VSLiveService_BasicHttpBinding"
          contract="WcfService.IVSLiveService"/>
        <endpoint
            address="rest"
            binding="webHttpBinding"
            behaviorConfiguration="jsonBehavior"
            bindingConfiguration="VSLiveService_WebHttpBinding"
            contract="WcfService.IVSLiveService"/>
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true">
        <listeners>
          <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\Traces.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
</configuration>

As you can see above, SOAP endpoint comes first, and it is using basicHttpBinding.  My REST endpoint is second, and it is using webHttpBinding  I am asing a behavior configuration to the latter one, enabling webHttp get/post methods.

This is all nice and simple, and you can now test it in browser.

Today, I am documenting REST consumption.

I am using HttpClient class to accomplish this task.  For example, here is how I am going to get the list of sessions.

        public async Task LoadData()
        {
            IsBusy = true;
            _client = new HttpClient();
            _client.MaxResponseContentBufferSize = int.MaxValue;
            var response = await _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri(_serviceUri + "GetList")));

            var data = response.Content.ReadAsString();

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Session>));
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
            {
                var list = serializer.ReadObject(stream) as List<Session>;
                Sessions = new ExtendedObservableCollection<Session>(list);
            }
            IsBusy = false;
        }

A few points about the code above.  I should have wrapped the call inside Try/Catch, I am just skipping it for the sake of a demo and to minimize the code I am showing.  I am using standard serializer to convert my JSON message into an object.  I also have a little progress ring that is playing while server communication is going on, and that is what my IsBusy property above is bound to. 

Now, let’s take a look at Create/Update call.  It is just as simple, but I am using Post method of HttpClient and I am creating a string content to post by converting Session object to JSON, again using the same serializer.

        public async void OnSave(object parameter)
        {
            if (SelectedSession != null)
            {
                IsBusy = true;
                string method = "Update";
                if (selectedSession.SessionID == 0)
                {
                    method = "Create";
                }
                _client = new HttpClient();
                _client.MaxResponseContentBufferSize = int.MaxValue;
                var content = new StringContent(ConvertSessionToJson());
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var response = await _client.PostAsync(new Uri(_serviceUri + method), content);

                var data = response.Content.ReadAsString();

                var session = ConvertJsonToSession(data);
                Sessions[Sessions.IndexOf(selectedSession)] = session;
                SelectedSession = session;
                IsBusy = false;
            }
        }

For delete method I am also using Post method, just my content is blank and my ID is passed to the server as query string parameter

        public async void OnDelete(Session parameter)
        {
            if (parameter != null)
            {
                if (parameter.SessionID > 0)
                {
                    IsBusy = true;
                    _client = new HttpClient();
                    _client.MaxResponseContentBufferSize = int.MaxValue;
                    var content = new StringContent(string.Empty);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var response = await _client.PostAsync(new Uri(_serviceUri + "Delete?sessionId=" + parameter.SessionID.ToString()), content);

                    var data = response.Content.ReadAsString();
                    Sessions.Remove(parameter);
                    IsBusy = false;
                }
                else
                {
                    Sessions.Remove(parameter);
                    IsBusy = false;
                }
            }
        }

 



European WCF Hosting - Amsterdam :: How to Host WCF Service in IIS 8 (Windows Server 2012)

clock April 25, 2013 06:56 by author Scott

This blog cover brief information how to host your WCF service in IIS8 (Windows Server 2012).

Here is the solution.

Server Roles

1. First make sure you have enabled IIS function and .net 3.5 in Features.
For the IIS features, please remember to enable ASP.NET3.5 and ASP.NET 4.5

2. Second, check the IIS Hostable WebCore
3. Finally, I think the most important is this:

Check Application Sever->Web Server (IIS) Support

I have also check the HTTP Activation in Windows Process Activation Service Support, but I do not know if it is required.

For the freatures,

1. Check all items in .NET 3.5
2. Check WCF Service in .NET 4.5

That’s it.

Last but not least, I have register the WCF Service from

C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i

Run the above in command line.

 



European Silverlight Hosting - Amsterdam :: Dynamic Compression in IIS 7

clock February 5, 2013 10:17 by author Scott

This is the question from one of our clients. The client insisted on returning large datasets, well in excess of 10,000 records. I will leave the story of figuring out how to properly specify the MaxItemsInObjectGraph service behavior attribute for some other post, but the other problem I was constantly aware of, was the data size returned from the server. With all filters set to max, the data set was well in excess of 30 megabytes. This might not be a big problem on a local network, but if some of your users are located across the big pond called Atlantic, you might want to compress your data before shipping it over.

Now, the IIS 7 console only allows you to enable or disable static compression, but it does not let you control which dynamic types are being compressed as well as the level of compression desired for each content type.

The command you are supposed to use instead is AppCmd.exe located in C:\Windows\System32\inetsrv directory.

So here are three sample commands that helped me reduce the size of my WCF RIA Domain Service's binary response by 80%. Needless to say I was pleasantly shocked.

Enable compression on WebDevel webserver (when you have multiple servers and want to do it specifically for each)


C:\Windows\System32\inetsrv>Appcmd.exe set config "WebDevel" -section:urlCompression -doStaticCompression:true -doDynamicCompression:true


Add mime-type application/msbin1 to dynamic compression list (service wide)


C:\Windows\System32\inetsrv>Appcmd.exe set config -section:system.webServer/httpCompression /+"dynamicTypes.[mimeType='application/msbin1',enabled='True']" /commit:apphost


Set compression levels for static and dynamic content (service wide)


C:\Windows\System32\inetsrv>Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:5



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