European Silverlight 4 & Silverlight 5 Hosting BLOG

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

FREE Silverlight 5 Spain Hosting - HostForLIFE.eu :: Silverlight: Updating the XAP Configuration Programmatically

clock March 20, 2014 08:16 by author Peter

One of the bigger annoyances dealing with programming in Silverlight 5 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.



Silverlight Italy Hosting - HostForLIFE.eu :: Silverlight Control Size and Browser Resize Problem

clock March 10, 2014 10:21 by author Peter

Sometime if Silverlight control have a bigger size than it create some problems. If browser is smaller than Silverlight control then some part of SL control get clipped. In this scenario sometime you want to get scrollbar some time you want to change SL control height according to browser.

There are some different scenario that how people want to embed there Silverlight control in there page

1. If Silverlight Control is long then it should be in scrollbar.

2. Silverlight control should filled whole page in width and height without caring of height – width ratio.

3. Silverlight control should filled page with maintaining aspect ratio.

Silverlight Control is long then it should be in scrollbar

If your Silverlight control height is fixed assume its 800px and width is 900px then you should define this in your user control in this way :

<UserControl x:Class=”Slider.Page” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;  
 xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;  
 Width=”700″ Height=”800″ xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243; mc:Ignorable=”d”>  
 <Grid x:Name=”LayoutRoot” Background=”White”>  
 </Grid>  
 </UserControl>   

and in aspx page it should be

<div id=”silverlightControlHost” style=”width:700;height:800; “>  

it will give you scrollbar.

Silverlight control should filled whole page in width and height without caring of height – width ratio

In this case you need put your layout in Canvas instead of Grid and add transforms in that way:

<UserControl x:Class=”SlSizeChange.Page” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;  
 xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221; Height=”Auto” Width=”Auto” Background=”#FF29D530″ HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” >  
 <Canvas HorizontalAlignment=”Center” x:Name=”Layout” Width=”930″ Height=”640″ VerticalAlignment=”Center” RenderTransformOrigin=”0.5,0.5″ Background=”#FFB9B839″>  
 <Canvas.RenderTransform>  
    <TransformGroup>  
       <ScaleTransform ScaleX=”1″ ScaleY=”1″ x:Name=”LayoutScale” />  
      <SkewTransform />  
      <RotateTransform />  
      <TranslateTransform />  
   </TransformGroup>  
 </Canvas.RenderTransform>  
 <TextBlock Height=”75″ Width=”276″ Canvas.Left=”71″ Canvas.Top=”18″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”77″ Width=”140″ Canvas.Left=”248″ Canvas.Top=”341″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”64″ Width=”69″ Canvas.Left=”365″ Canvas.Top=”509″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”52″ Width=”125″ Canvas.Left=”652″ Canvas.Top=”525″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 </Canvas>  
 </UserControl>  

Then attach sizeChanged event handler

public partial class Page : UserControl  
  {  
     public Page()  
     {  
      InitializeComponent();  
      this.SizeChanged += new SizeChangedEventHandler(Layout_SizeChanged);  
     }  
     void Layout_SizeChanged(object sender, SizeChangedEventArgs e)  
    {  
      LayoutScale.ScaleX = e.NewSize.Width / (Layout.Width);  
     LayoutScale.ScaleY = e.NewSize.Height / (Layout.Height);  
    }   
 }  

Silverlight control should filled page with maintaining aspect ratio

Now third case where you want to maintain your width – height aspect ratio.To achieve this follow last process in same way with a small difference:

<UserControl x:Class=”SlSizeChange.Page”  
 xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;  
 xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221; Height=”Auto” Width=”Auto” Background=”#FF29D530″ HorizontalAlignment=”Stretch” VerticalAlignment=”Stretch” >  
 <Canvas HorizontalAlignment=”Center” x:Name=”Layout” Width=”930″ Height=”640″ VerticalAlignment=”Top” RenderTransformOrigin=”0.5,0″ Background=”#FFB9B839″>  
 <Canvas.RenderTransform>  
   <TransformGroup>  
     <ScaleTransform ScaleX=”1″ ScaleY=”1″ x:Name=”LayoutScale” />  
     <SkewTransform />  
     <RotateTransform />  
     <TranslateTransform />  
   </TransformGroup>  
 </Canvas.RenderTransform>  
 <TextBlock Height=”75″ Width=”276″ Canvas.Left=”71″ Canvas.Top=”18″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”77″ Width=”140″ Canvas.Left=”248″ Canvas.Top=”341″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”64″ Width=”69″ Canvas.Left=”365″ Canvas.Top=”509″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 <TextBlock Height=”52″ Width=”125″ Canvas.Left=”652″ Canvas.Top=”525″ Text=”TextBlock” TextWrapping=”Wrap”/>  
 </Canvas>  
 </UserControl>  
 And for C#  
 public partial class Page : UserControl  
 {  
    public Page()  
    {     InitializeComponent();  
      this.SizeChanged += new SizeChangedEventHandler(Layout_SizeChanged);  
     }   
    void Layout_SizeChanged(object sender, SizeChangedEventArgs e)  
    {  
     double aspectRatio = e.NewSize.Width / e.NewSize.Height;  
     if (aspectRatio < (Layout.Width / Layout.Height))  
      LayoutScale.ScaleX = LayoutScale.ScaleY = e.NewSize.Width / (Layout.Width);  
     else  
      LayoutScale.ScaleX = LayoutScale.ScaleY = e.NewSize.Height / (Layout.Height);  
    }   
 }  

Now this will always maintain the aspect ratio.



Silvelight Germany Hosting - HostForLIFE.eu :: How To Clear Silverlight Cache

clock March 5, 2014 07:12 by author Peter

I recently had an issue where a Silverlight application was acting up on me. It was an application that I was using, not one I’d developed and I really didn’t have much experience with Silverlight at that point. It was working for other people and other browsers on my computer were experiencing the same problem. I’d already cleared the Internet cache multiple times including cookies and other stuff. I applied all the latest patches, hot fixes and service packs as well as updated my browsers to the latest versions. I finally came to the point where I updated Silverlight thinking it could be related to Silverlight itself. None of this solved the problem.

Finally another developer alerted me to the possibility of clearing the Silverlight cache. Now don’t laugh, but I didn’t know that Silverlight had its own cache. I looked online for quite a while on how to clear the Silverlight cache but came up empty. So, I went looking myself. Here’s how you do it.

Clear Silverlight Cache

1. Open the Microsoft Silverlight shortcut in your start menu. Depending on what version and how you manage your Start Menu, this could be in various places. You could also just click Run or browse to ”C:\Program Files\Microsoft Silverlight\{VERSION}\Silverlight.Configuration.exe” where {VERSION} equals the version you have installed. For me, as of writing this article, it was 5.1.20125.0.

2. You will see the Microsoft Silverlight Configuration application come up.

3. Click on the Application Storage tab and you will see tab contents like this.

4. Click on a web site you want to clear from cache and click the Delete button, or click the Delete all button to clear all web site data from cache.

5. Click OK

Congratulations! You’ve just cleared the Microsoft Silverlight cache on your system.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2012 HostingASP.NET 4.5 HostingASP.NET MVC 5 Hosting, and SQL 2014 Hosting.

Tag cloud

Sign in