European Silverlight Hosting BLOG

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

Silvelight 6 Hosting - HostForLIFE :: Introduction To Silverlight in ASP.Net

clock June 16, 2022 08:44 by author Peter

Silverlight is a web-based technology that allows web designers and web developers to explore the boundaries of web application development.

It is an integration of rich user interface of desktop applications, where we use the HTML and JavaScript web languages. Silverlight helps in building web applications that contain high-fidelity multimedia content and eye-catching visual effects.  

We will make a simple Silverlight application in Visual Studio 10. Open Visual Studio 10. Create a New Project by pressing Ctrl + Shift + N, under C# go to Silverlight and choose Silverlight application. Name it Silverlight_demo.

This is your mainpage.xaml page where you will write your design code. It is very similar to a default .aspx page where we write design code in ASP.NET.

These are the main default files that exist when you create a new project.


 

This is your mainpage.xaml page code.

    < UserControl x: Class = "SilverlightApplication4.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" >  
      
    <Grid x: Name = "LayoutRoot"  
    Background = "White" > <TextBox Height = "60"  
    HorizontalAlignment = "Left"  
    Margin = "28,104,0,0"  
    Name = "textBox1"  
    Text = "Welcome here for getting Silverlight"  
    VerticalAlignment = "Top"  
    Width = "343"  
    FontWeight = "Bold"  
    Background = "#FF89FF89"  
    Foreground = "#FF1847D1"  
    Padding = "12"  
    FontSize = "15" / ></Grid>    
        </UserControl >  

The design will look like the following.

 Now open your MainPage.Xaml.cs page to make some server-side code for your textbook. Add your code after the InitializeComponent() in the constructor.
    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;  
      
    namespace SilverlightApplication4 {  
      public partial class MainPage: UserControl {  
        public MainPage() {  
          // default constructor    
          InitializeComponent();  
          // we will add our textblock code here :    
          TextBlock txtn = new TextBlock() {  
      
            Name = "textBox1",  
            Text = "Welcome here for Getting Silverlight",  
            Foreground = new SolidColorBrush(Colors.Blue),  
      
          };  
      
        }  
      }  
    }


By pressing F5 you will get your output something like the following:



Silvelight 6 Hosting - HostForLIFE :: Duplexing in Silverlight

clock February 18, 2022 07:28 by author Peter

The idea of duplexing is very old, when I first read it, it reminded me about my Mom. Well actually not reminded me, but she never allowed me to even forget her, can you imagine 50 missed calls in a day!!! Annoyed . Okay, imagine you being a client and your Mom being the server. It's usually the client that starts communicating with server, requests for data, for authentication or for money, in this case. The server can either respond positively or negatively to the client's request. That is if your request is for money, then you either get it or don't, the later one usually happens in my case. Now what if the server initiates the communication? Yes! It's not always that the server listens to the client's request, but there are situations when the server also broadcasts the messages to all it's clients. This process is called Duplex polling. In Silverlight however, there are many ways to perform this server to client broadcasting, one way is through WCF Services that we are going to use now. So grab a cup of Coffee or two, because the journey is little bit lengthy and a bit complicated.

Before proceeding let's establish the strategy of what exactly we are going to do. What I planned is to keep it neat, clean and simple. So to start, let's create a Silverlight application first, naming it as MyPolling.

Now before going deep into WCF let's first set up our UI. It's nothing though, but a simple button and a text block. Here's how I arranged them in my XAML:

<UserControl x:Class="MyPolling.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">
<Grid x:Name="LayoutRoot" Background="White">
<Button x:Name="Start" Content="Send Message"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Click="Start_OnClick"/>
<TextBlock x:Name="TxtBlkInfo" Text="Press Button to start communication"
TextWrapping="Wrap" Width="200" Margin="0,0,200,251" />
</Grid>
</UserControl>

Looks cool isn't it? Okay, it's time to add some WCF stuff. On the web project "Add" -> "New item" -> "WCF Service" and name it "MyPollingService.svc". After clicking "Add" Visual Studio should have opened the "IMyPollingService" interface for you.


Delete the DoWork() function that is already in the interface. Now replace the interface with exactly the following lines of code:
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}


It's time to make another interface, the client one, that will actually do the heavy lifting of taking the data from the server to the client. So, below the IMyPollingService interface, add the following lines:
[ServiceContract(CallbackContract = typeof(IMyPollingClient))]
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}

