Silverlight-Catch video and Save Screenshot

In silverlight, we can catch video equipment to create video session system, or upload avatar through screenshot. In this post, I will introduce how to visit video equipment and download screentshot files to computer.

1. check if the default camera and microphone is available in silverlight.

2. Then, copy the following xaml code.

    <Grid x:Name=“LayoutRoot” Background=“White”>

    <Border BorderBrush=“Silver” BorderThickness=“1” Height=“346” HorizontalAlignment=“Left Margin=”21,19,0,0” Name=”border1” VerticalAlignment=”Top” Width=”477” >

    <Border.Background>

    <VideoBrush x:Name=“ShowVideo”></VideoBrush>

    </Border.Background>

    </Border>

        <Button Content=“Open Camera” Height=“32” HorizontalAlignment=“Left” Margin=“38,380,0,0” Name=“button1” VerticalAlignment=“Top” Width=“95” Click=“button1_Click” />

        <Button Content=“Close Camera” Height=“32” HorizontalAlignment=“Left” Name=“button2” Width=“85” VerticalAlignment=“Top” Margin=“268,380,0,0” Click=“button2_Click” />

        <Button Content=“Screenshot” Height=“32” Name=“button3” Margin=“153,380,0,0” HorizontalAlignment=“Left” Width=“91” VerticalAlignment=“Top” Click=“button3_Click” />

        <StackPanel Height=“346” HorizontalAlignment=“Left” Margin=“514,19,0,0” Name=“stackPanel1” VerticalAlignment=“Top” Width=“460” />

    </Grid>

We create a Border to display video image and add three buttons to control to open, close camera and printscreen. Then, add StackPanel to display the screenshot.

3. copy the following CS code.

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

        }

        //Provide Methods for Audio and Video

        CaptureSource video = new CaptureSource();

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            //Get Default Video Object on Computer

            VideoCaptureDevice camera = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

            //Succeed to Access to Video Equipment on Computer

            if (CaptureDeviceConfiguration.RequestDeviceAccess())

            {

                //Set Video Equipment as Camera

                video.VideoCaptureDevice = camera;

                //VideoBrush Set Source as video

                ShowVideo.SetSource(video);

                ShowVideo.Stretch = Stretch.Fill;

                //Catch Video

                video.Start();

            }

        }

        private void button3_Click(object sender, RoutedEventArgs e)

        {          

            //Screenshot

            WriteableBitmap wBitmap = new WriteableBitmap(border1, new MatrixTransform());

            Image img = new Image();

            img.Width = 450;

            img.Margin = new Thickness(2);

            img.Source = wBitmap;

            //Save Image

            if (wBitmap != null)

            {

                SaveFileDialog saveDlg = new SaveFileDialog();

                saveDlg.Filter = “JPEG Files (*.jpeg)|*.jpeg”;

                saveDlg.DefaultExt = “.jpeg”;

                if ((bool)saveDlg.ShowDialog())

                {

                    using (Stream fs = saveDlg.OpenFile())

                    {

                        SaveToFile(wBitmap, fs);

                        MessageBox.Show(“Succeed to Save”);

                    }

                }

            }

            this.stackPanel1.Children.Clear();

            this.stackPanel1.Children.Add(img);

        }

        ///<summary>

        ///Save Image

        ///</summary>

        ///<param name=”bitmap”></param>

        ///<param name=”fs”></param>

        private static void SaveToFile(WriteableBitmap bitmap, Stream fs)

        {

            int width = bitmap.PixelWidth;

            int height = bitmap.PixelHeight;

            int bands = 3;

            byte[][,] raster = new byte[bands][,];

            for (int i = 0; i < bands; i++)

            {

                raster[i] = new byte[width, height];

            }

            for (int row = 0; row < height; row++)

            {

                for (int column = 0; column < width; column++)

                {

                    int pixel = bitmap.Pixels[width * row + column];

                    raster[0][column, row] = (byte)(pixel >> 16);

                    raster[1][column, row] = (byte)(pixel >> 8);

                    raster[2][column, row] = (byte)pixel;

                }

            }

            FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel

            { colorspace = FluxJpeg.Core.ColorSpace.RGB };

            FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);

            //Encode the Image as a JPEG

            MemoryStream stream = new MemoryStream();

            FluxJpeg.Core.Encoder.JpegEncoder encoder =

                new FluxJpeg.Core.Encoder.JpegEncoder(img, 100, stream);

            encoder.Encode();

            //Back to the start

            stream.Seek(0, SeekOrigin.Begin);

            //Get teh Bytes and write them to the stream

            byte[] binaryData = new Byte[stream.Length];

            long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);

            fs.Write(binaryData, 0, binaryData.Length);

        }

        private void button2_Click(object sender, RoutedEventArgs e)

        {

            //Stop Video

            video.Stop();

        }

    }

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Advertisements

