European Silverlight 4 & Silverlight 5 Hosting BLOG

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

Silverlight 4 Hosting - HostForLIFE.eu :: How to Make Video Player?

clock April 12, 2016 23:41 by author Anthony

Today, I will make a tutorial about how to make simple video player with Silverlight 4. Once you have that lets make the project, We want to make a Silverlight Application and after naming your project, on the next dialogue select Silverlight 4 from the combo box.


The Pre-created code for our project should look like this:

<UserControl x:Class="SilverlightApplication3.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/exp<b></b>ression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">
 
    <Grid x:Name="LayoutRoot" Background="White">

    </Grid>

</UserControl>

However, We don't need all those links, We only need a couple they are
view sourceprint?

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

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

So you can delete the others, Once you have your code should look like this:
view sourceprint?

<UserControl x:Class="SilverlightApplication3.MainPage"

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

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid x:Name="LayoutRoot" Background="White">
        
    </Grid>

</UserControl>

After that minor tweak, We now need to add a Canvas tag to hold all of our video player elements together for us, To do this we need to put the <Canvas> Tag between the <Grid> Tags.

    <Grid x:Name="LayoutRoot" Background="White">

    <Canvas Name="Holder" Width="350" Height="220" Background="Black">

    </Canvas>

</Grid>


These properties of the Canvas are very common in our project, All our elements will have a Name, A Height and a Width. They are measured in Pixels so you can easily make this pixel-perfect if you want to. The name is what we use to address the element of the project, We will need this later on. So We have in effect a black shape. We now need to add the video in, to do this we need to use the <MediaElement> tag. This have three main properties that we need in addition to a Name, Width and Height we need the Source, Volume and AutoPlay settings.

- The source is what we want the media element to find and play, In our case the video is at media/media.wmv so, Our source would look like this

Source="media/media.wmv"

- The volume setting is pretty self explanitoriy so we will set it to 100 for this tutorial.
- The AutoPlay setting has two values, True or False, It determines if the video should automatically play when it has loaded, for this tutorial we will set it to False.

So after all that, Our MediaElement Code should look like this

<MediaElement Name="Video" Source="media/media.wmv" AutoPlay="False" Volume="100" />

I have named the element video so that we will not get confused to it's function later on in the tutorial.
Right ok, Now we have a video lets add some controls so that we can control it.  Using the resources I have provided, We will add a new image tag into our code, this will be our Play Button.

The code for this will be like so;

<Image Name="btnPlay" Height="17" Width="49" Source="media/play.png" />

As you can see, The element has a name, height, width and source. Because we have put all our resources into a folder in the project called media we always address the image as media/play.png instead of just play.png

We can also add other properties to this, As well as position it. To do so we will change the opacity to 0.4 and move it 220 pixels down from the canvas so we can see the button clearly. So, The code will now look like this;

<Image Name="btnPlay" Height="17" Width="49" Source="media/play.png" Opacity="0.4" Canvas.Top="220" />

The Opacity property can be any value between 0 and 1.

Right, We have an image that doesn't do anything which isn't entirely useful at the moment so lets add some code to it. Open the event window while the image is selected and find the event for MouseLeftButtonDown this is silverlights version of click. It will take you to the code behind the project for that event and this bit is very simple, the only code we need to put in this bit is Video.Play(); and thats all, That will make the video play! easy!

If your confused where to put it, this is what it should look like:

private void btnPlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

       {

           Video.Play();

       }

You may notice that the source of the media element has an error on it, To fix this you find the media.wmv in the media folder and change it's Build Action to Resource and it will work fine.
You can run it now and the video will play.

 

HostForLIFE.eu Silverlight 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



Silverlight 4 Hosting - HostForLIFE.eu :: How to Upload File In Silverlight?

clock April 5, 2016 21:06 by author Anthony

Today, I will eplain about a simple way to upload file in Silverlight. Uploading files is quite an easy one in Silverlight: it’s basically just a request made to another server and the file contents are passed in this request. A possible way of implementing this is by using the WebClient class:

private void UploadFile()
{
FileStream _data; // The file stream to be read
string uploadUri;
 
byte[] fileContent = new byte[_data.Length]; // Read the contents of the stream into a byte array
int bytesRead = _data.Read(fileContent, 0, CHUNK_SIZE);
 
WebClient wc = new WebClient();
wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
Uri u = new Uri(uploadUri);
wc.OpenWriteAsync(u, null, new object[] { fileContent, bytesRead }); // Upload the file to the server
}
 
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) // The upload completed
{
if (e.Error == null)
{
  // Upload completed without error
}

The above solution does the job of uploading the file well. However it does not indicate file upload progress at all: when uploading large files or when having slow internet connection this behaviour would be desirable.

Silverlight has no built-in way to monitor the number of bytes sent which means that the only way to indicate upload progress is sending the file to the server in multiple, smaller chunks. Of course this behaviour needs support from the server side as well.

The idea is that multiple calls are made to the server, every call submitting the next chunk of the file. On the server these chunks are appended to the file.


Silverlight Code Snippet

public const int CHUNK_SIZE = 4096;
public const string UPLOAD_URI = "http://localhost:55087/FileUpload.ashx?filename={0}&append={1}";
private Stream _data;
private string _fileName;
private long _bytesTotal;
private long _bytesUploaded;
private void UploadFileChunk()
{
    string uploadUri = ""; // Format the upload URI according to wether the it's the first chunk of the file
    if (_bytesUploaded == 0)
    {
        uploadUri = String.Format(UPLOAD_URI,_fileName,0); // Dont't append
    }
    else if (_bytesUploaded < _bytesTotal)
    {
        uploadUri = String.Format(UPLOAD_URI, _fileName, 1); // append
    }
    else
    {
        return;  // Upload finished
    }
    byte[] fileContent = new byte[CHUNK_SIZE];
    _data.Read(fileContent, 0, CHUNK_SIZE);
    WebClient wc = new WebClient();
    wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
    Uri u = new Uri(uploadUri);
    wc.OpenWriteAsync(u, null, fileContent);
    _bytesUploaded += fileContent.Length;
}
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
    if (e.Error == null)
    {  
        object[] objArr = e.UserState as object[];
        byte[] fileContent = objArr[0] as byte[];
        int bytesRead = Convert.ToInt32(objArr[1]);
        Stream outputStream = e.Result;
        outputStream.Write(fileContent, 0, bytesRead);
        outputStream.Close();
        if (_bytesUploaded < _bytesTotal)
        {
            UploadFileChunk();
        }
        else
        {
            // Upload complete
        }
    }
}

Since Silverlight is a client side technology the server side can be implemented in any language. In this example I’ve created .NET and PHP support for the server side.


.NET Server Side Code Snippet

public const int CHUNK_SIZE = 4096;
public const string UPLOAD_URI = "http://localhost:55087/FileUpload.ashx?filename={0}&append={1}";
private Stream _data;
private string _fileName;
private long _bytesTotal;
private long _bytesUploaded;
private void UploadFileChunk()
{
    string uploadUri = ""; // Format the upload URI according to wether the it's the first chunk of the file
    if (_bytesUploaded == 0)
    {
        uploadUri = String.Format(UPLOAD_URI,_fileName,0); // Dont't append
    }
    else if (_bytesUploaded < _bytesTotal)
    {
        uploadUri = String.Format(UPLOAD_URI, _fileName, 1); // append
    }
    else
    {
        return;  // Upload finished
    }
    byte[] fileContent = new byte[CHUNK_SIZE];
    _data.Read(fileContent, 0, CHUNK_SIZE);
    WebClient wc = new WebClient();
    wc.OpenWriteCompleted += new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
    Uri u = new Uri(uploadUri);
    wc.OpenWriteAsync(u, null, fileContent);
    _bytesUploaded += fileContent.Length;
}
void wc_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
    if (e.Error == null)
    {  
        object[] objArr = e.UserState as object[];
        byte[] fileContent = objArr[0] as byte[];
        int bytesRead = Convert.ToInt32(objArr[1]);
        Stream outputStream = e.Result;
        outputStream.Write(fileContent, 0, bytesRead);
        outputStream.Close();
        if (_bytesUploaded < _bytesTotal)
        {
            UploadFileChunk();
        }
        else
        {
            // Upload complete
        }
    }
}

PHP Server Side Code Snippet

