Simple Image Scroller Slide Show using Silverlight ListBox control


Last week I was working on a image scroll-er slide show using silverlight listbox control and it worked great and I thought I’d  share this.

Click here to view the live demo (images may take a while to load)
Click here to download the article

If you find the Image Scroller code library useful, please consider donating

Xaml C# Code

public class ImageScroller
 {
 public string Url { get; set; }
 }

 public partial class ImageGallery : UserControl
 {
 int index = 0;

 void StartSlideShow()
 {
 DispatcherTimer timer = new DispatcherTimer();
 timer.Interval = TimeSpan.FromMilliseconds(2500); //delayed for 2.5 seconds
 timer.Tick += (sender, e) =>
 {
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[index]); //scroll to the current item
 lbScrollGallery.SelectedIndex = index; //highlight the selected item in the list box scroller
 ImageScroller item = (ImageScroller)lbScrollGallery.Items[index]; // getting the current item
 imgPreview.Source = new BitmapImage(new Uri(item.Url, UriKind.Relative));
 if (index < lbScrollGallery.Items.Count - 1)
 {
 index++;
 }
 else
 {
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[0]); //scroll to the first item
 index = 0; //reset the index when it reaches to the last item
 }
 };
 timer.Start();
 }

 public ImageGallery()
 {
 InitializeComponent();
 LoadImages();
 StartSlideShow();
 }

 void LoadImages()
 {
 lbScrollGallery.ItemsSource = new List<ImageScroller>
 {
 new ImageScroller
 {
 Url = "images/Chrysanthemum.jpg"
 },
 new ImageScroller
 {
 Url = "images/Desert.jpg"
 },
 new ImageScroller
 {
 Url = "images/Hydrangeas.jpg"
 },
 new ImageScroller
 {
 Url = "images/Jellyfish.jpg"
 },
 new ImageScroller
 {
 Url = "images/Koala.jpg"
 },
 new ImageScroller
 {
 Url = "images/Lighthouse.jpg"
 },
 new ImageScroller
 {
 Url = "images/Penguins.jpg"
 },
 new ImageScroller
 {
 Url = "images/Tulips.jpg"
 }
 };

 imgPreview.Source = new BitmapImage(new Uri("images/Chrysanthemum.jpg", UriKind.Relative)); //load default image while page loads
 }

 void ScrollerSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
 ListBox listbox = (ListBox)sender;
 ImageScroller item = (ImageScroller)listbox.SelectedItem;
 if(item != null && ! string.IsNullOrEmpty(item.Url))
 {
 imgPreview.Source = new BitmapImage(new Uri(item.Url, UriKind.Relative));
 index = listbox.SelectedIndex;
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[index]);
 }
 }
 }

Hope this help and If you have any comments, please feel free to write your feedback.

Click here to view the live demo (images may take a while to load)

You can download the entire article from here

If you find the Image Scroller code library useful, please consider donating

Thanks
Deepu

Advertisements

Loading User Controls Dynamically in Silverlight


When you develop Silverlight web sites you may need to change the content that’s shown in the Silverlight page programmatically, normally changing the layout controls or child controls etc..

In the above image you can see three navigation button’s and when you press each button the content will load dynamically from each separate user control XAML file (shown right side of the image) and render the content inside the canvas.

The below few lines of code which loads the control loading  dynamically and render in to the canvas control

 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + "ControlName"); //replace with your user control class name
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);

In the each  button control I am setting the datacontext attribute value as the User Control Class Name ie DataContext=”HomeControl”

XAML Markup

<Canvas Grid.Row="0" Grid.Column="0" Background="Black">
<Button Width="100" DataContext="HomeControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="25" Content="Home"/>
<Button Width="100" DataContext="AboutControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="140" Content="About"/>
<Button Width="100" DataContext="ContactControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="255" Content="Contact"/>
</Canvas>

<Canvas Name="canvasBody" Grid.Row="1"  Grid.Column="0" Background="Black" />

Code behind

 public DefaultPage()
 {
 InitializeComponent();
 RenderControl("HomeControl"); //load default control for home page.
 }

 private void Navigation_Click(object sender, RoutedEventArgs e)
 {
 Button btn = sender as Button;
 if (btn != null && btn.DataContext != null)
 {
     RenderControl(btn.DataContext.ToString());
 }
 }

 void RenderControl(string currentControl)
 {
 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + currentControl);
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);
 }

