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 :: How to Convert Silverlight 4 to Silverlight 5

clock August 9, 2013 08:09 by author Scott

When we open Silverlight 4 application in Silverlight 5 we get following errors

1) error  : Unable to read the project file 'Silverlight4App.csproj'.

2) Silverlight4App.csproj(137,3): The imported project "C:\Program Files\MSBuild\Microsoft\Silverlight\v4.0\Microsoft.Silverlight.CSharp.targets" was not found. Confirm that the path in the declaration is correct, and that the file exists on disk.


This error occurs as the application was earlier built using Silverlight-4 Reference. So while opening this in Silverlight-5, the Visual studio looks for the Silverlight 5 reference files but it cannot find it.

To resolve this error you will have to follow following steps:

1) Open the project in Visual studio.

2) Go to solution explorer

3) Right click on the project that is not loaded and click on edit the CSPROJ file

4) And then change the Target Frame Work version to 5.0

5) Save and close this file and again right click on the project which is not loaded and click on Reload project.

6) Now the project will be reloaded successfully.

By following above steps your Silverlight 4 application will be converted to Silverlight 5 application.

If in case you again want to go back to Silverlight 4 then just repeat the above steps and set the Target Framework version to “v4.0”.

Hope this helps!!



European Silverlight 5 Hosting - Amsterdam :: ICustomTypeProvider in Silverlight 5

clock July 19, 2013 06:51 by author Scott

Why would I want to trick Silverlight into treating Dictionary values like real Properties?

There are scenarios when complex, data-intensive applications will need to data bind to keys/value pairs or generally determine the properties of a Class at runtime.  In cases where there could be large numbers of keys or the keys could change without an application re-deploy, this is a tricky problem to solve. 

In Silverlight 5, however, you can use ICustomTypeProvider to achieve the same goal in a clean fashion.

Data Facets

Some systems, such as Pivot Viewer, allow you to specify any number of pseudo-Properties about interesting items, which we’ll call Facets.  Using a structure like a Dictionary, we could specify any number of Facets.  Two-way data binding to these is problematic however since they aren’t real CLR properties.  In the full .NET Framework you can do tricks with ICustomTypeDescriptor, and now in Silverlight 5 we have System.Reflection.ICustomTypeProvider.
Let’s create a simple Facet class to represent data about the Facet we’d like to data bind to.

/// <summary>
/// Some facet of a dynamic type
/// </summary>
public class Facet
{
    /// <summary>
    /// Must be a valid CLR property name
    /// </summary>
    public string PropertyName { get; set; }

    public Type PropertyType { get; set; }

    //Couple of demo Facets

    public static Facet DynamicDemo0 = new Facet
    {
        PropertyName = "DynamicPropZero",
        PropertyType = typeof(string)
    };

    public static Facet DynamicDemo1 = new Facet
    {
        PropertyName = "DynamicPropOne",
        PropertyType = typeof(double)
    };
}

Next we’ll create an object with a regular CLR property and a dictionary to store key/value pairs.  These key value pairs will be made binding-friendly.

