European Silverlight 4 & Silverlight 5 Hosting BLOG

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

European WCF Hosting :: Use dataset across WCF service

clock September 16, 2011 06:50 by author Scott

Some times you need to return a set of data from a WCF service and When you are working with ado.net, dataset is the obvious reason you wish at your client side. But passing dataset can make service less interoportable because in that case you are forced to use dataset on your client code. Second point is that dataset might become very bulky as per size of the data grows. Instead, passing dataset we can pass compressed byte array of dataset from WCF service and consume it like a byte array on client end. After Uncompression, either you can convert it into dataset or you can use this XML in any other form you want.

For this, lets first create a WCF service:

[OperationContract]
public byte[] GetEmployee(string BranchId)
{
string sQ = "Select EmpId, EmployeeName from EmployeeMaster";

SqlConnection objConn = new SqlConnection("Data Source=[YourServer];Initial Catalog=[Database];User ID=[UserName];Password=[Password];MultipleActiveResultSets=True");
SqlCommand objCom = new SqlCommand(sQ, objConn);
SqlDataAdapter objDa = new SqlDataAdapter(objCom);
DataSet objDs = new DataSet();
objDa.Fill(objDs);
//Now we'll convert dataset into byte array and compress it using gzStream.
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
GZipStream gzStream = new GZipStream(memStream, CompressionMode.Compress);
objDs.WriteXml(gzStream);
binaryDataResult = memStream.ToArray();
gzStream.Close();
memStream.Close();
return binaryDataResult;
}

Here, We are first filling dataset from database then after compression using GZipStream, we are converting it to byte array. At client end we will get this byte array and we'll again follow these steps in reverse order.

ServiceClient s = new ServiceClient();
byte[] btEmployee = (byte[])s.GetEmployee("0");
if (btEmployee != null)
{
MemoryStream mEmployee = new MemoryStream(btEmployee);
GZipStream gStreamEmployee = new GZipStream(mEmployee, CompressionMode.Decompress);
DataSet objDsEmployee = new DataSet();
objDsEmployee.ReadXml(gStreamEmployee);
gStreamEmployee.Close();
gvEmployee.DataSource = objDsEmployee;
gvEmployee.DataBind();
}



European Silverlight 4 Hosting :: Tutorial - How to Send Email in Silverlight

clock August 25, 2011 07:07 by author Scott

In this tutorial I will show you how to send email with Silverlight using .NET framework.

1. Create Silverlight Application Using VS 2010



Above GUI xaml like following,



2. Add asp.net Generic Handler in Web.Project



3. Add Static Class and Create Send Email Function.



4. Add code to perform mail sending through the generic handler.



5. Add This Code At SilverLight Project(MainPage.xaml.cs) on send button click.



6. Then, configure the SMTP settign inside the configuration file, here is settings details.



7. Press F5 and run.

Hope it is help!!



European Silverlight 4 Hosting :: How to Edit Silverlight Page Data Using Domain Service

clock July 21, 2011 05:33 by author Scott

This post requires to create a Silverlight Business Application in Visual Studio 2010.

1. Open the Mainpage.xaml , Add the following XAML code to see the Save changes and Reject changes button

   1: <Button Content="Save Changes" Click="SaveButton_Click"
         Margin="5" 
   2:        x:Name="SaveButton"></Button>
   3: <Button Content="Reject Changes" Click="RejectButton_Click"
               Margin="5"
   4:         x:Name="RejectButton"></Button>
   5: <TextBlock x:Name="ChangeText" VerticalAlignment="Center"
      Width="Auto"></TextBlock>

2. Add the code for button click event handlers as shown below

   1: private void SaveButton_Click(object sender, RoutedEventArgs e)
   2:  {
   3:   awDept.SubmitChanges(OnSubmitCompleted, null);
   4:  }
   5: 
   6:  private void RejectButton_Click(object sender, RoutedEventArgs e)
   7:  {
   8:    awDept.RejectChanges();
   9:    CheckChanges();
  10:  }
  11: private void CheckChanges()
  12:  {
  13:   EntityChangeSet changeSet = awDept.EntityContainer.GetChanges();
  14:   ChangeText.Text = changeSet.ToString();
  15:   bool hasChanges = awDept.HasChanges;
  16:   SaveButton.IsEnabled = hasChanges;
  17:   RejectButton.IsEnabled = hasChanges;
  18:  }
  19: 
  20: private void OnSubmitCompleted(SubmitOperation so)
  21:  {
  22:    if (so.HasError)
  23:     {
  24:         MessageBox.Show(string.Format("Submit Failed: {0}", so.Error.Message));
  25:         so.MarkErrorAsHandled();
  26:      }
  27:             CheckChanges();
  28:  }

  29: private void departmentDataGrid_RowEditEnded(object sender,
          DataGridRowEditEndedEventArgs e)
  30: {
  31:          CheckChanges();
  32: }

3. Open the Metadata file in server project and add the editable attribute to the Id and modified date as shown below

   1: internal sealed class DepartmentMetadata
   2:         {
   3: 
   4:             // Metadata classes are not meant to be instantiated.
   5:             private DepartmentMetadata()
   6:             {
   7:             }
   8: 
   9:             [Editable(false)]
  10:             public short DepartmentID { get; set; }
  11: 
  12:             public string GroupName { get; set; }
  13:             [Editable(false)]
  14:             public DateTime ModifiedDate { get; set; }
  15: 
  16:             public string Name { get; set; }
  17:         }

4. When you run the application you should be able to see the below screen



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.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