Silverlight-Read Formatted Json Data on Server

Json data is one kind of lightweight data interchange formats. It is more efficient to deliver data than XML. Therefore, it is can be used in silverlight to get data more quickly and reduce sent amount of characters. In this post, I will talk about how to serialize one class to Json data and sent to Silverlight.

Create a new general processing program page “GetJson.ashx” on client. Use WriteObject() of DataContractJsonSerialize class to serialize to Json DataSet. Then, use ReadObject() to restore Json data to class. Next, use WebRequest to download data in silverlight.

Firstly, create a new silverlight application. Then add two class City.cs (several propertis contained) and Cities.cs (one property is List assembly of City class) on sever and silverlight.

    public class City

    {

        private string _CityName;

        private string _State;

        public string State

        {

            get { return _State; }

            set { _State = value; }

        }

        public string CityName

        {

            get { return _CityName; }

            set { _CityName = value; }

        }

    }

    public class Cities

    {   

        private List<City> _CityList;

        public List<City> CityList

        {

            get { return _CityList; }

            set { _CityList = value; }

        }

    }

Then, create a new general processing program page “GetJson.ashx” on server. Add the following code to instantiated several city objects and turn to Json data. Note: we need to add System.Runtime.Serialization.dll individually.

    ///<summary>

    ///GetJson Summary

    ///</summary>

    public class GetJson : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            //Step 1

            //Format Cities Class to Json String

            string JsonString = ToJsonString(GetCities());

            context.Response.ContentType = “text/plain”;

            context.Response.Write(JsonString);

        }

        private Cities GetCities()

        {

            //Instantiated String Data Group

            Cities cities = new Cities();

            cities.CityList = new List<City>()

            {

                new City(){ CityName=“New York”, State=“New York”},

                new City(){ CityName=“Los Angeles”, State=“California”},

                new City(){ CityName=“Chicago”, State=“Illinois”},

                new City(){ CityName=“Huston”, State=“Texas”},

                new City(){ CityName=“Philadelphia”, State=“Pennsylvania”}

            };

            return cities;

        }

        // Serialize Object Class to Json String

        public string ToJsonString(object ToJsonObject)

        {

            using (MemoryStream ms = new MemoryStream())

            {

                DataContractJsonSerializer serializer =

                    new DataContractJsonSerializer(ToJsonObject.GetType());

                serializer.WriteObject(ms, ToJsonObject);

                StringBuilder sb = new StringBuilder();

                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));

                return sb.ToString();

            }

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

Run GetJson.ashx and then we can get Json as following:

{“CityList”:[{“CityName”:“New York”, State=“New York”},

{“CityName”:“Los Angeles”, State=“California”},

{“CityName”:“Chicago”, State=“Illinois”},

{“CityName”:“Huston”, State=“Texas”},

{“CityName”:“Philadelphia”, State=“Pennsylvania”}]}

Add System.ServiceModel.Web.dll and System.Runtime.Serialization.dll firstly in silverlight and add the following code to call string which is gotten by general appication page. Then, deserialize it to class.

        public MainPage()

        {

            InitializeComponent();

            //Step 2

            // Call Json Data Stream Getting by http://localhost:2598/GetJson.ashx

            Uri endpoint = new Uri(http://localhost:2598/GetJson.ashx&#8221;);

            WebRequest request = WebRequest.Create(endpoint);

            request.Method = “POST”;

            request.ContentType = “application/x-www-form-urlencoded”;

            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);

        }

        private void ResponseReady(IAsyncResult asyncResult)

        {

            WebRequest request = asyncResult.AsyncState as WebRequest;

            WebResponse response = request.EndGetResponse(asyncResult);

            //Step 3

            //Call UI Thread to Update DataGrid

            this.dataGrid1.Dispatcher.BeginInvoke(()=>{

                this.dataGrid1.ItemsSource =

                    (Deserialize<Cities>(response.GetResponseStream()) as Cities).CityList;

            });

        }

        //Deserialize Json String Stream to Object

        public static T Deserialize<T>(Stream stream)

        {

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            return (T)serializer.ReadObject(stream);

        }

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Silverlight-Some Essential Dependency Properties