Before wrapping up with the interface part, we need to make the service know about the existence of the client interface. In order to do so, just above the IMyPollingService interface add the following (line #1):
[ServiceContract(CallbackContract = typeof(IMyPollingClient))]
public interface IMyPollingService
{
[OperationContract(IsOneWay = true)]
void SubmitResult(string rS);
}

The interface part is ready, what we've done so far is we've structured our service for how our service is to look like, what will it contain etc. In a nutshell, we have created the overall contract of our service. Next is to grab another cup of Coffee.

So far, so good. It's time to open MyPollingService.svc.cs file. As you will see, there would be a class MyPollingService implementing the interface IMyPollingService that we just have modified. Therefore, it might have errors. So click on the implemented interface and implement the non-implemented methods. After that, if you have the SubmitResult method left in the class, then you are with me. Now we are going to send numbers from 1…100 to the client from the server. In order to do that we will use my love of loops, here's the code:
public void SubmitResult(string rS)
{
var client = OperationContext.Current.GetCallbackChannel<IMyPollingClient>();
for (var i = 0; i < 100; i++)
{
client.ReturnResult(i.ToString(CultureInfo.InvariantCulture));
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}


Let's pause the coding for a few minutes and edit the configuration file, web.config. First we need to add the DLL System.ServiceModel.PollingDuplex.dll at the web side, to do this just right-click on refrences and browse to the following location: "C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Server" and add only the DLL present there. Similarly on the client side add the same DLL but from "C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client". We are then ready for web.config's modifications.

Modifying Web.config is very simple. Let's take small steps to configure the file. The original file that we have presented with is:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
 -->

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>

Step I
Naming behavior of the service
First we need to name the behavior of the service (line #16); let's set it to "BehaviourOfService":
<serviceBehaviors>
<behavior name="BehaviourOfService">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>


Step II
Setting custom binding for pollingduplex
Next we need to create the custom binding for pollingduplex so below the </behaviour> between lines #20 and #21 add the following:
<bindings>
<customBinding>
<binding name="pollingDuplexBinding">
<binaryMessageEncoding />
<pollingDuplex maxPendingSessions="2147483647"
maxPendingMessagesPerSession="2147483647"
inactivityTimeout="02:00:00"
serverPollTimeout="00:05:00"/>
<httpTransport />
</binding>
</customBinding>
</bindings>


Step III
Registering the pollingduplex extention
In order to use the polling duplex extension, we need to register it's DLL "System.ServiceModel.PollingDuplex.dll". To do so an extension for the DLL must be added. Here's the XML for the extension that is to be added just inside the <system.serviceModel> tag:
<extensions>
<bindingElementExtensions>
<add name="pollingDuplex"
type="System.ServiceModel.Configuration.PollingDuplexElement,
System.ServiceModel.PollingDuplex" />
</bindingElementExtensions>
</extensions>


Now here's how all the XML looks like:
<?xml version="1.0"?>
<!--
 For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
 -->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>

<system.serviceModel>
<extensions>
<bindingElementExtensions>
<add name="pollingDuplex"

type="System.ServiceModel.Configuration.PollingDuplexElement,
System.ServiceModel.PollingDuplex" />
</bindingElementExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="BehaviourOfService">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="pollingDuplexBinding">
<binaryMessageEncoding />
<pollingDuplex
maxPendingSessions="2147483647"
maxPendingMessagesPerSession="2147483647"
inactivityTimeout="02:00:00" serverPollTimeout="00:05:00"/>
<httpTransport />
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>


Step IV
Endpoint of the Service
The next and final step is to create the end points for the service. Copy the following code to after the </bindings> line #40:
<services>
<service behaviorConfiguration="BehaviourOfService" name="MyPolling.Web.MyPollingService">
<endpoint address="" binding="customBinding" bindingConfiguration="pollingDuplexBinding"
contract="MyPolling.Web.IMyPollingService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>


The two important things that must be looked after is the name of the service and the contract for the endpoint. The name of the service is basically the location of my class MyPollingService, that is inside the MyPolling.Web namespace. And the contract of the endpoint is basically the location of the interface IMyPollingService, that is again inside MyPolling.Web.

Okay, the hard time is over, now I must go and get another cup of Coffee, meanwhile you build your solution.

My solution built with no error. If your solution does compile with errors, it's not my fault.

It's time now to consume the service at the client. At the client Silverlight project, right-click on the reference and choose "Add Service Reference". Click on the "Discover" button in the dialog, and you should see "MyPollingService" as shown in the figure below.

Name the namespace PollingService. In the end, try to remember the click event that we'd made in the mainpage at the beginning. Yes! your right, we need to write some code to consume the response from the server in that event.

    We need to create the endpoint URL for our service.
    Create a PollingDuplexHttpBinding for the service.
    Set the client so as to listen to the server's broadcast.

The following code will do it all, just add it in the button click event:
private void Start_OnClick(object sender, RoutedEventArgs e)
{
EndpointAddress URL = new EndpointAddress("http://localhost:" +
HtmlPage.Document.DocumentUri.Port + "/MyPollingService.svc");
PollingDuplexHttpBinding Bind = new PollingDuplexHttpBinding();
_client = new MyPollingServiceClient(Bind, URL);
TxtBlkInfo.Text = "Sent...";
_client.SubmitResultAsync("Hello Server");

_client.ReturnResultReceived +=

new EventHandler<ReturnResultReceivedEventArgs>(_client_ReturnResultReceived);

}


In the end at line #9 I've created an event handler for the event when the server broadcasts the request. We need to continuously update the value of the Text Block with the results the server sends. So in the handler just add the following line:
void _client_ReturnResultReceived(object sender, ReturnResultReceivedEventArgs e)
{

TxtBlkInfo.Text = e.rS;


A long journey has come to an end. Just press "F5", my darling key, and hope your project compiles and runs successfully. Fingers crossed

Mine did. And yes on pressing the "send message" button the text block's value is updating continuously.



Silvelight Hosting - HostForLIFE :: Silverlight Grid Layout Control Example

clock October 1, 2021 08:13 by author Peter

In this article we will be seeing how to create Silverlight Grid Layout using Visual studio 2010. The term layout describes the process of sizing and positioning objects in your Silverlight-based application. In Silverlight we have 3 layout elements namely Canvas, StackPanel and Grid. In this we will be seeing how to create Grid layout in Silverlight.

StackPanel:
It defines a grid area which consists of rows and columns. By default it contains one row and one column. It is the root element used by the Visual Studio Silverlight template. It enables you to o create a variety of object layouts. You can position child controls in specific cells of the Grid by using the Grid.Column and Grid.Row.

Grid.Row:
It is used to place the child controls in the particular row of the grid.

Grid.Column:
It is used to place the child controls in the particular column of the grid.

ShowGridLines-True:
If you set ShowGridLines to true gridlines will be shown.


ShowGridLines-False:

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 Grid Layout:
I. Open MainPage.xaml file and replace the code with the following.
<UserControl x:Class="SilverlightApplication1.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">
    <Grid x:Name="layoutRoot" ShowGridLines="True"  Height="200" Width="400" Background="Orange">
        <Grid.RowDefinitions>
            <RowDefinition Height="32*" />
            <RowDefinition Height="121*" />          
        </Grid.RowDefinitions>
        <TextBlock Text="PROFILE" FontFamily="Verdana" FontSize="14" FontWeight="Bold" Foreground="White" Margin="14,20,-14,99"
Grid.RowSpan="2"></TextBlock>       
        <Grid Grid.Row="1" ShowGridLines="True" Background="White">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="144*" />
                <ColumnDefinition Width="256*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
                <RowDefinition Height="50*" />
            </Grid.RowDefinitions>
            <TextBlock Text="Name :" FontFamily="Verdana" Grid.Row="1" Grid.Column="0"  FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>
            <TextBlock Text="About Me :" FontFamily="Verdana" Grid.Row="2" Grid.Column="0" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>
            <TextBlock Text="Country :" FontFamily="Verdana" Grid.Row="3" Grid.Column="0" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2" ></TextBlock>          
            <TextBlock Text="Vijai Anand.R" FontFamily="Verdana" Grid.Row="1" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>
            <TextBlock Text="SharePoint Developer" FontFamily="Verdana" Grid.Row="2" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>
            <TextBlock Text="India" FontFamily="Verdana" Grid.Row="3" Grid.Column="1" FontSize="14" FontWeight="Bold" Foreground="Green" Margin="14,10,-14,21" Grid.RowSpan="2"></TextBlock>       
        </Grid>      
    </Grid>     
</UserControl>

ii. Build the solution.

iii. Hit ctrl+F5.



Silvelight 6 Hosting - HostForLIFE :: Difference Between WPF and Silverlight and Advantages of WPF

clock September 3, 2021 08:41 by author Peter

Many times in interview one question commanly used that is Difference Between WPF and Silverlight and Advantages of WPF, so by considering above requirement i have decided to write this blog to help freshers and job seekers also who might be wants to know about it.


So let us see

Difference Between  WPF And SilverLight:

  • WPF is based off of the desktop CLR which is the full version of the CLR.
  • Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth
  • of CLR features. It also has a much smaller version of the BCL
  • WPF you can create Windows App, Navigation app and XBAP (IE based) applicationWith Silverlight you can create only XAP (Browser based application.).
  • WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only.
  • Silveright does not support MultiBinding.
  • Silverlight supports the XmlDataProvider but not the ObjectDataProvider. WPF supports both.

Advantage of WPF:
Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and rich document viewing in addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all these with consisting programming model as well as tight integration when each type of media gets composited and rendered.

Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal applications it dont get decrease the size as the resolution gets increase. This is possible because WPF emphasis on vector graphics.

Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF applications can get the benefit of hardware acceleration for smoother graphics and all round better performance.

Declerative Programming: WPF takes the declarative programming to the next level with the introduction of Extensible Application Markup Language(XAML)

XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute directly to the look and feel of applications.



Silvelight 6 Hosting - HostForLIFE.eu :: Rectangle in Silverlight

clock June 17, 2021 08:29 by author Peter

Silverlight Rectangle Control
This article demonstrates how to create and use a Rectangle control in Silverlight using XAML and C#.


The Rectangle object represents a rectangle shape and draws a rectangle with the given height and width. The Width and Height properties of the Rectangle class represent the width and height of a rectangle. The Fill property fills the interior of a rectangle. The Stroke property sets the color and StrokeThickness represents the width of the outer line of a rectangle.

Creating a Rectangle

The Rectangle element represents a Silverlight Rectangle control in XAML.
<Rectangle/>

The code snippet in Listing 1 creates a rectangle by setting its width and height properties to 200 and 100 respectively. The code also sets the black stroke of width 4.
<Rectangle
    Width="200"
    Height="100"
    Fill="Blue"
    Stroke="Black"
    StrokeThickness="4" />


The output

The CreateARectangle method listed in Listing 2 draws same rectangle in Figure 1 dynamically.
/// <summary>
/// Creates a blue rectangle with black border
/// </summary>
public void CreateARectangle()

{
    // Create a Rectangle
    Rectangle blueRectangle = new Rectangle();
    blueRectangle.Height = 100;
    blueRectangle.Width = 200;           

    // Create a blue and a black Brush
    SolidColorBrush blueBrush = new SolidColorBrush();
    blueBrush.Color = Colors.Blue;
    SolidColorBrush blackBrush = new SolidColorBrush();
    blackBrush.Color = Colors.Black;

     // Set Rectangle's width and color
    blueRectangle.StrokeThickness = 4;
    blueRectangle.Stroke = blackBrush;

    // Fill rectangle with blue color
    blueRectangle.Fill = blueBrush;

    // Add Rectangle to the Grid.

    LayoutRoot.Children.Add(blueRectangle);

}


The RadiusX and RadiusY properties set the x-axis and y-axis radii of the ellipse that is used to round the corner of a rectangle.  By adding the following lines of code to Listing 7 creates a rounded rectangle, which looks like Figure 2.
// Set roundness

blueRectangle.RadiusX = 20;
blueRectangle.RadiusY = 20;

Formatting a Rectangle
We can use the Fill property of the Rectangle to draw a rectangle with any kind of brush including a solid brush, linear gradient brush, radial gradient brush, or an image brush. The code in Listing 3 uses linear gradient brushes to draw the background and foreground of a Rectangle.
<Rectangle
    Width="200"
    Height="100"          
    Stroke="Black"
    StrokeThickness="4" >

    <Rectangle.Fill>
        <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >
            <GradientStop Color="Blue" Offset="0.1" />
            <GradientStop Color="Orange" Offset="0.25" />
            <GradientStop Color="Green" Offset="0.75" />
            <GradientStop Color="Red" Offset="1.0" />
        </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>


The new Rectangle looks like Figure 3.

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


The new output looks like

Drawing a Semi-transparent Rectangle
The Opacity property represents the transparency of a Rectangle. The value of Opacity is between 0 and 1, where 0 is fully transparent and 1 is fully opaque. The code listed in Listing 5 generates a semi-transparent shape.
<Rectangle
    Width="200"
    Height="100"          
    Stroke="Black"
    StrokeThickness="4"
    Opacity="0.5">


The new output looks like

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



Silvelight 6 Hosting - HostForLIFE.eu :: A Simple Silverlight Application Implementing MVVM

clock May 21, 2021 08:36 by author Peter

A Simple Silverlight Application Implementing MVVM

MVVM

In simple words, View knows ViewModel, ViewModel knows Model, but not vice versa.

Why MVVM
    Easy to unit test.
    No need to change model to support changes in View.
    Very minor changes required in ViewModel to support changes in View.
    Separates UX designer and developer i.e the development team can focus on creating ViewModel classes, and the design team can focus on making user-friendly Views.

Simple Silverlight application using MVVM

Here I am just going to get a student name and age from the user and display the details in a GridView as in the figure.

The important areas covered are MVVM, using Relay Command and IValueConverter.

Creating a Student class

I created student class with the following properties, Name, Age, JoiningDate.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MVVMDemoinSL
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime JoiningDate { get; set; }
    }
}


Creating ViewModelBase and ViewModel class

It's always a good idea to have a ViewModelBase class and inherit all the ViewModels from that. Hence we can reuse the code for implementing INotifyPropertyChanged.

The main purpose of using INotifyPropertyChanged is to get notification whenever the property value is changed.
I created a ViewModelBase as below.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace MVVMDemoinSL
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

I also created a ViewModel class which inherits from ViewModelBase.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace MVVMDemoinSL
{
    public class ViewModel : ViewModelBase
    {
        private Student _student;
        private ObservableCollection<Student> _students;
        private ICommand _SubmitCommand;
        public Student Student
        {
            get
            {
                return _student;
            }
            set
            {
                _student = value;
                NotifyPropertyChanged("Student");
            }
        }

        public ObservableCollection<Student> Students
        {
            get
            {
                return _students;
            }
            set
            {
                _students = value;
                NotifyPropertyChanged("Students");
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                if (_SubmitCommand == null)
                {
                    _SubmitCommand = new RelayCommand(Submit);
                }
                return _SubmitCommand;
            }
        }

        public ViewModel()
        {
            Student = new Student();
            Students = new ObservableCollection<Student>();
            Students.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Students_CollectionChanged);
        }
        //Whenever new item is added to the collection, am explicitly calling notify property changed

        void Students_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            NotifyPropertyChanged("Students");
        }

        private void Submit()
        {
            Student.JoiningDate = DateTime.Today.Date;
            Students.Add(Student);
            Student = new Student();
        }
    }
}


