European Silverlight 4 & Silverlight 5 Hosting BLOG

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

Silverlight 6 Hosting Romania - HostForLIFE.eu :: How to Create Storyboard Animation using Expression Blend in Silverlight

clock June 30, 2015 06:11 by author Rebecca

There are two ways to animate in Silverlight, through storyboards and through code. Expression Blend offers extensive help in creating storyboard animations. Silverlight animation is time based not frame based, this means that your animation will benefit from running at the maximum frame rate that the users machine will allow. Multiple storyboards can be created and run at the same time, but for the purpose of this basic tutorial, you'll be shown how to create a single storyboard.

Follow these simple steps to create storyboard animation using expression blend in Silverlight:

Step 1

To create a new storyboard, go to the Objects and Timeline tab then click on the ‘plus’ icon.

If you are using the default UI layout in Blend, you may want to hit the ‘F6‘ key to switch the layout from design mode to animation mode, this will give you a better layout for working with storyboards.

Notice that after adding a storyboard a red circle will be displayed in the top right of the screen, this indicates that you are in record mode. When in record mode, every change you make is treated as an animation and will be tied to a Keyframe. To turn record mode on or off click on the red circle in the top right of the screen, it should toggle from red to grey.

Step 2

For the purpose of this tutorial I have created a ball graphic and a shadow graphic as shown below. You can use any objects thay you like to make your own animation project.  I have placed them off the page to the left so that they start out of site.

Step 3

Storyboard animation is based on Keyframes set to specific times. To add a Keyframe, go back to the ‘Objects and Timeline‘ tab, select the objects that you want to animate and click the Record Keyframe button as highlighted below. You will see that a new Keyframe is added by each object at zero seconds.

Step 4

To add a Keyframe at a specific point along your timeline, drag the yellow time bar to the required point and then hit the Record Keyframe button. To make our ball graphic animate I have selected a time stamp of 0.5 seconds and moved the ball to the position shown below:

Step 5

Then you can animate the ball and shadow graphics again at 1 second.

And once more at 1.5 seconds to finish the animation.

Step 6

Now that we have completed the animation we may want to loop it multiple times or loop it forever. To make the animation loop, make sure you have the storyboard selected under the ‘Objects and Timeline‘ tab, then go to your ‘Properties‘ tab and scroll down to the ‘Common Properties‘ section. Here you have an option to repeat the animation several times, for this tutorial, you have to set it to ‘Forever‘.

Step 7

Finally, you need to tell the storyboard to play. Sometimes you will need a storyboard to be called by the code behind file, but you can use ‘Behaviors’ to start a storyboard instead. ‘Behaviors’ are pre-set actions that can be dropped onto objects in Blend, they are an easy way to achieve functionality without requiring knowledge of C# or alternative languages. To tell the storyboard to autoplay, go to the ‘Assets‘ button on the main tool bar (the last icon), select ‘Behaviors‘ from the list on the left to bring up the selection of behaviors. Find the behavior titled ‘ControlStoryboardAction‘ and drag it onto your ‘LayoutRoot‘. See how the behavior is indented below the ‘LayoutRoot‘. Select the behavior and go to the ‘Properties‘ tab, scroll down to the ‘Triggers‘ section and set the following settings:

EventName = Loaded

ControlStoryboard… = Play

Storyboard = Storyboard1 (the name of your storyboard)

You are done with your storyboard animation!

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



Silverlight 6 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Get User's Geo Location

clock June 3, 2015 06:19 by author Rebecca

In this tutorial, I'm going to tell you about getting the Geo-location of the user of your Silverlight Application. We will use Javascript as the core of our scenario.

Step 1

You will be calling following JavaScript API here in the aspx page:

 <script language="JavaScript" type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>

Now there are functions in that API that will return the Latitude, Longitude, country name and whatever we demand. Some of the function are viz:

  •     geoip_country_code()
  •     geoip_country_name()
  •     geoip_latitude()
  •     geoip_longitude()

Instead of just calling these functions directly in Silverlight, we will write our functions that will call these functions and return whatever these functions return. For example here is the custom script written just beneath the API call:

<script type="text/javascript">

   function GetCountryCode() {

   return geoip_country_code();

      }

  function GetCountryName() {

  return geoip_country_name();

      }       

  function GetLatitude() {

  return geoip_latitude();

       }

   function GetLongitude() {

   return geoip_longitude();

        }
 </script>

So finally, here is what the aspx page with API call and the scripts that you have written:

 <script type="text/javascript" src="Silverlight.js"></script>

 <script language="JavaScript" type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>

 <script type="text/javascript">

 function GetCountryCode() {

 return geoip_country_code();

   }

 function GetCountryName() {

 return geoip_country_name();

   }

 function GetLatitude() {

 return geoip_latitude();

    }

 function GetLongitude() {

return geoip_longitude();

      }   
 </script>

Step 2

Now let's move toward your mainpage. You must make the JavaScript function call from the main page. As you all know, it is a simple method call:

HtmlPage.Window.Invoke("<JavaScriptMethod>");

The XAML of the main page consists of four Text Blocks, each to pursue the respective value for Country code, Country Name, Latitude and Longitude.

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

 <TextBlock x:Name="txtCountryCode" Margin="20 20 0 0"/>

 <TextBlock x:Name="txtCountryName" Margin="20 40 0 0"/>

 <TextBlock x:Name="txtLatitude" Margin="20 60 0 0"/>

  <TextBlock x:Name="txtLongitude" Margin="20 80 0 0"/>

  </Grid>


For giving the corresponding values to the Blocks, you need to write some C# in the code behind and in the constructor of the main page.

    public MainPage()

    {

   InitializeComponent();

  txtCountryCode.Text = HtmlPage.Window.Invoke("GetCountryCode").ToString();

  txtCountryName.Text = HtmlPage.Window.Invoke("GetCountryName").ToString();

  txtLatitude.Text = HtmlPage.Window.Invoke("GetLatitude").ToString();

  txtLongitude.Text = HtmlPage.Window.Invoke("GetLongitude").ToString();  


That's it. Just hit F5 and run the project. It will provide you all the information you've requested in the code.

Happy coding!

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Silverlight 6 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Drag & Drop a Rich TextBox in Silverlight

clock May 27, 2015 05:41 by author Rebecca

In this post, I will show you how to drag and drop a RichTextBox in Silverlight. For your information, the code below also could be adapted to drag any element around.

The XAML that you are going to use here consists of one Border control which contains your Rich TextBox.  The Border control has several event handlers defined to capture the Mouse Buttons and Movement:

<UserControl x:Class="TreeViewDragAndDrop.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:liquidTreeView="clr-namespace:Liquid;assembly=Liquid.TreeView"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White" VerticalAlignment="Top" HorizontalAlignment="Left">
        <liquidTreeView:Tree x:Name="tree" EnableDragAndDrop="true" Drop="Tree_Drop" Width="300" Height="151" Margin="4">
            <liquidTreeView:Tree.Nodes>
                <liquidTreeView:Node ID="0" Title="Root" Icon="images/folder.png" IconExpanded="images/folderOpen.png">
                    <liquidTreeView:Node.Nodes>
                        <liquidTreeView:Node ID="1" Title="Folder 1" Icon="images/folder.png" IconExpanded="images/folderOpen.png">
                            <liquidTreeView:Node.Nodes>
                                <liquidTreeView:Node ID="10" Title="File 1.doc" Icon="images/doc.png" />
                                <liquidTreeView:Node ID="11" Title="File 2.doc" Icon="images/doc.png" />
                            </liquidTreeView:Node.Nodes>
                        </liquidTreeView:Node>
                        <liquidTreeView:Node ID="2" Title="Folder 2" Icon="images/folder.png" IconExpanded="images/folderOpen.png">
                            <liquidTreeView:Node.Nodes>
                                <liquidTreeView:Node ID="20" Title="File 3.doc" Icon="images/doc.png" />
                                <liquidTreeView:Node ID="21" Title="File 4.doc" Icon="images/doc.png" />
                                <liquidTreeView:Node ID="21" Title="File 5.doc" Icon="images/doc.png" />
                            </liquidTreeView:Node.Nodes>
                        </liquidTreeView:Node>
                    </liquidTreeView:Node.Nodes>
                </liquidTreeView:Node>
            </liquidTreeView:Tree.Nodes>
        </liquidTreeView:Tree>
    </Grid>
</UserControl>

The C# for this tutorial contains the 3 event handlers which do the actual work here. Remember your Border control has been placed on a Canvas object which allows you to specify using absolute coordinates where the Border should be rendered:

using System.Windows.Controls;

using Liquid;

namespace TreeViewDragAndDrop
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }

        private void Tree_Drop(object sender, TreeEventArgs e)
        {
            e.DropAction = Tree.DropActions.InsertAfter;
        }
    }
}