We often use custom control in silverlight and create custom property in controls. However, it occupies memory to create default value of property when creating a large amounts of custome controls. Actually, we can just use default value, not the property directly everytime. Therefore, DependencyProperty is introduced in silverlight and WPF to save memory and use property flexibly.

In silverlight, there are two methods to create property: CLR Custom Property, DependencyProperty and Attached Property.

1. CLR Custom Property Creation:

        private string _RectWidth;

        public string RectWidth

        {

            get { return _RectWidth; }

            set { _RectWidth = value; }

        }

2. DependencyPropery is saved one key value mathing dictionary which is based on DependencyObject class. It isn’t saved in class it belongs to so that we don’t need to crate a property default value everytime.

            #regionSet X Coordinate Property

            public double X

            {

                get { return (double)GetValue(XProperty); }

                set { SetValue(XProperty, value); }

            }

        //Create a DependencyProperty named X and set the location of rectangle1 to change when X changes.

        public static readonly DependencyProperty XProperty =

            DependencyProperty.Register(“X”, typeof(double), typeof(Rectan), new PropertyMetadata(OnXChanged));

        static void OnXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            Rectan rec = d as Rectan;

            rec.rectangle1.SetValue(Canvas.LeftProperty, e.NewValue);

        }

            #endregion

Please pay attention to the operation when DependencyProperty changing in OnXChanged(DependencyObject d, DependencyChangedEventArgs e). In this example, we change the location of rectangle1. After registering DependencyProperty, we can control it by XAML and CS.

XAML Controls DependencyProperty

            <uc:Rectan  X=“15” Y=“105” x:Name=“Uil” Width=“105” Height=“45”  HorizontalAlignment=“Left” VerticalAlignment=“Top”></uc:Rectan>

                CS Controls DependencyPropery

            this.Ikd.SetValue(Rectan.XProperty, 150.0);

            this.Ikd.SetValue(Rectan.YProperty, 150.0);

Then, let’s learn parameters and usage of DependencyProperty Register function.

It is to register DependencyProperty by using DependencyProperty.Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata);. We can do logic operation when property value changes in OnXChanged().

            // Summary

            // Use specified property name and type, owner type and dependency property which is registered by property metadata.

            // Parameter:

            // name:

            // Dependency Object name which is needed to register.

            // propertyType:

            // Property type.

            // ownerType:

            // Registering dependency object owner type.

            // typeMetadata:

            // Property Metadata. It can include System.Windows.PropertyChangedCallback to realize reference.

            // Return Result:

            // Use dependency object tag to set public static readonly value in your class. Then, you can use the tag to add dependency property as reference in your code or any other third party customers’¡¥ code. It can used in setting property value programmatically or append in code.

            // System.Windows.Data.Binding

            public static DependencyProperty Register(string name, Type propertyType, Type ownerType, PropertyMetadata typeMetadata);

3. Attached Property is one special DependencyPropery, which is global DependencyProperty. The method to register is DependencyProperty.RegisterAttached(); and other parameter same to  register DependencyProperty.

Complete XAML code and XAML.CS code:

Rectan.xaml.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SLDependencyProp

{

    public partial class Rectan : UserControl

    {

        public Rectan()

        {

            InitializeComponent();

        }

        private string _RectWidth;

        public string RectWidth

        {

            get { return _RectWidth; }

            set { _RectWidth = value; }

        }

        #regionSet X Coordinate Property

        public double X

        {

            get { return (double)GetValue(XProperty); }

            set { SetValue(XProperty, value); }

        }

        // Create a DependencyProperty named X and set the location of rectangle1 to change when X changes.

        public static readonly DependencyProperty XProperty =

        DependencyProperty.Register(“X”, typeof(double), typeof(Rectan), new PropertyMetadata(OnXChanged));

        private static void OnXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            Rectan rec = d as Rectan;

            rec.rectangle1.SetValue(Canvas.LeftProperty, e.NewValue);

        }

        #endregion

        #regionSet Y Coordinate Property

        public double Y

        {

            get { return (double)GetValue(YProperty); }

            set { SetValue(YProperty, value); }

        }

        // Create a DependencyProperty named Y and set the location of rectangle1 to change when Y changes.

        public static readonly DependencyProperty YProperty =

        DependencyProperty.Register(“Y”, typeof(double), typeof(Rectan), new PropertyMetadata(OnYChanged));

        private static void OnYChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            Rectan rec = d as Rectan;

            rec.rectangle1.SetValue(Canvas.TopProperty, e.NewValue);

        }

        #endregion

    }

}

