Hi all,
In my previous post, I have shown how to display all the lists in a site using Client OM java script and using script link to control to register to a page. In this post, I will show the same thing but with Client OM .NET. Moreover, I will use SharePoint client DLLs. I will also filter the lists where title is not null. So, lets get started.
Step1: We first create a New Project in Visual Studio 2010 Beta 2/RC >> Choose "Visual C# - Windows" as base template >> select "Windows Forms Application" >> Name "RetriveLists" and click OK. . Please note that choose only .NET framework 3.5.
Step3: Drag two labels "URL" and "Lists", a text box (txtURL), a ListBox (lslLists) and a button "Show Lists". The form should look this.
Step4: Double click on the button. Add using statement for Client model. (using ClientOM = Microsoft.SharePoint.Client)
Step5: In button event, few things have to be noted:
private void btnShowLists_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
lstLists.Items.Clear();
using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(txtURL.Text))
{
ClientOM.Web site = ctx.Web;
ctx.Load(site);
ctx.Load(site.Lists);
ctx.Load(site, x => x.Lists.Where(l => l.Title != null));
ctx.ExecuteQuery();
foreach(ClientOM.List list in site.Lists)
{
lstLists.Items.Add(list.Title);
}
}
{
this.Cursor = Cursors.WaitCursor;
lstLists.Items.Clear();
using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(txtURL.Text))
{
ClientOM.Web site = ctx.Web;
ctx.Load(site);
ctx.Load(site.Lists);
ctx.Load(site, x => x.Lists.Where(l => l.Title != null));
ctx.ExecuteQuery();
foreach(ClientOM.List list in site.Lists)
{
lstLists.Items.Add(list.Title);
}
}
a) ClientContext is unmanaged code. Therefore we have to wrap it with "using" statement.
b) ClientOM = Microsoft.SharePoint.Client shows intellisense. So, when I typed in "ClientOM". visual studio 2010 showed corresponding properties. For an instance, ClientOM.Web, ctx.Load etc.
c) Load happens in the client and only when "ExceuteQurey" is executed, the form will talk to server.
d) ctx.Load(site, x => x.Lists.Where(l => l.Title != null)); Getting titles which are null are leveraging by Linq "Lambda" syntax.
This is a less-friendly, but at least consistent and more powerful, way to request data using Linq. Although a lot of scenarios may start with the "Pretty Query" syntax, in many cases Lambda syntax must be used for more advanced scenarios.
Now, when we execute ctx.Load, we use lambda expression to fetch only titles where title is not null in the top level sites Therefore, we will get the light weight object back.
Step6: Build and press F5. Key in the site URL and click on "Show Lists". We will get all the lists in site.
We can get a similar console application sample from MSDN site.
Cheers,
--aaroh
Download source here.
No comments:
Post a Comment