European Silverlight Hosting BLOG

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

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.



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.



European Silverlight 6 Hosting - HostForLIFE.eu :: Add Silverlight Into a Web Page

clock July 19, 2018 09:24 by author Peter

This article explains how to add Silverlight into a web page using HTML. Use the following procedure to do this.

  • Create a Silverlight application
  • Add some TextBox and button to the XAML file
  • Write the logic on the click event of the button in the .cs file
  • Add a HTML page and add some tags to access the Silverlight generated .xap file

Step 1: Create a new project of Silverlight application named "SilverlightExample".

Uncheck the checkbox to not create a web project for hosting the Silverlight.


Step 2: In the default page named "MainPage.xaml", add 2 Textboxes for getting the input named "txtvalue1" and "txtvalue2" with blank text by default ( text=””) and add a button named "btnAdd" with content "Add". Then create onClick event of the button.
<TextBox Name="txtValue1" Text="" HorizontalAlignment="Left" Height="23" Margin="130,34,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
<TextBox Name="txtValue2" Text="" HorizontalAlignment="Left" Height="23" Margin="130,85,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="120"/>
<Button  Name="btnAdd" Content="Add" Click="btnAdd_Click" HorizontalAlignment="Left" Margin="150,154,0,0" VerticalAlignment="Top" Width="75" />

Step 3: Write the code in the section of the onclick event of the button in "MainPage.xaml.cs" that will add the values of the textboxes and show the addition via alert message.
int value1 = Convert.ToInt32(txtValue1.Text);
int value2 = Convert.ToInt32(txtValue2.Text);
int result = value1 + value2;
MessageBox.Show(result.ToString());

Step 4: Now add a HTML Page named "MYPage.html" into the application.

Add an <object> tag to the HTML page with data, type, width and height attributes and <param> element with name and value attributes.
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
     width="500" height="500">
    <param name="source" value="Bin/Debug/SilverlightExample.xap" />
</object>

  • data attribute and its value are recommended to avoid performance issues on some browsers.
  • type attribute and the specific value shown are also required. This value uses the Silverlight MIME type to identify the plug-in and the required version.
  • width and height attributes are required for cross-browser compatibility.
  • the <param> element named source is required and indicates the location and name of your application file.

Note: .xap exists in the bin/Debug folder, that's why value="Bin/Debug/SilverlightExample.xap".

Open the HTML file using a browser.

Open the html file via browser
Enter the 2 integer values into the textboxes respectively and press the button to see the ouput.

You can also create the .html file anywhere in your system and put the Silverlight generated .xap file with in the same folder, but in this case you need to write the value="SilverlightExample.xap" because now the .xap and .html files are in the same folder or location.



European Silverlight 6 Hosting - HostForLIFE.eu :: Use Map in Silverlight to show the location

clock July 17, 2018 08:58 by author Peter

Silverlight can support maps in a page to show a particular location. Silverlight provides the Bing map control. To use the bing map you need use two dll files name as Microsoft.Maps.MapControl and another one is Microsoft.Maps.MapControl.Common. Reference of this two dll is must to work with bing map.

By right clicking on the Add Reference on the project name in Solution Explorer, you can add references of these two dlls. 

Once the references are added, you can use the map control as following in your .xaml page:
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006 
xmlns:m="clr-namespace:Microsoft.Maps.MapControl;assembly=Microsoft.Maps.MapControl"

The first mc is for the common map dll and second for the other dll name as MapControl. 

Now, in the Grid control add the map control like below:

<m:Map x:Name="testMapUs" CredentialsProvider="XXXXXXXXXX" ScaleVisibility="Collapsed" LogoVisibility="Collapsed" CopyrightVisibility="Collapsed" Background="White" Mode="Road" Center="" ZoomLevel="12"> 
<m:Pushpin Location="00.00000,-00.00000"/> 
</m:Map>

As shown above

The CredentialProvider is the key which can provide the credential to use the map that you can get it form this website.

http://www.bing.com/mapindia/?mkt=en-in

Also from this website, you will get the actual location that you want to show in your map control.

<m:Pushpin/> tag can show the pushpin location on your map so user can get the exact location directly.

You will also get an longitude of your location from the above site. As per shown above when you use this control it show Logo, Copyright text and scale on  the map. If you do not need to display these, you can remove it by setting its Visibility property to Collapsed. 

There is different modes in the map like Road and Aerial. To change the mode of the map there is one property name as Mode="Aerial". In both mode aerial and road, you can have possible to set the zoom level as per your requirement.


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