当前位置: 首页>>代码示例>>C#>>正文


C# ClientContext类代码示例

本文整理汇总了C#中ClientContext的典型用法代码示例。如果您正苦于以下问题:C# ClientContext类的具体用法?C# ClientContext怎么用?C# ClientContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ClientContext类属于命名空间,在下文中一共展示了ClientContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

        public void Execute(ClientContext ctx, string listTitle, XElement schema, Action<Field> setAdditionalProperties = null)
        {
            var displayName = schema.Attribute("DisplayName").Value;
            Logger.Verbose($"Started executing {nameof(CreateColumnOnList)} for column '{displayName}' on list '{listTitle}'");

            var list = ctx.Web.Lists.GetByTitle(listTitle);
            var fields = list.Fields;
            ctx.Load(fields);
            ctx.ExecuteQuery();

            // if using internal names in code, remember to encode those before querying, e.g., 
            // space character becomes "_x0020_" as described here:
            // http://www.n8d.at/blog/encode-and-decode-field-names-from-display-name-to-internal-name/
            // We don't use the internal name here because it's limited to 32 chacters. This means
            // "Secondary site abcde" is the longest possible internal name when taken into account
            // the "_x0020_" character. Using a longer name will truncate the internal name to 32
            // characters. Thus querying on the complete, not truncated name, will always return no
            // results which causes the field get created repetedly.
            var field = fields.SingleOrDefault(f => f.Title == displayName);
            if (field != null)
            {
                Logger.Warning($"Column '{displayName}' already on list {listTitle}");
                return;
            }

            var newField = list.Fields.AddFieldAsXml(schema.ToString(), true, AddFieldOptions.DefaultValue);
            ctx.Load(newField);
            ctx.ExecuteQuery();

            if (setAdditionalProperties != null)
            {
                setAdditionalProperties(newField);
                newField.Update();
            }
        }
开发者ID:ronnieholm,项目名称:Bugfree.Spo.Cqrs,代码行数:35,代码来源:CreateColumnOnList.cs

示例2: Execute

        public void Execute(ClientContext ctx, string library, Uri url, string description)
        {
            Logger.Verbose($"Started executing {nameof(AddLinkToLinkList)} for url '{url}' on library '{library}'");

            var web = ctx.Web;
            var links = web.Lists.GetByTitle(library);
            var result = links.GetItems(CamlQuery.CreateAllItemsQuery());

            ctx.Load(result);
            ctx.ExecuteQuery();

            var existingLink =
                result
                    .ToList()
                    .Any(l =>
                    {
                        var u = (FieldUrlValue)l.FieldValues["URL"];
                        return u.Url == url.ToString() && u.Description == description;
                    });

            if (existingLink)
            {
                Logger.Warning($"Link '{url}' with description '{description}' already exists");
                return;
            }

            var newLink = links.AddItem(new ListItemCreationInformation());
            newLink["URL"] = new FieldUrlValue { Url = url.ToString(), Description = description };
            newLink.Update();
            ctx.ExecuteQuery();
        }
开发者ID:ronnieholm,项目名称:Bugfree.Spo.Cqrs,代码行数:31,代码来源:AddLinkToLinkList.cs

示例3: ApplyProvisioningTemplateToSite

        private static void ApplyProvisioningTemplateToSite(ClientContext context, String siteUrl, String folder, String fileName, Dictionary<String, String> parameters = null, Handlers handlers = Handlers.All)
        {
            // Configure the XML file system provider
            XMLTemplateProvider provider =
                new XMLSharePointTemplateProvider(context, siteUrl,
                    PnPPartnerPackConstants.PnPProvisioningTemplates +
                    (!String.IsNullOrEmpty(folder) ? "/" + folder : String.Empty));

            // Load the template from the XML stored copy
            ProvisioningTemplate template = provider.GetTemplate(fileName);
            template.Connector = provider.Connector;

            ProvisioningTemplateApplyingInformation ptai = 
                new ProvisioningTemplateApplyingInformation();

            // We exclude Term Groups because they are not supported in AppOnly
            ptai.HandlersToProcess = handlers;
            ptai.HandlersToProcess ^= Handlers.TermGroups;

            // Handle any custom parameter
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    template.Parameters.Add(parameter.Key, parameter.Value);
                }
            }

            // Apply the template to the target site
            context.Site.RootWeb.ApplyProvisioningTemplate(template, ptai);
        }
开发者ID:pdemro,项目名称:PnP-Partner-Pack,代码行数:31,代码来源:PnPPartnerPackUtilities.cs

