European Silverlight Hosting BLOG

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

Silverlight Hosting- HostForLIFE.eu :: Why Should I Use Silverlight?

clock November 27, 2020 07:04 by author Peter

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

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

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

I am trying to resolve these conflicts over here.

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

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

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

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

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

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

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

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

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

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

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

ASP.NET



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

clock November 20, 2020 08:56 by author Peter

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

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


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


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

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


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



Silverlight Hosting - HostForLIFE.eu :: How to Use C# to Deploy AutoComplete Textbox?

clock October 9, 2020 09:32 by author Peter

In this article, you will implement an AutoComplete TextBox in Silverlight Applications using C#. An AutoCompleteBox is just a kind of TextBox in which, when you start typing, items that match are displayed in a dropdown list and you can pick an item from the list.

Step 1

Create a New “Silverlight Application” in Visual Studio and name it as you chooce (I named mine AutoCompleteBox). Now a new Silverlight Application Page (MainPage.xaml) will be generated.

Step 2

Now go to the Solution Explorer Window and right-click on "References" and click on "Add Reference".

Step 3

Now an "Add Reference" window will appear. Navigate to the .NET tab and search for System.Windows.Controls.Input reference and add it to your project.

Step 4

Now navigate to the MainPage.xaml portion in your project and add the following code for the reference:

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

Step 5

A reference is added to your project and now it's time to add the AutoCompleteBox. Navigate to the XAML code and in the Grid tag add the following code:

<sdk:AutoCompleteBox Name="Colors" Width="200" Height="25"/>

An AutoCompleteBox is added to your project (here I named it Colors but it's up to you what to use).

Step 6

Now it's time to add some data in the AutoCompleteBox. To do that navigate to the .cs file of your project MainPage.xaml.cs and add the following code to the MainPage() block:

public MainPage()
{
        InitializeComponent();
        this.Colors.ItemsSource = new string[]
        {
            "Aqua","Azure","Beige","Black","Blue","Brown","Cyan","Gold","Red","Green","Yellow"
        };
}

What we are doing is that we are simply adding the data to the AutoCompleteBox whenever the MainPage is Loaded. I am here adding Name of various colors for demo purposes, you can however add your own data. Now that's all; compile and run your project and whenever you type a letter into the AutoCompleteBox an intellisenese will appear with suggestions the same as you usually see in Visual Studio.

Step 7

Now Suppose you want to Auto fill the suggestions in your AutoCompleteBox; for that you just need to add a property called IsTextCompletionEnabled to True in your XAML code like:

<sdk:AutoCompleteBox Name="Colors" Width="200" Height="25" IsTextCompletionEnabled="True"/>

Now compile and run your project; you will see that whenever you type a letter, the words related to it are automatically placed into the AutoCompleteBox.

HostForLIFE.eu Silverlight 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



Silverlight Hosting - HostForLIFE.eu :: How to get unrestricted access in Silverlight 5?

clock April 24, 2020 07:18 by author Peter

As you all know Silverlight 5 released with unrestricted access in InBrowser mode which gives full control to the Silverlight developers in the client machine. This post is to describe what are the changes you need to do at the server side as well as client side to leverage the trusted application feature.Try HostForLife.eu, only with € 3.00/month, you can get a reasonable price with best service. This topic contains only brief information about why you must use Silverlight 4. So, if you want to be more familiar with Silverlight 5, you should try HostForLife.eu

Server side

- Make the IB elevated from project properties

- Sign the xap using certificate.

Client side

- Install the cert into “trusted publishers”

- Change the reg key “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Silverlight\AllowElevatedTrustAppsInBrowser” to

-The “Protected mode” of browser should be turned off for the zone.

The above steps are mainly for Silverlight 4 to Silverlight 5 conversion and want to get the full trust support. If you just upgrading your projects there is no need to do above items. Just open in Visual Studio 2010 after installing the SL 5 tools.It will show the conversion wizard and just follows that. One thing you need to make sure is the reference path to Sl 5 assemblies.

Steps to setup Silverlight 5 application to have unrestricted access in IB using elevated trust mode
Ok.Now lets look at details of how we can create new SL project which access a file from c:\ in the In-Browse mode.First as usual create a Silverlight 5 Application. Then place a Button inside and wire the Click event handler.Write the below code in the handler to write a file to c:\

private void btnWriteToCDrive_Click ( object sender, RoutedEventArgs e )

{

    File.WriteAllText(@"c:\FromSL5.txt","This is written from Silverlight 5 web application in InBrowser mode");

}

Giving Elevated trust to SL 5 application

Just to go to the Silverlight 5 project properties and in the Silverlight tab check the “Require elevated trust when running in-browser” check box.See the below screen shot for reference.

Signing the xap
Next step is to sign the xap file with a certificate. Just goto Silverlight project properties and check the “Sign the Xap File” check box.If you don’t have any certificate just create a new one using the “Create Test Certificate” button.

Disable the browser protected mode

The above changes are mainly for the server side. You need to do some at client side as well.The first one is to disable the protected mode in browser.Goto the internet options and disable it.

Change registry entry

As mentioned above just change the registry entry as it is.If you cant find the key just add a DWORD and set to 1. Still I am not sure how this step is carried out in other platforms such as MAC and Linux. That’s it.Now run your application.It will create a file inside c:\ from in browser.Just uploaded the sample by removing the certificate as it give some information about my company laptop.



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.



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