Sofware Architecture-SharePoint 2010-Getting name of all the Lists in a site via client-side object model

August 30, 2011

The new client-side object model provides remote access to the functionality of the SharePoint Foundation server-side object model. In previous releases of SharePoint Foundation, SOAP Web services provided access to only a fraction of the server-side object model, but in SharePoint Foundation 2010, the client object model fills many of the gaps.

Client Object model can be one of the following type:
1. ECMAScript (JavaScript, JScript)
2. .NET managed
3. Silverlight client
According to SDK Documentation:

The new ECMAScript (JavaScript, JScript), .NET managed, and Silverlight client object models each provide a subset of the server object model that is defined in Microsoft.SharePoint.dll, including objects that correspond to major objects at the site-collection level or lower in the SharePoint Foundation hierarchy. To improve security and performance, the client object models focus on the most relevant APIs for client-side development, and do not contain all the types and members that are represented in the server object model.
The client object models are provided through proxy .js and managed .dll files, respectively, which can be referenced in custom applications like other object models. The object models are implemented as a Windows Communication Foundation (WCF) service (.../_vti_bin/client.svc), but uses Web bindings to implement efficient request batching. All operations are inherently asynchronous, and commands are serialized into XML and sent to the server in a single HTTP request. For every command, a corresponding server object model call is made, and the server returns a response to the client in compacted JavaScript Object Notation (or JSON) format, which the proxy parses and associates with appropriate objects. 

1. Getting name of all the Lists in a site via ECMAScript (JavaScript, JScript).
Create a new site page and in contentplaceholder add following code:

<a href="#"  onclick="getAllSPLists();"> Click me</a>
<script type="text/javascript">
var  myLists;
function getAllSPLists()
{
 // get current context
 var ctx =  SP.ClientContext.get_current();
 // point  to get all the lists 
 myLists =  ctx.get_web().get_lists();
 // Load all lists
 ctx.load(myLists );
 // async excute
 ctx.executeQueryAsync(Function.createDelegate(this,this.succeeded) , Function.createDelegate(this,this.failed));
 }
 
 function succeeded(sender, args)
 {
 alert('Call succeeded......');
//get enumerator
 var ListEnumerator = this.myLists.getEnumerator();
// iterate to all items
 while(ListEnumerator.moveNext())
 {
 // point to current item
 var currentItem = ListEnumerator.get_current();
 // show item
 alert('Item:  ' + currentItem.get_title());
 }
 
 }
 function failed(sender, args)
 {
 alert('Failed. ' + args.get_message() + '\n' + args.get_stackTrace());
 }
</script>

Save site page and run it to see the result.
2. Getting name of all the Lists in a site via .NET managed
Create a console project and add reference to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll
After that following piece of code provide name of all the lists in a sharepoint site:

 using (var ctx = new ClientContext("http://win2k8-ultimate/sites/Call/"))
            {
               var list = ctx.Web.Lists;
               ctx.Load(list );
               ctx.ExecuteQuery();
               foreach (var item in list)
               {
                   Console.WriteLine("Item: " + item.Title + " - " + item.Description+ "\n");
               }
            }

Console will show name of all lists.
3. Getting name of all the Lists in a site via Silverlight Client.
Create a silver project and in main page “MainPage.xaml”, add a list box with following tag as:

<ListBox Height="100" HorizontalAlignment="Left" Margin="10,10,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" />

The code behind of this page will be as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace ClientSideSilverApp
{
    public partial class MainPage : UserControl
    {
        IEnumerable<List> spList = null;
        public MainPage()
        {
            InitializeComponent();
            using (var ctx =  ClientContext.Current)
            {

                spList = ctx.LoadQuery(ctx.Web.Lists);
                ctx.ExecuteQueryAsync(Succeded, Failed);

            }
        }

        private void Succeded(object sender, ClientRequestSucceededEventArgs e)
        {
            Dispatcher.BeginInvoke(BindList);
        }
        private void Failed(object sender, ClientRequestFailedEventArgs e)
        {
            
        }

        private void BindList()
        {
            listBox1.Items.Clear();
            listBox1.ItemsSource = spList;
            listBox1.DisplayMemberPath = "Title";
        }
    }
}