示例4: SetProperties

 public void SetProperties(ClientContext context, Web webToConfigure, Dictionary<string, string> properties)
 {
     foreach (KeyValuePair<string, string> property in properties)
     {
         SetProperty(context, webToConfigure, property);
     }
 }
开发者ID:ceg692001,项目名称:sherpa,代码行数:7,代码来源:PropertyManager.cs

示例5: CreateContentTypeIfDoesNotExist

        private static void CreateContentTypeIfDoesNotExist(ClientContext cc, Web web)
        {
            ContentTypeCollection contentTypes = web.ContentTypes;
            cc.Load(contentTypes);
            cc.ExecuteQuery();

            foreach (var item in contentTypes)
            {
                if (item.StringId == "0x0101009189AB5D3D2647B580F011DA2F356FB3")
                    return;
            }

            // Create a Content Type Information object
            ContentTypeCreationInformation newCt = new ContentTypeCreationInformation();
            // Set the name for the content type
            newCt.Name = "Contoso Sample Document";
            //Inherit from oob document - 0x0101 and assign 
            newCt.Id = "0x0101009189AB5D3D2647B580F011DA2F356FB3";
            // Set content type to be avaialble from specific group
            newCt.Group = "Contoso Content Types";
            // Create the content type
            ContentType myContentType = contentTypes.Add(newCt);
            cc.ExecuteQuery();

            Console.WriteLine("Content type created.");
        }
开发者ID:NicolajLarsen,项目名称:PnP,代码行数:26,代码来源:Program.cs

示例6: Main

        static void Main()
        {
            // get client context
              ClientContext clientContext = new ClientContext("http://intranet.wingtip.com");

              // create variables for CSOM objects
              Site siteCollection = clientContext.Site;
              Web site = clientContext.Web;
              ListCollection lists = site.Lists;

              // give CSOM instructions to populate objects
              clientContext.Load(siteCollection);
              clientContext.Load(site);
              clientContext.Load(lists);

              // make round-trip to SharePoint host to carry out instructions
              clientContext.ExecuteQuery();

              // CSOM object are now initialized
              Console.WriteLine(siteCollection.Id);
              Console.WriteLine(site.Title);
              Console.WriteLine(lists.Count);

              // retrieve another CSOM object
              List list = lists.GetByTitle("Documents");
              clientContext.Load(list);

              // make a second round-trip to SharePoint host
              clientContext.ExecuteQuery();

              Console.WriteLine(list.Title);

              Console.ReadLine();
        }
开发者ID:kimberpjub,项目名称:GSA2013,代码行数:34,代码来源:Program.cs

示例7: ProvisionAssets

        private static void ProvisionAssets(ClientContext ctx)
        {
            Console.WriteLine("Provisioning assets:");

            string[] fileNames = {
                                     "jquery-1.11.2.min.js",
                                     "knockout-3.3.0.js",
                                     "event-registration-form.js",
                                     "event-registration-form-template.js"};
            
            List styleLibrary = ctx.Web.Lists.GetByTitle("Style Library");
            ctx.Load(styleLibrary, l => l.RootFolder);
            Folder pnpFolder = styleLibrary.RootFolder.EnsureFolder("OfficeDevPnP");
            foreach (string fileName in fileNames)
            {
                Console.WriteLine(fileName);

                File assetFile = pnpFolder.GetFile(fileName);
                if (assetFile != null)
                    assetFile.CheckOut();

                string localFilePath = "Assets/" + fileName;
                string newLocalFilePath = Utilities.ReplaceTokensInAssetFile(ctx, localFilePath);

                assetFile = pnpFolder.UploadFile(fileName, newLocalFilePath, true);
                assetFile.CheckIn("Uploaded by provisioning engine.", CheckinType.MajorCheckIn);
                ctx.ExecuteQuery();
                System.IO.File.Delete(newLocalFilePath);
            }
            Console.WriteLine("");
        }
开发者ID:nishantpunetha,项目名称:PnP,代码行数:31,代码来源:Program.cs

