European Silverlight 4 & Silverlight 5 Hosting BLOG

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

European Silverlight 5 Hosting - HostForLIFE.eu :: Hyperlink in Silverlight

clock January 17, 2019 08:52 by author Peter

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

Creating a HyperlinkButton

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

The Width and Height attributes of the HyperlinkButton element represent the width and the height of a HyperlinkButton. The Content attribute represents the text of a HyperlinkButton.  The x:Name attribute represents the name of the control, which is a unique identifier of a control.

The code snippet in Listing 1 creates a HyperlinkButton control and sets the name, height, width, and content of a HyperlinkButton control.
<HyperlinkButton Width="200" Height="30"
     Content="C# Corner Link"
     Background="Black" Foreground="Orange"
     FontWeight="Bold">          
</HyperlinkButton>


Listing 1

The output looks like Figure 1.

The NavigateUri property of the HyperlinkButton represents the URI to navigate when the HyperlinkButton is clicked. The TargetName property represents the target window or frame to navigate within the page specified by the NavigateUri.

The code in Listing 2 sets the NavigateUri and TargetName properties of the HyperlinkButton control.
<HyperlinkButton Width="200" Height="30"
     Content="C# Corner Link"
     Background="Black" Foreground="Orange"
     FontWeight="Bold"
     x:Name="CCSLink"
     NavigateUri="http://www.hostforlife.eu"
     TargetName="_blank">          
</HyperlinkButton>


Listing 2
Formatting a HyperlinkButton
The Background and Foreground properties of the HyperlinkButton set the background and foreground colors of a HyperlinkButton. You may use any brush to fill the border. The following code snippet uses linear gradient brushes to draw the background and foreground of a HyperlinkButton.
<HyperlinkButton.Background>
    <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>
</HyperlinkButton.Background>

<HyperlinkButton.Foreground>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1" >                  
        <GradientStop Color="Orange" Offset="0.25" />
        <GradientStop Color="Green" Offset="1.0" />                  
    </LinearGradientBrush>
</HyperlinkButton.Foreground>

The new HyperlinkButton looks like Figure 2.

Setting Image as Background of a HyperlinkButton
To set an image as background of a HyperlinkButton, we can set an image as the Background of the HyperlinkButton. The following code snippet sets the background of a HyperlinkButton to an image.
<HyperlinkButton.Background>
    <ImageBrush ImageSource="dock.jpg" />
</HyperlinkButton.Background>


The new output looks like Figure 3.

Accessing and Setting HyperlinkButton Properties Dynamically
There are two ways to access a HyperlinkButton control dynamically from code. First, you can set a name of the control and use it like any other control.  The following code snippet creates a Hyperlink button and sets its name to HomeLink.
<HyperlinkButton Width="50.5" Height="18" x:Name="HomeLink"
      Content="HOME" Foreground="#FF383836"
      FontWeight="Bold" HorizontalAlignment="Left" Margin="125.5,102,0,0"
      VerticalAlignment="Top" GotFocus="HyperlinkButton_GotFocus"
                 MouseEnter="HyperlinkButton_MouseEnter"
                 MouseLeave="HyperlinkButton_MouseLeave"/>


Second way to access a control by using the event handler.

Let's set foreground property of a Hyperlink button dynamically on mouse over and mouse leave. I am going to change the foreground property to green on mouse over and back to gray again when mouse is not over.

The following code snippet shows how to set the foreground color in both ways.
private void HyperlinkButton_MouseEnter(object sender, MouseEventArgs e)
{
    HomeLink.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Green);
    //HyperlinkButton btn = (HyperlinkButton)sender;
    //btn.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Green);
}

private void HyperlinkButton_MouseLeave(object sender, MouseEventArgs e)
{
    HomeLink.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Gray);
    //HyperlinkButton btn = (HyperlinkButton)sender;
    //btn.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Gray);
}


Summary
In this article, I discussed how we can create a HyperlinkButton control in Silverlight and C#.  We also saw how we can format a HyperlinkButton by setting its background, and foreground properties. After that, we saw you to set an image as the background of a HyperlinkButton.

 



European Silverlight 5 Hosting - HostForLIFE.eu :: Canvas Control in Silverlight

clock December 19, 2018 10:38 by author Peter

This article demonstrates how to create a scale on a canvas. We can create a scale on a canvas control in Silverlight. For that we have created a custom control named Ruler Control in Silverlight.

Use this control on a canvas in our Silverlight application.

Step 1: Create a Ruler Control in Silverlight.
In RulerControl.Xaml file we have a canvas named LayoutRoot.
<Canvas x:Name="LayoutRoot" Background="White" />

Draw a line with the help of function in Silverlight. So we can add those lines on the canvas.

In RulerControl.Xaml.cs, we have a method which draws the lines on the canvas.
     public RulerControl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MyrulerControl_Loaded);
        }

        void MyrulerControl_Loaded(object sender, RoutedEventArgs e)
        {
            AddLine();
        }

        public void AddLine()
        {
            int count = 0;
            for (int i = 0; i <= 500; i++)
            {
                if (i == 0 || i % 50 == 0)
                {
                    Line l = new Line
                    {
                        Stroke = new SolidColorBrush(Colors.Black),
                        X1 = i,
                        Y1 = this.Height - 2,
                        X2 = i,
                        Y2 = this.Height - 2 - this.Height / 2
                    };
// Add lines in Canvas
                    LayoutRoot.Children.Add(l);

                    TextBlock tb = new TextBlock();
                    tb.Text = count.ToString();
                    tb.FontSize = 9;
                    tb.SetValue(Canvas.LeftProperty, (double)(i - 3));
                    tb.SetValue(Canvas.TopProperty, 15.5);
                    LayoutRoot.Children.Add(tb);
                    count++;

                }

                else if (i % 10 == 0)
                {
                    Line l = new Line
                    {
                        Stroke = new SolidColorBrush(Colors.Black),
                        X1 = i,
                        Y1 = this.Height - 2,
                        X2 = i,
                        Y2 = this.Height - 2 - this.Height / 4
                    };
                    LayoutRoot.Children.Add(l);
                }
 
            }
        }