<?php
//  This is the most basic of scripts with no try catches
$filename = isset($_REQUEST["filename"]) ? $_REQUEST["filename"] : "jjj";
$append = isset($_REQUEST["append"]);
try
{
    if(!$append)
        $file = fopen($filename,"w");
    else
        $file = fopen($filename,"a");
    $input = file_get_contents ("php://input");
    fwrite($file,$input);
    fclose($file);
}
catch (Exception $e)
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>

Notes : Before running the project, set the UPLOAD_URI variable to point to the appropriate .asmx or .php file. The script is not suited for production environment because of the following:
Files are uploaded directly to the root directory of the web application. The files are created and constantly appended to. A more desirable approach would be to store the unfinished files in a temp folder until upload is complete and then move them to the upload folder

 

HostForLIFE.eu Silverlight 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



Silverlight 4 Hosting Italy - HostForLIFE.eu :: Create a basic Movement using Silverlight Animations

clock March 30, 2015 06:40 by author Rebecca

Do you want to make a game using Silverlight? At the first, you need something that moves around the screen. For example, you need at least four buttons that move a sprite in four directions. How do you do that? Well, there are multiple ways to accomplish this movement, some more flexible than others. Today, I’m going to tell you how to use Silverlight animations to do that job.

Silverlight animations are not hard to use, but what is hard to master are the dynamic animations, which require multiple classes to create and set up. You have to set up a storyboard, create an animation, and then set the target information. When it is all said and done, you will end up with something like this:

[silverlight width="400" height="300" src="aMovement1.xap" border="true"]

As with any Silverlight app, we need to start with some Xaml:

  <Canvas Height="300" Name="canvas1" Width="400" >
<Canvas.Resources>

<Storyboard x:Name="mySB"></Storyboard>

</Canvas.Resources>

<Ellipse x:Name="myEllipse" Width="50" Height="50" Canvas.Left="175"
>
<Canvas.Top="125" Fill="Black" />

</Canvas>

I know what you are thinking, maybe this is not enough XAML for animations. Well, this is what we’re going to do. We are actually creating all of the animations dynamically and adding them to the storyboard. Then, to start with, we need an event (a keyboard triggered event).

What we need is a Key Up event,  that only fires when we release a key, as opposed to pushing it down. Now I am using Visual Studio 2010 (which is currently under beta, so it is a free download), so I am not adding the event to the Canvas myself, but it is one line of code you can find. As I stated above, you need to setup a Key Up event. This event also has to be tied to the Canvas, so it works no matter where you click the application:

private void canvas1_KeyUp(object sender, KeyEventArgs e)
{

}

The first thing that we need to add to our event is key capturing. If you have ever done this before, you will recognize the code, if not it is extremely easy to do:

private void canvas1_KeyUp(object sender, KeyEventArgs e)
{

if (e.Key == Key.Left)

{

}

else if (e.Key == Key.Right)

{

}

else if (e.Key == Key.Up)

{

}

else if (e.Key == Key.Down)

{

}

}

What is going on here is that we are taking the key pressed, in this case a property of “e”, which is passed with the event. This gives up information about what key was pressed so we can compare it to key codes built into C#, which is given as an easy to use “e” num. As you can see, it is pretty obvious how to capture the right key.

Now we can start to setup some variables (movement speed and movement distance). Speed corresponds to how long it will take to travel a length equal to movement distance. For example we will set movement distance at 100 and speed at 0.5, making the animation travel 100 pixels in half a second. All we are doing right now is setting these variables, for later use:

private void canvas1_KeyUp(object sender, KeyEventArgs e)
{

Double mDist = 100.00;

Double mSpeed = 0.5;

if (e.Key == Key.Left)
{

}

else if (e.Key == Key.Right)

{

}

else if (e.Key == Key.Up)

{

}

else if (e.Key == Key.Down)

{

}

}

The next step is to start setting up the animation. To do this, we utilize a lot of different classes and methods like:

private void canvas1_KeyUp(object sender, KeyEventArgs e)
{

Double mDist = 100.00;

Double mSpeed = 0.5;
Double x = Canvas.GetLeft(myEllipse);
Double y = Canvas.GetTop(myEllipse);

DoubleAnimation animation = new DoubleAnimation();
animation.Duration = new Duration(TimeSpan.FromSeconds(mSpeed));

if (e.Key == Key.Left)
{

animation.From = x;

animation.To = x - mDist;

Storyboard.SetTargetProperty(

animation, new PropertyPath(Canvas.LeftProperty));

}

else if (e.Key == Key.Right)

{

animation.From = x;

animation.To = x + mDist;

Storyboard.SetTargetProperty(

animation, new PropertyPath(Canvas.LeftProperty))
}
else if (e.Key == Key.Up)

{

animation.From = y;

animation.To = y - mDist;

Storyboard.SetTargetProperty(

animation, new PropertyPath(Canvas.TopProperty));
}
else if (e.Key == Key.Down)

{

animation.From = y;

animation.To = y + mDist;

Storyboard.SetTargetProperty(

animation, new PropertyPath(Canvas.TopProperty));
}

Storyboard.SetTarget(animation, myEllipse);
mySB.Children.Add(animation);
mySB.Begin();
}

So starting from the top, the first thing we do is get the current position of our Ellipse. We can't really do very much without our object's current position. It is important to do this at a specific point, because the animation is of course going to change that position. Once we have the position, we begin to create the animation. Yes, there is a Double Animation object we can use, but that is not the only important object.

The first thing we do with our animation is set up its duration, which is done using the Duration object and Time span class. Using Time span's methods, we can set the duration to seconds, minutes, hours, or even days.

Now, it gets a little crazy when we get to the different movement directions. For each direction, we have to set the animation's To and From properties. Then we use some a static method in the Storyboard class called SetTargetProperty(), which allows us to tell the animation what property to animate on the target. For horizontal movement, that would be the LeftProperty, vertical the TopProperty. The tricky thing is that you have to use the Canvas class to get these properties. To make things even crazier, you have to pass it as an object called PropertyPath so you have to create that object as well. Then whole thing ends up being a web of objects and static methods.

Before we can finally add the animation to the storyboard, we have to set its target. In this case we are going to target our ellipse. We do this with the static method SetTargetin the Storyboard class. Once the target has been set, we add it to the storyboard, then start the animation.

If you ran the code we have now, you will notice one thing, it only works once. If you try to add the animation more than once, Silverlight doesn't really like it, so it fails. What we have to do is remove the current animation from the storyboard, or better yet, clear it entirely. This was the really tricky part.

In order to clear the storyboard, any animations attached have to be stopped. This is fine, but in order for things to work, we have to take the position of the ellipse before we clear the animations. So, we pause, take the position, then finally stop and clear the animations. But, one final step is setting the position of the ellipse. This has to do with animating only one axis at a time. While the animation is going, only one axis is truly updated, so we need to set the position to make sure we have the right coordinates for the animation. The final version will look something like so:

private void canvas1_KeyUp(object sender, KeyEventArgs e)
{
  Double mDist = 100.00;
  Double mSpeed = 0.5;
  mySB.Pause();
  Double x = Canvas.GetLeft(myEllipse);
  Double y = Canvas.GetTop(myEllipse);
  mySB.Stop();
  mySB.Children.Clear();
  Canvas.SetLeft(myEllipse, x);
  Canvas.SetTop(myEllipse, y);
  DoubleAnimation animation = new DoubleAnimation();
  animation.Duration = new Duration(TimeSpan.FromSeconds(mSpeed));
  if (e.Key == Key.Left)
  {
    animation.From = x;
    animation.To = x - mDist;
    Storyboard.SetTargetProperty(
      animation, new PropertyPath(Canvas.LeftProperty));
  }
  else if (e.Key == Key.Right)
  {
    animation.From = x;
    animation.To = x + mDist;
    Storyboard.SetTargetProperty(
      animation, new PropertyPath(Canvas.LeftProperty));
  }
  else if (e.Key == Key.Up)
  {
    animation.From = y;
    animation.To = y - mDist;
    Storyboard.SetTargetProperty(
      animation, new PropertyPath(Canvas.TopProperty));
  }
  else if (e.Key == Key.Down)
  {
    animation.From = y;
    animation.To = y + mDist;
    Storyboard.SetTargetProperty(
      animation, new PropertyPath(Canvas.TopProperty));
  }

  Storyboard.SetTarget(animation, myEllipse);
  mySB.Children.Add(animation);
  mySB.Begin();
 }

This gives us the animated movement we are looking for. Not a lot of code, but there is a lot going on. After using 3 separate key classes, and even more objects, we can dynamically create and use animations to move our ellipse around the screen.

Easy right?

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



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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in