RelayCommand
Since we are following the MVVM pattern, instead of having a Button click event in code behind, we are going to use the Command Property of the button. The RelayCommand allows you to inject the command's logic via delegates ed into its constructor. This approach allows for terse, concise command implementation in ViewModel classes. RelayCommand is a simplified variation of the DelegateCommand. RelayCommand implementation using CommandManager is not possible using Silverlight.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MVVMDemoinSL
{
    public class RelayCommand : ICommand
    {
        private Func<bool> canExecute;
        private Action executeAction;
        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action executeAction,
            Func<bool> canExecute)
        {
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        public RelayCommand(Action executeAction)
|        {
           this.executeAction = executeAction;
            this.canExecute = () => true;
        }

        public void RaiseCanExecuteChanged()
       {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }

        public bool CanExecute(object parameter)
         {
           return canExecute == null ? true : canExecute();
        }

        public void Execute(object parameter)
        {
            executeAction();
        }
    }
}

View

Now we have to create a view and bind it with ViewModel properties. The code for the view can be found below. I have used a window, Grid, Textbox, TextBlock, Button and GridView.
<UserControl x:Class="MVVMDemoinSL.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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:viewmodel="clr-namespace:MVVMDemoinSL"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <viewmodel:ViewModel x:Key="ViewModel"/>
        <viewmodel:DatetimeToDateConverter x:Key="MyConverter"/>
    </UserControl.Resources>

    <Grid DataContext="{Binding Source={StaticResource ViewModel}}">
        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="Name" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="0" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Name, Mode=TwoWay}"/>
        <TextBlock Grid.Row="1" Grid.Column="0" Text="Age" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Age, Mode=TwoWay}"/>
        <Button Content="Submit" Command="{Binding SubmitCommand}" HorizontalAlignment="Right" Grid.Row="2" Grid.Column="0"/>
        <sdk:DataGrid ItemsSource="{Binding Students}" Grid.Row="3" Grid.Column="0" Width="200" AutoGenerateColumns="False">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="Name"  Binding="{Binding Name}" Width="60"/>
                <sdk:DataGridTextColumn  Header="Age" Binding="{Binding Age}" Width="60"/>
                <sdk:DataGridTextColumn Header="Joining Date" Binding="{Binding JoiningDate, Converter={StaticResource MyConverter}}" Width="80" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
    </Grid>
