European Silverlight Hosting BLOG

BLOG about Latest Silverlight 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 :: Silverlight ImageBrush Example

clock November 9, 2018 11:15 by author Peter

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

ImageBrush is used to paint an area with the imagesource. The object contents can be made as an image using ImageBrush.

Namespace: System.Windows.Media
Assembly: System.Windows


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.


Adding an image in the solution:

Right click on the solution, select Add => New Folder.
Name the folder as Images and click OK.
Right click on the Images folder, select Add =>Existing Item.
Choose the image and click Ok.


Creating the UI:
Open MainPage.xaml file and replace the code with the following.
<UserControl x:Class="SilverlightImageBrush.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Canvas Height="200" Width="200" Background="White">
    <Rectangle Canvas.Left="50" Canvas.Top="50" Height="100" Width="100" >
        <Rectangle.Fill>
            <ImageBrush ImageSource="/SilverlightApplication6;component/Images/img7.png"/>
        </Rectangle.Fill>
    </Rectangle>     
</Canvas>
</UserControl>


Testing the solution:
Build the solution.
Hit ctrl+F5.
Rectangle control content  is filled with an image.

 

 



European Silverlight 6 Hosting - HostForLIFE.eu :: Cropping or Clipping in Silverlight

clock September 6, 2018 09:06 by author Peter

The Clip property of an element (defined in the UIElement class) is used to clip a region and represents the geometry that defines the content of an element.

The Clip property takes a Geometry type that can be a line, rectangle, ellipse, or group geometry.
The following XAML code snippet uses an Image object to display an image.
<Image Source="Waterfall.jpg"
           Width="300" Height="300">


The output looks like this

The XAML code in Listing 1 sets the Image.Clip property to an EllipseGeometry and sets the RadiusX, RadiusY, and Center properties of the geometry. 
<Image Source="Waterfall.jpg"
   Width="300" Height="300">
<Image.Clip>
    <EllipseGeometry
          RadiusX="100"
          RadiusY="100"
          Center="200,150"/>
</Image.Clip>
</Image>


The new output looks like this,

Figure 2. A clipped image

Since the Clip property is defined in the UIElement, it can be applied to any element. For example, the following code generates a rectangle looks like Figure 3.
<Rectangle Width="300" Height="200"
       Stroke="Black" StrokeThickness="4"

       Fill="Yellow">
<Rectangle.Clip>
    <EllipseGeometry
          RadiusX="150"
          RadiusY="100"
          Center="150,100"/>
</Rectangle.Clip>
</Rectangle>

Now we can apply clipping on the rectangle and the new output looks like Figure 4 with the following code.
<Rectangle Width="300" Height="200"
       Stroke="Black" StrokeThickness="4"
       Fill="Yellow">
<Rectangle.Clip>
    <EllipseGeometry
         RadiusX="150"
          RadiusY="100"
          Center="150,100"/>
</Rectangle.Clip>
</Rectangle>

 



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.



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