Rectan.xaml:

        <UserControl x:Class=“SLDependencyProp.Rectan”

        xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

        xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml&#8221;

        xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

        xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

        mc:Ignorable=“d”

        d:DesignHeight=“45” d:DesignWidth=“105”>

        <Canvas x:Name=“LayoutRoot” Background=“White”>

        <Rectangle Height=“45” HorizontalAlignment=“Left”  RadiusX=“15” RadiusY=“15” Fill=“BurlyWood”  Name=“rectangle1” Stroke=“Black” StrokeThickness=“1” VerticalAlignment=“Top” Width=“105” />

        </Canvas>

        </UserControl>

MainPage.xaml.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SLDependencyProp

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            this.Ikd.SetValue(Rectan.XProperty, 150.0);

            this.Ikd.SetValue(Rectan.YProperty, 150.0);

        }

    }

}

MainPage.xaml:

            <UserControl x:Class=“SLDependencyProp.MainPage”

            xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

            xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml&#8221;

            xmlns:d=http://schemas.microsoft.com/expression/blend/2008&#8221;

            xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006&#8221;

            xmlns:uc=“clr-namespace:SLDependencyProp”

            mc:Ignorable=“d”

            d:DesignHeight=“300” d:DesignWidth=“400”>

            <Grid x:Name=“LayoutRoot” Background=“White”>

            <uc:Rectan  X=“15” Y=“105” x:Name=“Uil” Width=“105” Height=“45”  HorizontalAlignment=“Left” VerticalAlignment=“Top”></uc:Rectan>

            <uc:Rectan                x:Name=“Ikd”  Width=“105” Height=“45” HorizontalAlignment=“Left” VerticalAlignment=“Top”></uc:Rectan>

            <uc:Rectan   Width=“105” Height=“45” HorizontalAlignment=“Left” VerticalAlignment=“Top”></uc:Rectan>

            </Grid>

            </UserControl>

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Silverlight-Use WebClient to Upload and Download String and Stream

It is usual to upload and download data in silverlight. In this post, I will introduce how to use WebClient upload and download String, upload and download Stream.

What is WebClient class?

Main functions of WebClient:

  • OpenReadAsync: open readable stream which flows to specified resource.
  • OpenWriteAsync: open one stream to write data to secified resource. These methods cannot prevent from calling threads.
  • DownloadStringAsync: download resource located in specified Uri by string.
  • UploadStringAsync: upload specified string to specified resource. These methods cannot prevent from calling threads.

Main Methods of WebClient:

  • OpenReadCompleted: happen when completing to read in asynchronous resource.
  • OpenWritecompleted: happen when completing to open stream to write data to resource.
  • DownloadStringCompleted: happen when completing to download in asynchronous resource.
  • DownloadProgressChanged: happen when completing to download and send part or total data in asynchronous.
  • UploadStringCompleted: happen when completing upload in asynchronous string.
  • UploadProgressChanged: happen when completing to upload and convert part or total data in asynchronous.

Then, there is an example about uploading and download string and stream with WebClient.

Firstly, write xaml foreground code. There are four buttons which stand for uploading String, downloading String, uploading Stream, downloading Stream.

    <Grid x:Name=“LayoutRoot” Background=“White”>
      <Canvas Name=“lRoot”></Canvas>
        <Button Content=“WebClient Download XAP” Height=“23” HorizontalAlignment=“Left” Margin=“410,60,0,0” Name=“button1” VerticalAlignment=“Top” Width=“178” Click=“buttonOpenReadAsync_Click” />
        <Button Content=“DownloadStringAsync Download XML” Height=“23” HorizontalAlignment=“Left” Margin=“410,100,0,0” Name=“button2” VerticalAlignment=“Top” Width=“178” Click=“buttonDownloadStringAsync_Click” />
        <Button Content=“UploadStringAsync Upload String” Height=“23” HorizontalAlignment=“Left” Margin=“410,140,0,0” Name=“button3” VerticalAlignment=“Top” Width=“178” Click=“buttonUploadStringAsync_Click” />
        <Button Content=“OpenWriteAsync Upload Image” Height=“23” HorizontalAlignment=“Left” Margin=“410,180,0,0” Name=“button4” VerticalAlignment=“Top” Width=“178” Click=“buttonOpenWriteAsync_Click” />
    </Grid>