Compile the project to make sure that there is no compile time error.
Now login to sharepoint site, Upload .xap file generated from above acivity to document library of sharepoint site and copy the URL of file.
Go to “Edit” >> “Insert”, click on web part, select category of “Media and Content” , select “Silverlight web part” and click on add. Provide the URL of file obtained from previous step. Configure the properties of web part as per requirement.
This will show list box with name of all the list in sharepoint site.
Happy coding for SharePoint……:)


Protected: Software Architecture – To Study PCMS – Pegasus ERP Cargo Management System-Release-7 from Architecture perspective

November 6, 2010

This content is password protected. To view it please enter your password below:


Protected: Software Architecture – Assemblies Abstractness vs. Instability for PCMS – Pegasus ERP Cargo Management System Release-7

November 6, 2010

This content is password protected. To view it please enter your password below:


Protected: Software Architecture – Assemblies Dependencies Diagram PCMS – Pegasus ERP Cargo Management System Release-7

November 6, 2010

This content is password protected. To view it please enter your password below:


Software Architecture-Silverlight 4.0-New Features Blog series

October 8, 2010

While exploring Silverlight 4.0. I have posted few new post on my blog.
Some of new posts are as:
Printing Option
https://softarchitect.wordpress.com/2010/10/08/software-architecture-silverlight-4-0-new-feature-printing-option/

Clipbaord Support https://softarchitect.wordpress.com/2010/10/08/software-architecture-silverlight-4-0-new-feature-clipbaord-support/

COM interop API changes
https://softarchitect.wordpress.com/2010/10/08/software-architecture-silverlight-4-0-new-feature-com-interop-api-changes/

MouseRightButtonDown and MouseRightButtonUp events
https://softarchitect.wordpress.com/2010/10/08/software-architecture-silverlight-4-0-new-feature-right-click-as-mouserightbuttondown-and-mouserightbuttonup-events/

FullScreenOptions property
https://softarchitect.wordpress.com/2010/09/28/software-architecture-sliverlight-4-0-new-feature-fullscreenoptions-property/

Implicit Style
https://softarchitect.wordpress.com/2010/09/28/software-architecture-silverlight-4-new-feature-implicit-style/

Flow for Arabic and Hebrew
https://softarchitect.wordpress.com/2010/09/28/software-architecture-silverlight-4-new-feature-flow-for-arabic-and-hebrew/

Keep enjoying Silverlight 4.0

Related Post:
.Net /C# 4.0 Series
https://softarchitect.wordpress.com/2010/09/18/software-architecture-new-features-in-c-sharp-net-4-0-blog-series/


Software Architecture-Silverlight 4.0-New Feature-Printing Option

October 8, 2010

In Silverlight 4.0, new printing class is provided in named PrintDocument in namespace of System.Windows.Printing, which help to print any UIElement and its content (Childs) of Visual tree.

This class has three main events; First PrintPage which helps to identify what is the content to be printed via PrintPageEventArgs.PageVisual. Second BeginPrint helps to do some action before printing actually starts. Third EndPrint help to some action after printing actually ends.

A sample code will look like as:

  public partial class PrintPage : Page
    {
        PrintDocument printD;
        public PrintPage()
        {
            InitializeComponent();
            printD = new PrintDocument();
            printD.PrintPage += new EventHandler<PrintPageEventArgs>(printD_PrintPage);
            printD.BeginPrint += new EventHandler<BeginPrintEventArgs>(printD_BeginPrint);
            printD.EndPrint += new EventHandler<EndPrintEventArgs>(printD_EndPrint);
        }

        void printD_EndPrint(object sender, EndPrintEventArgs e)
        {
            MessageBox.Show("Printing Ended.......");
        }

        void printD_BeginPrint(object sender, BeginPrintEventArgs e)
        {
            MessageBox.Show("Printing Started.......");
        }

        void printD_PrintPage(object sender, PrintPageEventArgs e)
        {
            MessageBox.Show("Height: " + e.PrintableArea.Height + "Width: " + e.PrintableArea.Width);
            e.PageVisual = PrintArea;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            printD.Print("Test Page");
        }

    }

