Grand total in a Silverlight DataGrid

I see that my post here about creating Summary rows(sub totals) in  a Silverlight datagrid is getting a lots of hits. So, I have decided to write another post on getting Grand total in a Silverlight datagrid.

Let us get in to the action.

The below application that we are going to build is going to display Datagrid with data about the revenues of each Restaurant and finally the total Revenue value of all the Restaurants.

1. Create a Silverlight project. Add a DataGrid in to the MainPage.xaml.

2. Create a class called Revenue and add Properties in to it like Restaurant and Revenue as shown below.

<br /><%%KEEPWHITESPACE%%>  public class Revenues<br /><%%KEEPWHITESPACE%%>    {<br /><%%KEEPWHITESPACE%%>        public string Restaurant { get; set; }<br /><%%KEEPWHITESPACE%%>        public decimal Revenue { get; set; }<br /><%%KEEPWHITESPACE%%>    }<br />

3. Now, lets use ObservableCollection and add data to our Revenue class created above through ObservableCollection in the MainPage Constructor .
ObservableCollection(NameSpace : System.Collections.ObjectModel)

<br /><%%KEEPWHITESPACE%%>            OCRevenues.Add(new Revenues() { Restaurant = "McDonalds", Revenue = 3000 });<br /><%%KEEPWHITESPACE%%>            OCRevenues.Add(new Revenues() { Restaurant = "KFC", Revenue = 1000 });<br /><%%KEEPWHITESPACE%%>            OCRevenues.Add(new Revenues() { Restaurant = "Pizza Hut", Revenue = 12000 });<br />

4. Now, in order to calculate the Grand total of the values in the Revenues column, put the below line of code.

<br /><%%KEEPWHITESPACE%%>           OCRevenues.Add(new Revenues() { Restaurant = "Grand Total", Revenue = OCRevenues.Sum(o =&gt; o.Revenue) });<br />

5. In the above line we are adding a new data item to OCRevenues ObservableCollection with Restaurant value as “Grand Total”, and the Revenue value to be the sum of all the Revenue values in the OCRevenues using lambda expression.

6. Build and compile the application, you will get the output as shown below.

Untitled

7. Let us make it little a bit more attractive by coloring the Grand Total row alone grey, so that it gets highlighted.

8. This can be achieved by attaching a LoadingRow event to the DataGrid. So, attach LoadingRow event to the DataGrid and then in the event handler write the following code.

<br /><%%KEEPWHITESPACE%%>    private void dgGrandTotal_LoadingRow(object sender, DataGridRowEventArgs e)<br /><%%KEEPWHITESPACE%%>        {<br /><%%KEEPWHITESPACE%%>            Revenues revenueDetails = e.Row.DataContext as Revenues;<br /><br /><%%KEEPWHITESPACE%%>            if (revenueDetails.Restaurant.Contains("Grand Total"))<br /><%%KEEPWHITESPACE%%>            {<br /><%%KEEPWHITESPACE%%>                e.Row.Background = new SolidColorBrush(Colors.DarkGray);<br /><%%KEEPWHITESPACE%%>            }<br /><%%KEEPWHITESPACE%%>        }<br />

9. In the above coding we are checking if the value of the Restaurant property in the current row is “Grand Total” and then giving the row a Dark grey background. Once you build and execute the application you will get an output as shown below.

Untitled

Advertisements

Getting the total number of characters (count) from a Silverlight text box.

Let’s say that we have a requirement where we should restrict the users to enter only a certain number of characters (let’s say 150) in a TextBox of a Silverlight usercontrol. We will see how to achieve that in Silvelright.

1. Create a Silverlight project and add a Text Box in to it as shown below.


<TextBox Height="100" Width="600" FontSize="20" HorizontalAlignment="Left" TextChanged="tbPost_TextChanged" Name="tbPost" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Top"  />

as seen above we have set its height and width to a large number to make it look like a RichTextBox, we have also added a Event Handler called tbPost_TextChanged for TextChanged Event and also the AcceptsReturn has been set to true for multiline functionality.

2. Add a TextBlock below the TextBox to display the number of characters being entered in to the TextBox.

<TextBlock FontFamily="Tahoma" Name="tblkCharLeft" Width="150" HorizontalAlignment="Left" FontSize="12" FontWeight="Light" >
 </TextBlock>