Step 2: Use a RulerControl on another Silverlight page
Let's say we have MainPage.Xaml.
<x:Class="SilverlightApplication.MainPage">
<xmlns:rulerctrl="clr-namespace:SilverlightApplication.Controls">

<Canvas Height="27"  Name="canvas1"  Width="522" Background="White" Canvas.Left="27" >
 <rulerctrl:RulerControl Height="18" VerticalAlignment="Top"x:Name="firstruler"/>
</Canvas>


It looks like as below.
canvas control in silverlight

Step 3: Move button on canvas scale.
We can move the button on the canvas. Take one Button in the Canvas as follows.
<Grid x:Name="LayoutRoot" Background="White">
        <Canvas Height="27"  Name="canvas1"  Width="522" Background="White" VerticalAlignment="Top" MouseMove="canvas1_MouseMove">
            <rulerctrl:RulerControl Height="18" VerticalAlignment="Top" x:Name="firstruler"></rulerctrl:RulerControl>
            <Button Height="18" Width="20" Canvas.Left="61" Canvas.Top="34" x:Name="btnFirst" Content="F" Style="{StaticResource btnstyle }">
                <Button.RenderTransform>
                    <RotateTransform Angle="180"></RotateTransform>
                </Button.RenderTransform>
            </Button>
        </Canvas>
    </Grid>


Here we have MouseMove event of canvas. Using this we can move the button on canvas.
Like,
private void canvas1_MouseMove(object sender, MouseEventArgs e)
 {
     btnFirst.SetValue(Canvas.LeftProperty, e.GetPosition(canvas1).X);
 }


Output looks like as followingThis article demonstrates how to create a scale on a canvas. We can create a scale on a canvas control in Silverlight. For that we have created a custom control named Ruler Control in Silverlight. Use this control on a canvas in our Silverlight application.

Step 1: Create a Ruler Control in Silverlight.
In RulerControl.Xaml file we have a canvas named LayoutRoot.
<Canvas x:Name="LayoutRoot" Background="White" />

Draw a line with the help of function in Silverlight. So we can add those lines on the canvas.

In RulerControl.Xaml.cs, we have a method which draws the lines on the canvas.
     public RulerControl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MyrulerControl_Loaded);
        }

        void MyrulerControl_Loaded(object sender, RoutedEventArgs e)
        {
            AddLine();
        }

        public void AddLine()
        {
            int count = 0;
            for (int i = 0; i <= 500; i++)
            {
                if (i == 0 || i % 50 == 0)
                {
                    Line l = new Line
                    {
                        Stroke = new SolidColorBrush(Colors.Black),
                        X1 = i,
                        Y1 = this.Height - 2,
                        X2 = i,
                        Y2 = this.Height - 2 - this.Height / 2
                    };
// Add lines in Canvas
                    LayoutRoot.Children.Add(l);

                    TextBlock tb = new TextBlock();
                    tb.Text = count.ToString();
                    tb.FontSize = 9;
                    tb.SetValue(Canvas.LeftProperty, (double)(i - 3));
                    tb.SetValue(Canvas.TopProperty, 15.5);
                    LayoutRoot.Children.Add(tb);
                    count++;

                }

                else if (i % 10 == 0)
                {
                    Line l = new Line
                    {
                        Stroke = new SolidColorBrush(Colors.Black),
                        X1 = i,
                        Y1 = this.Height - 2,
                        X2 = i,
                        Y2 = this.Height - 2 - this.Height / 4
                    };
                    LayoutRoot.Children.Add(l);
                }
 
            }
        }


Step 2: Use a RulerControl on another Silverlight page
Let's say we have MainPage.Xaml.
<x:Class="SilverlightApplication.MainPage">
<xmlns:rulerctrl="clr-namespace:SilverlightApplication.Controls">

<Canvas Height="27"  Name="canvas1"  Width="522" Background="White" Canvas.Left="27" >
 <rulerctrl:RulerControl Height="18" VerticalAlignment="Top"x:Name="firstruler"/>
</Canvas>

It looks like as below.

canvas control in silverlight

Step 3: Move button on canvas scale.
We can move the button on the canvas. Take one Button in the Canvas as follows.
<Grid x:Name="LayoutRoot" Background="White">
        <Canvas Height="27"  Name="canvas1"  Width="522" Background="White" VerticalAlignment="Top" MouseMove="canvas1_MouseMove">
            <rulerctrl:RulerControl Height="18" VerticalAlignment="Top" x:Name="firstruler"></rulerctrl:RulerControl>
            <Button Height="18" Width="20" Canvas.Left="61" Canvas.Top="34" x:Name="btnFirst" Content="F" Style="{StaticResource btnstyle }">
                <Button.RenderTransform>
                    <RotateTransform Angle="180"></RotateTransform>
                </Button.RenderTransform>
            </Button>
        </Canvas>
    </Grid>