</UserControl>


If you see the above XAML code, you can see I am using Windows resources in my view. In resources, I am adding a reference to my ViewModel and DateTimeToDateConverter.

ValueConverter

We might often get some values from the property but we have to display some other value in the View. Say for example in my project, the Joining date is a date time value but I need to display only date. I can do this either by String format in binding or else ValueConverter. I just want to go with the latter one, since you can understand ValueConverter also.
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Globalization;

namespace MVVMDemoinSL
{
    public class DatetimeToDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime date = (DateTime)value;
            return date.ToString("MM/d/yyyy");
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}


For implementing MVVM in WPF, please go through the following article.



Silvelight 6 Hosting - HostForLIFE.eu :: PopUp Control In Silverlight

clock April 23, 2021 10:40 by author Peter

Pop Up Control is a Visual Prompt Control provided in Silverlight. There are certain times when you need to really grab the user's attention. Maybe you need to display details about a critical error. Then you can just use this control. This visual prompt is designed to simulate a dialog box.
In our Sample Application we will just demonstrate how to use it.

Create a Silverlight Project

Figure 1.1 Creating Silverlight Project

Designing the Application
Here is an idea, we will add three images (ImageControls) to our application and on theirs LeftMouseButtonDown Event we will display the PopUp. So I have taken the help of Blend 3 to design the application. It will have 3 Images as Home, Search and Reports. The following figure displays our application.