3. In the MainPage.xaml.cs write the following code in the tbPost_TextChanged  event.

private void tbPost_TextChanged(object sender, TextChangedEventArgs e)
        {
            count = 150 - tbPost.Text.Count();
            tblkCharLeft.Text = Convert.ToString(count);

            tblkCharLeft.Foreground = count  > 150 ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black);
        }

4. In the above code, we are getting the number of characters in the Text Box and subtracting it from 150(which is the total number of characters allowed) and storing the result in an Integer variable called count. And then display the number in the Text Block.

5. In the last line we are changing the Foreground of the Text block to Red color after checking if the value of the integer variable count is greater than 150 using tertiary operator.

6. When you build and run the application. You can see that, as you type in the text box the number of characters in the text box gets displayed in the text block.

7. The color of the text in the text block gets changed when the number goes more than 150 as shown in the below screenshot.

Untitled

Documents uploaded Statistics Chart in Silverlight web part

Hi All,

I’m writing a blog almost after an year. I developed a web part a few months ago in Silvelight for the Ministry of Finance, Bahrain. This web part was deployed in to the Document Center sub site of the Intranet portal. So, now you should have guessed that this web part must have something related to the document libraries.

Yes, This web part was developed to show the number of documents in each document library in the sub site in which it is deployed in. The number of documents are shown in a column chart provided by Visifire.

I have used Client Object Model that is available in SharePoint 2010 in order to access the SharePoint data in Silverlight.

Untitled

As shown in the above screenshot the chart gets display with the document library name (shorter form, you can see the full name when you hover over the columns) and the number of documents get displayed at the top of each column.

Let us look at the coding to develop this web part.

1. Create a Silverlight a Project.

2. Add a reference to the visifire dll.

3. Add the following 2 namespaces to your code file.

  • using Visifire.Charts;
  • using Visifire.Commons;

4. Now add reference to the following Silverlight client object model dlls.

  • a. Microsoft.SharePoint.Client.Runtime.
  • b. Microsoft.SharePoint.Client.Silverlight.Runtime.
The above 2 dlls are available in the following path C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin
5. Add the following namespace to the code file.
  • using Microsoft.SharePoint.Client;
6. Declare all the variables that are going to be used.
        ClientContext ctx;
        Web web;
        ListCollection listcoll;
        IEnumerable<List> NonHiddenLists;
        private IEnumerable<ListItem> listItems = null;
        private delegate void UpdateUIMethod();

7. In the MainPage constructor, write the following coding to retrieve all the SharePoint lists which are of type document library, present in the Quicklaunch, and are not hidden.

       public MainPage()
        {
            InitializeComponent();
            ctx = ClientContext.Current; //geting the current context
            web = ctx.Web; //loading the current web
            listcoll = ctx.Web.Lists; // getting the list collection from the web
            // getting the lists which are Doc. Liba nd not hidden and are on Quicklaunch
            NonHiddenLists = ctx.LoadQuery(
            listcoll
                .Where(list => !list.Hidden &&
                      list.BaseType == BaseType.DocumentLibrary && list.OnQuickLaunch == true && list.LastItemModifiedDate >= dt));
            ctx.ExecuteQueryAsync(onQuerySucceeded, null); // executing it asynchronously
        }

      private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayInfo;
            this.Dispatcher.BeginInvoke(updateUI);
        }

