Fork me on GitHub

使用ConditionalScope进行高效的SharePoint CSOM编程

在上一篇文章中讲述了 ExceptionHandlingScope的使用后,本章主要讲述ConditionalScope的用法。

ConditionalScope在设计思路和解决问题上同ExceptionHandlingScope几乎是相同的,主要为了解决如何在一次请求中实现if else这样需求。

我们知道,在SharePoint API中,获取不到某些对象时,有的时候是出异常的,有的时候是返回空的,有的时候是能返回对象,但是只能使用某些属性。本文中使用的例子就是文件对象,使用过ServerAPI的人都知道,SPWeb.GetFile获取SPFile对象时,如果文件不存在,API也不会抛出异常,而是SPFile.Exsit=false,因此我们在获取file对象时会用到以下代码:

            using (ClientContext clientContext = new ClientContext("https://cnblogtest.sharepoint.com"))
            {

                var pasword = new SecureString();

                "abc123!@#".ToCharArray().ToList().ForEach(pasword.AppendChar);

                clientContext.Credentials = new SharePointOnlineCredentials("test001@cnblogtest.onmicrosoft.com", pasword);//设置权限

                var currentWeb = clientContext.Web;

                var file = currentWeb.GetFileByServerRelativeUrl("/Shared%20Documents/Sharepoint.png");
                file.ListItemAllFields["Test"] = "StartIfTrue";
                file.ListItemAllFields.Update();

                clientContext.ExecuteQuery();//提交修改,如果文件不存在会出异常
            }

 

这个地方我们在执行请求之前不知道文件是否存在,因此如何用一次请求来解决这个问题呢?这个就需要用ConditionalScope来实现:

            using (ClientContext clientContext = new ClientContext("https://cnblogtest.sharepoint.com"))
            {
                var pasword = new SecureString();
                "abc123!@#".ToCharArray().ToList().ForEach(pasword.AppendChar);

                clientContext.Credentials = new SharePointOnlineCredentials("test001@cnblogtest.onmicrosoft.com", pasword);//设置权限

                var currentWeb = clientContext.Web;

                var file = currentWeb.GetFileByServerRelativeUrl("/Shared%20Documents/Sharepoint1.png");

                var conditionalScope = new ConditionalScope(clientContext, () => file.Exists, true);

                using (conditionalScope.StartScope())
                {
                    file.ListItemAllFields["Test"] = "StartIfTrue";
                    file.ListItemAllFields.Update();
                }

                clientContext.ExecuteQuery();//提交修改,如果文件不存在也不会出异常

                if (conditionalScope.TestResult.HasValue)
                {//显示ConditionalScope条件的值
                    Console.WriteLine("Condition Value:" + conditionalScope.TestResult.Value);
                }

            }

这种方式很好的实现了一次请求中,实现条件判断。请求报文和ExceptionHandlingScope的构成基本类似,这里不再赘述。合理的使用这个类也能很好的提升和SharePoint进行交互时的效率。

posted @ 2014-09-28 22:23  独上高楼  阅读(1108)  评论(0编辑  收藏  举报