As you can see, you have detected when the mouse is clicked over the border (using the Border_MouseLeftButtonDown event) and set _mouseDown = true, you also call myBorder.CaptureMouse(), this is important as it tells Silverlight to route allmouse events to the Border control.

When the user moves the mouse the new position of the Border is calculated by adding the amount of pixels the cursor has moved since the last MouseMove event was called.  This is all handled in the Border_MouseMove event. And the final mouse event handler, Border_MouseLeftButtonUp clears the _mouseDown flag releases the capture lock we set previously.

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Silverlight 6 Hosting with Free ASP.NET Hosting - HostForLIFE.eu :: How to Use Isolated Storage Feature in Silverlight

clock May 20, 2015 07:05 by author Rebecca

In Silverlight, due to security issues, an ordinary application is NOT allowed to write to/read from arbitrary locations on the file system (except through some dialogs). How do we save those data temporarily inside the file system (such as a text file) so that the application can retrieve and use it later? Sure you can use the Isolated Storage Feature in Silverlight.

Isolated Storage allows you to access to a small segment of hard-disk space, which you will have no idea where the files are being stored. Usually you need it when you want to store small amounts of not essential information (eg: user-specific details, user preferences). Especially when you want to communicate with the web service, having the back-up storage can enable to page to reload the data without the user retyping again.

You can save DateTime into the memory and can retrieve it using Isolated Storage. Here is the example:'

Step 1

First, you need to open an Isolated Store. You can use the IsolatedStorageFile class and call the static IsolatedStorageFile.GetUserStoreForApplication() method:

IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()

With this, you can use System.IO namespace to write and read data.

Step 2

Now, you have to write DateTime into memory as follows:

using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = store.CreateFile("Date.txt"))
                {
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(DateTime.Now);
                    writer.Close();
                }
                textBox1.Text = "Data written";
            }

Step 3

Then, you can retrieve DateTime from memory, use this following code:

using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = store.OpenFile("Date.txt", FileMode.Open))
                {
                    StreamReader reader = new StreamReader(stream);
                    textBox2.Text = reader.ReadLine();
                    reader.Close();
                }
            }

Simple right?

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Silverlight 6 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Create Web Service in SIlverlight

clock May 13, 2015 06:35 by author Rebecca

Have you ever wonder, how do you actually program on the server side to handle the requests by the client? And how do a client know that his uploading request has been complete before proceeding to the another one? There are several approaches for the solution. Here, I introduce how to create WCF (Windows Communication Foundation) web service in Silverlight, which involves lesser code.

 

How to Create a WCF Web Service:

a) Right-click your ASP.NET website, add the Silverlight-enabled WCF Service template.
b) Create a new method (with the OperationContract attribute)
c) Right-click your Silverlight project -> Add Service. Click Discover button. Then Click OK button.

After you have add a service reference, Visual Studio actually creates a proxy class that you can interface with the Web Service. The proxy class is named after the original Service class name + the world Client at the end.

How to use or call the WCF Web Service:

Import the namespace for the service reference. In Silverlight, all web services are asynchronous. That means after you have called the method to fire it, it returns immediately and proceed to the next line of code. When the response is received, you handle the event inside the MethodNameCompleted.

A standard order of using the web service is as follow:

    Service1Client myService = new Service1Client();
    myService.BeginUploadCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(myService_BeginUploadCompleted);
    myService.BeginUploadAsync(...);

That's all, simple, right?

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Silverlight 6 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Add Data into a DataGrid Dynamically

clock May 6, 2015 06:48 by author Rebecca