Figure 1.2 Designing our Application

Adding a PopUp Control
This is actually disturbing; you can't find the control in the toolbox. But if you start typing the control name it will satisfy you. So I have added some controls like Border, StackPanel and Displaying Text and Button to close the PupUp.
    <Popup x:Name="myPopup" Margin="-34,0,-31,0" Grid.Row="2" Grid.Column="1" Height="78" VerticalAlignment="Bottom"  >    <Border CornerRadius="10" Background="Silver" BorderThickness="2" BorderBrush="Black">  
        <StackPanel Margin="10">  
                    <TextBlock x:Name="PopUpText"/>  
                    <Button x:Name="PopUpButton" Height="30" Width="90" Content="Close" Click="PopUpButton_Click" />  
        </StackPanel>  
        </Border>  
    </Popup>  


PopUp Control has a unique property called IsOpen which returns a boolean value of either true or false. The default value is always false. With this concept in mind let's add some events and use this property to control the show of the PopUp.

Calling the PopUp Control
As we discussed earlier we can handle the display of the PopUp by using the property IsOpen. Now we will see how we have used in our sample application.
    private void PopUpButton_Click(object sender, RoutedEventArgs e)  
    {  
          myPopup.IsOpen = false;  
    }  
      
    private void Home_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Home";  
          myPopup.IsOpen = true;  
    }  
      
    private void Search_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Search";  
          myPopup.IsOpen = true;  
    }  
      
    private void Reports_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    {  
          PopUpText.Text = "You Clicked Reports";  
          myPopup.IsOpen = true;  
    }  