XAML will look like as:

<navigation:Page x:Class="ImplicitThemeProc.PrintPage" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="PrintPage Page">
    <Grid x:Name="LayoutRoot">
        <StackPanel Name="PrintArea" Height="400" Margin="264,40,170,40">
            <TextBlock  Text="Hellllo Sarwar......." FontSize="16"></TextBlock>
            <TextBlock Text="Hellllo Sarwar......." FontSize="16"></TextBlock>
            <TextBlock Text="Hellllo Sarwar......." FontSize="16"></TextBlock>
        </StackPanel>
        <Button Content="Print......" Height="23" HorizontalAlignment="Left" Margin="104,131,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</navigation:Page>

Printed page will look like as:


Software Architecture-Silverlight 4.0-New Feature-Clipbaord Support

October 8, 2010

While exploring new features of Silverlight 4.0, I discoivered that one of the new cool feature is Clipbaord support.

Text is written to Clipboard as:

Clipboard.SetText(" Data to be put Clipboard");            

Text is fetched from Clipboard as:

MessageBox.Show( Clipboard.GetText());

Clipboard access under partial trust (normal application) requires confirming access by via message box as:

The access details can be seen by right clicking the silverlight page in the permission tabs as:

Clipboard access under out-of-browser application (elevated rights), does not require permission confirmation message box.


Software Architecture-Silverlight 4.0-New Feature-COM interop API changes

October 8, 2010

COM interop API changes

In Silverlight 4, System.Windows.Interop name space is renamed as System.Runtime.InteropServices.Automation and main static class used for COM Factory is renamed from ComAutomationFactory to AutomationFactory.

Lets consider a small example to automate MS Word via Silverlight Project.

Add namespace as System.Runtime.InteropServices.Automation to Silverlight page. Add refeerence of Microsoft.CSharp for type dynamic.

COM interop is supported only in Out-of-Browser applications with ElevatedPermission.
Incase of normall silverlight application exception is thrown with details as” This operation is not supported in the current context.”

Consider some manipulation of word document as below.

            if (App.Current.IsRunningOutOfBrowser && App.Current.HasElevatedPermissions)
            {
                if (AutomationFactory.IsAvailable)
                {
                    dynamic wordFactory = AutomationFactory.CreateObject("Word.Application");
                    dynamic doc = wordFactory.Documents.Add();
                    wordFactory.Visible = true;
                    doc.Content.Font.Name = "Tahoma";
                    doc.Content.Font.Size = 24;
                    doc.Content.Font.Bold = true;
                    doc.Content.Font.Italic = true;
                    doc.Content = "Hello Shahzad Sarwar- Testing......Testing......Testing......";
                    dynamic tblNew = doc.Tables.Add(doc.Range(0, 0), 6, 8);
                    int intCount = 1;
                    foreach (var cell in tblNew.Range.Cells)
                    {
                        cell.Range.InsertAfter("Cell " + intCount);
                        intCount++;
                    }
                    doc.SaveAs("ShahzadFile.doc");

                }
            }

For details about dynamic usage see here.


Software Architecture-Silverlight 4.0-New Feature- right click as MouseRightButtonDown and MouseRightButtonUp events

October 8, 2010

In Silverlight 4.0, Microsoft has 2 new events for right click as MouseRightButtonDown and MouseRightButtonUp events to the base UIElement class.

Let use these events to implement a right click menu on a button.

Assume a button with events MouseRightButtonDown as

<Button Content="Context Menu...." Height="23" HorizontalAlignment="Left" Margin="78,85,0,0" Name="button1" VerticalAlignment="Top" Width="148" MouseRightButtonDown="button1_MouseRightButtonDown"  />