示例8: CreateOneNote

        /// <summary>
        /// Creates the OneNote.
        /// </summary>
        /// <param name="clientContext">The client context.</param>
        /// <param name="clientUrl">The client URL.</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <returns>Returns the URL of the OneNote</returns>
        internal static string CreateOneNote(ClientContext clientContext, Uri clientUrl, Matter matter)
        {
            string returnValue = string.Empty;
            try
            {
                byte[] oneNoteFile = System.IO.File.ReadAllBytes("./Open Notebook.onetoc2");

                Microsoft.SharePoint.Client.Web web = clientContext.Web;
                Microsoft.SharePoint.Client.File file = web.GetFolderByServerRelativeUrl(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", clientUrl.AbsolutePath, Constants.Backslash, matter.MatterGuid + ConfigurationManager.AppSettings["OneNoteLibrarySuffix"], Constants.Backslash, matter.MatterGuid)).Files.Add(new FileCreationInformation()
                {
                    Url = string.Format(CultureInfo.InvariantCulture, "{0}{1}", matter.MatterGuid, ConfigurationManager.AppSettings["ExtensionOneNoteTableOfContent"]),
                    Overwrite = true,
                    ContentStream = new MemoryStream(oneNoteFile)
                });
                web.Update();
                clientContext.Load(file);
                clientContext.ExecuteQuery();
                ListItem oneNote = file.ListItemAllFields;
                oneNote["Title"] = matter.MatterName;
                oneNote.Update();
                returnValue = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}", clientUrl.Scheme, Constants.COLON, Constants.Backslash, Constants.Backslash, clientUrl.Authority, file.ServerRelativeUrl, "?Web=1");
            }
            catch (Exception exception)
            {
                Utility.DisplayAndLogError(Utility.ErrorFilePath, "Message: " + "Matter name: " + matter.MatterName + "\n" + exception.Message + "\nStacktrace: " + exception.StackTrace);
                throw;
            }

            return returnValue;
        }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:37,代码来源:MatterProvisionHelper.cs

示例9: Steps

        public Steps(ServiceContext serviceContext, ClientContext clientContext)
        {
            _serviceContext = serviceContext;
            _clientContext = clientContext;

            _messages = new ReplaySubject<Tuple<string, IMessage>>();
        }
开发者ID:jamesleech,项目名称:Harmonize,代码行数:7,代码来源:Steps.cs

示例10: ProcessSiteCreationRequest

        public string ProcessSiteCreationRequest(ClientContext ctx, SiteCollectionRequest siteRequest)
        {
            // Resolve full URL 
            var webFullUrl = String.Format("https://{0}.sharepoint.com/{1}/{2}", siteRequest.TenantName, siteRequest.ManagedPath, siteRequest.Url);

            // Resolve the actual SP template to use
            string siteTemplate = SolveActualTemplate(siteRequest);

            Tenant tenant = new Tenant(ctx);
            if (tenant.SiteExists(webFullUrl))
            {
                // Abort... can't proceed, URL taken.
                throw new InvalidDataException(string.Format("site already existed with same URL as {0}. Process aborted.", webFullUrl));
            }
            else
            {
                // Create new site collection with storage limits and settings from the form
                tenant.CreateSiteCollection(webFullUrl,
                                            siteRequest.Title,
                                            siteRequest.Owner,
                                            siteTemplate,
                                            (int)siteRequest.StorageMaximumLevel,
                                            (int)(siteRequest.StorageMaximumLevel * 0.75),
                                            siteRequest.TimeZoneId,
                                            0,
                                            0,
                                            siteRequest.Lcid);

                return webFullUrl;
            }
        }
开发者ID:Calisto1980,项目名称:PnP,代码行数:31,代码来源:SiteManager.cs

示例11: About

        public ActionResult About()
        {
            Global.globalError1 += "Only World No Hello, ";
            using (ClientContext clientContext = new ClientContext("https://stebra.sharepoint.com/sites/sd1"))
            {

                if (clientContext != null)
                {

                    string userName = "[email protected]";

                    SecureString passWord = new SecureString();
                    string passStr = "Simoon123";
                    foreach (char c in passStr.ToCharArray()) passWord.AppendChar(c);

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
                    new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext);
                }
            }

            //        var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            //using (var clientContext = spContext.CreateUserClientContextForSPHost())
            //{ new RemoteEventReceiverManager().AssociateRemoteEventsToHostWeb(clientContext); }

            ViewBag.RemoteEvent = " Hello globalError: " + Global.globalError + " \n globalError1: " + Global.globalError1;
            return View();
        }
开发者ID:stebra-consulting,项目名称:newsFlash,代码行数:28,代码来源:HomeController.cs