Hope this will help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Multiple file uploading in Silverlight


In this article I am going to explain how we can upload multiple files in Silverlight 3.0 using OpenFileDialog class

Click here to download the article

Open VS 2008 and create a new Xaml file called MultiFileUploader.xaml. Copy paste the below markup.

<Canvas Width=”640″>

<TextBlock Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”150″ x:Name=”txtProgress”  Foreground=”Green” Width=”120″/>

<Button Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”180″ Click=”FileUpload_Click” Width=”100″ Height=”25″ Content=”Select Files”/>

</Canvas>

In above Xaml I have placed two controls ie Button and Textbox.  Button control for selecting files and Texbox control,
shows the total file count which is uploaded in the server.

Code behind for MultiFileUploader.xaml.cs

int totalFilesToUpload = 0;
int totalFilesUploaded = 0;

private void FileUpload_Click(object sender, RoutedEventArgs e)
 {
 this.txtProgress.Text = string.Empty;

 OpenFileDialog oFileDialog = new OpenFileDialog();
 oFileDialog.Filter = "All Image Files ( JPEG,GIF,BMP,PNG)|*.jpg;*.jpeg;*.gif;*.bmp;*.png|JPEG Files ( *.jpg;*.jpeg )|*.jpg;*.jpeg|GIF Files ( *.gif )|*.gif|BMP Files ( *.bmp )|*.bmp|PNG Files ( *.png )|*.png";
 oFileDialog.FilterIndex = 1;
 oFileDialog.Multiselect = true;

 string data = string.Empty;

 if (oFileDialog.ShowDialog() == true)
 {
 foreach (var file in oFileDialog.Files)
 {
 using (System.IO.Stream fileStream = GetFileData(file.OpenRead()))
 {
 StreamResourceInfo oStreamResource = new StreamResourceInfo(fileStream, null);

 byte[] array = new byte[oStreamResource.Stream.Length];

 oStreamResource.Stream.Read(array, 0, (int)oStreamResource.Stream.Length);

 data = Convert.ToBase64String(array);

 WebClient oWebClient = new WebClient();

 string fileName = Guid.NewGuid().ToString().Replace("-", "") + file.Extension;

 oWebClient.UploadStringAsync(new Uri("http://localhost:50848/FileUpload.ashx?file=" + fileName), null, data, fileName);

 oWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(oWebClient_UploadtxtProgressChanged);

 totalFilesToUpload += 1;

 data = string.Empty;
 }
 }
 }

 }

 System.IO.MemoryStream GetFileData(System.IO.Stream oFileStream)
 {
 oFileStream.Seek(0, System.IO.SeekOrigin.Begin);
 byte[] data = new byte[oFileStream.Length];
 oFileStream.Read(data, 0, (int)oFileStream.Length);
 return new System.IO.MemoryStream(data);
 }

 void oWebClient_UploadtxtProgressChanged(object sender, UploadProgressChangedEventArgs e)
 {
 totalFilesUploaded += 1;

 txtProgress.Text = !string.IsNullOrEmpty(txtProgress.Text) ? (int.Parse(txtProgress.Text) + e.BytesSent).ToString() : e.BytesSent.ToString();

 if (totalFilesUploaded == totalFilesToUpload)
 {
 txtProgress.Text = totalFilesUploaded + " files uploaded successfully (" +  txtProgress.Text + " bytes sent )";
 }
 }

The next step I am going to create a receiver application which can convert the stream object to image file and save to server. I am creating a GenericHandler  file to achieve this task (You can do it in Aspx page also).

using System;
using System.Web;
using System.IO;

namespace SilverlightApplicationDemo.Web
{
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var fileName = context.Request["file"];
            string data;
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                data = sr.ReadToEnd();
                byte[] array = Convert.FromBase64String(data);
                using (FileStream fs = new FileStream(context.Server.MapPath("~/images/") + fileName, FileMode.Create))
                {
                    fs.Write(array, 0, array.Length);
                }
            }

        }

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

Note :  I have hard-coded the FileUpload url as (http://localhost:50848/FileUpload.ashx). Don’t forget to replace with your file  upload URL.

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here

Thanks
Deepu