8. Now, in the DisplayInfo function let us retrieve the name of the document library and the number of documents in the document library (i.e. is the Item Count) from the NonHiddentLists IEnumerable collection using LINQ Query as shown below.

      private void DisplayInfo()
        {
           var details = from list in NonHiddenLists
                       where list.ItemCount > 0
                       select new { listName = list.Title, Count = list.ItemCount };

9. Now, let us loop through each each item in the above formed “details” collection to create a DataPoint and add it to a DataSeries to bind it to a Visifire chart as shown below

            Chart chart = new Chart();

            chart.Width = 400;
            chart.Height = 200;

            chart.View3D = false;
            Title title = new Title();
            chart.ToolTipEnabled = true;
            title.FontWeight = FontWeights.Black;
            title.Text = "Document Library Statistics";
            title.VerticalAlignment = VerticalAlignment.Bottom;
            chart.Titles.Add(title);

            DataSeries ds = new DataSeries();

            ds.LabelEnabled = true;
            ds.RenderAs = RenderAs.StackedColumn;

            // looping the items in the ListDetails class and creating a DataPoint and adding it to a DataSeries
            foreach (var data in Details)
            {
                DataPoint dp = new DataPoint();
                dp.AxisXLabel = data.List;
                dp.YValue = data.Count;
                dp.Cursor = Cursors.Hand;
                ds.DataPoints.Add(dp);
            }

            chart.Series.Add(ds);

10. Add the above created chart to the LayoutRoot Grid as shown below.

ChartPnl.Children.Add(chart);

Subtotals (Summary rows) in Silverlight DataGrid

I was breaking my head a lots with the knowledge and the experience that I have on Silverlight itself on the whole. After creating a complex Stored procedure in SQL and binding the results to a Silverlight DataGrid and grouping them  I was asked to insert Subtotals after each of the Group of Rows. After working hard on Grouping in the DataGrid I started working on Inserting the Subtotals and finally accomplished.

Well, guys I was finally able to accomplish this using ObservableCollection, PagedCollectionView,  and CollectionViewGroup.

Fine Lets start with them then.

1. Create a Silverlight project, I’m not gonna go deep in to it as you guys should know how to create a Silverlight project.

2. Add a DataGrid to the  MainPage.XAML.

3. Now, lets create a class and properties in them which are gonna be bound to the DataGrid.

public class Revenues
    {
        public string Restaurant { get; set; }
        public string Shift { get; set; }
        public decimal Revenue { get; set; }
    }

4.Now, lets use ObservableCollection and add data to our Class through ObservableCollection in the MainPage Constructor .
ObservableCollection(NameSpace : System.Collections.ObjectModel)

            ObservableCollection<Revenues> OCRevenues = new ObservableCollection<Revenues>();

            OCRevenues.Add(new Revenues() { Restaurant = "McDonalds", Shift = "Breakfast", Revenue = 3000 });
            OCRevenues.Add(new Revenues() { Restaurant = "McDonalds", Shift = "Lunch", Revenue = 2000 });
            OCRevenues.Add(new Revenues() { Restaurant = "McDonalds", Shift = "Dinner", Revenue = 4000 });
            OCRevenues.Add(new Revenues() { Restaurant = "KFC", Shift = "Breakfast", Revenue = 1000 });
            OCRevenues.Add(new Revenues() { Restaurant = "KFC", Shift = "Lunch", Revenue = 5000 });
            OCRevenues.Add(new Revenues() { Restaurant = "KFC", Shift = "Dinner", Revenue = 8000 });
            OCRevenues.Add(new Revenues() { Restaurant = "Pizza Hut", Shift = "Breakfast", Revenue = 12000 });
            OCRevenues.Add(new Revenues() { Restaurant = "Pizza Hut", Shift = "Lunch", Revenue = 15000 });
            OCRevenues.Add(new Revenues() { Restaurant = "Pizza Hut", Shift = "Dinner", Revenue = 10000 });

5. Now, create a PagedCollectionView which is to be grouped and then bind it to the ObservableCollection  created above.

PagedCollectionView (NameSpace: using System.Windows.Data)

PagedCollectionView PGV = new PagedCollectionView(OCRevenues);

6. Group the PagedCollectionViewb by Restaurant property of the Revenues class using PropertyGroupDescription after checking if it can be grouped.

      if (PGV.CanGroup)
            {
                PGV.GroupDescriptions.Add(new PropertyGroupDescription("Restaurant"));
            }

7. Create  a Generic List for the Revenue class. This Generic List is going to store the the subtotals in future. Also, declare a decimal variable whose usage will be known shortly.

            List<Revenues> lstRev = new List<Revenues>();

            decimal subtotal = 0;

8. Now, let’s loop through each of the Groups in PagedCollectionView using CollectionViewGroup and then loop through each row in the CollectionViewGroup and calculate the Subtotals.

        foreach (CollectionViewGroup CVG in PGV.Groups)
            {
                foreach (var row in CVG.Items)
                {
                    subtotal = ((Revenues)row).Revenue + subtotal;
                }

                Revenues revenues = new Revenues();
                revenues.Revenue = subtotal;
                revenues.Restaurant = CVG.Name.ToString();
                lstRev.Add(revenues);
                subtotal = 0;
            }

Let me explain what is happening in this part of coding. We are looping through each CollectionViewGroup  in the PagedCollectionView . And then looping through each row inside the CollectionViewGroup  to sum the value in the Revenue property and store it in the subtotal variable.

Then, create a new object for the Revenue class. Assign the above subtotaled value to the Revenue property of the newly created object for the Revenue class and also assign the name of the CollectionViewGroup  to the Restaurant property.

Now, add the above create object for the Revenue class to the Generic List lstRev that was created previously.

And also make the value of the subtotal variable to be zero, so that the its value does not get added continuously.

7. Now, lets loop through each data in the Generic List lstRev and add it to the ObservableCollection and refresh our PagedCollectionView so that our new data in the ObservableCollection  gets added to it and bind the PagedCollectionView  to the DataGrid.

      foreach (var data in lstRev)
            {
                OCRevenues.Add(data);
            }

            PGV.Refresh();

            RevenueDG.ItemsSource = PGV;

Now, let’s execute the application to see the output.

Untitled

Once executed we will get a DataGrid with each group of data having a row in the end with a total.

Integrating Silverlight with Sharepoint-Building a Silverlight Usercontrol and deploying it in Sharepoint as a Webpart

Well, This is my first post and this is the first I have integrated Silverlight with Sharepoint.All I did is deploying a Silverlight Usercontrol as a webpart in a Sharepoint site.Fine, let me explain the steps involved in performing this.

Requirements:

1.Download and Install the Visual Studio SP1 from here if you do not have it.

2.Download and Install the Microsoft Silverlight 2 tools for Visual STudio SP1 from here.

Steps for creating the Silverlight Application:

1. Open Visual Studio 2008 and click “Creat Project” option and choose Silverlight Application as the project template.

2. Name the project as Sharesilver(its your wish).

3. Replace the code

<Grid x:Name=”LayoutRoot” Background=”White”></Grid>

with follow the follwing code:

<Canvas x:Name=”hi” >

<Canvas.Background>

<LinearGradientBrush StartPoint=”0,0″ EndPoint=”1,1″>

<GradientStop Color=”Aqua” Offset=”0″/>

<GradientStop Color=”Beige” Offset=”0.5″/>

<GradientStop Color=”GreenYellow” Offset=”1″/>

</LinearGradientBrush>

</Canvas.Background>

<TextBlock x:Name=”fn” Height=”88″ Width=”96″ FontWeight=”Bold” FontSize=”20″  Canvas.Left=”54″ Canvas.Top=”74″ Text=”First Name”>

<TextBlock.RenderTransform><RotateTransform Angle=”342″></RotateTransform></TextBlock.RenderTransform>

<TextBlock.Foreground>

<LinearGradientBrush StartPoint=”0,0″ EndPoint=”1,1″>

<GradientStop Color=”Green” Offset=”0″/>

<GradientStop Color=”GreenYellow” Offset=”0.5″/>

<GradientStop Color=”Black” Offset=”1″/>

</LinearGradientBrush>

</TextBlock.Foreground>

</TextBlock>

<TextBox x:Name=”fn1″ Canvas.Left=”237″ Canvas.Top=”38″ Width=”115″ Height=”30″>

<TextBox.RenderTransform>

<RotateTransform Angle=”20″></RotateTransform>

</TextBox.RenderTransform>

</TextBox>

<TextBlock x:Name=”sn” Text=”Second Name” Canvas.Left=”61″ Canvas.Top=”114″ Height=”88″ Width=”96″ FontWeight=”Bold” FontSize=”20″>

<TextBlock.RenderTransform>

<RotateTransform Angle=”18″>

</RotateTransform>

</TextBlock.RenderTransform>

<TextBlock.Foreground>

<LinearGradientBrush StartPoint=”0,0″ EndPoint=”1,1″>

<GradientStop Color=”Green” Offset=”0″/>

<GradientStop Color=”GreenYellow” Offset=”0.5″/>

<GradientStop Color=”Black” Offset=”1″/>

</LinearGradientBrush>

</TextBlock.Foreground>

</TextBlock>

<TextBox x:Name=”sn1″ Canvas.Left=”230″ Canvas.Top=”158″ Width=”115″ Height=”30″>

<TextBox.RenderTransform>

<RotateTransform Angle=”340″></RotateTransform>

</TextBox.RenderTransform>

</TextBox>

<Button x:Name=”b1″ Canvas.Left=”170″  Canvas.Top=”200″ Content=”Click Here” Width=”115″ Height=”30″ Click=”b1_Click” >

<Button.Background>

<LinearGradientBrush StartPoint=”0,0″ EndPoint=”1,1″>

<GradientStop Color=”RoyalBlue” Offset=”0″/>

<GradientStop Color=”GreenYellow” Offset=”0.5″/>

<GradientStop Color=”Black” Offset=”1″/>

</LinearGradientBrush>

</Button.Background>

</Button>

<TextBlock x:Name=”t1″ Canvas.Top=”250″ Width=”115″ Height=”30″ Text=”hi” Visibility=”Collapsed”>

</TextBlock>

<Canvas.Resources>

<Storyboard x:Name=”s1″>

<DoubleAnimation Storyboard.TargetName=”t1″ Storyboard.TargetProperty=”(Canvas.Left)” From=”0″ To=”400″ By=”20″ Duration=”0:0:1″  RepeatBehavior=”Forever”></DoubleAnimation>

</Storyboard>

</Canvas.Resources>

</Canvas>

<Grid x:Name=”LayoutRoot” Background=”White”>
</Grid>

You will get the output like this:

Untitled

4. Click the Page.xaml.cs file and copy this code snippet below the page constructor:

private void b1_Click(object sender, RoutedEventArgs e)

{

t1.Text = fn1.Text + ” ” + sn1.Text;

t1.Visibility = Visibility;

s1.Begin();

}

5. Build the project.

Steps for deploying the Silverlight Usercontrol in Sharepoint as a webpart in Sharepoint:

1. Open the Sharepoint 3.0 Central Administration.

2. Create a Web application and Site collection with a template of your wish.

3. Now open the Site Collection and and click “View all site content” in the quick launch of the site.

4. The View all site content page opens.Click the “Create” option and the select “Documet Library” in the Libraries category.

5. Create a  Document library called “XAPFiles”.

6. Now, open the folder of the Silverlight application that you created in the Windows Explorer.

7. Open the XAP files document library and upload the XAP file of the Silverlight Application that you created which will be available in the Bin –> Debug  folder of your Silverlight applpication folder.

8. Open the Home page of the Site collection and click on the “SIte Actions” drop down menu option on the top right hand corner of the Site and select  “Edit Page”.

9. The Site now gets opened in the Editable format.Click the “Add a Web Part” option at any of the zones that are available.

10. The Add Web Part dialog box opens.Now, select the “Content Editor Web Part”  Check Box under the Miscellaneous category adn click the Add button.

11. Now the Web Part gets added to the selected zone.Select the “Open the tool pane” option.

12. The tool pane gets opened in the right hand corner.Click the “Source Editor” button.The Source Editor dialog box opens.

13. Open the TestPage.html page of your Silverlight Application which is in the Bin –> Debug  folder in Visual Studio.

14. Copy the <div> element in the Testpage.html and paste it in the Source Editor and make the following 2 changes.

a. Specify the full path of the XAP file which is in the Document Library.For eg. http://servername/Port no./XAPFiles/sharesilver.xap.

b.Change the width and the height property as that of the Silverlight usercontrol that we created in a pixel value.

Here is my TestPage.html:

<div id=”silverlightControlHost”>

<object data=”data:application/x-silverlight,” type=”application/x-silverlight-2″ width=”400px” height=”300px”>

<param name=”source” value=”http://servername/Port no./XAPFiles/sharesilver.xap”/>

<param name=”onerror” value=”onSilverlightError” />

<param name=”background” value=”white” />

<param name=”minRuntimeVersion” value=”2.0.31005.0″ />

<param name=”autoUpgrade” value=”true” />

<a href=”http://go.microsoft.com/fwlink/?LinkID=124807&#8243; style=”text-decoration: none;”>

<img src=”http://go.microsoft.com/fwlink/?LinkId=108181&#8243; alt=”Get Microsoft Silverlight” style=”border-style: none”/>

</a>

</object>

<iframe style=’visibility:hidden;height:0;width:0;border:0px’></iframe>

</div>

15. Save it and click OK in the tool pane of the web part.Now the Usercontrol get displayed in the web partthat we created in the site.

Here is the Scree Shot of of my sharepoint site:

Untitled