示例12: DeliveryClient

        /// <summary>
        /// Constructor of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.DeliveryClient"/> class.
        /// </summary>
        /// <param name="policyFactory">An instance of IDeliveryPolicyFactory. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IDeliveryPolicyFactory"/></param>
        /// <param name="maConfig">Mobile Analytics Manager configuration. <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.MobileAnalyticsManagerConfig"/></param>
        /// <param name="clientContext">An instance of ClientContext. <see cref="Amazon.Runtime.Internal.ClientContext"/></param>
        /// <param name="credentials">An instance of Credentials. <see cref="Amazon.Runtime.AWSCredentials"/></param>
        /// <param name="regionEndPoint">Region endpoint. <see cref="Amazon.RegionEndpoint"/></param>
        public DeliveryClient(IDeliveryPolicyFactory policyFactory, MobileAnalyticsManagerConfig maConfig, ClientContext clientContext, AWSCredentials credentials, RegionEndpoint regionEndPoint)
        {
            _policyFactory = policyFactory;
            _deliveryPolicies = new List<IDeliveryPolicy>();
            _deliveryPolicies.Add(_policyFactory.NewConnectivityPolicy());

            _clientContext = clientContext;
            _appID = clientContext.AppID;
            _maConfig = maConfig;
            _eventStore = new SQLiteEventStore(maConfig);

#if PCL
            _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
#elif BCL
            if (null == credentials && null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient();
            }
            else if (null == credentials)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(regionEndPoint);
            }
            else if (null == regionEndPoint)
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials);
            }
            else
            {
                _mobileAnalyticsLowLevelClient = new AmazonMobileAnalyticsClient(credentials, regionEndPoint);
            }
#endif
        }
开发者ID:yeurch,项目名称:aws-sdk-net,代码行数:40,代码来源:DeliveryClient.cs

示例13: RemoveEventReceiversFromHostWeb

        public void RemoveEventReceiversFromHostWeb(ClientContext clientContext)
        {
            List myList = clientContext.Web.Lists.GetByTitle(LIST_TITLE);
            clientContext.Load(myList, p => p.EventReceivers);
            clientContext.ExecuteQuery();

            var rer = myList.EventReceivers.Where(e => e.ReceiverName == RECEIVER_NAME_ADDED).FirstOrDefault();

            try
            {
                System.Diagnostics.Trace.WriteLine("Removing receiver at "
                        + rer.ReceiverUrl);

                var rerList = myList.EventReceivers.Where(e => e.ReceiverUrl == rer.ReceiverUrl).ToList<EventReceiverDefinition>();

                foreach (var rerFromUrl in rerList)
                {
                    //This will fail when deploying via F5, but works
                    //when deployed to production
                    rerFromUrl.DeleteObject();
                }
                clientContext.ExecuteQuery();
            }
            catch (Exception oops)
            {
                System.Diagnostics.Trace.WriteLine(oops.Message);
            }

            clientContext.ExecuteQuery();
        }
开发者ID:RapidCircle,项目名称:O365-DefaultValues,代码行数:30,代码来源:RemoteEventReceiverManager.cs

示例14: UploadFilesInFolder

 public void UploadFilesInFolder(ClientContext context, Web web, List<ShContentFolder> contentFolders)
 {
     foreach (ShContentFolder folder in contentFolders)
     {
         UploadFilesInFolder(context, web, folder);
     }
 }
开发者ID:olemp,项目名称:sherpa,代码行数:7,代码来源:ContentUploadManager.cs

示例15: UploadDocument

        public static void UploadDocument(string siteURL, string documentListName, string documentListURL, string DocuSetFolder, string documentName, FileStream documentStream, string status, string version, string contentID, string newFileName)
        {
            using (ClientContext clientContext = new ClientContext(siteURL))
            {

                //Get Document List
                Microsoft.SharePoint.Client.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

                var fileCreationInformation = new FileCreationInformation();
                fileCreationInformation.ContentStream = documentStream;
                //Allow owerwrite of document

                fileCreationInformation.Overwrite = true;
                //Upload URL

                fileCreationInformation.Url = siteURL + documentListURL + DocuSetFolder + newFileName;

                Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
                    fileCreationInformation);

                //Update the metadata for a field

                uploadFile.ListItemAllFields["ContentTypeId"] = contentID;
                uploadFile.ListItemAllFields["Mechanical_x0020_Status"] = status;
                uploadFile.ListItemAllFields["Mechanical_x0020_Version"] = version;
                uploadFile.ListItemAllFields["Comments"] = "Autogenerated upload";

                uploadFile.ListItemAllFields.Update();
                clientContext.ExecuteQuery();

            }
        }
开发者ID:rogerjo,项目名称:SupplierSites,代码行数:32,代码来源:Helper.cs


注:本文中的ClientContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。