Here we have MouseMove event of canvas. Using this we can move the button on canvas.
Like,
private void canvas1_MouseMove(object sender, MouseEventArgs e)
 {
     btnFirst.SetValue(Canvas.LeftProperty, e.GetPosition(canvas1).X);
 }


Output looks like as following



European Silverlight 5 Hosting - HostForLIFE.eu :: How to Implement AutoComplete Text in Silverlight?

clock December 7, 2018 10:39 by author Peter

Introduction

Silverlight is evolving with a lot of new features in each and every version release. The AutoComplete text feature is one such example. In this article I will demonstrate the implementation of the AutoComplete text feature in a Silverlight application. I will also create a sample Silverlight application to help explain the code. I have used Silverlight 4.0 and Visual Studio 2010 for developing the sample application.

AutoComplete Functionality

AutoComplete text functionality is not only a fancy effect but it's also a pretty useful feature from a user prospective and this feature is available in most of the latest applications. As the user enters text in a text box, a list of values gets populated and are listed in a similar fashion to that of a drop down based on the entered text. So the user is able to see the possible suggestions and can select a value from them or they also have the freedom to enter their own text as the base control is a textbox.

Some popular websites implementing the auto complete functionality are www.google.com,www.youtube.com, etc.,

Silverlight AutoCompleteBox Control

Implementing the autocomplete functionality in a Silverlight application is pretty straight forward because of the availability of the AutoCompleteBox control. This control is available in Silverlight 3.0 and higher versions. The developer only needs to set the ItemSource property of the AutoCompleteBox control with the value collection that is to be listed. The rest will be taken care by the control itself. 

Below are some of the useful settings that can be leveraged from the AutoCompleteBox control.

  1. FilterMode – Specifies the filter mode to display the data (StartsWith, Contains, Equals, etc.,)
  2. MinimumPrefixLength – Minimum prefix length for the auto complete feature to be triggered
  3. MaxDropDownHeight – Maximum height of the dropdown
  4. IsTextCompletionEnabled – If set to true then the first match found during the filtering process will be populated in the TextBox

 

Silverlight AutoCompleteBox Implementation

In this section we will create a sample Silverlight window implementing the autocomplete text feature. In the MainWindow.xaml add an AutoCompleteBox control and set the basic properties. Below is the code:

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  
    x:Class="AutoCompleteBoxSample.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">
        <Canvas>
            <sdk:Label Content="Enter the city: " Margin="46,76,264,198" />
            <sdk:AutoCompleteBox Height="28" H
orizontalAlignment="Left" Margin="142,77,0,0" FilterMode="StartsWith"
MinimumPrefixLength="1" MaxDropDownHeight="80" Name="autoCompleteBox1" VerticalAlignment="Top" Width="120"
Canvas.Left="-6" Canvas.Top="-5" />
        </Canvas>
    </Grid>
</UserControl>

namespace AutoCompleteBoxSample
{
    public partial class MainPage : UserControl
    {
        List<string> _cities;

        public MainPage()
        {
            InitializeComponent();
            autoCompleteBox1.ItemsSource = PopulateCities();
        }

        private IEnumerable PopulateCities()
        {
            _cities = new List<string>();
            _cities.Add("Boston");
            _cities.Add("Bangalore");
            _cities.Add("Birmingham");
            _cities.Add("Auckland");
            _cities.Add("Amsterdam");
            _cities.Add("Aspen");
            return _cities;
        }
    }
}

Run the application and you will see the figure below:

 

 

Using a DomainDataSource

In the above case we had the data directly in the application and it was hence hard-coded. In case if the data lies in the database, then the WCF RIA service and the DomainDataSource comes into play. Create a WCF RIA service and hook up the service to expose the data in the table through a generated data context method. Use a DomainDataSource to act as an ItemSource for the AutoCompleteBox control.

Below is the XAML code:

<Canvas>
     <riaControls:DomainDataSource AutoLoad="True"
                                      QueryName="GetCities"
                                      x:Name="CityDataSource">
          <riaControls:DomainDataSource.DomainContext>
                    <web:MyDatabaseContext />
          </riaControls:DomainDataSource.DomainContext>
     </riaControls:DomainDataSource>
     <sdk:Label Content="Enter the city: " Margin="46,76,264,198" />
<sdk:AutoCompleteBox Height="28" ItemsSource="{Binding Data, ElementName=CityDataSource}"
HorizontalAlignment="Left" Margin="142,77,0,0" FilterMode="StartsWith" MinimumPrefixLength="1" MaxDropDownHeight="80"
Name="autoCompleteBox1" VerticalAlignment="Top" Width="120" Canvas.Left="-6" Canvas.Top="-5" />
</Canvas>



European Silverlight 6 Hosting - HostForLIFE.eu :: Updating the XAP Configuration Programmatically

clock August 23, 2018 11:30 by author Peter

One of the bigger annoyances dealing with programming in Silverlight 6 is the deployment of XAP files. In order to properly update a XAP file you typically:

1. Rename XAP file to a ZIP file.

2. Extract the ServiceReferences.ClientConfig file.

3. Update the configuration file with the proper IP information.

4. Update the ZIP file and save.

5. Rename ZIP file back to XAP.

So, how do we do that with code so we can skip this frustration? Let’s first look at a few factors:

We are using the .Net 4.0 Framework. Don’t bother using System.IO.Packaging.ZipPackage. It thinks XAP files are always corrupt. It’s annoying. We are just updating the IP information. First, let’s look at how we update the configuration file if it was committed to a MemoryStream. In this snippet we:

1. Grab all the contents from the MemoryStream.

2. Replace the IP information in the content.

3. Clear the MemoryStream.

4. Overwrite the stream contents with the new content.

5. Reset the position in the stream to 0.

/// <summary>
/// Updates the configuration file
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="replacementIp">The replacement ip.</param>
/// <param name="destinationIp">The destination ip.</param>
/// <returns></returns>
private bool UpdateConfigurationFile(MemoryStream stream,
    string replacementIp, string destinationIp)
{
    bool isSuccessful = false;
    try
    {
        // Read current file
        var reader = new StreamReader(stream);
        stream.Position = 0;
        var contents = reader.ReadToEnd();       
        // Update IP information
        var newContents = contents.Replace(replacementIp, destinationIp);
        // Reset contents of stream
        stream.SetLength(0);
        // Overwrite original configuration file
        var writer = new StreamWriter(stream);
        writer.Write(newContents);
        writer.Flush();
        // Set position in stream to 0.
        // This allows us to start writing from the beginning of the stream.
        stream.Seek(0, SeekOrigin.Begin);
        // Success
        isSuccessful = true;
    }
    catch (Exception)
    {
    }
    // return
    return isSuccessful;
}

Our main method below does this:

- Extract the ServiceReferences.ClientConfig file.
- Call the UpdateConfigurationFile method above to revise the IP information.
-  Update the ZIP file and commit the changes.
/// <summary>
/// Updates the silverlight configuration file.
/// </summary>
/// <param name="configFileName">Name of the config file.</param>
/// <param name="xapFilePath">The xap file path.</param>
/// <param name="replacementIp">The replacement ip.</param>
/// <param name="destinationIp">The destination ip.</param>
/// <returns></returns>
private bool UpdateSilverlightConfigurationFile(string configFileName,
    string xapFilePath, string replacementIp, string destinationIp)
 {
    // Check file path
    if (!File.Exists(xapFilePath)) { return false; }
    // Open XAP and modify configuration
   using (var zip = ZipFile.Read(xapFilePath))
    {
        // Get config file
        var entry = zip[configFileName];
        var stream = new MemoryStream();
        entry.Extract(stream);
        // Manipulate configuration
        var updated =
            UpdateConfigurationFile(stream, replacementIp, destinationIp);
        // Evaluate
        if (updated)
        {
            // Replace existing configuration file in XAP
            zip.UpdateEntry(configFileName, stream);
            zip.Save();
        }
    }
    // return
    return true;
}

So, let’s look at the code in it’s entirety so that we get an implementation example as well as the needed includes:
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Ionic.Zip;
namespace XAPFileUpdaterTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            // Intialize UI
            InitializeComponent();
            // Parameters
            string configFile = "ServiceReferences.ClientConfig";
            string xap = @"MyAwesomeApp.xap";
            string replacementIp = "127.0.0.1";
            string destinationIp = "12.23.45.67";
             // Check
            var isClientConfigUpdated =
                UpdateSilverlightConfigurationFile(
                   configFile, xap, replacementIp, destinationIp); 
            // Setup message
            var message =
                (isClientConfigUpdated) ? "was successful" : "failed"; 
            // Notify user
            MessageBox.Show("The current update " + message);
        }
        /// <summary>
        /// Updates the configuration file.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="replacementIp">The replacement ip.</param>
        /// <param name="destinationIp">The destination ip.</param>
        /// <returns></returns>
        private bool UpdateConfigurationFile(MemoryStream stream,
            string replacementIp, string destinationIp)
        {
            bool isSuccessful = false;
           try
            {
                // Read current file
                var reader = new StreamReader(stream);
                stream.Position = 0;
                var contents = reader.ReadToEnd();
                // Update IP information
                var newContents = contents.Replace(replacementIp, destinationIp);
                // Reset contents of stream
                stream.SetLength(0);
                // Overwrite original configuration file
                var writer = new StreamWriter(stream);
                writer.Write(newContents);
                writer.Flush();
                // Set position in stream to 0.
                // This allows us to start writing from the beginning of the stream.
                stream.Seek(0, SeekOrigin.Begin);
                // Success
                isSuccessful = true;
            }
            catch (Exception)
            {
            }
            // return
            return isSuccessful;
        }
        /// <summary>
        /// Updates the silverlight configuration file.
        /// </summary>
        /// <param name="configFileName">Name of the config file.</param>
        /// <param name="xapFilePath">The xap file path.</param>
        /// <param name="replacementIp">The replacement ip.</param>
        /// <param name="destinationIp">The destination ip.</param>
        /// <returns></returns>
        private bool UpdateSilverlightConfigurationFile(string configFileName,
            string xapFilePath, string replacementIp, string destinationIp)
        {
            // Check file path
            if (!File.Exists(xapFilePath)) { return false; } 
            // Open XAP and modify configuration
            using (var zip = ZipFile.Read(xapFilePath))
            {
                // Get config file
                var entry = zip[configFileName];
               var stream = new MemoryStream();
                entry.Extract(stream);
                // Manipulate configuration
                var updated =
                    UpdateConfigurationFile(stream, replacementIp, destinationIp);
                // Evaluate
                if (updated)
                {
                    // Replace existing configuration file in XAP
                    zip.UpdateEntry(configFileName, stream);
                    zip.Save();
                }
            }
           // return
            return true;
        }
    }
}

That’s all for now. I hope I helped you with this annoyance.



European Silverlight 6 Hosting - HostForLIFE.eu :: Tic Tac Toe, Silverlight Drawing Basics