Running the Application
When you click different images you will be notified by the PopUp Control.

Figure 1.3 PopUp is displayed

That's it, we have successfully used the PopUp Control. Enjoy Coding.



Silvelight 6 Hosting - HostForLIFE.eu :: How to Move Image or Object in Silverlight ?

clock December 18, 2020 08:25 by author Peter

The control that you just like drag or move with the mouse is embedded among a Border control then handle the mouse down, up and move events to create the object move among your layout panel.

See sample .xaml code:
<Canvas x:Name="LayoutRoot" Background="White">
<Border x:Name="border1"
Canvas.Top="100"
Canvas.Left="10"
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove"> 
<Image x:Name="MyImage" Source="images/Basket.png" Stretch="Uniform" ></Image>           
</Border>
</Canvas>


In the above code, a Border control is placed within the Canvas. The foremost necessary code to notice is:
MouseLeftButtonDown="border1_MouseLeftButtonDown"
MouseLeftButtonUp="border1_MouseLeftButtonUp"
MouseMove="border1_MouseMove"


The above lines outline 3 events that we tend to like to handle. because the name indicates, we are handling the mouse button down, mouse button up and mouse move events for the left mouse.

In the code behind, once the left button is pressed, we are going to set a global variable to point that user has started moving. within the mouse move event, we are going to get the current location of the mouse pointer and then set the new position for the border control. once the left mouse button is discharged, we are going to reset the global variable in order that we are going to not move the item from now on.
See the code for the code behind class:
public partial class Page : UserControl
{
// Global variable to indicate if user has clicked border
// and started/stopped moving.
private bool moving = false;
private double offSetX;
private double offSetY;
public Page()
{
InitializeComponent();
}

private void border1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Left mouse button clicked within border. start moving.
moving = true;

Point offset = e.GetPosition(border1);
offSetX = offset.X;
offSetY = offset.Y;
}