Upload String:

Create TestHandle.ashx and write the following code to it to receive uploaded String in Silverlight.

    ///<summary>
    ///TestHandle Summary
    ///</summary>
    public class TestHandle : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            int bytelength = context.Request.ContentLength;
            byte[] inputbytes = context.Request.BinaryRead(bytelength);
            string message = System.Text.Encoding.Default.GetString(inputbytes);
            context.Response.ContentType = “text/plain”;
            context.Response.Write(“You have submitted data:” + message);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Code for Silverlight Client:

        WebClient Appclient = new WebClient();
        #regionUploadStringAsync Upload String
        private void buttonUploadStringAsync_Click(object sender, RoutedEventArgs e)
        {
            //Start to Call UploadStringAsync asynchronous upload String
            Appclient.UploadStringAsync(new Uri(http://localhost:3993/TestHandle.ashx&#8221;, UriKind.RelativeOrAbsolute), “<TD></TD>”);
            Appclient.UploadStringCompleted += new UploadStringCompletedEventHandler(Appclient_UploadStringCompleted);
        }

        private void Appclient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
            Appclient.UploadStringCompleted -= new UploadStringCompletedEventHandler(Appclient_UploadStringCompleted);
        }
        #endregion

Download String:

Download existed XML file under ClientBin

        #region DownloadStringAsync Download XML
        private void buttonDownloadStringAsync_Click(object sender, RoutedEventArgs e)
        {

            // Start to Call DownloadStringAsync Asynchronous Download Document and Read
            Appclient.DownloadStringAsync(new Uri(http://localhost:3993/ClientBin/222.xml&#8221;, UriKind.RelativeOrAbsolute));
            Appclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Appclient_DownloadStringCompleted);
        }

        private void Appclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
            Appclient.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(Appclient_DownloadStringCompleted);
        }
        #endregion

Upload Stream:

Create one AddFileHandle.ashx and write the following code to it to receive uploaded Stream in Silverlight.

    ///<summary>
    ///AddFileHandle Summary
    ///</summary>
    public class AddFileHandle : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // Get Uploaded Stream
            using (Stream sr = context.Request.InputStream)
            {
                string filename = “Fir”;
                byte[] buffer = new byte[4096];
                int bytesRead = 0;

                // Write Current Stream to Fir.jpg under ClientBin
                using (FileStream fs = File.Create(context.Server.MapPath(“ClientBin/” + filename + “.jpg”), 4096))
                {
                    while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {

                        // Write Data to File
                        fs.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Silverlight reads image data and submits to server. (Note: it is not to verify the uploaded date. If needing, please call OpenFieldDialog.Filter).

        #region  OpenWriteAsync Upload Image
        private void buttonOpenWriteAsync_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                //Start to Call OpenWriteAsync Method to Upload Data
                Appclient.OpenWriteAsync(new Uri(http://localhost:3993/AddFileHandle.ashx&#8221;, UriKind.RelativeOrAbsolute), “POST”, dialog.File.OpenRead());
                Appclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(Appclient_OpenWriteCompleted);
            }
        }

        private void Appclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            //Send Image Stream to Server
            Stream inputStream = e.UserState as Stream;
            Stream outputStream = e.Result;
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
            }
            outputStream.Close();
            inputStream.Close();
            MessageBox.Show(“Succeed”);
            Appclient.OpenWriteCompleted -= new OpenWriteCompletedEventHandler(Appclient_OpenWriteCompleted);
        }
        #endregion

Download Stream:

        #region OpenReadAsync Download XAP
        private void buttonOpenReadAsync_Click(object sender, RoutedEventArgs e)
        {
            //1. Use WebClient Download SLRandarHitTest to Asynchronous Read
            Appclient.OpenReadAsync(new Uri(“SLRandarHitTest.xap”, UriKind.Relative));
            Appclient.OpenReadCompleted += new OpenReadCompletedEventHandler(Appclient_OpenReadCompleted);
        }
        private void Appclient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            CreateXAPResource(“SLRandar.dll”, “SLRandar.MainPage”, e.Result);
            Appclient.OpenReadCompleted -= new OpenReadCompletedEventHandler(Appclient_OpenReadCompleted);
        }

        ///<summary>
        ///Create XAP Package Reflection Example and Retrofit to Canvas
        ///</summary>
        ///<param name=”dllStr”>Run DLL when Completing XAP Package Compilation</param>
        ///<param name=”mainStr”>Need Instantiated Start Page</param>
        ///<param name=”resultStream”>Use Downloaded Stream by WebClient</param>

        private void CreateXAPResource(string dllStr, string mainStr, Stream resultStream)
        {
            //2. Get Reresource Stream from other Package
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new StreamResourceInfo(resultStream as Stream, null), new Uri(dllStr, UriKind.RelativeOrAbsolute));

            //3. Reflect Stream
            AssemblyPart assemblyPart = new AssemblyPart();
            Assembly assembly = assemblyPart.Load(streamResourceInfo.Stream);

            //4. Create Instance
            var uc = (UserControl)assembly.CreateInstance(mainStr);
            lRoot.Children.Clear();
            lRoot.Children.Add(uc);
        }
        #endregion

