Sunday, February 21, 2010

How to: Showing all the lists in a site using SharePoint 2010 with Windows Application (Part 3: .NET)

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.  

Step2: Add References in Solution Explorer and browse to 14\ISAPI folder. 

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;

            using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(txtURL.Text))
                ClientOM.Web site = ctx.Web;
                ctx.Load(site, x => x.Lists.Where(l => l.Title != null));


                foreach(ClientOM.List list in site.Lists)


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.


Download source here.

No comments:

How to: Use cascading drop-down lists in PowerApps

Hi all, Using cascading dropdown, users can easily fill the forms by selecting drop-down values dependent on values from another dro...