Saturday, October 30, 2010

Silverlight 4.0 with SharePoint 2010 (1 of 2)

It’s been a while since I used SharePoint as I was focusing lately on Silverlight, In this post I will start exploring how to use Silverlight 4.0 with SharePoint 2010, I must mention that I’m not a SharePoint expert so please feel free to update me if there’s something mentioned that is not correct.

What I like about SharePoint 2010 is that Silverlight comes right out of the box. The first thing you will note when you access SharePoint2010 sites (assuming that you have Silverlight installed) is that SP2010 makes use of Silverlight in many places, for example the Create Dialog is a just a Silverlight application

The Silverlight Create Dialog in SharePoint2010

Also the videos you upload to SP2010 assets libraries are played using a Silverlight media player

Silverlight Media Player

the entry point for you Silverlight application into SharePoint is the Silverlight Web Part which is built into SP2010, you can insert this web part into any web page

Insert a Silverlight Web Part

Let’s try to use this web part, first we will create a Silverlight application, Start Visual Studio –> Create a new Silverlight Application, no need to create a web application to host the Silverlight application as we will be hosting it inside SharePoint.

The Silverlight application is very simple, we have a TextBlock and a Button

  1. <Grid x:Name="LayoutRoot" Background="White">
  2.     <StackPanel VerticalAlignment="Center">
  3.         <TextBlock Width="200" x:Name="lbl"></TextBlock>
  4.         <Button Content="Click Me" Width="200" Click="Button_Click"></Button>
  5.     </StackPanel>
  6. </Grid>

When we click the button we set the text of the TextBlock

  1. private void Button_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             lbl.Text = "Hello SharePoint2010";
  4.         }

After we build the application we will have the xap file, upload this file to a document library on the SharePoint site

Uploading the xap file to SharePoint

Once the xap file is uploaded we need to copy its URL, right click the xap file in the documents list and select copy shortcut


Now we will add a Silverlight Web Part to host our application, So edit the current page in SharePoint and go to the Insert tab and Click on the Web Part button


Select the Silverlight Web Part (inside the Media and Content category) and click Add


A dialog box will ask you to specify the URL of the xap file, paste the URL of the xap file that you uploaded to the document library


Save the page to exit the edit mode, now try to click the button to see the text in the label


You can edit the web part to see its properties, you will find the default properties (Width, height, etc.), you can also change the xap file or you can pass custom initialization parameters to Silverlight


So now we saw how we can run a Silverlight application inside SharePoint, for smooth development it’s not convenient to go and upload the xap file to SharePoint manually, we can solve this by using VS2010 support for SharePoint, let’s start by adding a new empty SharePoint project to the Solution we had earlier. specify the site that you will use for debugging and choose the trust level to be sandboxed solution, the solution should look like the following


To deploy files to SharePoint you must add a Module to the SharePoint project let’s call it SilverlightApp


Visual Studio will add a sample.txt file, we need to replace this by the xap file, to do this first delete the sample.txt file then click on the SilverlightApp module in the Solution Explorer and go to the Properties window click the ellipse beside the property Project Output References 


The Project Output References dialog box will appear, click the Add button, Set the Project Name property to the Silverlight project and set the Deployment Type property to ElementFile

Adding The Silverlight project output to the SharePoint Module

Open the Elements.xml file, you can see our xap file specified inside the Module, change the Url attribute to point to a location inside the Master Pages document library, the Elements.xml file should look like the following

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Elements xmlns="">
  3.   <Module Name="SilverlightApp">
  4.     <File Path="SilverlightApp\SilverlightSP.xap"
  5.           Url="_catalogs/masterpage/SilverlightApp/SilverlightSP.xap" />
  6.   </Module>
  7. </Elements>

Now we are set to go, Set the SharePoint project as a startup project then Press F5 to deploy the solution to SharePoint. to verify that the solution was installed successfully go to Site Actions-> Site Settings–> Galleries–> Solutions, you should see our SharePointSL solution there

SharePoint Site Solution Gallery