Silverlight Components Recommend:

Spire.Doc for Silverlight, a professional Silverlight Word component, is used to operate MS Word document for Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS for Silverlight, a professional Silverlight Excel component, is used to operate MS Excel for Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.

Silverlight-Distribute Radar Scan Points Randomly and Simulate Scanned Equipment

In last post, we have simulated a radar scan to monitor several computers. Now, there are many equipments and every one has CPU usage property. If the CPU value is over 90, the color turns to red when radar scanning.

In this post, we will throw several equipment points in radar scan randomly. The location of these points in radar scan is set by X and Y coordinate property and a flicker animation is generated.

Create a new custom control and name it Device.xaml.

Firstly, calculate X, Y coordinate and set CPU signalvalue Value. We can use Rondom object rom.Next(Math.Sin(45)*250) function to get X and Y coordinate of equipment. Temporarily, we set central coordinate as (0,0) and radius as 250. It is possible that X or Y coordinate is negative. At that time, we can call Random object to get number less than 2. If it is 1, set the number which is gotten randomly as negative. Please note that Random object is to use system clock to generate seed value. Therefore, we should set only one Random object in global scope. If setting several Random objects, we get the same value at the same time. The solution is to set one public static global scope random object. It can meet the requirement by calling Next() function of this object. The coordinate is set as (0,0) at the beginning, after calculating, X, Y coordinate plus 300 and the central point location becomes (300, 300). Besides, assign number within 100 which random object gets to CPU usage signalvalue Value of equipment.

Code as following:

        public Device()

        {

            InitializeComponent();

            InitData();

        }

        private double _X;

        private double _Y;

        private double _Value;

        ///<summary>

        ///X Coordinate

        ///</summary>

        public double X

        {

            get { return _X; }

            set { _X = value; }

        }

        ///<summary>

        ///Y Coordinate

        ///</summary>

        public double Y

        {

            get { return _Y; }

            set { _Y = value; }

        }

        ///<summary>

        ///Equipment Key Signalvalue

        ///</summary>

         public double Value

         {

             get { return _Value; }

             set { _Value = value; }

         }

        public static Random rom = new Random();

        public void InitData()

        {

            #regionDistribute Equipment to Radar Scan Randomly and Simulate Scanned Equipment.

            //Simulate Equipment CPU Value

            Value = rom.Next(100);

            //Simulate Equipments and Distribute them in Scan Randomly.

            //Simulate X Coordinate           

            X = rom.Next(200);

            //Simulate X Coordinate Symbol. If 0, it is positive. If 1, negative.

            int Xmark = rom.Next(2);

            if (Xmark == 1)

            {

                X = -X;

            }

            X = X + 300.0;

            //Simulate Y Coordinate

            Y = rom.Next(Convert.ToInt32(Math.Sin(45)*250));

            //Simulate Y Coordinate Symbol. If 0, it is positive. If 1, negative.

            int Ymark = rom.Next(2);

            if (Ymark == 1)

            {

                Y = -Y;

            }          

            Y = Y + 300.0;

            Storyboard1.Begin();

            #endregion

            //tip Displays Current Value

            devicetip.Content = “CPU usage:” + Value + “–X:” + X + “–Y:” + Y;

        }