The DataGrid control in the Silverlight is one of the very important and useful controls. It is highly customizable with support of sorting, editing, grouping and paging. Here, this tutorial will talk about how to add data dynamically into the DataGrid. Specifically, it lets the user to input the Staff data during run time, as many as he/she likes.

Here the example of output in Silverlight that I have made:

Add a DataGrid by Drag and Drop, then add 3 columns

Note that each column has a binding path to the variable it displays.

    <sdk:DataGrid AutoGenerateColumns="False" Height="206" HorizontalAlignment="Left" Margin="12,65,0,0" Name="myDataGrid" VerticalAlignment="Top" Width="352" >
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTextColumn Header="Name" Binding="{Binding Path=staffName, Mode=OneWay}" Width="120"></sdk:DataGridTextColumn>
                    <sdk:DataGridTextColumn Header="ID" Binding="{Binding Path=staffID, Mode=OneWay}" Width="100"></sdk:DataGridTextColumn>
                    <sdk:DataGridTextColumn Header="Age" Binding="{Binding Path=staffAge, Mode=OneWay}" Width="100"></sdk:DataGridTextColumn>
                </sdk:DataGrid.Columns>
            </sdk:DataGrid>

Create a class for the Data Object. Eg: Staff.cs

Define the variables which used in the data binding in the class

            public string staffName { get; set; }
            public string staffID { get; set; }
            public string staffAge { get; set; }

            public Staff(string _name, string _id, string _age)
            {
                staffName = _name;
                staffID = _id;
                staffAge = _age;
            }

Add Button

This is the button that fires the event assigning the values. Here, I use ObservableCollection<Staff> to store the data inside the DataGrid. (Define it as a global variable).

            private void AddButton_Click(object sender, RoutedEventArgs e)
            {
                //Get the text from the textboxes
                string _name = textBox1.Text;
                string _id = textBox2.Text;
                string _age = textBox3.Text;
              
                //Add them inside the ObservableCollection variable: collectionInRow
                collectionInRow.Add(new Staff(_name, _id, _age));

                //This is the Most Vital line: assign the Source of the dataGrid to the ObservableCollection
                myDataGrid.ItemsSource = collectionInRow;
            }

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Silverlight 6 Hosting Denmark - HostForLIFE.eu :: How to Get and Set the Control's Coordinate

clock April 29, 2015 06:40 by author Rebecca

Unlike normal C#, in Silverlight, you can't access a control's coordinate through the object.Location.X and object.Location.Y. Instead, it is more troublesome to get and set the values. So this tutorial will tell you wow to get and set the control's coordinate/location/position.

For example, if you want to add Label on the GUI through the code instead of XAML, you have to do the following codes:

          Label[] arrayScores = new Label[MAX_PLAYERS]; //MAX_PLAYERS = 4
          for (int i = 0; i < arrayScores.Length; i++)
                {
                    arrayScores[i] = new Label();
                    arrayScores[i].Name = "Scores" + i;
                    arrayScores[i].Width = 50;
                    arrayScores[i].Height = 30;
                }

But that's not enough, you haven't set the coordinates of the Labels. You might think that adding the remaining codes at anywhere can do the job. However, it does not. Remember to put the coordinates setting code 'AFTER' the page is loaded.

Step 1

Add this.Loaded event in the constructor after the InitializeComponent()

    public MainPage()
            {
                InitializeComponent();
                ...
                ...
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }

Step 2

Set coordinates using CANVAS: set position, then add into canvas.

void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Canvas.SetLeft(arrayScores[0], SCORE_OFFSET_LEFT);
            Canvas.SetLeft(arrayScores[1], SCORE_OFFSET_LEFT);
            Canvas.SetLeft(arrayScores[2], SCORE_OFFSET_LEFT);
            Canvas.SetLeft(arrayScores[3], SCORE_OFFSET_LEFT);
            canvas1.Children.Add(arrayScores[0]);
            canvas2.Children.Add(arrayScores[1]);
            canvas3.Children.Add(arrayScores[2]);
            canvas4.Children.Add(arrayScores[3]);
        }

That's all! And you're done!

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



Silverlight with Free ASP.NET Hosting - HostForLIFE.eu :: How to Make Silverlight Overlay Notification