Now we will add a Silverlight Web Part and set the Url of the xap file to the path we specified in the Module file (/_catalogs/masterpage/SilverlightApp/SilverlightSP.xap)

And you should be able to see the SL application running.

Another thing you will definitely need when you start developing Silverlight applications for SharePoint is debugging, you can easily enable this by going to the SharePoint project properties, on the SharePoint tab check the “Enable Silverlight debugging” check box.

Enabling Silverlight Debugging from a SharePoint project

To test this let’s add a breakpoint in our Silverlight application, we will add the breakpoint inside the Button click event handlers, Press F5 to start debugging, go to the Silverlight web part, click the button and you should be switched back to VS

Debugging Silverlight From SharePoint

That is pretty much it for this post, we saw how we can start integrating Silverlight into SharePoint 2010, in the next post we will see how we can program against SharePoint from within Silverlight.

Friday, October 08, 2010

Join us @ ROCS

The first Riyadh Online Community Summit (ROCS) will be held on 21-22 October. this is the first online event in Riyadh organized by Riyadh Communities (RSUG, DevLifeStyle, WindowsPhoneME), we are having speakers from the local communities as well as MVPs from all over the world.

the detailed agenda can be found here

Registration link

Thursday, October 07, 2010

Silverlight 4.0 Tutorial (9 of N): Using the WebCam as a Barcode Scanner

You can find a list of the previous tutorial posts here

Continuing our RegistrationBooth Application, we want to allow registered users to evaluate sessions, we don’t have a credentials store in our application so to identify the registered attendees we will use a simpler approach, in part2 we allowed printing a name tag for registered attendees, this name tag contains a barcode of the attendee id, in this post we will see how can we use the new Silverlight 4.0 WebCam functionality to be able to scan/read barcodes and extract the attendee id to identify the corresponding attendee.

During PDC09 Keynote, Scott Guthrie demonstrated a Silverlight Application that scans a book ISBN barcode and passes this ISBN to Amazon web service to retrieve the book information, we will reuse the code from this sample which can be downloaded from here.

This sample actually uses a code from a CodeProject Article (by Berend Engelbrecht) that detects barcodes inside an image. the code is located in the file BarcodeImaging.cs, so we will copy this file to our project.

The sample also has another class BarcodeCapture that derives from VideoSink, according to MSDN “To obtain video information from a video input device in Silverlight, you derive a custom video sink from VideoSink” , the important method to override in this class is OnSample which is called when the video device captures a complete video sample. the code in this method calls the BarcodeImaging method that scans the current sample bitmap for a barcode, if a barcode is found the BarcodeCapture class fires a custom event BarcodeDetected that propagates the detected barcode. so we will need to copy the BarcodeCapture.cs file to our project.

On the UI we will have two components, the first one is a rectangle that we will display the webcam stream inside it.

<Border x:Name="nameTagScannerArea" Padding="10" Grid.Column="1" Height="400" Grid.RowSpan="2" Background="{StaticResource greenBrush}" CornerRadius="30" d:IsHidden="True" >
            <TextBlock TextAlignment="Center" FontSize="14.667" FontWeight="Bold" Foreground="White" >Place your name tag infront of the camera</TextBlock>
            <Rectangle x:Name="barcodeScanner" Fill="White" Width="400" Height="300"          />                  

The second UI component is another rectangle that will be shown when a barcode is detected, the rectangle will display a simple welcome message to the user, we will add more functionality later.

<Border x:Name="welcomeArea" Padding="10" Grid.Column="1" Height="150" Grid.RowSpan="2" Background="{StaticResource orangeBrush}" CornerRadius="30" >
         <StackPanel Orientation="Horizontal">
         <TextBlock TextAlignment="Center" FontSize="14.667" VerticalAlignment="Center" FontWeight="Bold" Foreground="White" >Welcome </TextBlock>          
         <TextBlock x:Name="userName" TextAlignment="Center" FontSize="14.667" VerticalAlignment="Center" FontWeight="Bold" Foreground="White" ></TextBlock>          