Secondly, generate animation of equipment point. Add two same rectangle boxes in Device.xaml (RectangleRed, Rectangleblue). The two boxes become one small ring which has white center and transparent external surface by CompositeTransform. We can control ScaleX and ScaleY of RetangleRed ring from 0.3 times to 2 times within 1 sec and control ScaleX and ScaleY of Rectangleblue ring from 2 times to 0.3 times within 1 sec. Then, we can get a flickering point.

XAML code:

    <UserControl.Resources>

    <Storyboard x:Name=“Storyboard1” RepeatBehavior=“Forever”>

    <DoubleAnimation Duration=“0:0:1” From=“0.3” To=“2”   Storyboard.TargetProperty=“(UIElement.RenderTransform).(CompositeTransform.ScaleX)” Storyboard.TargetName=“RectangleRed” />

    <DoubleAnimation Duration=“0:0:1” From=“0.3” To=“2” Storyboard.TargetProperty=“(UIElement.RenderTransform).(CompositeTransform.ScaleY)” Storyboard.TargetName=“RectangleRed” />

    <DoubleAnimation Duration=“0:0:1” From=“2” To=“0.3”   Storyboard.TargetProperty=“(UIElement.RenderTransform).(CompositeTransform.ScaleX)” Storyboard.TargetName=“Rectangleblue” />

    <DoubleAnimation Duration=“0:0:1” From=“2” To=“0.3” Storyboard.TargetProperty=“(UIElement.RenderTransform).(CompositeTransform.ScaleY)” Storyboard.TargetName=“Rectangleblue” />

    </Storyboard>

    </UserControl.Resources>

    <Grid x:Name=“LayoutRoot” >

    <Rectangle HorizontalAlignment=“Left”   VerticalAlignment=“Top” Height=“16” x:Name=“RectangleRed” RadiusX=“15” RadiusY=“15” Width=“15” RenderTransformOrigin=“0.5,0.5”>

    <Rectangle.RenderTransform>

    <CompositeTransform/>

    </Rectangle.RenderTransform>

    <Rectangle.Fill>

    <RadialGradientBrush>

    <GradientStop Color=“White” Offset=“0”/>

    <GradientStop Color=“#30FFFFFF” Offset=“0.276”/>

    <GradientStop Color=“Transparent” Offset=“0.582”/>

    </RadialGradientBrush>

    </Rectangle.Fill>

    </Rectangle>

    <Rectangle HorizontalAlignment=“Left”   VerticalAlignment=“Top” Height=“16” x:Name=“Rectangleblue” RadiusX=“15” RadiusY=“15” Width=“15” RenderTransformOrigin=“0.5,0.5”>

    <Rectangle.RenderTransform>

    <CompositeTransform/>

    </Rectangle.RenderTransform>

    <Rectangle.Fill>

    <RadialGradientBrush>

    <GradientStop Color=“White” Offset=“0”/>

    <GradientStop Color=“#30FFFFFF” Offset=“0.276”/>

    <GradientStop Color=“Transparent” Offset=“0.582”/>

    </RadialGradientBrush>

    </Rectangle.Fill>

    <ToolTipService.ToolTip>

    <ToolTip x:Name=“devicetip” />

    </ToolTipService.ToolTip>

    </Rectangle>

    </Grid>

Finally, put several scanning point which is created when radar scan is intialized in scan.

            #region Add Flicker Equipment

            for (int i = 0; i < 15; i++)

            {

                Device dev=new Device();

                //Set X, Y Coordinate and Z Level

                dev.SetValue(Canvas.TopProperty,dev.Y);

                dev.SetValue(Canvas.LeftProperty,dev.X);

                dev.SetValue(Canvas.ZIndexProperty, 600);

                LayoutRoot.Children.Add(dev);

            }

            #endregion

Result:

Two Components Recommend:

Spire.Doc, is used to operate MS Word document for .Net and Silverlight, including basic manipulations (generate, open, edit documents), mail merge and other Word functions manipulations.

Spire.XLS, is used to operate MS Excel for .NET and Silverlight, including basic manipulations (generate, open, edit files), chart creation and data exporting.