Silverlight Dashboard


I  have found a dashboard control from Microsoft expression website (created by infragistics.com) which  inspired me to create a  dashboard control.

Click here to watch live   |   Click here to Download

In this article I’m going to explain the types of controls used to create a interactive dashboard.

  1. Grid based layout
  2. Customer Master / Detail  list
  3. Chart control
  4. Bing Map control
  5. Custom Splash screen


Grid based layout

A simple grid  layout with 2/2 row column.

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5"/>
<RowDefinition Height="85"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>

Customer Master / Detail  list

For master detail scenario ListBox control is the right choice to build.. The control will list the customer name and location, once you click the detail link its going to take you to a popup window for more information.
<ListBox x:Name="lbCustomer" Style="{StaticResource ListBoxBackground}" SelectionChanged="CustomerChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel>
<TextBlock Text="{Binding Name}" Foreground="YellowGreen" FontSize="14" />
<HyperlinkButton Content="Detail" Foreground="DarkRed" Name="lnkDetailCustomer" Click="CustomerDetailClick" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Chart Controls

Bar Chart

<toolkit:Chart Style="{StaticResource ChartBackground}" Name="chartCoulumn" Width="490" Height="290">
<toolkit:Chart.Series>
<toolkit:ColumnSeries SelectionChanged="ColumnSeriesChanged" Name="chart1" Title="Sales" DependentValuePath="Profit"
IndependentValuePath="Month"
AnimationSequence="Simultaneous"
IsSelectionEnabled="True">
<toolkit:ColumnSeries.DataPointStyle>
<Style TargetType="toolkit:ColumnDataPoint">
<Setter Property="Background" Value="YellowGreen"/>
<Setter Property="BorderBrush" Value="YellowGreen"/>
</Style>
</toolkit:ColumnSeries.DataPointStyle>
</toolkit:ColumnSeries>
</toolkit:Chart.Series>
</toolkit:Chart>

Pie chart

<toolkit:Chart Style="{StaticResource ChartBackground}" x:Name="chartPie" VerticalAlignment="Top" Width="340" Height="290">
<toolkit:Chart.Series>
<toolkit:PieSeries Margin="0,0,0,0" Padding="0,0,0,0" IndependentValuePath="Month"
DependentValuePath="Profit" AnimationSequence="Simultaneous"/>
</toolkit:Chart.Series>
</toolkit:Chart>

Map

<bing:Map Width="600" Grid.Row="2" Margin="2,2,2,2" HorizontalAlignment="Center" VerticalAlignment="Stretch"
CredentialsProvider="<Replace your credential here" Name="map" LogoVisibility="Collapsed" Culture="en-US" >
</bing:Map>

Click here to watch live   |   Click here to Download

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

Animation using PathListBox control in Silverlight


The PathListBox is new control introduced in Silverlight 4.0 for listing items in a various shapes like path, circle, arc, rectangle etc. This control is similar to traditional ListBox control which support data binding and display of one or more items at design time or dynamically at run time. The pathlistbox provides many properties like orienation, padding etc.

Watch Video |  Live Demo Download Source Code | Download Presentation


In this tutorial, we’ll create a simple animation using PathListBox Control..

Open Expression Blend Editor & Create a new project in Silverlight Application + Website.

Add a new shape  Ellipse in to the page.

Add a PathListBox control in to the page(PLB).

Drag & drop few images in to PLB control. (Press control to select multiple items from the project properties).

 Select PLB control from object & time line window.

Go to PLB control properties window and find out Layout Paths.

Click on select an object to use as a LayoutPath.

Select Ellipse shape as the LayoutPath


The images should show in circular layout path


Add a Projection for Ellipse  shape called PlaneProjection to rotate the Ellipse.

Add a StoryBoad control from object & time line window.

Switch to XAML version and write few lines of XAML code for animation purpose.

Add a Double Animation inside the StoryBoard control and set Target name & properties.

Add the following line of code in the Page Load method in order to start the animation.

Hit F5 and see the demo.


Watch Video |  Live Demo Download Source Code | Download Presentation

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

Thanks
Deepu

Silverlight Integration in MOSS 2007 with out WebPart


In this article I will walk you through how you can integrate a Silverlight application in Sharepoint with out using any webpart. (Download the STP file)



I will use one of  my existing silverlight slide show application for this demo..

Upload your silverlight related files in the sharepoint repository,  here I  am uploading Silvrlight.js, Silverlight XAP file  and images folder in the Shared Document library


The next step is open the website in  SPD (Sharepoint Designer) and create a aspx page under Shared Documents library and add some markup code inside the content place holder (PlaceHolderMain) and copy paste the silverlight object and javascript code.

