本文整理汇总了C#中ClientContext类的典型用法代码示例。如果您正苦于以下问题:C# ClientContext类的具体用法?C# ClientContext怎么用?C# ClientContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ClientContext类属于命名空间,在下文中一共展示了ClientContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: IsWebPartOnPage
public static bool IsWebPartOnPage(ClientContext ctx, string relativePageUrl, string title)
{
var webPartPage = ctx.Web.GetFileByServerRelativeUrl(relativePageUrl);
ctx.Load(webPartPage);
ctx.ExecuteQuery();
if (webPartPage == null)
{
return false;
}
LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
ctx.Load(limitedWebPartManager.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
ctx.ExecuteQueryRetry();
if (limitedWebPartManager.WebParts.Count >= 0)
{
for (int i = 0; i < limitedWebPartManager.WebParts.Count; i++)
{
WebPart oWebPart = limitedWebPartManager.WebParts[i].WebPart;
if (oWebPart.Title.Equals(title, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
}
return false;
}
开发者ID:Rtoribiog,项目名称:PnP-Transformation,代码行数:29,代码来源:SetupManager.cs
示例17: SPService
public SPService(string username, string password, string url)
{
using (ClientContext ctx = new ClientContext(url))
{
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
ctx.Credentials = onlineCredentials;
web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
//ctx.GetFormDigestDirect().DigestValue
var authCookie = onlineCredentials.GetAuthenticationCookie(new Uri(url));
//var fedAuthString = authCookie.TrimStart("SPOIDCRL=".ToCharArray());
webinfo = new WebInfo { Title = web.Title, ErrorMessage = "", DigestInfo = authCookie.ToString() };
context = ctx;
}
}
开发者ID:maxali,项目名称:search-addin,代码行数:25,代码来源:SPService.cs
示例18: AddList
/// <summary>
/// Adds a list to a site
/// </summary>
/// <param name="properties">Site to operate on</param>
/// <param name="listType">Type of the list</param>
/// <param name="featureID">Feature guid that brings this list type</param>
/// <param name="listName">Name of the list</param>
/// <param name="enableVersioning">Enable versioning on the list</param>
public static List AddList(ClientContext ctx, Web web, ListTemplateType listType, string listName)
{
ListCollection listCollection = web.Lists;
ctx.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName));
ctx.ExecuteQuery();
if (listCollection.Count == 0)
{
ListCollection listCol = web.Lists;
ListCreationInformation lci = new ListCreationInformation();
lci.Title = listName;
lci.TemplateType = (int)listType;
List newList = listCol.Add(lci);
newList.Description = "Demo list for remote event receiver lab";
newList.Fields.AddFieldAsXml("<Field DisplayName='Description' Type='Text' />",true,AddFieldOptions.DefaultValue);
newList.Fields.AddFieldAsXml("<Field DisplayName='AssignedTo' Type='Text' />",true,AddFieldOptions.DefaultValue);
newList.Update();
return newList;
//ctx.Load(listCol);
//ctx.ExecuteQuery();
}
else
{
return listCollection[0];
}
}
开发者ID:modulexcite,项目名称:TrainingContent,代码行数:34,代码来源:LabHelper.cs
示例19: CreateSearchNavigationNodes
internal static void CreateSearchNavigationNodes(ClientContext clientContext, Web web, Dictionary<string, string> searchNavigationNodes)
{
if (searchNavigationNodes == null || searchNavigationNodes.Count == 0) return;
var searchNavigation = web.Navigation.GetNodeById(1040);
NavigationNodeCollection nodeCollection = searchNavigation.Children;
clientContext.Load(searchNavigation);
clientContext.Load(nodeCollection);
clientContext.ExecuteQuery();
for (int i = nodeCollection.Count - 1; i >= 0; i--)
{
nodeCollection[i].DeleteObject();
}
foreach (KeyValuePair<string, string> newNode in searchNavigationNodes.Reverse<KeyValuePair<string, string>>())
{
nodeCollection.Add(new NavigationNodeCreationInformation
{
Title = newNode.Key,
Url = newNode.Value
});
}
clientContext.ExecuteQuery();
}
开发者ID:olemp,项目名称:sherpa,代码行数:27,代码来源:SearchNavigationManager.cs
示例20: ProvisionLists
private static void ProvisionLists(ClientContext ctx)
{
Console.WriteLine("Provisioning lists:");
Console.WriteLine("Events");
List eventsList = ctx.Web.CreateList(ListTemplateType.Events, "Events", false, false, "Lists/Events", false);
eventsList.CreateField(@"<Field Type=""Boolean"" DisplayName=""Registration Allowed"" ID=""{d395011d-07c9-40a5-99c2-cb4d4f209d13}"" Name=""OfficeDevPnPRegistrationAllowed""><Default>1</Default></Field>", false);
ctx.Load(eventsList);
ctx.ExecuteQueryRetry();
Console.WriteLine("Event Registration");
List regList = ctx.Web.CreateList(ListTemplateType.GenericList, "Event Registration", false, false, "Lists/Event Registration", false);
Field field = regList.CreateField(@"<Field Type=""Lookup"" DisplayName=""Event"" ID=""{39e09239-3da4-455f-9f03-add53034de0a}"" Name=""OfficeDevPnPEventLookup"" />", false);
ctx.Load(regList);
ctx.Load(field);
ctx.ExecuteQueryRetry();
// configure event lookup field
FieldLookup eventField = ctx.CastTo<FieldLookup>(field);
eventField.LookupList = eventsList.Id.ToString();
eventField.LookupField = "Title";
eventField.Indexed = true;
eventField.IsRelationship = true;
eventField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Cascade;
eventField.Update();
ctx.ExecuteQueryRetry();
// configure author field
Field authorField = regList.Fields.GetFieldByName<Field>("Author");
authorField.Indexed = true;
authorField.Update();
ctx.ExecuteQueryRetry();
Console.WriteLine("");
}
开发者ID:nishantpunetha,项目名称:PnP,代码行数:33,代码来源:Program.cs
注:本文中的ClientContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论