本文整理汇总了C#中ClientContext.ExecuteQuery方法的典型用法代码示例。如果您正苦于以下问题:C# ClientContext.ExecuteQuery方法的具体用法?C# ClientContext.ExecuteQuery怎么用?C# ClientContext.ExecuteQuery使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ClientContext
的用法示例。
在下文中一共展示了ClientContext.ExecuteQuery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
示例2: SetTaxonomyField
/// <summary>
/// Helper Method to set a Taxonomy Field on a list item
/// </summary>
/// <param name="ctx">The Authenticated ClientContext</param>
/// <param name="listItem">The listitem to modify</param>
/// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param>
public static void SetTaxonomyField(ClientContext ctx, ListItem listItem, Hashtable model)
{
FieldCollection _fields = listItem.ParentList.Fields;
ctx.Load(_fields);
ctx.ExecuteQuery();
foreach(var _key in model.Keys)
{
var _termName = model[_key].ToString();
TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(_key.ToString()));
ctx.Load(_field);
ctx.ExecuteQuery();
Guid _id = _field.TermSetId;
string _termID = AutoTaggingHelper.GetTermIdByName(ctx, _termName, _id );
var _termValue = new TaxonomyFieldValue()
{
Label = _termName,
TermGuid = _termID,
WssId = -1
};
_field.SetFieldValueByValue(listItem, _termValue);
listItem.Update();
ctx.ExecuteQuery();
}
}
示例3: 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();
}
}
示例4: Execute
// when SharePoint creates security groups for owners, visitors, and
// members upon web creation, these groups aren't created at web-level.
// Instead they're created at site level and referenced from web level.
// Thus, running group creation code multiple times, even after removing
// the group from a web, it may fail because the group will still be
// present at the site level.
public void Execute(ClientContext ctx, string groupTitle, string groupDescription, Action<Group> setAdditionalProperties = null)
{
Logger.Verbose($"Started executing {nameof(CreateSecurityGroup)} for group with title '{groupTitle}'");
var groups = ctx.Site.RootWeb.SiteGroups;
ctx.Load(groups);
ctx.ExecuteQuery();
var existingGroup = groups.SingleOrDefault(g => g.Title == groupTitle);
if (existingGroup != null)
{
Logger.Warning($"Group with title '{groupTitle}' already exist in site collection");
return;
}
var newGroup = groups.Add(
new GroupCreationInformation
{
Title = groupTitle,
Description = groupDescription
});
ctx.ExecuteQuery();
if (setAdditionalProperties != null)
{
setAdditionalProperties(newGroup);
}
newGroup.Update();
ctx.ExecuteQuery();
}
示例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.");
}
示例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();
}
示例7: CreateNewSiteCollection
public void CreateNewSiteCollection(string title, string name, string owner)
{
var url = string.Format("https://{0}-admin.sharepoint.com", _generatorDefinition.TenantName);
using (ClientContext context = new ClientContext(url))
{
context.Credentials = new SharePointOnlineCredentials(_generatorDefinition.Username, Utilities.Common.StringToSecureString(_generatorDefinition.Password));
var officeTenant = new Microsoft.Online.SharePoint.TenantAdministration.Tenant(context);
var newSiteProperties = new SiteCreationProperties()
{
Url = string.Format("https://{0}.sharepoint.com/sites/{1}", _generatorDefinition.TenantName, name),
Owner = _generatorDefinition.SiteCollOwnerLogin,
Template = "STS#0",
};
var spo= officeTenant.CreateSite(newSiteProperties);
context.Load(spo, i => i.IsComplete);
context.ExecuteQuery();
while (!spo.IsComplete)
{
System.Threading.Thread.Sleep(10000);
spo.RefreshLoad();
context.ExecuteQuery();
}
}
}
示例8: SetThemeBasedOnName
public void SetThemeBasedOnName(ClientContext ctx, Web web, Web rootWeb, string themeName)
{
// Let's get instance to the composite look gallery
List themeList = rootWeb.GetCatalog(124);
ctx.Load(themeList);
ctx.ExecuteQuery();
CamlQuery query = new CamlQuery();
string camlString = @"
<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Name' />
<Value Type='Text'>{0}</Value>
</Eq>
</Where>
</Query>
</View>";
// Let's update the theme name accordingly
camlString = string.Format(camlString, themeName);
query.ViewXml = camlString;
var found = themeList.GetItems(query);
ctx.Load(found);
ctx.ExecuteQuery();
if (found.Count > 0)
{
Microsoft.SharePoint.Client.ListItem themeEntry = found[0];
//Set the properties for applying custom theme which was jus uplaoded
string spColorURL = null;
if (themeEntry["ThemeUrl"] != null && themeEntry["ThemeUrl"].ToString().Length > 0)
{
spColorURL = MakeAsRelativeUrl((themeEntry["ThemeUrl"] as FieldUrlValue).Url);
}
string spFontURL = null;
if (themeEntry["FontSchemeUrl"] != null && themeEntry["FontSchemeUrl"].ToString().Length > 0)
{
spFontURL = MakeAsRelativeUrl((themeEntry["FontSchemeUrl"] as FieldUrlValue).Url);
}
string backGroundImage = null;
if (themeEntry["ImageUrl"] != null && themeEntry["ImageUrl"].ToString().Length > 0)
{
backGroundImage = MakeAsRelativeUrl((themeEntry["ImageUrl"] as FieldUrlValue).Url);
}
// Set theme for demonstration
web.ApplyTheme(spColorURL,
spFontURL,
backGroundImage,
false);
// Let's also update master page, if needed
if (themeEntry["MasterPageUrl"] != null && themeEntry["MasterPageUrl"].ToString().Length > 0)
{
web.MasterUrl = MakeAsRelativeUrl((themeEntry["MasterPageUrl"] as FieldUrlValue).Url); ;
}
ctx.ExecuteQuery();
}
}
示例9: CreateContentType
/// <summary>
/// Create Content Type
/// </summary>
public static void CreateContentType(ClientContext clientContext, string ContentTypeName, string ContentTypeDescription, string ContentTypeId, string[] filedNames)
{
var contentType = CSOMUtil.GetContentTypeById(clientContext, ContentTypeId);
// check if the content type exists
if (contentType == null)
{
ContentTypeCollection contentTypeColl = clientContext.Web.ContentTypes;
clientContext.Load(contentTypeColl);
clientContext.ExecuteQuery();
// Specifies properties that are used as parameters to initialize a new content type.
ContentTypeCreationInformation contentTypeCreation = new ContentTypeCreationInformation();
contentTypeCreation.Name = ContentTypeName;
contentTypeCreation.Description = ContentTypeDescription;
contentTypeCreation.Group = "Property Manager My App Content Types";
contentTypeCreation.Id = ContentTypeId;
//// Add the new content type to the collection
contentType = contentTypeColl.Add(contentTypeCreation);
clientContext.Load(contentType);
clientContext.ExecuteQuery();
CSOMUtil.BindFieldsToContentType(clientContext, contentType, filedNames);
}
}
示例10: SendMonitoringData
public void SendMonitoringData(int UniqueID, string type, double value)
{
// Get access to source site
using (var ctx = new ClientContext(tenant))
{
//Provide count and pwd for connecting to the source
var passWord = new SecureString();
foreach (char c in passwordString.ToCharArray()) passWord.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);
// Actual code for operations
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List myList = web.Lists.GetByTitle("MonitorLiveData");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem newItem = myList.AddItem(itemCreateInfo);
newItem["AlertID"] = UniqueID.ToString();
newItem["DataType"] = type.ToString();
newItem["DataValue"] = value;
newItem.Update();
ctx.ExecuteQuery();
}
}
示例11: ConnectToSite
private static void ConnectToSite()
{
Console.WriteLine("Please enter the URL to the SharePoint Site");
url = Console.ReadLine();
Console.WriteLine("Please enter the username");
userName = Console.ReadLine();
Console.WriteLine("Please enter the Password");
SecureString securePassword = getPassword();
clientContext = new ClientContext(url);
passWord = new SecureString();
string charpassword = new NetworkCredential(string.Empty, securePassword).Password;
foreach (char c in charpassword.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(userName, passWord);
mysite = clientContext.Site;
clientContext.Load(mysite);
clientContext.ExecuteQuery();
mySiteRelativeUrl = mysite.ServerRelativeUrl;
clientContext.Load(mysite.RootWeb);
clientContext.ExecuteQuery();
Console.WriteLine("");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Successfully connected to site at " + mysite.Url);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Press any key to continue..");
Console.ReadLine();
}
示例12: CreateSite
public void CreateSite(ClientContext context,
string UrlOfSiteRelativeToRoot,
string NameOfSite,
string Description)
{
Web rootWeb = context.Site.RootWeb;
context.Load(rootWeb, w => w.CustomMasterUrl);
WebCreationInformation wci = new WebCreationInformation();
wci.Url = UrlOfSiteRelativeToRoot;
wci.Title = NameOfSite;
wci.Description = Description;
wci.UseSamePermissionsAsParentSite = true;
wci.WebTemplate = "BLANKINTERNET#0";
wci.Language = 1033;
Web subWeb = context.Site.RootWeb.Webs.Add(wci);
context.ExecuteQuery();
//Update MasterPage
subWeb.CustomMasterUrl = rootWeb.CustomMasterUrl;
subWeb.MasterUrl = rootWeb.CustomMasterUrl;
subWeb.Update();
context.Load(subWeb);
context.ExecuteQuery();
}
示例13: GetTaxonomyHierarchy
/// <summary>
/// Gets the taxonomy hierarchy.
/// </summary>
/// <param name="clientContext">Client object containing Client data</param>
/// <param name="termStoreDetails">Term Store object containing Term store data</param>
/// <returns>Fetch Group Terms Status</returns>
internal static string GetTaxonomyHierarchy(ClientContext clientContext, TermStoreDetails termStoreDetails)
{
string returnFlag = ConstantStrings.FALSE;
try
{
TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
TermStore termStore;
clientContext.Load(taxonomySession.TermStores);
clientContext.ExecuteQuery();
termStore = taxonomySession.TermStores[0];
clientContext.Load(
termStore,
store => store.Name,
store => store.Groups.Include(
group => group.Name));
clientContext.ExecuteQuery();
returnFlag = GetReturnFlag(clientContext, termStore, termStoreDetails);
}
catch (Exception exception)
{
Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
}
return returnFlag;
}
示例14: button1_Click
private void button1_Click(object sender, EventArgs e)
{
string siteUrl = "https://hp-27b0ee14ded081.sharepoint.com/teams/spohub/ACSMigrationManager/";
ClientContext clientContext = new ClientContext(siteUrl);
System.Security.SecureString pwd = new System.Security.SecureString();
pwd.AppendChar('p');
pwd.AppendChar('a');
pwd.AppendChar('s');
pwd.AppendChar('s');
pwd.AppendChar('@');
pwd.AppendChar('w');
pwd.AppendChar('o');
pwd.AppendChar('r');
pwd.AppendChar('d');
pwd.AppendChar('1');
clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", pwd);
Web site = clientContext.Web;
clientContext.Load(site);
clientContext.ExecuteQuery();
SP.List oList = clientContext.Web.Lists.GetByTitle("Migration Tasks");
CamlQuery query;
string sitesText = "" + textBox1.Text;
sitesText = sitesText.Replace("\r", "");
sitesText = sitesText.Replace("\n", ",");
string[] sites = null;
if (sitesText.Length > 0)
{
sites = sitesText.Split(',');
for (int i = 0; i < sites.Length; i++)
{
if (sites[i].Trim().Length > 0)
{
query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Contains><FieldRef Name='ContentSource'/><Value Type='Text'>" +
sites[i] + "</Value></Contains></Where></Query></View>";
ListItemCollection collListItem = oList.GetItems(query);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
if (collListItem.Count == 1)
{
ListItem oListItem = collListItem[0];
//listBox1.DataSource = collListItem;
textBox3.Text += oListItem["Title"].ToString() + @"
";
oListItem["MigrationStatus"] = textBox2.Text;
oListItem.Update();
clientContext.ExecuteQuery();
}
}
}
}
}
示例15: AssociateWebProvisionedEventReceiver
/// <summary>
/// deployes event receiver at site level
/// </summary>
/// <param name="clientContext"></param>
public void AssociateWebProvisionedEventReceiver(ClientContext clientContext)
{
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(clientContext.Site);
clientContext.Load(clientContext.Site.EventReceivers);
clientContext.ExecuteQuery();
EventReceiverDefinitionCreationInformation receiver = new EventReceiverDefinitionCreationInformation();
receiver.EventType = EventReceiverType.WebProvisioned;
OperationContext op = OperationContext.Current;
Message msg = op.RequestContext.RequestMessage;
receiver.ReceiverUrl = msg.Headers.To.ToString();
receiver.ReceiverName = ReceiverName;
receiver.Synchronization = EventReceiverSynchronization.Synchronous;
receiver.SequenceNumber = 5000;
//adding receiver the host web.
// we are adding event receiver to site context so that event receriver fires for sub-sub-sites
clientContext.Site.EventReceivers.Add(receiver);
clientContext.ExecuteQuery();
//upload theme related files
themeHelper.DeployFiles(web);
//delete oob composed looks
themeHelper.DeleteOOBComposedLooks(clientContext);
//apply theme and set default theme
themeHelper.AddComposedLooksAndSetDefaultTheme(clientContext);
}