How to Add Items to Sharepoint list using Silverlight Object Model

Last few days I am working around Silverlight Object Model with sharepoint. In this post I am explaining about adding items to Sharepoint list using Silverlight Object Model. I created a list in sharepoint with few columns like Name, Email and Comments.

And I created a Silverlight application with few textboxes and a submit button.

Silverlight Screen

Silverlight Screen

Here is the code.

ClientContext clientContext = null;
Web web = null;
List list = null;

clientContext = new ClientContext("http://sharepoint:2010");
web = clientContext.Web;
list = web.Lists.GetByTitle("samplelist");
ListItem listItem = list.AddItem(new ListItemCreationInformation());
listItem["Title"] = Guid.NewGuid().ToString();
listItem["Name"] = this.txtName.Text;
listItem["Email"] = this.txtEmail.Text;
listItem["Comments"] = this.txtcomments.Text;
listItem.Update();
clientContext.Load(list, olist => olist.Title);
clientContext.ExecuteQueryAsync(
    new ClientRequestSucceededEventHandler(delegate(object o, ClientRequestSucceededEventArgs successargs)
    {
        this.Dispatcher.BeginInvoke(new Action(delegate()
        {
            MessageBox.Show("New Item Created " + listItem["Title"]);
        }), null);
    }),
    new ClientRequestFailedEventHandler(delegate(object o, ClientRequestFailedEventArgs failedArgs)
    {
        this.Dispatcher.BeginInvoke(new Action(delegate()
        {
            MessageBox.Show("New Item creation failed");
        }), null);
    })
);

How to access SharePoint List Items using Silverlight Object Model

In the last postI introduced the Silverlight Object Model, which helps to access the SharePoint objects directly from Silverlight. In this I am posting about how to access SharePoint List Items using Silverlight Object Model. In this I am using Caml query object, which is used to get the Fields.

private Web oWebSite = null;
private List oList = null;
private ListItemCollection oListItems = null;
private ClientContext clientContext = null;

this.clientContext = ClientContext.Current;
if (this.clientContext == null)
{
this.clientContext = new ClientContext(url);
}
using (this.clientContext)
{
this.oWebSite = clientContext.Web;
this.oList = this.oWebSite.Lists.GetByTitle(this.listName);
this.oListItems = this.oList.GetItems(CamlQuery.CreateAllItemsQuery());
    clientContext.Load(this.oListItems);
clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
}

private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
{
//FillItems method converts the List items to Class Properties
//and binds them to the Silverlight User Interface.
this.Dispatcher.BeginInvoke(new Action(FillItems));
}

private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
{
MessageBox.Show("An error occured.\n" + args.Message + "\n" + args.StackTrace);
}

And if you don’t want all the columns or you want to specify the columns you want to access you can use Caml Query object’s ViewXml property.

CamlQuery camlQuery = new CamlQuery();
string query = "<OrderBy><FieldRef Name='Name' Ascending='False' /></OrderBy>";
camlQuery.ViewXml = query;
this.oListItems = this.oList.GetItems(camlQuery);

You can access CustomLists and Document Libraries by this method.

Using the Silverlight Object Model

Recently I moved to a new project where I have to integrate Silverlight with SharePoint. I had done a few posts regarding this also. Yesterday I found that in SharePoint 2010(SharePoint foundation), Microsoft introduces Silverlight Object Model which helps to access SharePoint Lists and Document Libraries directly from Silverlight.

Here is my first experiment with Silverlight Object Model which helps to retrieve all the Lists from a given SharePoint site, and displays it in a Combo Box.

private Web oWebSite;
private ListCollection collList;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    using (ClientContext clientContext = new ClientContext("http://sharepoint2010/"))
    {
        this.oWebSite = clientContext.Web;
        this.collList = this.oWebSite.Lists;
        clientContext.Load(collList);
        clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
    }
}

private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
{
    this.Dispatcher.BeginInvoke(new Action(DisplayLists));
}
private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
{
    MessageBox.Show("An error occured.\n" + args.Message + "\n" + args.StackTrace);
}

private void DisplayLists()
{
    foreach (List item in collList)
    {
        lstItems.Items.Add(item.Title);
    }
}

Because query execution is asynchronous when you use the SharePoint Foundation Silverlight object model, you must pass delegates for callback methods as parameters in the ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method.

Silverlight in Sharepoint (WSS 3.0)

Recently I got an assignment to integrate Silverlight to WSS 3.0, in Sharepoint Foundation(WSS 4.0) there is an out of the box web part available to do the integration. Instead of using that, in this post I am creating a reusable web part which helps to load Silverlight application in SharePoint. It is lot similar like smart part web part in WSS, which helps to render dotnet user controls (ACSX) files as webparts.