clock August 16, 2018 11:32 by author Peter

Silverlight is being on high recognition in the industry and it is really cool! In this article I am trying to create a marker control that allows the user to mark certain areas on the image canvas.  This will work as the drawing board for our Tic Tac Toe game.  We can see the usage of Canvas and its Children property applied with the Line class.

The application provides with a layer of buttons on choosing the pen, eraser or the color selector.  The board is represented by a Canvas class.

Canvas
In this application, the Canvas instance serves as our main drawing board.  The canvas is named BoardCanvas.  The drawings over the canvas are captured as Line objects and added to the Children property of the canvas.  The Children property accepts of type UIElement.

Line
The Line instances are used whenever the user marks over the board.  For each stroke a number of line objects are created to represent the stroke.  The user can choose two colors from the screen.
Repeating  that the line objects are created and added to the Children property of the canvas.

Delete
The delete functionality allows the user to delete the line under mouse cursor position.  This helps the user to remove an unwanted line.

The functionality is implemented by taking the mouse X, Y position and parsing through the line collection.  Each line's X, Y will be checked with the mouse positions and if a match found, the line is deleted from the canvas object.

Clear
There is a Clear button on the screen that will clear the board canvas. This will quickly help the user to restart the game.

The functionality is implemented by clearing all the lines from the canvas Children property.

Functionality Explained

The enumeration Mode is used to represent the active drawing mode of the application.  When the application starts, the default mode will be Draw.
public enum Mode
{
    None,
    Draw,
    Delete
}

When the user presses the Pen button, the mode will be set to Draw.

private void PenButton_Click(object sender, RoutedEventArgs e)
{
    _mode = Mode.Draw;
}


When the user presses the Delete button, the mode will be set to Delete.
private void Delete_Click(object sender, RoutedEventArgs e)
{
    _mode = Mode.Erase;
}

When the user presses, the Clear button, there is no mode change – the ClearAll() method is called.  The ClearAll() method will clear the Children property of the canvas and resets the mode to Draw. There is a private variable _lines which is used to hold all the lines of the drawing.
private void ClearAll()
{
    foreach (Line line in _lines)
        BoardCanvas.Children.Remove(line);
    _lines.Clear();
    _mode = Mode.Draw;
}



European Silverlight 6 Hosting - HostForLIFE.eu :: Using Static Resource in Silverlight

clock August 9, 2018 09:19 by author Peter

In this article we will discuss more about using and managing Static Resource in Silverlight. Static Resource is nothing but a Resource which is defined and cannot be changed but can be used multiple times.

Steps to Bind Static Resource
Define the respective Namespaces
Define the instance in ResourceDictionary and give a name to it's x:key
To Bind to it, use the {StaticResource} markup extension.

Binding to a Static Resource of Simple String
Create a Silverlight Application and add two TextBoxes.

In the xaml code behind add the namespace:
xmlns:sys="clr-namespace:System;assembly=mscorlib"

Now add a String resource as described below:
<UserControl.Resources>
    <sys:String x:Key="SingleString">Hello World</sys:String>
</UserControl.Resources>


As we discussed earlier it can be used multiple number of times. We will use it in both TextBoxes:
<Grid>
  <TextBlock Margin="0,0"
             Text="{Binding Source={StaticResource SingleString}}" />
  <TextBlock  Margin="0,16" Text="{Binding Source={StaticResource SingleString}, Path=Length}"/>
</Grid>


Path is an attribute using which we can refer to a property of Static Resource.
Binding to a Static Resource of a single instance of a Custom Class
Create a Silverlight Application and add a class; name it as Users.cs.

Now define the class using the following properties:
public class Users
{
public string FirstName { get; set; }
public string LastName { get; set; }}


To use it in xaml first define the namespace:
xmlns:local="clr-namespace:StaticResourceSL3"

And then add the resources as follows:
<UserControl.Resources>
    <local:Users x:Key="SingleUser" FirstName="Diptimaya" LastName="Patra"/>
</UserControl.Resources>


To bind it to follow the earlier instructions and use Path attribute to use the property:
<TextBlock Text="{Binding Source={StaticResource SingleUser}, Path=FirstName}"/>

Binding to a Static Resource of a Collection of Custom Instances

We will follow the above example i.e. we will use the same class Users.cs. We will add another class called UserList which will inherit List of Users. As follows:
public class Users
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UsersList : List<Users>
{
public UsersList
{
this.Add(new Users() { FirstName = "John", LastName = "Lock"});
this.Add(new Users() { FirstName = "James", LastName = "Soyer"});
this.Add(new Users() { FirstName = "Jack", LastName = "Sephered"});
}}


As usual add the namespace to have a reference of the class.

Now add the Resources to xaml code behind:
Before that refer to this assembly.
xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
<UserControl.Resources>
<local:UsersList x:Key="UsersList"/></UserControl.Resources>


Now bind the Static Resource to a ListBox's ItemSource as follows:
<ListBox  Margin="0,135,0,50" ItemsSource="{StaticResource UsersList }"/>

Or you can bind the FirstName attribute as follows:
<ListBox  Margin="0,60,0,120" >
<ListBox.ItemsSource>
        <Binding Source="{StaticResource somePersons}" />
</ListBox.ItemsSource>
        <ListBox.ItemTemplate>
                    <DataTemplate>
<TextBlock Text="{Binding Path=FirstName}"></TextBlock>
                     </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>


Binding to a Static Resource of a Collection of Strings

Now assume that you need a collection of strings to be added to a ListBox or to a AutoCompleteBox, how will you do it:

Create a class and name it as ObjectCollection and add the following constructors:
public partial class ObjectCollection : Collection<object>
{
public ObjectCollection()
{
}
public ObjectCollection(IEnumerable collection)

{
  foreach (object obj in collection)
 {
    Add(obj);
 }
}
}

Now in xaml code behind add the Resources as follows:
<UserControl.Resources>
 <controls:ObjectCollection x:Key="SampleData">
    <sys:String>User 1</sys:String>
    <sys:String>User 2</sys:String>
    <sys:String>User 3</sys:String>
 </controls:ObjectCollection>
</UserControl.Resources>


Now you can use it as the ItemSource of a ListBox or AutoCompleteBox or others:
<ListBox  Margin="0,135,0,50" ItemsSource="{StaticResource SampleData}"/>
That's it you have successfully used Static Resources



European Silverlight 6 Hosting - HostForLIFE.eu :: Silverlight UserControl Custom Property Binding

clock August 7, 2018 12:00 by author Peter

In this article we will be seeing how to create a Custom Silverlight UserControl and Binding the Property. We will use a dependency Property in this example.

Created a Project as SamplePro.
Added an a new User Control as MyNewControl.

Dependency Property:
Now let's add a dependency property. To know more about DP, check out this site:
http://msdn.microsoft.com/en-us/library/cc221408(v=vs.95).aspx

My dependency property code looks as follows:
//  Dependency Property - Begin
        public const string DisplayTextPropertyName = "DisplayText";
        public string DisplayText
        {
            get
            {
                return (string)GetValue(DisplayTextProperty);
            }
            set
            {
                SetValue(DisplayTextProperty, value);
            }
        }
        public static readonly DependencyProperty DisplayTextProperty = DependencyProperty.Register(
DisplayTextPropertyName,typeof(string), typeof(MyNewControl),new PropertyMetadata(String.Empty));
//  Dependency Property - End


The UserControl MyNewControl looks as below:
public partial class MyNewControl : UserControl
    {
//  Dependency Property - Begin
        public const string DisplayTextPropertyName = "DisplayText";
        public string DisplayText
        {
            get
            {
                return (string)GetValue(DisplayTextProperty);
            }
            set
            {
                SetValue(DisplayTextProperty, value);
            }
        }
        public static readonly DependencyProperty DisplayTextProperty = DependencyProperty.Register(
DisplayTextPropertyName,typeof(string), typeof(MyNewControl),new PropertyMetadata(String.Empty));
//  Dependency Property - End
        public MyNewControl()
        {
            InitializeComponent();
            btn.SetBinding(Button.ContentProperty, new Binding() { Source = this, Path = new PropertyPath("DisplayText"), Mode = BindingMode.TwoWay });
        }
    }


MyNewControl is ready for use as shown below:
<UserControl x:Class="SamplePro.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:SamplePro"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <local:MyNewControl Width="300" Height="300"  Foreground="Black" x:Name="newcontrol" DisplayText="Hit Me Now !!!"> </local:MyNewControl>
    </Grid>
</UserControl>


Let's give it a run:



European Silverlight 6 Hosting - HostForLIFE.eu :: PasswordBox control in Silverlight using C#

clock July 31, 2018 11:15 by author Peter

PasswordBox control
PasswordBox control is used to hide the characters a user is typing for privacy and security reasons. It is essential to use this control whenever you are receiving a password from a user.

Creating a Password in XAML
<PasswordBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="PasswordBox1" VerticalAlignment="Top" Width="120" />
The Width and Height attributes of the PasswordBox element represent the width and the height of a Password. The Name attribute represents the name of the control, which is a unique identifier of a control. The default view of the PasswordBox control looks like this.


Creating a PasswordBox control at run time
PasswordBox pwd = new PasswordBox();    
pwd.Height = 30
pwd.Width = 200
pwd.MaxLength = 25
pwd.PasswordChar = "*"
LayoutRoot.Children.Add(pwd)


Properties - These are the following properties of the PasswordBox control.

  • Width - The Width property of the Passwordbox control represent the width of a PasswordBox.
  • Height -  The Height property of the Passwordbox control represent the width of a PasswordBox.
  • MaxLength - The MaxLength property is used to get and set the maximum number of characters you can enter in a PasswordBox.
  • Password property - The Password property is used to get and set the current password in a PasswordBox.
  • PasswordChar - PasswordChar property is used to get and set the masking character for the PasswordBox. The default masking character is a dot(.).
  • VerticalAlignment - VerticalAlignment is used to Gets or sets the vertical alignment characteristics applied to this element when it is composed within a parent element such as a panel or items control.
  • HorizontalAlignment - HorizontalAlignment is used to Get or set the horizontal alignment characteristics applied to this element when it is composed within a parent element.
  • Name - Name property is used to Get and set the identifying name of the element.


Using the property PasswordChar
The default masking character is a dot(.) but we can change masking character . to * or other char. For example we change property PasswordChar =* and then enter password in the box. It will looks like this.
Output looks like this.

Using MaxLength property
The maxLenth property Defines the maximum number of character that we enter in the PasswordBox control. For example - suppose we sets the MaxLenth property = 6 then it will take only 6 char after 6 char it will stop to take character automatically.
Output looks like this.

fig3.gif

Using Background property
Set the background property to display the background color of the control. Output looks like this.

We can also select a background image in PasswordBox control.

<PasswordBox.Background>
<ImageBrush ImageSource="/SilverlightApplication34;component/Images/flowers-image.jpg" />
</PasswordBox.Background>


