European Silverlight Hosting BLOG

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

HostForLife.eu Proudly Launches Premier European SQL 2008 R2 Hosting

clock May 24, 2011 06:30 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 2008 R2 hosting in our entire servers environment. HostForlife customers have a choice between SQL Server 2008 and SQL 2008 R2 when creating a database from inside the HostForLife hosting control panel.

SQL Server 2008 R2 delivers several breakthrough capabilities that will enable your organization to scale database operations with confidence, improve IT and developer efficiency, and enable highly scalable and well managed Business Intelligence on a self-service basis for your users. For more information on SQL Server 2008 R2, visit the Microsoft website, http://www.microsoft.com/sqlserver/en/us/default.aspx.

Some of the capabilities that customers and partners will benefit from include:

1. PowerPivot: a managed self-service analysis solution that empowers end users to access, analyze and share data across the enterprise in an IT managed environment using Excel 2010 and SharePoint Sever 2010.
2. Master Data Services: helps IT organizations centrally manage critical data assets companywide and across diverse systems, and enables more people to securely manage master data directly, and ensure the integrity of information over time.
3. Application and Multi-server Management: helps organizations proactively manage database environments efficiently at scale through centralized visibility into resource utilization and streamlined consolidation and upgrade initiatives across the application lifecycle.
4. Report Builder 3.0: report authoring component with support for geospatial visualization. This new release provides capabilities to further increase end user productivity with enhanced wizards, more powerful visualizations, and intuitive authoring.
5. StreamInsight: a low latency complex event processing platform to help IT monitor, analyze and act on the data in motion to make more informed business decisions in near real-time.

For more information about this new product, please visit our site http://hostforlife.eu/SQL-2008-R2-European-Hosting.aspx.

About HostForLife

As a leading small to mid-sized business web hosting provider, we strive to offer the most technologically advanced hosting solutions available to our customers across the world. Security, reliability, and performance are at the core of our hosting operations to ensure each site and/or application hosted on our servers is highly secured and performs at optimum level. Unlike other web hosting companies, we do not overload our servers.



European Silverlight 4 Hosting :: Command Control in Silverlight 4

clock May 23, 2011 06:38 by author Scott

In this article we will take this proof of concept and demonstrate how through the use of commanding and binding we can virtually eliminate all code behind and implement to a strong MVVM architectural pattern.

Getting Started

I think few would argue with the value of a strong separation of concerns within the design of an application.  Over the last year the MVVM pattern has gained popularity in the Silverlight development community.  One of the challenges that developers faced in previous versions of the framework was the lack of commanding support in Silverlight.  Without commanding many developers had to write there own attached properties, or worse  yet, resort to event handling in their code behind, just to deal with responding to a button being clicked.  Today both the button and HyperlinkButton support commanding.

Model-View-ViewModel

Even though our sample application will only be a single page, we will still implement the MVVM pattern to eliminate any code in code behind of our MainPage.xaml.  MVVM requires that for every View we have a corresponding ModelView (MV) class.  Our View will set its DataContext equal to this class and bind all of the views data through public properties.


using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;


using System.ComponentModel;

namespace VideoCaptureExample
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
    . . . . .
    }
}


In our mainPage.xaml we will initialize our ViewModel class and set our LayoutRoot DataContext to this resource.  If our ViewModel required additional context or possibly aservices be injected into its constructor I would opts to use a ViewModel locator that has been stored as a ApplicationResource.

<UserControl x:Class="VideoCaptureExample.MainPage"
    . . . .
    d:DesignHeight="360" d:DesignWidth="610">
    <UserControl.Resources>
        <local:MainPageViewModel x:Key="MainViewModel"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White"         DataContext="{Binding Source={StaticResource MainViewModel}}">
    . . . . . .
    </Grid>
</UserControl
>

SaveCommand