clock April 22, 2015 07:01 by author Rebecca

Most of us do not like applications that continuosly bothering with popup messages to make us aware that something happened. Sometimes, a message box coming up saying "Changes were saved succesfully" right after pressing the save button, this condition is so bothering because our work can be interrupted by the unimportant notification box. Maybe, we better would like to be told that it worked if it allows us to keep going or you'd better be told if something went wrong.

For example, during Christmas a lot of messages full of best wishes are going around. You can sent one of those to one friend and after a while an Overlay Notification appeared at the bottom of your screen saying "Message received by [contact]". So, in this post, I will tell you how to make that kind of notification in Silverlight which isn't keep bothering you while you were working on something.

Step 1

First, let us create a User Control. The control will be the already mentioned Overlay Notification. You canl make it appear and disappear after a while without user interaction. This could be the XAML code:

 <UserControl x:Class="SilverlightTestApp.Controls.OverlayNotification"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
   
    <UserControl.Resources>
        <Storyboard x:Name="ShowMessage" Completed="ShowMessage_Completed">
            <DoubleAnimation
            Duration="00:00:06"
            From="0.00"
            To="1.00"
            AutoReverse="True"
            Storyboard.TargetName="Popup"
            Storyboard.TargetProperty="Opacity"/>           
        </Storyboard>       
    </UserControl.Resources>
   
    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Center" >
        <Border BorderBrush="Black" BorderThickness="1" MinWidth="150" MaxWidth="550" MaxHeight="75"
                   CornerRadius="4" Background="Transparent" Visibility="Collapsed" Opacity="0" x:Name="Popup">
            <TextBlock x:Name="lblMessage" HorizontalAlignment="Center" TextWrapping="Wrap" MaxWidth="400" MaxHeight="75"></TextBlock>
        </Border>
    </Grid>   

</UserControl>

Step 2

You have a Storyboard that will be triggered whenever you want to show the Notification. It will last 6 seconds (plus another 6 because of the AutoReverse=true). And will change the Opacity of our notification area to give the impression that it fades in and out.

Then you already had a Border with rounded corners. You'll have to make it visible whenever you want to show the message and hide it when the Storyboard is done. Inside of this Border, you will have a Textblock where your message will be displayed.

Let's take a look at the code behind:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SilverlightTestApp.Controls
{
    public partial class OverlayNotification : UserControl
    {
        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }
            set
            {
                _message = value;
                lblMessage.Text = value;
                Popup.Visibility = Visibility.Visible;
                ShowMessage.Begin();
            }
        }

        private System.Windows.Media.Color _color;
        public System.Windows.Media.Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                _color = value;
                var newBrush = new SolidColorBrush();
                newBrush.Color = value;
                lblMessage.Foreground = newBrush;
            }
        }

        public OverlayNotification()
        {
            InitializeComponent();
        }

        private void ShowMessage_Completed(object sender, System.EventArgs e)
        {
            Popup.Visibility = Visibility.Collapsed;
        }
    }
}

You will expose at least the Message property (you also have the Color property for the font). Notice that everytime you set the Message property we update the Textblock's text, make the Border visible and trigger the Storyboard. Also noticed that you can handle the Storyboard's completed event to hide the Border.

To use it, just add this new User Control into the view where you want to use it in the same way that you would place a Textbox or any other control:

<my:OverlayNotification x:Name="myOverlayNotification"/>

Then, whenever you want to show a Notification, just set the Message property with the message you want to display:

 myOverlayNotification.Color = Colors.Red;
 myOverlayNotification.Message = "This is a test notification";

Feel free to play around with it modifying the layout and appeareance of the control in the XAML or adding more properties to be able to customize it more, for example, adding a BackgroundColor property.

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service. Once your trial period is complete, you decide whether you'd like to continue.



Silverlight with Free ASP.NET Hosting - HostForLIFE.eu :: How to Create Simple Navigation in Silverlight ?

clock April 21, 2015 08:08 by author Peter

Navigation Framework is absolutely good however in some cases we have a tendency to don't need to use the Navigation Framework. This navigation technique may be used instead that provides simple Navigation. Add the following code in App.xaml:

private static Grid root    
public static void Navigate(UserControl newPage)
{
UserControl oldPage = root.Children[0] as UserControl;
root.Children.Add(newPage);
root.Children.Remove(oldPage);
}

Now, Edit the App.xaml as shown below:
Previous code: 
private void Application_Startup(object sender, StartupEventArgs e)
{
 this.RootVisual = new MainPage();
 }

Modified code:

private void Application_Startup(object sender, StartupEventArgs e)
{
root = new Grid();
root.Children.Add(new MainPage());
this.RootVisual = root;     
}


Create a new usercontrol NewPage . Add Button to the Page inorder to navigate to the home. equally produce a button within the MainPage.xaml as well inorder to navigate to the NewPage. within the Button Click event add the following code:
       App app = (App)Application.Current;
        App.Navigate(new NewPage());


Application.Current gets the System.Windows.Application object for this application. The new instance of the Page is passed to the Navigate method of App class. When we run the code we are able to navigate between the MainPage and also the NewPage.xaml.

 

Silverlight 6 with Free ASP.NET Hosting

Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service. Once your trial period is complete, you decide whether you'd like to continue.

 



Silverlight 6 with Free ASP.NET Hosting - HostForLIFE.eu :: How to Create a Progress Bar while Uploading File

clock April 15, 2015 06:04 by author Rebecca

When you worked with Silverlight to create an GUI to let the user to upload the file, it is important to create a progress bar to make the user aware of the uploading progress.Today, I will show you how to create a progress bar while uploading a file.

Here is the sample of the progress bar that I've created:

Several resources can be obtained online, but the explaination is either not clear enough, or there are redundant codes confusing people. Here, the code is as simplest as possible, with the assumption that,
a) there is no connection lost between the client and the server during the process
b) there is no data corrupted during the transmission
c) small file size (can be edited)

Before we go with code, first you can observe that there are 4 UI components:
a) Browser button
b) Textbox shows file name (can be disabled)
c) Upload button
d) Progress bar + labels

Browser Button

Here's the code to create the browser button:

    OpenFileDialog dialog = new OpenFileDialog(); //OpenFileDialog will open a file dialog which allows the use to browser the wanted file.
    if ((bool)dialog.ShowDialog())
    {
          globalFileStream = dialog.File.OpenRead();
          ....
          ....
    }

Upload Button

An always updating progress bar means that, the upload progress has to be done 'Chunk' by 'Chunk'. To achieve this, we read the file stream 'Chunk' by 'Chunk and upload it.

Step 1 : Send First Chunck

    int steps = (int)(fileLength / (long)CHUNK_SIZE);
    progressBar1.Minimum = 0;               //set prograssbar info
    progressBar1.Maximum = steps;
    int read = 0;
    byte[] buffer = null;                                                                //buffer to store the file stream chunk by chunk
    if (globalFileStream.Length <= CHUNK_SIZE)                            //consider if the file size is smaller than the predefined chunk size
    {
          buffer = new byte[(int)globalFileStream.Length];
    }
    else
    {
          buffer = new byte[CHUNK_SIZE];
    }
    read = globalFileStream.Read(buffer, 0, buffer.Length);
    filePosition += read;
    myUpload.BeginUploadAsync(fileName, destinationFolder, buffer);       //begin upload the first chunk

Step 2: Sends second and subsequent chunk

    UpdateProgressBar(); //Update progress bar
    if (filePosition < fileLength)
    {
         int read = 0;
         int readSize = CHUNK_SIZE;
         byte[] buffer = null;
         long diff = fileLength - filePosition;
         if (diff < CHUNK_SIZE)
         {
               readSize = (int)diff;
         }
         buffer = new byte[readSize];
         globalFileStream.Seek(filePosition, SeekOrigin.Begin);
         read = globalFileStream.Read(buffer, 0, readSize);
         filePosition += read;
         myUpload.ContinueUploadAsync(theFileName, "here", buffer);

For your information, progress bar provided by Silverlight doesn't have the percentage displayed. Hence, I additionally put a label on top of the progress bar. The label contents are the percentage of the file stream sent to the server.

Silverlight 6 with Free ASP.NET Hosting
Try our Silverlight 6 with Free ASP.NET Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



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