Using foreground property
Set the Foreground property to display the char color of the control.
Output looks like this.



European Silverlight 6 Hosting - HostForLIFE.eu :: Creating a Beautiful Splash Screen For Silverlight Applications

clock July 26, 2018 08:18 by author Peter

There are many other great articles and blog posts on how to create simple Silverlight Splash Screens. This article adds on top of them and helps you design a more complex splash screen with Story Boards and Floating Text Blocks. I am not a great designer and thus I am taking a design que from Telerik's Silverlight Demos splash screen. They have some amazing designers and their splash screen is an amazing example of that. If you have not already noticed it please visit http://demos.telerik.com/silverlight/ and have a look yourself. We will try to replicate the same behavior in our splash screen. Here is a step-by-step guide to do this.

1. Create your XAML
In order to add the splash screen you will first need to add a new Silverlight 1.0 JavaScript (we will refer to it as SLJS for the sake of writing simplicity) page on your server side code.

Since you cannot modify this file in Blend, I created a new Silverlight project and created a new Silverlight User control in it.
Once I had completed the design of this page in Blend, I copied the content to the Silverlight JS page on the server side.
I had to make a few modifications that are listed below.

  • First delete the x:class namespace as that is not supported on a SLJS page
  • Also delete the underlying code file (in my case it was SplashScreen.xaml.cs)
  • I added a storyboard animation to float the text from left to right

<Grid.Resources>
  <Storyboardx:Name="sb1"RepeatBehavior="1x"Completed="onCompleted">
    <DoubleAnimationDuration="0:0:5"To="255"
    Storyboard.TargetProperty="X"Storyboard.TargetName="myTranslate"d:IsOptimized="True"/>
  </Storyboard>