Prepare Right click menu as

private void CreatePopup()
        {

            /// Use StackPanel control as contianer control for context menu.
            StackPanel panel1 = new StackPanel();            
            panel1.Background = new SolidColorBrush(Colors.LightGray);

            // Style a border
            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.Black);
            border.BorderThickness = new Thickness(5.0);
                       
           // First Menu item
            TextBlock textblock1 = new TextBlock();
            textblock1.Text = "Popup Menu";
            textblock1.Margin = new Thickness(5.0);
            textblock1.FontSize = 16;
            textblock1.MouseLeftButtonDown += new MouseButtonEventHandler(MouseLeftButtonDownHandler);
            // Second Menu item
            TextBlock textblock2 = new TextBlock();
            textblock2.Text = "New window";
            textblock2.Margin = new Thickness(5.0);
            textblock2.MouseLeftButtonDown += new MouseButtonEventHandler(MouseLeftButtonDownHandler);
            // Third Menu item
            TextBlock textblock3 = new TextBlock();
            textblock3.Text = "Close";
            textblock3.Margin = new Thickness(5.0);
            textblock3.MouseLeftButtonDown += new MouseButtonEventHandler(MouseLeftButtonDownHandler);

            // Add menu item to panel
            panel1.Children.Add(textblock1);
            panel1.Children.Add(textblock2);
            panel1.Children.Add(textblock3);
            border.Child = panel1;

            // Set the Child property of Popup to the border 
            // which contains a stackpanel, textblock and button.
            p.Child = border;
                        
        }

Call this method in constructor of page and declare pop in in page scope as:

// Create the popup object.
            Popup p = new Popup();

Event will look like that.

private void button1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            p.HorizontalOffset = e.GetPosition(null).X + 10;
            p.VerticalOffset = e.GetPosition(null).Y + 10;
            p.IsOpen = true;
            e.Handled = true;

        }

The output of menu will look like that.


Software Architecture-Sliverlight 4.0-New Feature-FullScreenOptions property

September 28, 2010

Silverlight supports full screen mode. So there are 2 modes, one embedded mode and second full screen mode.
Full screen mode looks like as:

Embeded screen mode looks like as:

Full screen mode support was already there in previous versions of Silverlight. But in Sliverlight 4.0, we have a new feature by FullScreenOptions property.

Lets suppose a sample with following three radio button with xaml as:

First button code use IsFullScreen property to false (default value is false- So it can be avoided for embedded code mode) as:

private void radioButton1_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rdo = sender as RadioButton;
            if (rdo.IsChecked==true)
            {
                App.Current.Host.Content.IsFullScreen = false;
            }
        }

Second button code set the full screen mode to true. Secondly FullScreenOptions
is set to None-means that full screen mode will not be maintained when screen is not active.[It is default]

private void radioButton2_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rdo = sender as RadioButton;
            if (rdo.IsChecked == true)
            {
                App.Current.Host.Content.FullScreenOptions = System.Windows.Interop.FullScreenOptions.None; // default value-No need to specify.
                App.Current.Host.Content.IsFullScreen = true;
            }
        }

Thrid button code set full screen mode to true. Secondly, FullScreenOptions is set to StaysFullScreenWhenUnfocused means that full screen mode will be maintained when screen is not active.

private void radioButton3_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton rdo = sender as RadioButton;
            if (rdo.IsChecked == true)
            {
                App.Current.Host.Content.FullScreenOptions = System.Windows.Interop.FullScreenOptions.StaysFullScreenWhenUnfocused;
                App.Current.Host.Content.IsFullScreen = true;
            }
        }

An option to save setting for FullScreenOptions is asked by silverlight as:

You can see the setting info by right clicking the Silverlight page as below:

Limitation of Full screen mode:
1. No Drag-and-drop support
2. No OpenFileDialog and SaveFileDialog dialog boxes support.
3. No Multitouch input support.
4. Most keyboard events are disabled.