/// <summary>
/// An Class with normal properties, but also supporting dynamic properties
/// </summary>
public class FacetedObject : ICustomTypeProvider, INotifyPropertyChanged,
INotifyDataErrorInfo
{
    Dictionary<string, object> _facetValues;

    public object this[string key]
    {
        get
        {
            if (!_facetValues.ContainsKey(key))
            {
                return null;
            }
            return _facetValues[key];
        }
        set
        {
            _facetValues[key] = value;
            OnPropertyChanged(key);
        }
    }

The interesting thing here is the ICustomTypeProvider interface implementation. 

ICustomTypeProvider Implementation

On any CLR object you can call GetType().  If you’ve ever done any reflection programming you’re aware of all the rich runtime metadata about your classes that System.Type can provide.  System.Type is also an abstract class, and ICustomTypeProvider requires only a single method implementation:

public Type GetCustomType()
{
    return new FacetedObjectType<FacetedObject>(_currentFacets);
}

So, we can create a class that extends System.Type and do some interesting things.  We can trick the Silverlight runtime into thinking our Facets are real CLR Properties.  While my FacetObjectType<TSource> implementation is about 300 lines long, here’s the most interesting part:

/// <summary>
/// A custom System.Type implementation that can provide different Properties at runtime.
 All operations except those related to
/// Property logic delegated to the type of TSource
/// </summary>
/// <typeparam name="TSource"></typeparam>
public class FacetedObjectType<TSource> : System.Type
{
//snip…


    public override System.Reflection.PropertyInfo[] GetProperties(BindingFlags bindingAttr)
    {
        var properties = ProxyTargetType.GetProperties(bindingAttr);

        if (
           BindingFlags.Instance == (bindingAttr & BindingFlags.Instance)
        && BindingFlags.Public == (bindingAttr & BindingFlags.Public)
        )
        {
            var dynamicProperties = GetPublicDynamicProperties();
            var allprops = new List<PropertyInfo>();
            allprops.AddRange(properties);
            allprops.AddRange(dynamicProperties);
            return allprops.ToArray();
        }
        return properties;
    }
//snip…

So, for system types that implement ICustomTypeProvider, we can intercept important requests for reflection information and supplement that information.  In our case here, we can claim that properties exist that aren’t really on our class at compile time.  In terms of telling the runtime how to actually Get and Set these dynamic properties, we need to create a class that extends PropertyInfo.  Here’s a type called DynamicPropertyInfo, and the two most interesting methods:

public class DynamicPropertyInfo : PropertyInfo
{
    public DynamicPropertyInfo(Type propertyType, Type declaringType, string propertyName)
    {
        _propertyType = propertyType;
        _declaringType = declaringType;
        _name = propertyName;
    }

    public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder,
        object[] index, System.Globalization.CultureInfo culture
    {
        var fo = obj as FacetedObject;
        return fo[Name];
    }

    public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder,
        object[] index, System.Globalization.CultureInfo culture)
    {
        var fo = obj as FacetedObject;
        fo[Name] = value;
    }

In here, we can just use the this[] indexer of our FacetedObject class to get and set values.

Demo App

To show how this concept works, let’s create a Silverlight 5 application with a DataGrid.  We’re going to get the datagrid to display “properties” that technically speaking are not there.  First we’ll create a couple of Facets assigned to FacetedObject by default called “DynamicPropZero” and “DynamicPropOne”.  For these two we can create DataGridColumns along with an actual compile-time Property of FacetedObject.

            <sdk:DataGrid.Columns>
                <
sdk:DataGridTextColumn Header="Id" IsReadOnly="True" Binding="{Binding Id}" />
                <
sdk:DataGridTemplateColumn Header="Dynamic Property 0">
                    <
sdk:DataGridTemplateColumn.CellTemplate>
                        <
DataTemplate>
                            <
TextBox Text="{Binding DynamicPropZero, Mode=TwoWay,
                               
NotifyOnValidationError=True,
                               
ValidatesOnNotifyDataErrors=True,                              ValidatesOnDataErrors=True,ValidatesOnExceptions=True}"/>
                        </
DataTemplate>
                    </
sdk:DataGridTemplateColumn.CellTemplate>
                </
sdk:DataGridTemplateColumn>
                <
sdk:DataGridTextColumn Header="Dynamic Property 1"
                                       
Binding="{Binding DynamicPropOne, Mode=TwoWay}" />
            </
sdk:DataGrid.Columns>

Here’s the code we’re using to create the sample data in our main ViewModel.  Note that we're going to explose the dictionary values as properties.

public class ShellViewModel : INotifyPropertyChanged
{
    public ShellViewModel()
    {
        Items = new ObservableCollection<FacetedObject>();
        var d0 = new FacetedObject();
        d0[Facet.DynamicDemo0.PropertyName] = "I'm a property!";
        d0[Facet.DynamicDemo1.PropertyName] = 42.42;

        var d1 = new FacetedObject();
        d1[Facet.DynamicDemo0.PropertyName] = "Would you like to be a property too?";
        Items.Add(d0);
        Items.Add(d1);

And as you can see, it works:

Notice the buttons above the DataGrid.  These dynamic properties wouldn’t be very useful unless they are first-class citizens, and they are.  Note that FacetedObject also implements INotifyPropertyChanged and INotifyDataErrorInfo.  By clicking the buttons we fire commands that affect changes in code, and the UI reflects the changes for the dynamic properties.

Now, recall at the beginning that I said this could be completely dynamic and that we could actually create both the Facet data and visuals in a data driven fashion at runtime.  Clicking on the Add Facet button demonstrates this.

After clicking OK, we can do some work to add this Fact to the items on the ViewModel, and also dynamically create a new DataGridColumn to display the data.

public void AddNewFacet(string name, object defaultValue, string clrType)
{
    var typeDict = new Dictionary<string, Type>();
    typeDict["string"] = typeof(string);
    typeDict["int"] = typeof(int);
    typeDict["double"] = typeof(double);

    //1. Create a new Facet
    var newFacet = new Facet
    {
        PropertyName = name,
        PropertyType = typeDict[clrType]
    };

    //2. Tell objects to clear out cached state
    //3. Assign a default value we can see in the UI
    var vm = DataContext as ShellViewModel;   

    foreach (var item in vm.Items)
    {
        item.AddFacet(newFacet);
        item[newFacet.PropertyName] = defaultValue;
    }

    //4. create visuals to bind to new facet
    var sb = new StringBuilder("<DataTemplate
xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >")
    .Append("<TextBox Text=\"{Binding  ")
    .Append(name)
    .Append(", Mode=TwoWay}\" />")
    .Append("</DataTemplate>");

    var dt = (DataTemplate)XamlReader.Load(sb.ToString());
    var column = new DataGridTemplateColumn();
    column.Header = name;
    column.CellTemplate = dt;
    FacetGrid.Columns.Add(column);
}

Our new DynamicProperty is now shown in the DataGrid and we can edit it with two-way binding support:

For some, this last piece of code will look like the worst kind of voodoo, but there are cases where your requirements will dictate this level of flexibility and this combination of techniques will help you get there.



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 Silverlight Hosting - Amsterdam :: Silverlight Watermark TextBox Behavior

clock April 29, 2013 10:48 by author Scott

Maybe there is a working solution for this already out there, but I created my own Silverlight Behavior for a basic TextBox Watermark which might be useful.

I wanted to use it like this in my XAML (look at the behaviors tag):

<TextBlock Margin="5">Watermarked textbox:</TextBlock>
<TextBox Margin="5">
    <Interactivity:Interaction.Behaviors>
        <local:Watermark Text="Watermark" Foreground="LightGray" />
    </Interactivity:Interaction.Behaviors>
</TextBox>

The result should be something like this:

To create a Behavior for Silverlight, you must get hold of the System.Windows.Interactivity assembly which ships with Expression Blend. In my system it’s located at:

c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries\System.Windows.Interactivity.dll

And the code for the Behavior:

public class Watermark : Behavior<TextBox>
{
    private bool _hasWatermark;
    private Brush _textBoxForeground;
 
    public String Text { get; set; }
    public Brush Foreground { get; set; }
 
    protected override void OnAttached()
    {
        _textBoxForeground = AssociatedObject.Foreground;
 
        base.OnAttached();
        if (Text != null)
            SetWatermarkText();
        AssociatedObject.GotFocus += GotFocus;
        AssociatedObject.LostFocus += LostFocus;
    }
 
    private void LostFocus(object sender, RoutedEventArgs e)
    {
        if (AssociatedObject.Text.Length == 0)
            if (Text != null)
                SetWatermarkText();
    }
 
    private void GotFocus(object sender, RoutedEventArgs e)
    {
        if (_hasWatermark)
            RemoveWatermarkText();
    }
 
    private void RemoveWatermarkText()
    {
        AssociatedObject.Foreground = _textBoxForeground;
        AssociatedObject.Text = "";
        _hasWatermark = false;
    }
 
    private void SetWatermarkText()
    {
        AssociatedObject.Foreground = Foreground;
        AssociatedObject.Text = Text;
        _hasWatermark = true;
    }
 
    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotFocus -= GotFocus;
        AssociatedObject.LostFocus -= LostFocus;
    }
}

Like so many Watermark-solutions out there I’m hooking into the GotFocus/LostFocus events and to the work there. Works for me.

 



European Silverlight Hosting - Amsterdam :: Silverlight BlurEffect Example

clock March 11, 2013 07:12 by author Scott

In this article we will be seeing how to create Silverlight BlurEffect using Visual studio 2010.

Pixel shader effects in Silverlight allows you to add effects, such as gray scale, red eye removal, pixel brightness, and shadows, to rendered objects. There are two types of Pixel Shader effects in Silverlight. They are BlurEffect and DropShadowEffect. In this we will be seeing about BlurEffect and its properties.

Namespace: System.Windows.Media. Effects

Assembly: System.Windows

BlurEffect:

BlurEffect is used to represent an effect that we can apply to an object that simulates looking at the object through an out-of-focus lens. It is defined by the Radius property.

Radius:

This property is used to specify the amount of blur to apply to an object.

Without BlurEffect:

<Canvas Height="200" Width="200" Background="white">
        <Rectangle Height="50" Width="50" Fill="Orange" Canvas.Left="25" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="White" Canvas.Left="75" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="Green" Canvas.Left="125" Canvas.Top="75"></Rectangle>
</Canvas>

With BlurEffect:

<Canvas Height="200" Width="200" Background="white">
        <Canvas.Effect>
            <BlurEffect Radius="120"></BlurEffect>
        </Canvas.Effect>   
        <Rectangle Height="50" Width="50" Fill="Orange" Canvas.Left="25" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="White" Canvas.Left="75" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="Green" Canvas.Left="125" Canvas.Top="75"></Rectangle>
</Canvas>

Steps Involved:

Creating a Silverlight Application:

-
Open Visual Studio 2010. 
-
Go to File => New => Project. 
-
Select Silverlight from the Installed templates and choose the Silverlight Application template. 
-
Enter the Name and choose the location. 
-
Click OK. 
-
In the New Silverlight Application wizard check the "Host the Silverlight Application in a new Web site". 
-
Click OK.

Creating the UI:

Open MainPage.xaml file and replace the code with the following.

<UserControl x:Class="SilverlightBlurEffect.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">
    <Canvas Height="200" Width="200" Background="white">
        <Canvas.Effect>
            <BlurEffect Radius="120"></BlurEffect>
        </Canvas.Effect>   
        <Rectangle Height="50" Width="50" Fill="Orange" Canvas.Left="25" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="White" Canvas.Left="75" Canvas.Top="75"></Rectangle>
        <Rectangle Height="50" Width="50" Fill="Green" Canvas.Left="125" Canvas.Top="75"></Rectangle>
    </Canvas>
</UserControl>

To test it, please just build the solution and hit CTRL+F5

 



European Silverlight 5 Hosting - Amsterdam :: Using MVVM to Show Busy Indicator in Silverlight

clock February 25, 2013 05:05 by author Scott

Introduction

When using Silverlight, everything is asynchronous. It seems to be the trend, the same goes for Windows 8. This means that you will need to inform the user about progress in the background.

Silverlight uses the BusyIndicator for this behavior. Using MVVM, it might be a bit harder to implement the BusyIndicator in a correct way, but Catel provides the IPleaseWaitService for years which can be mocked easily during test scenarios.

However, it didn’t support a busy indicator per view yet. This fact has changed today, as you can see in the screenshot below:

A long requested feature in Catel was the support for tags in the ServiceLocator. The ServiceLocator is the IoC solution that Catel provides by default. A customer of Catel recently required the busy indicators to show up per view. I thought a bit about it and this could be solved by the recently (read: this week) introduction of the tags in the ServiceLocator.

Setting up the views

The view is responsible for registering the service. This can easily be done using the Catel user controls. Create a view like you always do, then use the following code-behind:

   1:  protected override void OnViewModelChanged()
   2:  {
   3:      var serviceLocator = ServiceLocator.Default;
   4:  
   5:      var viewModel = ViewModel;
   6:      if (viewModel != null)
   7:      {
   8:          serviceLocator.RegisterInstance(typeof (IPleaseWaitService), new PleaseWaitService(this), viewModel);
   9:      }
  10:  }

This code will be executed when the ViewModel property of the control changes. The view registers a view specific instance of the PleaseWaitService service in the ServiceLocator. It uses the new view model as tag so that will be used to distinguish the services.

Setting up the view models

The view model can retrieve the PleaseWaitService very easily because the tag is itself. To show the view specific please wait service, use this code:

   1:  var pleaseWaitService = GetService<IPleaseWaitService>(this);
   2:  pleaseWaitService.Show();

To hide the window again, use this code:

   1:  var pleaseWaitService = GetService<IPleaseWaitService>(this);
   2:  pleaseWaitService.Hide();

Customizing the PleaseWaitService

Customizing the please wait service is very, very easy. Just override the class like this:

   1:  public class MyCustomPleaseWaitService : PleaseWaitService
   2:  {
   3:      protected override FrameworkElement CreateBusyIndicator()
   4:      {
   5:          var busyIndicator = new MyBusyIndicatorControl();
   6:          
   7:          busyIndicator.SetBinding(System.Windows.Controls.BusyIndicator.BusyContentProperty, new Binding("Status"));
   8:          busyIndicator.SetBinding(System.Windows.Controls.BusyIndicator.IsBusyProperty, new Binding("IsBusy"));
   9:          
  10:          return busyIndicator();
  11:      }
  12:  }

The base implementation will automatically take care that the data context is updated and that the control is centered as required.

 



European Silverlight Hosting - Amsterdam :: How to Enable Dynamic Compression in IIS 7/7.5

clock February 18, 2013 07:47 by author Scott

In this tutorial I will show you how to enable dynamic compression in IIS 7. For other post of dynamic compression, please just see our last post.

You’ll see this error message when you haven’t setup dynamic compression on your IIS:

“The dynamic content compression module is not installed.”

Ok, let’s start the tutorial:

1. Open server manager

2. Roles --> IIS

3. Role Services (scroll down) --> Add Role Services

4. Add desired role (Web Server --> Performance > Dynamic Content Compression)

5. Wait till finish.

To enable this feature, here are the steps:

1. Open server manager

2. Roles --> Web Server (IIS) --> Internet Information Services (IIS) Manager

3. Then, go to your site --> your website

4. IISà compression

And dynamic compression has been enable on your server. Hope this tutorial is interesting.

 



European Silverlight Hosting - Amsterdam :: Silverlight FluentDataGrid

clock January 24, 2013 07:14 by author Scott

Almost every application to work with the data we have to work with the tables for display to the user of any data which it has applied. For users familiar applications such pages and comfortable enough, but not always easy to implement a particular display logic for complex data structures such as the customer wants them to be. We give a simple example, let us have the lists A and B, are related by 1: n, each element of the list B contains three attributes - the key, the record type and value, types of records that can be repeated. Suppose we want to display the record of A, so that each row of A list displays all values ​​from the list B, the record type is used as a title 

Students (List A) 

Id

Name

1

John

2

Alex

3

Sara

Marks (List B) 

Id

Student

Category

Value

1

1

C#

5

2

1

Java

3

1

HTML & CSS

4

4

2

C#

4

5

3

Java

3

We need to get the following table:

Id

Name

Marks

C#

Java

HTML & CSS

1

John

5

4

4

2

Alex

4

-

-

3

Sara

-

3

-

Application in which I faced with such a task was developed using the technology of Silverlight. Built-in DataGrid functionality described above is not realized. This led to the development of special control FluentGrid. 

How it works:

FluentDataGrid - is the control that builds a table based on a custom data source FluentGridSource. Currently, the construction of the table (view) is available only at runtime. FluentGridSource has Fluent-like interface for the formation of rules of construction.

The key source of data is the formation of the class, which will be a "model line." She describes one row of the result table, for our example of such a class might look like:

public class ExampleRow : PropertyChangedBase
{
    public ExampleRow(int id, string name, IList<IDynamicElement> marks)
    {
        _id = id;
        _name = name;
        Marks = marks;
    }

    private int _id;
    private string _name;

    [DynamicHeader("Id", false, HorizontalAlignment = HorizontalAlignment.Right)]
    public int Id
    {
        get { return _id; }
        set
        {
            NotifyPropertyChanged(() => Id);
            _id = value;
        }
    }

    [DynamicHeader("Name", false,
        HorizontalAlignment = HorizontalAlignment.Left, Width = 200)]
    public string Name
    {
        get { return _name; }
        set
        {
            NotifyPropertyChanged(() => Name);
            _name = value;
        }
    }

    public IList<IDynamicElement> Marks { get; set; }
}

public class MarkDynamicElement : PropertyChangedBase, IdynamicElement
{
    private object _value;

    public MarkDynamicElement(DynamicHeader header, object value)
    {
        Header = header;
        Value = value;
    }

    /// <summary>
    /// Header for the value
    /// </summary>
    public DynamicHeader Header { get; set; }

    /// <summary>
    /// Value that will be displayed
    /// </summary>
    public object Value
    {
        get { return _value; }
        set
        {
            _value = value;
            NotifyPropertyChanged(() => Value);
        }
    }
}

The base class implements the INotifyPropertyChanged PropertyChangedBase. We see that in the line two "static" column Id and Name, attribute DynamicHeader helps us set a cap column. There is also a list of Marks, a "dynamic" of the table, which can be constructed, for example, by using LINQ. Its elements have to implement a special interface IDynamicElement.

In forming a data source, you can add formatting rules AddFromatter (), totals AddSummary (), validation rules for totals AddValidator (), the validation rules of values ​​in table cells AddCellValidator (), and set rules for the formation of the hierarchy. In order to specify the hierarchy, you must specify the property model - key (Id), the property - a reference to the parent element (ParentId) and the property on which to display the hierarchy. 

How to use:  

The first step is defining the control in the XAML file:  

<CurriculumControl Source="{Binding SimpleSampleSource,Mode=TwoWay}" SelectedItem="{Binding SelectedRow, Mode=TwoWay}" /> 

Next step is to create a row with the appropriate attributes for the grid as described above. 

Than you should create view model, construct FluentGridSource

DynamicExampleSource = FluentGridSource.CreateFrom(DynamicExampleSource, Repository.GetExampleRows());
Constructing FluentGrisSource may be more complex if you set some validation, totals
ValidationSampleSource = new FluentGridSource(typeof(SimpleRow));
ValidationSampleSource = FluentGridSource.CreateFrom(ValidationSampleSource, Repository.GetSimpleRows());

#region Formatters

ValidationSampleSource
    .SetOptions(true, 50)
    .AddFormatter(new DynamicHeader {Name = "Min", HeaderGroup = new OverallSalaryHeaderGroup()},
                  (row, value) => ((double) value).ToString("c", new CultureInfo("en-us")));
#endregion

#region Summaries
ValidationSampleSource
    .AddSummary(new DynamicHeaderCollection {new DynamicHeader {Name = "Employee name"}}, x => "Total")
    .AddSummary(
        new DynamicHeaderCollection
            {new DynamicHeader {Name = "Min", HeaderGroup = new OverallSalaryHeaderGroup()}},
        delegate(IDictionary<DynamicHeader, IEnumerable> allValues)
            {
                var header = allValues.Keys.Single(x => x.Name == "Min");
                var values = (List<object>) allValues[header];
                return values.Sum(x => (double) x);
            })
    .AddSummary(
        new DynamicHeaderCollection
            {new DynamicHeader {Name = "Max", HeaderGroup = new OverallSalaryHeaderGroup()}},
        delegate(IDictionary<DynamicHeader, IEnumerable> allValues)
            {
                var header = allValues.Keys.Single(x => x.Name == "Max");
                var values = (List<object>) allValues[header];
                return values.Sum(x => (double) x);
            });
#endregion

#region Validations

ValidationSampleSource
    .AddCellValidator(new DynamicHeader { Name = "Min", HeaderGroup = new OverallSalaryHeaderGroup() },
        delegate(object row, object value)
        {
            var simpleRow = (SimpleRow)row;
            var min = (double)value;

            if (min > simpleRow.Max)
                return "Minimum cannot be higher than maximum!";
            if (min < 5000)
                return "Minimum cannot be lower than $5000";

            return null;
        })
    .AddCellValidator(new DynamicHeader { Name = "Max", HeaderGroup = new OverallSalaryHeaderGroup() },
        delegate(object row, object value)
        {
            var simpleRow = (SimpleRow)row;
            var max = (double)value;

            if (max < simpleRow.Min)
                return "Maximum cannot be lower than minimum!";
            if (max > 500000)
                return "Maximum cannot be heigher than $500000";

            return null;
        });

#endregion

 



European World-Class Windows and ASP.NET Web Hosting Leader - HostForLIFE.eu

clock December 18, 2012 07:10 by author Scott

Fantastic and Excellent Support has made HostForLife.eu the Windows and ASP.NET Hosting service leader in European region. HostForLife.eu delivers enterprise-level hosting services to businesses of all sizes and kinds in European region and around the world. HostForLife.eu started its business in 2006 and since then, they have grown to serve more than 10,000 customers in European region. HostForLife.eu integrates the industry's best technologies for each customer's specific need and delivers it as a service via the company's commitment to excellent support. HostForLife.eu core products include Shared Hosting, Reseller Hosting, Cloud Computing Service, SharePoint Hosting and Dedicated Server hosting.

HostForLife.eu service is No #1 Top Recommended Windows and ASP.NET Hosting Service in European continent. Their services is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries. For more information, please refer to http://www.microsoft.com/web/hosting/HostingProvider/Details/953.

HostForLife.eu has a very strong commitment to introduce their Windows and ASP.NET hosting service to the worldwide market. HostForLife.eu starts to target market in United States, Middle East and Asia/Australia in 2010 and by the end of 2013, HostForLife.eu will be the one-stop Windows and ASP.NET Hosting Solution for every ASP.NET enthusiast and developer.

HostForLife.eu leverages the best-in-class connectivity and technology to innovate industry-leading, fully automated solutions that empower enterprises with complete access, control, security, and scalability. With this insightful strategy and our peerless technical execution, HostForLife.eu has created the truly virtual data center—and made traditional hosting and managed/unmanaged services obsolete.

HostForLIFE.eu currently operates data center located in Amsterdam (Netherlands), offering complete redundancy in power, HVAC, fire suppression, network connectivity, and security. With over 53,000 sq ft of raised floor between the two facilities, HostForLife has an offering to fit any need. The datacenter facility sits atop multiple power grids driven by TXU electric, with PowerWare UPS battery backup power and dual diesel generators onsite. Our HVAC systems are condenser units by Data Aire to provide redundancy in cooling coupled with nine managed backbone providers.

HostForLife.eu does operate a data center located in Washington D.C (United States) too and this data center is best fits to customers who are targeting US market. Starting on Jan 2013, HostForLife.eu will operate a new data centre facility located in Singapore (Asia).

With three data centers that are located in different region, HostForLife.eu commits to provide service to all the customers worldwide. They hope they can achieve the best Windows and ASP.NET Hosting Awards in the World by the end of 2013.

About HostForLIFE.eu

HostForLife.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. Their 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 many top European countries.

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 :: Telerik Rad HtmlPlaceHolder in Silverlight 5 Via WCF Service

clock December 6, 2012 08:14 by author Scott

Today, in this article let's concentrate on another Silverlight application, whereby communicating with a WCF Service to perform some operation.

The Telerik Rad Controls for Silverlight can be found from http://www.telerik.com/products/silverlight/overview.aspx

Question: What is RadHtmlPlaceHolder?

In simple terms "It is the special controls which enables to render external WebPages into Silverlight App".

Let's get this implemented practically for a better idea of this!!!

Step 1: The complete code of the IService1.cs looks like this:

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

namespace Wcf_RadPlaceHolder
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string url(string a);
    }
}

Step 2: The complete code of the Service1.svc.cs looks like this:

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

namespace Wcf_RadPlaceHolder
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public string url(string a)
        {
            return a;
        }
    }