Save & preview the page in browser you should be able to see your Silverlight application running inside  Sharepoint..

Download the STP file

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

Thanks
Deepu

Export Data Grid to Excel in Silverlight 4.0


One of the great feature in Silverlight 4.0 is  COM interoperability, now your Silverlight application can talk with Office applications using Com Automation Factory. This feature requires a trusted application (elevated permissions). In this article I am going to explain how you can export your data from datagrid to excel spread sheet as  OOB (Out of browser) application using C# 4.0 magic keyword called “dynamic“.

You can Download the complete source code from here

Create a new Silverlgiht 4.0 project using VS 2010 and add Microsoft.CSharp as reference (for C# 4.0 dynamic keyword) and also the add the name space System.Runtime.InteropServices.Automation for  com interoperability

I am using a customer class with some getter and setter properties to bind the datagrid.

Customer Class


using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Runtime.InteropServices.Automation;

 public class Customer
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public bool IsSubscribed { get; set; }
 }

Method for Binding customer list to the Data Grid

 public ExportToExcel()
 {
 InitializeComponent();
 BindDataGrid();
 }

 void BindDataGrid()
 {
 int count = 10;
 List<Customer> customers = new List<Customer>();
 for (int i = 0; i < count; i++)
 {
 customers.Add(new Customer()
 {
 FirstName = "First Name " + i,
 LastName = "Last Name " + i,
 Age = i + 10,
 IsSubscribed = (i % 2 == 0)
 });
 }
 dgCustomers.ItemsSource = customers;
 }

Method for exporting data from data grid to excel spread sheet

 void GenerateSpreadSheet(object sender, RoutedEventArgs e)
 {
 int rowIndex = 1;
 int coulmnIndex = 1;

 try
 {
 dynamic excel = AutomationFactory.CreateObject("Excel.Application");

 excel.workbooks.Add();

 dynamic sheet = excel.ActiveSheet;

 for (int i = 0; i < dgCustomers.Columns.Count; ++i)
 {
 dynamic headerCell = sheet.Cells[rowIndex, coulmnIndex + i];
 headerCell.Value = dgCustomers.Columns[i].Header;
 headerCell.Font.Bold = true;
 headerCell.Interior.Color = 0xFF00;
 }

 foreach (Customer customer in dgCustomers.ItemsSource)
 {
 rowIndex++;

 //column 1
 dynamic cellFirstName = sheet.Cells[rowIndex, 1];
 cellFirstName.Value = customer.FirstName;
 cellFirstName.Font.Color = 003399;

 //column 2
 dynamic cellLastName = sheet.Cells[rowIndex, 2];
 cellLastName.Value = customer.LastName;
 cellLastName.Font.Color = 003399;

 //column 3
 dynamic cellAge = sheet.Cells[rowIndex, 3];
 cellAge.Value = customer.Age;
 cellAge.Font.Color = 003399;

 //column 4
 dynamic cellSubscribed = sheet.Cells[rowIndex, 4];
 cellSubscribed.Value = customer.IsSubscribed ? "Yes" : "No";
 cellSubscribed.Font.Color = 003399;
 }
 excel.Visible = true;
 }
 catch (Exception ex)
 {
 MessageBox.Show("Error generating excel: " + ex.Message);
 }
 }

The xaml code creates a data grid and a button

<Grid x:Name="LayoutRoot" Background="White">
 <Grid.RowDefinitions>
 <RowDefinition Height="350"></RowDefinition>
 <RowDefinition Height="5"></RowDefinition>
 <RowDefinition Height="25"></RowDefinition>
 <RowDefinition Height="*"></RowDefinition>
 </Grid.RowDefinitions>
 <my:DataGrid x:Name="dgCustomers" Grid.Row="0" AutoGenerateColumns="True" HeadersVisibility="All"
 RowBackground="Azure" AlternatingRowBackground="LightSteelBlue" ColumnWidth="85" RowHeight="30">
 </my:DataGrid>
 <Button  Grid.Row="2" Content="Export To Excel" Height="25" Width="120" Name="btnExportExcel" Click="GenerateSpreadSheet"  />
 </Grid>

Out of Browser set up

It is really easy to make a Silverlight applicaton as run out of browser mode. Right click the Silverlight project, select properties and check the ENABLE RUNNING APPLICATION OUT OF THE BROWSER.

Elevated permissions (Trusted Application)

Right click Silverlight Project – > Select Properties – > Click Out-Of-Browser Settings

You can Download the complete source code from here

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

Thanks
Deepu

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

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