One of the great advantages to commanding is encapsulation.  When an application has a function like “Save” its very likely that more then one action can trigger this behavior.  In our example we intend to allow the save to be triggered from a button, right click context menu as well a something being dragged to a specific location on the screen.  Creating a command has two parts.  First we need to write a class that implements the ICommand interface and second expose it through our view model..  The following is the general format of such a class.  When I create commands in Silverlight I like to inject my ViewModel in the event I need to check the state of my view before executing the command

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Input;


namespace VideoCaptureExample
{
    public class SaveCommand : ICommand
    {
        private MainPageViewModel _viewModel;

        public SaveCommand(MainPageViewModel viewModel)
        {
            _viewModel = viewModel;
        }


        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter)
        {
            return (_viewModel.SelectedCapture != null) ? true : false;
        }


        public void Execute(object parameter)
        {
            Capture capture = parameter as Capture;
            if (capture != null)
            {
             . . . . .
            }
        }


        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }


        public void RaiseCanExecuteChanged()
        {
            OnCanExecuteChanged(EventArgs.Empty);
        }
    }
}


In the above snippet there are three requirements when implementing the ICommand interface.  First we need to define a function called CanExecute.  This will be called to determine if a buttons enabled state is set to true or false.  What is great about CanExecute is that it eliminates custom business logic to determine if a command can be fired.  The second is an Execute method that is called when the user clicks a button referenced by the command.  All of my “Save” logic will be placed inside of this method.  A argument is passed to this method that allows data to be injected into the call. Setting CommandParameter on a Button will define what gets passed during the execute. The last requirement is the CanExecuteChanged event.  We can fire this event anytime we want buttons that are bound to this command to re-evaluate there enabled state.

To implement this command in our ViewModel, we need to expose the class as a property.

private SaveCommand _saveCommand;
public SaveCommand Save
{
    get
    {
        if (_saveCommand == null)
            _saveCommand = new SaveCommand(this);
        return _saveCommand;
    }
}


Once exposed, we can reference the SaveCommand through simple binding applied to the Button’s Command property and CommandParameter.  Now each time that a user clicks the “Save” button our command will be fired.

<Button x:Name="saveBtn" Content="Save"
    Width="70" Height="22" Margin="10,0,0,0"
    HorizontalAlignment="Right" VerticalAlignment="Center"
    Command="{Binding Save}"
    CommandParameter="{Binding ElementName=listImages, Path=SelectedItem}"/>


DelegateCommand

More often than not our command is not needed outside of the context of a single view.  If this is the case, we can delegate the implementation of the CanExecute and Execute to the ViewModel.  Lets say for example you have a command like “StartCapture” that is only appropriate for a single View.  In this scenario its a lot easier to have the business logic directly in the ViewModel than in a separate class. 

Using the same ICommand interface, we can create a reusable class that delegates both of these methods.  The following is the most popular approach.

using System;
using System.Windows.Input;

namespace VideoCaptureExample
{
    public class DelegateCommand : ICommand
    {
        private Predicate<object> _canExecute;
        private Action<object> _method;
        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<object> method)
            : this(method, null)
        {
        }

        public DelegateCommand(Action<object> method, Predicate<object> canExecute)
        {
            _method = method;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _method.Invoke(parameter);
        }


        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }


        public void RaiseCanExecuteChanged()
        {
            OnCanExecuteChanged(EventArgs.Empty);
        }
    }
}

To implement this DelegateCommand class we do the following in our ViewModel.  Notice how our constructor gets passed two delegates, one for  CanExecute and one for Execute.  Calling this command from XAML is identical to our SaveCommand class.

private DelegateCommand _captureCommand;
public DelegateCommand Capture
{
    get
    {
        if (_captureCommand == null)
            _captureCommand = new DelegateCommand(OnCapture, CaptureCanExecute);

        return _captureCommand;
    }
}
. . . .
private void OnCapture(object parameter)
{
    UIElement element = parameter as UIElement;
    if (this.CaptureSource != null)
    {
    . . . .
    }
}
. . . .
private bool CaptureCanExecute(object parameter)
{
    return (_isCapturingVideo) ? true : false;
}

Using Binding to Avoid Commanding