Step 3: The complete code of the Web.Config looks like this:

<?xml version="1.0"?>
<
configuration>

  <system.web>
    <
compilation debug="true" targetFramework="4.0" />
  </
system.web>
  <
system.serviceModel>
    <
behaviors>
      <
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="false"/>
        </
behavior>
      </
serviceBehaviors>
    </
behaviors>
    <
serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </
system.serviceModel>
  <
system.webServer>
    <
modules runAllManagedModulesForAllRequests="true"/>
  </
system.webServer>

</configuration>

Step 4: The complete code of the Clientaccesspolicy.xml looks like this (to avoid a cross domain problem in Silverlight):

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Step 5: The complete code of the MainPage.xaml looks like this:

<UserControl x:Class="RadPlaceHolderApplication.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:telerik="http://schemas.telerik.com/2008/xaml/presentation"
              mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
       <Grid x:Name="LayoutRoot">

            <telerik:RadHtmlPlaceholder x:Name="placeHolder1"
                                        ScrollViewer.HorizontalScrollBarVisibility="Visible"
                                        ScrollViewer.VerticalScrollBarVisibility="Visible"
                                        Margin="11,74,13,0" />
        <TextBlock Height="23"
                   HorizontalAlignment="Left"
                   Margin="34,16,0,0"
                   Name="textBlock1"
                   Text="Please Enter Web URL: "
                   FontFamily="Verdana"
                   FontSize="15"
                   VerticalAlignment="Top" />

        <TextBox Height="23"
                 HorizontalAlignment="Left"
                 Margin="219,16,0,0"
                 Name="textBox1"
                 VerticalAlignment="Top"
                 Width="212" />

        <Button Content="Go"
                Background="DeepSkyBlue"
                FontFamily="Verdana"
                FontSize="15"
                Height="23"
                HorizontalAlignment="Left"
                Margin="429,15,0,0"
                Name="button1"
                VerticalAlignment="Top"
                Width="75"
                Click="button1_Click"/>
    </Grid>
</UserControl>

Step 6: The complete code of the MainPage.xaml.cs looks like this:

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 Telerik.Windows.Controls;
using RadPlaceHolderApplication.ServiceReference1;

namespace RadPlaceHolderApplication
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void url_Call(object sender, urlCompletedEventArgs e)
        {
            placeHolder1.SourceUrl = new Uri(e.Result.ToString(), UriKind.RelativeOrAbsolute);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("Please Enter Some Values", "RadHtmlPlaceHolder- WCF", MessageBoxButton.OKCancel);
            }
            else
            {
                objClient.urlCompleted += new EventHandler<urlCompletedEventArgs>(url_Call);
                objClient.urlAsync(textBox1.Text);
            }

        }

        #region Instance Variables
        Service1Client objClient = new Service1Client();
        #endregion

    }

Step 7: The output of the application looks like this:

Step 8: The output of the Nothing Entered Application looks like this:

Step 9: The output of URL Entered Application looks like this:

I hope this article is useful for you.

 



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