Selecting and Displaying Images and Text Files from a Client Machine using Silverlight 2
A Silverlight application runs in a Sandbox security model. We therefore cannot access files directly from the client machine, where the application is running. One of the ways is to retrieve the file from the server; by first saving that file to the server and then retrieving it back. This takes more time and consumes server memory. Many a times we do not intend saving that file to the server. In this article, I will demonstrate how to select image and text (doc/.txt/.rtf/etc) files from client machine and show data from that to user.
I have seen a nice article previously written by Suprotim which discusses about Loading and Playing Media Files at Runtime using Silverlight 2. Silverlight provides a safe File Open dialog box, to ease the process of creating safe file uploads. We will use the same concept of Open File Dialog and Streaming over here. This article will interest users who want to create a carousal or a similar kind of an application by selecting and reading images/text files from their machine.
In this demonstration, we will place an Image and a TextBlock field on the Page. We will then select the image from the Client Machine and will set the Source of that Image to that selected image. Similarly we will select a doc/text file from the Client Machine and will set the text of that text block from the file selected. Let us get started:
Step 1: Open Visual Studio 2008 > File > New Project > Select the language (C# or VB.NET) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Application’.
Step 2: Type a name (SettingImageAndReadingWordAndDocFileFromClient) and location for the project> click ok (see Figure below).
Choose the first option ‘Add a new ASP.NET Web project to the solution to host Silverlight’ and the project type as ‘ASP.NET Web Site’ and click OK. You will see that two projects are created: SettingImageAndReadingWordAndDocFileFromClient.Web and SettingImageAndReadingWordAndDocFileFromClient.
Step 3: In the Page.Xaml file, add two controls; one will be an Image and the other a TextBlock Control. We will place both these controls in a Canvas and will set their attached property ‘Canvas.Top’ so that both will come one below the other. We will not set the Image Source and Textblock text property, so initially they will be empty.
After setting a few additional properties, our Xaml will look like this.
<Canvas x:Name="LayoutRoot" Background="White">
<Image x:Name="img" Height="200" Width="200" Canvas.Top="0" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform></Image>
<TextBlock x:Name="txtBlock" Height="600" Canvas.Top="200"></TextBlock>
</Canvas>
Step 4: We will add a storyboard with a small animation which will rotate our image by 90 degree. We will call this animation once the image has loaded completely.
Our Storyboard will look like this.
<UserControl.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="214"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="269.697"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
The entire Page.xaml will look similar to the following:
<UserControl x:Class="SettingImagesAndReadingWordAndDocFileFromClient.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<UserControl.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="214"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="1"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="img" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)">
<SplineDoubleKeyFrame KeyTime="00:00:02" Value="269.697"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Canvas x:Name="LayoutRoot" Background="White">
<Image x:Name="img" Height="200" Width="200" Canvas.Top="0" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform></Image>
<TextBlock x:Name="txtBlock" Height="600" Canvas.Top="200"></TextBlock>
</Canvas>
</UserControl>
Step 5: Let us write some code in the Page.Xaml.cs or .vb file for selecting the Text file and the Image File from our client machine. We will use a OpenFileDialog. After we have selected the Text file using the OpenFileDialog, we will start reading the stream and then will open another OpenFileDialog for selecting the Image.
Note 1: Do not forget to add the namespace System.IO;and System.Windows.Browser;
Note 2: Please note that the order is important here. First select the Text File and then the Image File, or else modify the logic according to your need.
We will attach the loaded event in the Page constructor and write our logic over there. Our code behind will look like this:
C#
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Windows.Media.Imaging;
namespace SettingImagesAndReadingWordAndDocFileFromClient
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
//Attach Loaded Event so that on load completion of user control our code //will execute
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
//At first we are selecting text files
OpenFileDialog opndialog = new OpenFileDialog();
opndialog.Filter = ".txt|*.txt|.doc|*.doc|.docx|*.docx";
if ((bool)opndialog.ShowDialog())
{
FileInfo file = opndialog.File;
Stream fileContents;
fileContents = file.OpenRead();
using (StreamReader reader = new StreamReader(fileContents))
{
txtBlock.Text = reader.ReadToEnd();
}
}
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = false;
opendialog.Filter = ".jpg|*.jpg|.jpg|*.jpeg";
if ((bool)opendialog.ShowDialog())
{
try
{
FileInfo finfo = opendialog.File;
BitmapImage bmp = new BitmapImage();
bmp.SetSource(finfo.OpenRead());
img.Source = bmp;
Storyboard1.Begin();
}
catch
{
}
}
}
}
}
VB.NET
Imports System.Windows
Imports System.Windows.Controls
Imports System.IO
Imports System.Windows.Media.Imaging
Namespace SettingImagesAndReadingWordAndDocFileFromClient
Partial Public Class Page
Inherits UserControl
Public Sub New()
InitializeComponent()
'Attach Loaded Event so that on load completion of user control our code //will execute
AddHandler Loaded, AddressOf Page_Loaded
End Sub
Private Sub Page_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
'At first we are selecting text files
Dim opndialog As New OpenFileDialog()
opndialog.Filter = ".txt|*.txt|.doc|*.doc|.docx|*.docx"
If CBool(opndialog.ShowDialog()) Then
Dim file As FileInfo = opndialog.File
Dim fileContents As Stream
fileContents = file.OpenRead()
Using reader As New StreamReader(fileContents)
txtBlock.Text = reader.ReadToEnd()
End Using
End If
Dim opendialog As New OpenFileDialog()
opendialog.Multiselect = False
opendialog.Filter = ".jpg|*.jpg|.jpg|*.jpeg"
If CBool(opendialog.ShowDialog()) Then
Try
Dim finfo As FileInfo = opendialog.File
Dim bmp As New BitmapImage()
bmp.SetSource(finfo.OpenRead())
img.Source = bmp
Storyboard1.Begin()
Catch
End Try
End If
End Sub
End Class
End Namespace
On running the application, we are presented with a dialog. Select a text file first and click on Open in the OpenFileDailog. In a similar manner choose an Image File and click Open. You will see that the text file and the image gets displayed as shown below. The image also gets animated when loading. The output will vary on your machine depending on the text and image file you have selected:
I hope you liked the article and I thank you for viewing it.
Harsh Bardhan (MCTS) has developed IT solutions with a diverse background in server side and client side development. He is currently working with SymphonyServices as a Software developer. Harsh continues to be an integral part of open forums on cutting-edge technology like Silverlight, including the .NET Framework and Web Services. Harsh has expertise with many Microsoft technologies, including .NET, LINQ, WCF Service, Silverlight and a strong background in SQLServer.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!