Here is my web part code. It uses two JavaScript files as includes, first one the Silverlight.js, which is used by the Silverlight runtime, other one contains the script part which handles any error. Both of this files need to copied to LAYOUTS folder so that we can re-use the code to any application in the server.

public class SilverlightWebpart : WebPart
{
    private string _xapFileName = string.Empty;
    private int _contentHeight = 100;
    private int _contentWidth = 200;
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        ClientScriptManager _ClientScriptManager = Page.ClientScript;
        if (!_ClientScriptManager.IsClientScriptIncludeRegistered("sl_javascript"))
            _ClientScriptManager.RegisterClientScriptInclude(this.GetType(), "sl_javascript", "/_LAYOUTS/SL3/Silverlight.js");
        if (!_ClientScriptManager.IsClientScriptBlockRegistered("SilverlightError"))
        {
            _ClientScriptManager.RegisterClientScriptInclude(this.GetType(), "SilverlightError", "/_LAYOUTS/SL3/SilverlightError.js");
        }

    }

    public override void RenderControl(HtmlTextWriter writer)
    {
        writer.WriteLine( string.Format("</pre>
<div id="\&quot;silverlightControlHost\&quot;" style="_0height: {0};">",
 this._contentHeight.ToString(), this._contentWidth.ToString()));
 writer.WriteLine("<object width="\&quot;100%\&quot;" height="\&quot;100%\&quot;" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="&quot;source&quot;" value="\&quot;{0}\&quot;/" /><param name="&quot;onError&quot;" value="\&quot;onSilverlightError\&quot;" /><param name="&quot;background&quot;" value="\&quot;white\&quot;" /><param name="&quot;minRuntimeVersion&quot;" value="\&quot;3.0.40818.0\&quot;" /><param name="&quot;autoUpgrade&quot;" value="\&quot;true\&quot;" /><param name="src" value="\&quot;data:application/x-silverlight-2,\&quot;" /><embed width="\&quot;100%\&quot;" height="\&quot;100%\&quot;" type="application/x-shockwave-flash" src="\&quot;data:application/x-silverlight-2,\&quot;" "source"="\&quot;{0}\&quot;/" "onError"="\&quot;onSilverlightError\&quot;" "background"="\&quot;white\&quot;" "minRuntimeVersion"="\&quot;3.0.40818.0\&quot;" "autoUpgrade"="\&quot;true\&quot;" />"); writer.WriteLine(string.Format("", this._xapFileName)); writer.WriteLine(""); writer.WriteLine(""); writer.WriteLine(""); writer.WriteLine(""); writer.WriteLine("<a href="\&quot;http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0\&quot;" style="\&quot; text-decoration:none\&quot;">"); writer.WriteLine("<img src="\&quot;http://go.microsoft.com/fwlink/?LinkId=161376\&quot;" alt="\&quot; Get" style="\&quot;border-style:none\&quot;/" />"); writer.WriteLine("</a>"); writer.WriteLine("</object><iframe id="\&quot;_sl_historyFrame\&quot;" style="_0visibility: hidden; height: 0px; width: 0px; border: 0px\&quot;;" width="320" height="240"></iframe></div>
<pre>
");
    }

    [WebBrowsable(true),
    WebDescription("Specify the Height of the XAP File Content"),
    WebDisplayName("Content Height"),
    Personalizable(PersonalizationScope.User)]
    public int ContentHeight
    {
        get
        {
            return this._contentHeight;
        }
        set
        {
            this._contentHeight = value;
        }
    }

    [WebBrowsable(true),
    WebDescription("Specify the Width of the XAP File Content"),
    WebDisplayName("Content Width"),
    Personalizable(PersonalizationScope.User)]
    public int ContentWidth
    {
        get
        {
            return this._contentWidth;
        }
        set
        {
            this._contentWidth = value;
        }
    }

    [WebBrowsable(true),
    WebDescription("Specify the XAP File to load"),
    WebDisplayName("XAP File Name"),
    Personalizable(PersonalizationScope.User)]
    public string XAPFile
    {
        get
        {
            return this._xapFileName;
        }
        set
        {
            this._xapFileName = value;
        }
    }
}

The code is pretty self-explanatory. After deploying the webpart and adding the webpart to the Page, select Modify Shared Webpart, you will get Sharepoint customize option like this.

Customize Silverlight Webpart

Customize Silverlight Webpart

Please make sure you created a Folder with name SL3 in the _LAYOUTS folder, and copied the two javascript files to the location. The output of the Silverlight project also you need to copy to the Folder. The location will be C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\SL3. Specify the XAP File Name property as the XAP File copied to SL3 folder from ClientBin folder. You can also modify the Height and Width of the silverlight application. Click Apply and OK, exit from Edit Mode. The Silverlight application is integrated to sharepoint.