private void border1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// Left mouse button release. Stop moving.
moving = false;
}

private void border1_MouseMove(object sender, MouseEventArgs e)
{
if (moving)
{
    // Get the new mouse pointer position
    Canvas parent = (Canvas)this.border1.Parent;
    Point p = e.GetPosition(parent);
    double x = p.X - offSetX;
    double y = p.Y - offSetY;
    // Set the new position for the border control.
    this.border1.SetValue(Canvas.LeftProperty, x);
    this.border1.SetValue(Canvas.TopProperty, y);
}
}
}

HostForLIFE.eu Silverlight 6 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 :: Why Should I Use Silverlight?

clock November 27, 2020 07:04 by author Peter

Why should I use Silverlight? Why does Silverlight stand ahead of all other technologies?

Well!! When I began to write small applications using Silverlight, there were many questions in my mind.

Why do we use Silverlight? What would be the reason for Silverlight when there is ASP.NET, Windows apps, and the latest WPF.

I am trying to resolve these conflicts over here.

As per my working knowledge, Microsoft released ASP.NET and the Windows Application platform. It was a great revolution for the web and the internet world.

Windows applications are called thick clients and an ASP.NET Web application is called a thin client. Since a Windows application will be installed in the client machine, it is called a thick client. Whereas in a web application, there is no installation required on the client-side.

But, there were two problems the company/developer faced.

They needed to maintain two versions for Windows and web applications. i.e. the company has to maintain two versions of the same application. Because some clients want the same application in both a Windows version and a web version. So, it becomes a great headache for companies and developers. Since it was taking not only time for the UI design/Application layer but also for code-behind work.
 
Even though Ajax is a superb concept adapted to ASP.Net for animation like some of the visual effects, still there was difficulty achieving the same UI types for both web and Windows Applications.
 
Since there is a need for two versions of applications, there is a maintenance problem.
 
So later Microsoft came up with a new technology called "WPF". WPF was introduced with a new style of markup language called XAML. There are two types of applications; one is Web browser WPF and WPF application. A WPF web browser app runs in a browser and works as a web application and the other WPF application works as a Windows application. So a developer can use the same XAML for both versions.
 
The look and feel of both versions are the same and it provides a rich UI better than a normal ASP.Net and Windows application.

But, again there was a problem; that is, again the company/developer must maintain two versions of an application:

Web browser WPF.
Normal WPF (as Win form).

So, again Microsoft came up with a new and robust technology called "SILVERLIGHT". Silverlight falls in between thin and thick client concepts.

So, in Silverlight Microsoft has introduced Silverlight applications and Silverlight out-of-browser applications. Silverlight as an out-of-browser application provides the same effect as Windows applications. Even though its run's under the sandbox and doesn't have full pledge permissions as in Windows applications, still it has some of the permissions to access local resources.