One of the things that I think a lot developers forget is that TwoWay binding can be a great way to avoid having to create a command or event handler to respond to a user click.  Commands are great, but if you don’t need them don’t use them.

When all you want to do is take some action when a user clicks on an item in a list its very easy to allow a change in the lists SelectedItem to notify other controls.  Take for example the list of EffectShader displayed in the image below.  When a user clicks on any of the shaders, I want to apply that effect to my rectangle which is displaying my VideoBrush.  I can do this entirely using binding applied to both elements.

If we examine the code below, you will see a bunch of bindings.  First, our ListBox.ItemSource is bound to an ObservableCollection<Effect> of effects.  This allows us to add effects to the ListBox by simply updating our collection.  Second, our ListBox.IsEnabled is bound to a property in our ViewModel.  Notice the use of TargetNullValue and FallbackValue.  These new properties on the binding extension method allow us to override what gets used in the event the property we are binding to is NULL value.  In this example we have a ViewModel property that stores a reference to a capture that has been selected in the ListBox of captures.  If nothing is selected, the property is null.  Since a null is not a boolean, we use TargetNullValue and FallbackValue to ensure we have a true/false response.

<ListBox Height="50" Name="listEffects" Width="Auto"  HorizontalAlignment="Stretch"
     ItemsSource=
"{Binding Path=Effects}"
     IsEnabled=
"{Binding TargetNullValue=true, FallbackValue=false, Path=SelectedCapture}"
     ItemTemplate=
"{StaticResource EffectItemTemplate}"
     ItemsPanel=
"{StaticResource WrapItemPanel}"
     ScrollViewer.HorizontalScrollBarVisibility=
"Disabled"
     ScrollViewer.VerticalScrollBarVisibility=
"Auto" >
</ListBox>


Another place we use binding is in the DataTemplate of this list box.  Here we will bind both the Effect of the rectangle and its Fill.  Our Effect will get bound to the ShaderEffect property of this item being rendered , while the Fill will navigate back to the main DataContext and bind to a property called Brush located within our  MainPageViewModel.  This property might be a SolidBrush, VideoBrush or even an ImageBrush of an existing capture.

<DataTemplate x:Key="EffectItemTemplate">
    <Border BorderThickness="1" BorderBrush="Black" CornerRadius="2"
        HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,0,3,0">
        <Rectangle Width="48" Height="36" Stretch="Fill"
            Effect="{Binding ShaderEffect}"
            Fill="{Binding Source={StaticResource MainViewModel}, Path=Brush}" />
    </Border>
</DataTemplate>


So that ensures that our list of effects looks correct, but how exactly does our rectangle displaying our live webcam video with the correct ShaderEffect applied?

Again we lean on Binding to avoid any procedural code.  using ElementName binding we bind the styled buttons Effect property to the SelectedItem of our ListBox of effects.  Now each time a user clicks on an item in our list of effects the rectangles will change immediately.

<Button Name="rectVideo"
    Style=
"{StaticResource RectangleButtonStyle}"

    Width=
"320" Height="240"

    Effect=
"{Binding ElementName=listEffects, Path=SelectedItem.ShaderEffect, Mode=TwoWay}"

    Command=
"{Binding Capture}"

    CommandParameter=
"{Binding ElementName=rectVideo}"/>



European Silverlight 4 Hosting :: Binding to a ComboBox in Silverlight

clock May 11, 2011 06:26 by author Scott

Binding to a Combobox

Before we can get to the “gotcha” I came across, we first need to set up how to use binding with a Combobox.  For my example we will be using a simplistic MVVM architecture because it helps to demonstrate the point a bit better.  Just as a reminder, you don’t have to use binding with the Combobox or to recreate the issue described in this post.