</Grid.Resources>

 
Based on your design, the following content may change (I designed it to match the same as Telerik's splash page):
<Grid Background="#FFF4F4F4" RenderTransformOrigin="0.5,0.5"> <Grid.RowDefinitions> <RowDefinition Height="120"/> <RowDefinition Height="32"/> <RowDefinition Height="8"/> <RowDefinition Height="20"/>
 <RowDefinition Height="375*"/> </Grid.RowDefinitions> <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Grid.Row="0" Text="Silverlight" VerticalAlignment="Top" Height="153" Width="806" FontSize="133.333"
Foreground="#FFEEEEEE" Grid.RowSpan="3"/> <!--<StackPanel Orientation="Horizontal" Grid.Row="1" Margin="100,0,0,0" >
<Image Source="/Content/np_logo.PNG" Margin="0,0,5,0" Width="32" />
<TextBlock Text="Netpractise" FontSize="26.667" Foreground="Black"  FontFamily="Moire Light" x:Name="editing" FontWeight="ExtraBold" Height="32"/>
</StackPanel>--> <Image Source="/Content/np.PNG" Grid.Row="1" Margin="100,0,0,0" HorizontalAlignment="Left" /> <Rectangle Height="5" Fill="#FFA0DA0A" Width="200" HorizontalAlignment="Left"  Margin="100,0,0,0"
Grid.Row="2"/> <!--<TextBlock Text="digital communication innovation" Loaded="onTextBoxDigitalLoaded" Margin="100,0,0,0"  HorizontalAlignment="Left" FontFamily="Moire" FontSize="13.333" Height="16" Grid.Row="3"/>-->
<Image Source="/Content/baseline.PNG"  Margin="100,0,0,0" Width="300"  HorizontalAlignment="Left" Grid.Row="3"/> <!-- Progress bar--> <Rectangle Fill="#FF24A9F3" Height="5" HorizontalAlignment="Left" x:Name="uxProgress"
Grid.Row="2"/> <!--floating text boxes--> <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="Be it Videos, Images, Flash or Audio we support all."
VerticalAlignment="Center" Grid.Row="4" Height="400"
Width="510" Foreground="#FF24A9F3" FontSize="48" FontFamily="Segoe WP Light" RenderTransformOrigin="0.5,0.5"
Loaded="onTextBoxLoaded" Margin="20,0,0,0"> <TextBlock.RenderTransform> <TransformGroup> <TranslateTransform x:Name="myTranslate"/> </TransformGroup> </TextBlock.RenderTransform> <!--The story board can be placed
within this to run from XAML or JS functions can be used.--> <!--<TextBlock.Triggers>
<EventTrigger RoutedEvent="TextBlock.Loaded">
<BeginStoryboard>
</BeginStoryboard>
</EventTrigger>               
</TextBlock.Triggers>--> </TextBlock> <TextBlock x:Name="txtProgressPercentage" Grid.Row="4" HorizontalAlignment="Right" Margin="0,-150,-170,0" VerticalAlignment="Center" TextWrapping="Wrap" Height="358" Width="651"
FontSize="300" Foreground="#FFE4E4E4"/> </Grid>


2. Code the logic in JavaScript file
When you add a new SLJS page in your application, it also creates an underlying .js file where you can write your code logic.
All I had to do was to create 3 functions in it ; they are:

onSourceDownloadProgressChanged

This is to update the progress bar and the big textblock that shows % update in numbers.
var i = 0;
function onSourceDownloadProgressChanged(sender, eventArgs)
{
sender.findName("txtProgressPercentage").Text = Math.round(Math.round((eventArgs.progress * 1000)) / 10, 1).toString();
//get browser width   var width = window.document.body.clientWidth;
sender.findName("uxProgress").Width = (width * eventArgs.progress);
}
 

onTextBoxLoaded
This is to trigger the first story board.
function onTextBoxLoaded(sender, eventArgs)
{
// Retrieve the Storyboard and begin it.     sender.findName("sb1").begin();
}


onCompleted
This is to change the Text of the floating Text box and start the Storyboard again with updated text.
function onCompleted(sender, eventArgs)
{
try{
i++;
sender.findName("myTranslate").X = 0;
switch (i) {
case 1:
sender.findName("textBlock").Text = "This is my first content";
break;
case 2:
sender.findName("textBlock").Text = "This is my second content";
break;
case 3:
sender.findName("textBlock").Text = "This is my third content.";
break;
case 4:
sender.findName("textBlock").Text = "This is my fourth content";
break;
case 5:
sender.findName("textBlock").Text = "This is my fifth content.";
break;
case 6:
sender.findName("textBlock").Text = "This is my sixth content";
i = 1;
break;
}
}catch(e){
}
sender.findName("sb1").begin();


I have 6 text block contents that show up on the screen one by one. You can have as many as you want and can also pull them from a collection if that's what you need.

3. Updating the Default.html or Default.aspx page
This is an important and the last step to hook the splash screen we created to our Silverlight application.
Just add a few parameters and a link to the JavaScript file just below the </head> tag.
<script type="text/javascript" src="splashscreen.js"></script>

The following new parameters go in <div id="silverlightControlHost">:
<param name="splashscreensource" value="SplashScreen.xaml" /> <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />

The first parameter just tells your app which splash screen to load at startup and the second one calls the js function that eventually updates the progress bar and % progress textblock with numbers.



European Silverlight 6 Hosting - HostForLIFE.eu :: Fixing Win32 Unhandled Exception in Silverlight Web App

clock July 24, 2018 08:49 by author Peter

Today while testing we encountered a strange scenario in our Silverlight Web App. We were getting a System Win 32 error when running the deployed application. unfortunately the error was not reproducible when running the app in debug (F5) mode.

Here is a snapshot of the exception message.

When starting a new instance of Visual Studio to debug this JIT issue all we got was that there was a Stack Overflow causing this issue. But that's all; no source code or stack trace to pinpoint the exact code that was causing the trouble.

How often do you get in a scenario where you can see a bug in deployed or published code but not in debug mode giving you no option to pinpoint the exact code causing the trouble? Believe me, it happens to me all the time.
 
I pop-in many Message Boxes in the methods that I feel could be erroneous & keep deleting them when I am sure that the method is not the one I am looking for.
 
Returnng to the issue today, I have a record in my Silverlight Grid, which when double-clicked should open a child window having the details & this part of the code was the culprit. Feels great to zero-in & find the guilty.
 
So the problem is in the child window looking forward tells me it's a TextBox that has the ValidatesOnDataErrors property set to true.

Here was how it was layed out on the screen:
<TextBox Text="{Binding ProfileName,ElementName=RadWinEditMenuProfile, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True,ValidatesOnDataErrors=True, TargetNullValue=''}"
 x:Name="txtBoxProfile" MaxLength="50" />
 
Notice the  ValidatesOnDataErrors=True property.
So next step was to remove it & Voila! It worked. No error this time.  But wait, we have that property set for a reason. We want to force the TextBox to show an error on all data validation errors. Having that figured out I knew the next thing we need to look into was the code that was doing the data validation.

Here is the code used for it:
Public ReadOnly Property [Error] As String Implements System.ComponentModel.IDataErrorInfo.Error
    Get
        Return _Errors
    End Get
End Property

Default Public ReadOnly Property Item(propertyName As String) As String Implements System.ComponentModel.IDataErrorInfo.Item
    Get
        Select Case propertyName
            Case "ProfileName"
                If String.IsNullOrWhiteSpace(ProfileName) = False Then
                    'ProfileName = ProfileName.Trim
                    If context.MenuProfiles.Any(Function(t) t.Id <> SelectedProfile.Id AndAlso t.ProfileName.ToLower.Trim = ProfileName.ToLower.Trim) Then
                        _Errors = _ErrorsText
                        Return "Profile Name is already in use."
                    ElseIf Regex.IsMatch(ProfileName.ToLower.Trim, CustomDeclaration.REG_NAME) = False Then
                        _Errors = _ErrorsText
                        Return CustomDeclaration.INVALID_NAME
                    End If
                End If
                Exit Select
        End Select
        Return Nothing
    End Get
End Property
Private _ProfileName As String
Public Property ProfileName() As String
    Get
        Return SelectedProfile.ProfileName
    End Get
    Set(ByVal value As String)
        _ProfileName = value
        SelectedProfile.ProfileName = value
        NotifyPropertyChanged("ProfileName")
    End Set
End Property

This is a standard implementation of IDataErrorInfo, so I will not get into the gory details of it and go directly to the code that was the issue.
Note that I have commented-out the line:
'ProfileName = ProfileName.Trim
 
This was the exact line of code causing the issue. I was trimming the property & then assigning it back, that in turn was calling the setter of the property & that in turn was calling the validation again.
 
Evidently, these two caused an infinite loop L L Not a good deal. This was the reason why we were getting the Stack Overflow error.  Commenting out that line & using trim wherever we were actually using the property.

For example:
Changed ProfileName.ToLower to ProfileName.ToLower.Trim fixed the issue once & for all. Nice & Cool.
 
So the next time you hit a stack overflow in your published code try to pin point the code & check if you are not implementing IDataErrorInfo or any other 2 properties that are dependent on each other like I was implementing it.



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