So, there is no need to maintain two versions of applications. Any Silverlight application can be converted into an Out-Of-Browser app and as well as revert it into a web app. The app will have the power of the desktop but delivered by the web.

Next, let me cover some more extra futures of Silverlight:

Smart client
 
Already I have explained the smart client concept in my previous articles.
 
A smart client is nothing but, the application will be installed on the client, and whenever the application launches, downloads the latest and also is able to handle online as well as offline with the help of a local DB.
 
Service-oriented business applications
 
Socket Programming.
 
One of the most important things is socket programming in Silverlight. First of all, what are sockets?
 
Silverlight has built-in support for sockets which creates really very interesting possibilities.
 
Suppose, if I need to update on the client-side for each update in the server, then probably I should go for polling.
 
In this polling, the client contacts the server for each regular interval of time to get the updates.
 
Even though there is no update on the server, still the client checks for updates. So, this could cause a traffic overload or unnecessary server round trips.
 
How would it be, if there is a system which sends the updates from the server whenever the data is changed?
 
In this case, sockets are relevant. So, sockets are nothing but, a listener server to listen to clients.
 
By using this socket, a client can send data to the server as well as the server can send data to the client. So, it is a two-way transaction or duplex mode.
 
The .Net framework supports sockets in the namespace "System.net.sockets".
 
I will explain about socket programming in the next chapter.
 
While operating outside the sandbox of the browser.
 
There are some restrictions for the web application so that they can not get round in the browser because of security. We can't access the system, can't write the user's disk except for cookies and HTML 5 offline storage. Also can't access devices connected to the user machine.
 
By using a Silverlight Out –of – Browser app or elevated trust these restrictions can be lifted.
 
When an application needs to look exactly alike in all platforms.
 
There is no guarantee on HTML5/web applications about rendering over different browsers. So, if you want a pixel perfect app, then Silverlight would be the better option.
 
When there is a need to support multi-touch.

ASP.NET



Silverlight Hosting- HostForLIFE.eu :: How to Custom Events on Silverlight Controls ?

clock November 20, 2020 08:56 by author Peter

Today, I am going to tell you about Custom Events on Silverlight 5 controls. Generally when you employ or develop controls the events you employ are a lot of straight forward however this case, we possess a dial therefore the 'mouseover' or click is not actually need you would like. So exactly what we need is once the dial moves to some place we need the 'position changed' event called.

To start out along with you need a few custom event args as we wish to pass the 'angle' from the dial towards the event handler inside the consuming application. Therefore the custom event args appearance such as this:
public class DialEventArgs : EventArgs
{
private double angle;
public DialEventArgs(double _Angle)
{
this.angle = _Angle;
}
public double Angle
{
get
{
return angle;
}
}
}


During this case it is a fairly straight forward class which drives from eventargs so we add a constructor which lets us established the angle property simply. Next we would like in our own control class to outline the event such as this :
public delegate void PositionChangeHandler (Object Sender, DialEventArgs e);
public event PositionChangeHandler PositionChangedEvent;
protected virtual void OnPositionChanged(DialEventArgs e)
{
PositionChangedEvent(this, e);
}


Using this set up a consuming xaml page if they utilize the control can set an event handler for that event. However first we have to truly call the event once the angle in the dial changes : In the method which sets the angle we've this code :
OnPositionChanged(new DialEventArgs(AngleOfRotation));

Currently if you get an event handler set in xaml you will get the event called in the correct time. In xaml this may look such as this:
<cc:Dial x:Name="NewKnobControl" Height="100" Width="100" PositionChangedEvent="NewKnobControl_PositionChangedEvent" Minimum="45.0" Max="135" >
<cc:Dial.KnobFace>
<Grid >
<Ellipse Fill="Aquamarine" />
<Rectangle x:Name="Indicator" Height="10" Width="49" Fill="Blue" Margin="1,45,50,45" />
</Grid>
</cc:Dial.KnobFace>
</cc:Dial>


Now inside the client code you'll need an event handler and during this case inside my demo app it's similar to this :
private void NewKnobControl_PositionChangedEvent(Object sender, DialEventArgs e)
{
// applicable values
double Angle = e.Angle;
}



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