So let’s get started with our view model.  For our purposes, the view can be rather simplistic, needing only 2 properties.  I added a method to populate our list data just for completion.

    public class MainPageViewModel : INotifyPropertyChanged
    {
        private string _favoriteConf;

        public MainPageViewModel()
        {
            PopulateConfs();
        }

        public string FavoriteConf
        {
            get { return _favoriteConf; }
            set
            {
                _favoriteConf = value;
                NotifyPropertyChanged("FavoriteConf");
            }
        }

        private List<string> _confs;

        public List<string> Confs
        {
            get { return _confs;  }
            set
            {
                _confs = value;
                NotifyPropertyChanged("Confs");
            }
        }
        private void PopulateConfs()
        {
            Confs = new List<string>()
                {"MIX", "TechEd", "PDC", "DevConnections"};
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected  void NotifyPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

As you can see, we have just the two properties : FavoriteConf and Confs.  Our constructor calls the PopulateConfs to add some data for us to work with.  (Yes, Conf = Conference, I just didn’t want to write out Conference too many times. ).

Now that we have our view model, the next step would be to create our XAML.  For this demonstration, we are going to show two elements: a Combobox and a TextBox.  The Combobox will have our list of conferences (bound to the Confs property) and the TextBox will show the selected conference by binding to the the FavoriteConf property.

If you look at the Combobox, you will notice two different binding statements.  The first one is the ItemsSource is bound to the Confs property.  This is done with the default OneWay binding, since our Combobox will never be modifying the list of data.  The second is the SelectedValue with is bound to the FavoriteConf property.  Since we want to update the FavoriteConf value in our view mode when the user selects a drop down, then we do a two-way binding.

Here is our XAML:

<UserControl x:Class="ComboBoxBinding.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:local="clr-namespace:ComboBoxBinding"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:MainPageViewModel x:Key="viewModel"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White"
          DataContext="{StaticResource viewModel}">
        <Grid HorizontalAlignment="Center" VerticalAlignment="Center"
              Background="LightGray"
              Height="Auto" Width="Auto">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150"/>
                <ColumnDefinition Width="150"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="25"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock HorizontalAlignment="Center"
                       Text="Select Favorite Conference"/>
            <TextBlock Text="Choose One :" Grid.Row="1"/>
            <ComboBox Grid.Row="1" Grid.Column="1"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"
                      ItemsSource="{Binding Confs}"/>
            <TextBlock Text="You Picked :" Grid.Row="2"/>
            <TextBox Text="{Binding FavoriteConf}" Grid.Row="2"
                     Grid.Column="1"/>
        </Grid>
    </Grid>
</UserControl>

Note: Since this is a demonstration, I’m creating a static copy of our view model in the resources of our XAML and binding the LayoutRoot’s DataContext to this resource.

If you run the project the application should look something like this:



When you select an item from the Combobox, the TextBox will update with the selected value of the Combobox.



Great! It works, everything is add it should be, right?

Note: Silverlight 4 added some additional properties to the Combobox to make binding easier.  You can read a walkthru of using them on John Papa’s blog
here.

Ordering of XAML Properties : The Gotcha

So let’s take our example one step further, but setting a default value for our FavoriteConf value.  To do this, we are going to change up our constructor to our view model by adding another line of code:

        public MainPageViewModel()
        {
            PopulateConfs();
            FavoriteConf = "MIX";
        }

If we run our example again, this is what we get:



Not exactly what I was looking for.  The TextBox picked up the default value of the FavoriteConf, but why didn’t the Combobox?  Well it turns out, after much head scratching, that the answer is in our XAML.

Let’s take a look at the XAML of our Combobox again:

            <ComboBox Grid.Row="1" Grid.Column="1"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"
                      ItemsSource="{Binding Confs}"/>

Do you see where we went wrong?

It looked right to me for a while.  However, it turns out that ordering of the properties in XAML can affect the behavior of the control.  If we switch the order of the ItemsSource and the SelectedValue, your XAML will now look something like this:

            <ComboBox Grid.Row="1" Grid.Column="1"
                      ItemsSource="{Binding Confs}"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"/>

Now, if we run the two examples side-by-side, we get the following:



It turns out that ordering in your XAML can be important and something to look out for if you are not getting the results that you are looking for. If you have found yourself in a similar situation, hopefully this will post will help.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in