We will add two new visual states, the first one is “ScanningNameTag” in this state we display the barcode scanning area and the attendee list, here’s how the UI looks like in this state

ScanningNameTag State

The button “Back” moves the UI back to the Default state by using a MoveToStateAction behavior

 MoveToStateAction behavior to go to the Default State

The second state is “WelcomeAttendee”, in this state we show the welcome area and the attendee list, here’s how the UI looks like in this state

WelcomeAttendee State

As you can see we added a Good Bye Button (btnLogout), we will add a MoveToStateAction behavior to this button so that when we click it we move to the Default state

The logout button takes us back to the default state

when we click the  “Login” button, we will start the cam and move to the “ScanningNameTag” state

private void btnLogin_Click(object sender, RoutedEventArgs e)
            if (ActivateCamera())
                if (m_Capture == null)
                    m_Capture = new BarcodeCapture();
                    m_Capture.BarcodeDetected += new EventHandler<BarcodeEventArgs>(OnBarcodeDetected);
                    m_Capture.CaptureSource = m_CaptureSource;
                VisualStateManager.GoToState(this, "ScanningNameTag", true);

The code first activates the camera to start capturing by calling the ActivateCamera function shown below

bool ActivateCamera()
            if (m_CaptureSource == null)
                m_CaptureSource = new CaptureSource();
                m_CaptureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

                VideoBrush previewBrush = new VideoBrush();
                previewBrush.Stretch = Stretch.Uniform;
                barcodeScanner.Fill = previewBrush;

                Size diff = new Size(double.MaxValue, double.MaxValue);
                Size wantedSize = new Size(640, 480);
                VideoFormat bestFormat = null;
                foreach (VideoFormat format in m_CaptureSource.VideoCaptureDevice.SupportedFormats)
                    double x = Math.Abs(format.PixelWidth - wantedSize.Width);
                    double y = Math.Abs(format.PixelHeight - wantedSize.Height);

                    if (x < diff.Width && y < diff.Height)
                        bestFormat = format;
                        diff.Width = x;
                        diff.Height = y;
                if (bestFormat != null)
                    m_CaptureSource.VideoCaptureDevice.DesiredFormat = bestFormat;
                if (CaptureDeviceConfiguration.RequestDeviceAccess() || CaptureDeviceConfiguration.AllowedDeviceAccess)
                    return true;
                    return false;
                return true;

after starting the camera we create an instance of our VideoSink (BarcodeCapture) and link the capture source with our video sink, we must also register to the event BarcodeDetected to be notified when the BarcodeCapture video sink detects a barcode in the image.

Here is the event handler for the BarcodeDetected event

void OnBarcodeDetected(object sender, BarcodeEventArgs e)
            if (e.Barcode.Length < 8)//barcode formate is ATTXXXXX

            int attendeeID=0;
            if (!Int32.TryParse(e.Barcode.Substring(3, 5), out attendeeID))

                RegistrationDomainContext context = this.Resources["registrationDomainContext"] as RegistrationDomainContext;
                        delegate(LoadOperation<Attendee> loadOperation)
                            foreach (var attendee in loadOperation.Entities)
                                lblUserName.Text = string.Format(" {0} {1}", attendee.FirstName ,attendee.LastName);
                            VisualStateManager.GoToState(this, "WelcomeAttendee", true);

First We validate the barcode format, then we call a new domain service method that retrieves the attendee based on the id, note that we are using Dispatcher.BeginInvoke method so that our code runs on the main UI thread.

Let’s run the application, click on the Login button, the webcam will start, hold the name tag in front of the webcam, you may need to move the name tag closer/way from the webcam till it picks the barcode

Barcode scanning through the web cam

Once the barcode is detected, the application will move to the WelcomeAttendee state


Note: i used the Silverlight Barcode Library to generate the barcode, cause the previous method we used (the font 3 of 9) was not recognized by Berend library

You can download the source code from here.

See you in the next post.