本文整理汇总了C#中ListItem.Update方法的典型用法代码示例。如果您正苦于以下问题:C# ListItem.Update方法的具体用法?C# ListItem.Update怎么用?C# ListItem.Update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ListItem
的用法示例。
在下文中一共展示了ListItem.Update方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
}
示例2: HandleWikiPageProvision
private void HandleWikiPageProvision(ListItem listItem, WebPartDefinitionBase webpartModel)
{
if (!webpartModel.AddToPageContent)
return;
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");
var context = listItem.Context;
var targetFieldName = string.Empty;
if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");
targetFieldName = BuiltInInternalFieldNames.WikiField;
}
else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");
targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
}
else
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
return;
}
var wikiTemplate = new StringBuilder();
var wpId = webpartModel.Id
.Replace("g_", string.Empty)
.Replace("_", "-");
var content = listItem[targetFieldName] == null
? string.Empty
: listItem[targetFieldName].ToString();
wikiTemplate.AppendFormat(
"<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
wikiTemplate.AppendFormat(" <div class='ms-rtestate-read {0}' id='div_{0}'>", wpId);
wikiTemplate.AppendFormat(" </div>");
wikiTemplate.AppendFormat("</div>");
var wikiResult = wikiTemplate.ToString();
if (string.IsNullOrEmpty(content))
{
TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Page content is empty Generating new one.");
content = wikiResult;
listItem[targetFieldName] = content;
listItem.Update();
context.ExecuteQueryWithTrace();
}
else
{
if (content.ToUpper().IndexOf(wpId.ToUpper()) == -1)
{
TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Replacing web part with ID: [{0}] on the page content.", wpId);
content += wikiResult;
listItem[targetFieldName] = content;
listItem.Update();
context.ExecuteQueryWithTrace();
}
else
{
TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
"Cannot find web part ID: [{0}] the page content. Provision won't add web part on the page content.",
new object[]
{
wpId
});
}
}
}
示例3: ProcessItem
//.........这里部分代码省略.........
writer.Write(updateXml);
writer.Flush();
memoryStream.Position = 0;
Logger.LogInfoMessage(String.Format("Saving contents of InfoPath File [{0}] of Web [{1}] ...", fileName, webUrl), false);
// Approach to save File contents depends on Auth Model chosen
if (Program.UseAppModel == true)
{
Folder targetFolder = null;
Logger.LogInfoMessage(String.Format("Getting folder of File [{0}] of Web [{1}] ...", fileName, webUrl), false);
try
{
targetFolder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
web.Context.Load(targetFolder);
web.Context.ExecuteQuery();
Logger.LogInfoMessage(String.Format("Got folder"), false);
}
catch (Exception ex)
{
Logger.LogErrorMessage(String.Format("ProcessItem() failed for File [{0}] in the Form Library {1}] of Web [{2}]: Reason={3}; Error={4}", fileName, listName, webUrl,
"Upload Folder was not Found.",
"[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false);
lstPeoplepickeroutput.Add(LogExceptionMessages(Peoplepickeroutput, ex));
return;
}
Logger.LogInfoMessage(String.Format("Uploading file [{0}] ...", fileName), false);
try
{
targetFolder.UploadFile(fileName, memoryStream, true);
Logger.LogInfoMessage(String.Format("Uploaded file"), false);
}
catch (Exception ex)
{
Logger.LogErrorMessage(String.Format("ProcessItem() failed for File [{0}] in the Form Library {1}] of Web [{2}]: Reason={3}; Error={4}", fileName, listName, webUrl,
"File Upload Failed.",
"[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false);
lstPeoplepickeroutput.Add(LogExceptionMessages(Peoplepickeroutput, ex));
return;
}
}
else
{
try
{
fileUrl = String.Format("{0}/{1}", folderServerRelativeUrl, string.Format(fileName, lastModifiedTimeStamp.ToString()));
Microsoft.SharePoint.Client.File.SaveBinaryDirect(_context, fileUrl, memoryStream, true);
}
catch (Exception ex)
{
Logger.LogErrorMessage(String.Format("ProcessItem() failed for File [{0}] in the Form Library {1}] of Web [{2}]: Reason={3}; Error={4}", fileName, listName, webUrl,
"File Upload Failed.",
"[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false);
lstPeoplepickeroutput.Add(LogExceptionMessages(Peoplepickeroutput, ex));
return;
}
}
Logger.LogInfoMessage(String.Format("Saved contents of File [{0}] in FormLibrary [{1}] of Web [{2}]", fileUrl, listName, webUrl), true);
try
{
_context.Load(item);
_context.ExecuteQuery();
item["Editor"] = fuLastModifiedUser;
item["Modified"] = lastModifiedTimeStamp.ToString();
item.Update();
_context.ExecuteQuery();
Peoplepickeroutput.Status = Constants.SuccessStatus;
Peoplepickeroutput.ErrorDetails = Constants.NotApplicable;
}
catch (Exception ex)
{
Logger.LogErrorMessage(String.Format("ProcessItem() failed for InfoPath Form Library [{0}] of Web [{1}]: Reason={2}; Error={3}", listName, webUrl,
"ited update failed for old Editor & Modified.",
"[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false);
lstPeoplepickeroutput.Add(LogExceptionMessages(Peoplepickeroutput, ex));
return;
}
//Logger.LogInfoMessage(String.Format("Updated Item with previous Editor [{0}] and Modified Timestamp [{1}] in FormLibrary [{2}] of Web [{3}]",
// lastModifiedUser, lastModifiedTimeStamp.ToString(), listName, webUrl), true);
}
}
else
{
Peoplepickeroutput.Status = Constants.NoUpdateRequired;
Peoplepickeroutput.ErrorDetails = Constants.NotApplicable;
}
lstPeoplepickeroutput.Add(Peoplepickeroutput);
}
}
catch (Exception ex)
{
Logger.LogErrorMessage(String.Format("ProcessItem() failed for InfoPath Form Library [{0}] of Web [{1}]: Reason={2}; Error={3}", listName, webUrl,
"failed while processing item.",
"[" + ex.Message + "] | [" + ex.HResult + "] | [" + ex.Source + "] | [" + ex.StackTrace + "] | [" + ex.TargetSite + "]"), false);
return;
}
}
示例4: SetListItemValue
private void SetListItemValue(List list, ListItem listItem, Dictionary<string, string> updatedValues)
{
string _key = listItem[SiteClassificationFields.FLD_KEY_INTERNAL_NAME].ToString();
switch(_key)
{
case SiteClassificationKeys.AudienceReachKey:
if(updatedValues.ContainsKey(SiteClassificationKeys.AudienceReachKey))
{
listItem[SiteClassificationFields.FLD_VALUE_INTERNAL_NAME] = updatedValues[SiteClassificationKeys.AudienceReachKey];
listItem.Update();
}
break;
case SiteClassificationKeys.BusinessImpactKey:
if (updatedValues.ContainsKey(SiteClassificationKeys.BusinessImpactKey))
{
listItem[SiteClassificationFields.FLD_VALUE_INTERNAL_NAME] = updatedValues[SiteClassificationKeys.BusinessImpactKey];
listItem.Update();
}
break;
default:
break;
}
}
示例5: HandleWikiPageProvision
private void HandleWikiPageProvision(ListItem listItem,
WebPartDefinitionBase webpartModel, Guid? webPartStoreKey, Guid? oldWebParKey)
{
if (!webpartModel.AddToPageContent)
return;
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");
var context = listItem.Context;
var targetFieldName = string.Empty;
if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");
targetFieldName = BuiltInInternalFieldNames.WikiField;
}
else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");
targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
}
else
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
return;
}
var wikiTemplate = new StringBuilder();
var existingWebPartId = string.Empty;
var definitionWebPartId = webpartModel.Id.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-"); ;
var upcomingWebPartId = definitionWebPartId;
// aa....
// extremely unfortunate
if (webpartModel is XsltListViewWebPartDefinition)
{
upcomingWebPartId = webPartStoreKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-"); ;
}
if (!oldWebParKey.HasGuidValue())
{
// first provision
existingWebPartId = webPartStoreKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-");
}
else
{
// second, so that we had web part and use that ID
existingWebPartId = oldWebParKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-");
}
var content = listItem[targetFieldName] == null
? string.Empty
: listItem[targetFieldName].ToString();
// actual ID will be replaced later
wikiTemplate.AppendFormat("<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
wikiTemplate.Append(" <div class='ms-rtestate-read {0}' id='div_{0}'>");
wikiTemplate.AppendFormat(" </div>");
wikiTemplate.AppendFormat("</div>");
var wikiTemplateOutput = wikiTemplate.ToString();
if (string.IsNullOrEmpty(content))
{
// page is empty, pre-generating HTML
// pushing web part as the current WebPart Key
TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
"Page content is empty Generating new one.");
content = string.Format(wikiTemplateOutput, upcomingWebPartId);
listItem[targetFieldName] = content;
listItem.Update();
context.ExecuteQueryWithTrace();
}
else
{
// we had web part on the page
// so we need to change the ID
if (oldWebParKey.HasGuidValue())
{
// was old on the page?
if (content.ToUpper().IndexOf(existingWebPartId.ToUpper()) != -1)
{
// yes, replacing ID
//.........这里部分代码省略.........
示例6: HandleWikiPageProvision
private void HandleWikiPageProvision(ListItem listItem,
WebPartDefinitionBase webpartModel, Guid? currentWebPartStoreKey, Guid? oldWebParStoreKey)
{
if (!webpartModel.AddToPageContent)
return;
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");
var context = listItem.Context;
var targetFieldName = string.Empty;
if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");
targetFieldName = BuiltInInternalFieldNames.WikiField;
}
else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");
targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
}
else
{
TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
return;
}
// any on the page?
var existingWebPartId = string.Empty;
// current from the new provision
var upcomingWebPartId = string.Empty;
// weird, by some web part ignor ID from the XML
// so webpartStoreKey from the previous CSOM adding web part to the page must be used
// M2 covers that fact with the regression testing, so we know what are they
// and we have NOD idea why it happens
if (ShouldUseWebPartStoreKeyForWikiPage)
{
upcomingWebPartId = currentWebPartStoreKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-"); ;
}
else
{
// get from the model
upcomingWebPartId = webpartModel.Id.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-"); ;
}
if (!oldWebParStoreKey.HasGuidValue())
{
// first provision
existingWebPartId = currentWebPartStoreKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-");
}
else
{
// second provision,
// we had web part on the page and can reuse that ID to relink on wiki content
existingWebPartId = oldWebParStoreKey.ToString()
.Replace("g_", string.Empty)
.Replace("_", "-");
}
var content = listItem[targetFieldName] == null
? string.Empty
: listItem[targetFieldName].ToString();
var wikiTemplate = new StringBuilder();
// actual ID will be replaced later
wikiTemplate.AppendFormat("<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
wikiTemplate.Append(" <div class='ms-rtestate-read {0}' id='div_{0}'>");
wikiTemplate.AppendFormat(" </div>");
wikiTemplate.AppendFormat("</div>");
var wikiTemplateOutput = wikiTemplate.ToString();
if (string.IsNullOrEmpty(content))
{
// page is empty, pre-generating HTML
// pushing web part as the current WebPart Key
TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
"Page content is empty Generating new one.");
content = string.Format(wikiTemplateOutput, upcomingWebPartId);
listItem[targetFieldName] = content;
listItem.Update();
context.ExecuteQueryWithTrace();
}
else
//.........这里部分代码省略.........
示例7: CommitToSP
private void CommitToSP(ListItem itemIn, Microsoft.SharePoint.Client.File uploadedFile)
{
try
{
itemIn.Update();
ctx.Load(uploadedFile);
ctx.ExecuteQuery();
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
}
}
示例8: GetTermIdForTaxonomyField
private string GetTermIdForTaxonomyField(TaxonomyField field, string term, ListItem pendingItem,Microsoft.SharePoint.Client.File pendingFile)
{
if (_terms == null)
_terms = new Dictionary<string, IDictionary<string, string>>();
if (!_terms.Keys.Contains(field.Title))
_terms[field.Title] = new Dictionary<string, string>();
if (_terms[field.Title].Keys.Contains(term))
return _terms[field.Title][term].ToString();
var termId = string.Empty;
//before we go forward,save pending item
pendingItem.Update();
ctx.Load(pendingFile);
ctx.ExecuteQuery();
TaxonomySession tSession = TaxonomySession.GetTaxonomySession(ctx);
ctx.Load(tSession.TermStores);
ctx.ExecuteQuery();
TermStore ts = tSession.TermStores.First();
TermSet tset = ts.GetTermSet(field.TermSetId);
LabelMatchInformation lmi = new LabelMatchInformation(ctx);
lmi.Lcid = 1033;
lmi.TrimUnavailable = true;
lmi.TermLabel = term;
TermCollection termMatches = tset.GetTerms(lmi);
ctx.Load(tSession);
ctx.Load(ts);
ctx.Load(tset);
ctx.Load(termMatches);
ctx.ExecuteQuery();
if (termMatches != null && termMatches.Count() > 0)
termId = termMatches.First().Id.ToString();
_terms[field.Title][term] = termId;
return termId;
}
示例9: ProcessSiteRequest
/// <summary>
/// Processes the request list item
/// </summary>
/// <param name="ctx"></param>
/// <param name="request"></param>
private void ProcessSiteRequest(ClientContext ctx, ListItem request, SiteType siteType)
{
bool isSubSite = false;
var web = ctx.Web;
ctx.Load(web, w => w.Url);
var title = request["Title"].ToString();
Console.WriteLine("Found site request for new site with title '{0}'...", title);
//Update list item to indicate that we are processing the request
request["ProvisioningStatus"] = "Provisioning...";
request.Update();
ctx.ExecuteQueryRetry();
Console.WriteLine("Updated list item with status 'Provisioning...'");
string baseTemplate = string.Empty;
string templateFileRelativeUrl = string.Empty;
string templateFileName = string.Empty;
string siteTitle = string.Empty;
string siteUrl = string.Empty;
string siteDescription = string.Empty;
//Get basic metadata for logging
siteTitle = title;
siteUrl = GetNewSiteUrl(request);
#region ProvisioningTemplate
Console.WriteLine("Loading provisioning template...");
//Throw exception request doesn't have a template
var templateLookupValue = request["SiteTemplate"] as FieldLookupValue;
if (templateLookupValue == null)
throw new Exception(String.Format("Request with title {0} does not have a value for the Site Template field.", title));
//Get provisioning template
int id = templateLookupValue.LookupId;
string lookupListTitle = "Site Templates";
ListItem templateFile = GetListItemFromLookupList(ctx, id, lookupListTitle);
string url = templateFile["FileRef"].ToString();
templateFileName = templateFile["FileLeafRef"].ToString();
templateFileRelativeUrl = url;
baseTemplate = templateFile["BaseTemplate"].ToString();
ProvisioningTemplate provisioningTemplate = GetProvisioningTemplate(ctx, this.SiteTemplatesListTitle, templateFileName);
//Throw exception if can't find it
if (provisioningTemplate == null)
throw new Exception(string.Format("Could not find template {0}", templateFileName));
//===========================================================
//Un-comment to use template created from source web instead
//===========================================================
//template = clientContext.Web.GetProvisioningTemplate();
#endregion
#region ParentWeb
string parentWebUrl = string.Empty;
if (siteType == SiteType.Subsite)
{
var parentSiteLookupValue = request["ParentWeb"] as FieldLookupValue;
if (parentSiteLookupValue == null)
throw new Exception(String.Format("Subsite request with title {0} does not have a value for the parent site collection field.", title));
//Get provisioning template
int clientSiteItemId = parentSiteLookupValue.LookupId;
ListItem parentSiteListItem = GetListItemFromLookupList(ctx, clientSiteItemId, this.SiteCollectionRequestsListTitle);
ctx.Load(parentSiteListItem, p => p["LinkToProvisionedSite"]);
try
{
var parentWeb = parentSiteListItem["LinkToProvisionedSite"] as FieldUrlValue;
parentWebUrl = parentWeb.Url;
}
catch (Exception ex)
{
throw new Exception(String.Format("The parent site collection '{0}' for the requested subsite '{1}' has not been successfully provisioned. Aborting subsite creation.",
parentSiteLookupValue.LookupValue, siteTitle));
}
isSubSite = true;
}
#endregion
//Log all parameters before continuing
Console.WriteLine("Found site request. Properties: {0}");
Console.WriteLine("Base template: {0}", baseTemplate);
Console.WriteLine("Template file: {0}", templateFileRelativeUrl);
Console.WriteLine("Template file name: {0}", templateFileName);
Console.WriteLine("Requested title: {0}", siteTitle);
Console.WriteLine("Requested URL: {0}", siteUrl);
//Execute in limited try/catch scope so new web is deleted if any exceptions are thrown
//.........这里部分代码省略.........
示例10: IncrementArticlesFulfilled
private void IncrementArticlesFulfilled(ListItem articlesListItem, Decimal units)
{
if (articlesListItem != null)
{
decimal oldUnits = Convert.ToDecimal(articlesListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_FULFILLED]);
decimal fulfilled = oldUnits + units;
articlesListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_FULFILLED] = fulfilled;
articlesListItem.Update();
}
else
{
errorlogWriter.WriteLog("WARNING: Fulfillment Tracking RER Item ADDING", "Articles list item not found. Not INCREMENTED");
}
}
示例11: IncrementAllocationsFulfilled
private void IncrementAllocationsFulfilled(ListItem allocationListItem, Decimal units)
{
if (allocationListItem != null)
{
decimal oldUnits = Convert.ToDecimal(allocationListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_FULFILLED]);
decimal oldRemaining = Convert.ToDecimal(allocationListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_REMAINING]);
decimal newRemaining = oldRemaining - units;
decimal fulfilled = oldUnits + units;
allocationListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_REMAINING] = newRemaining;
allocationListItem[FulfillmentTrackingRER.LIST_ITEM_ALLOCATIONS_FULFILLED] = fulfilled;
allocationListItem.Update();
}
else
{
errorlogWriter.WriteLog("WARNING: Fulfillment Tracking RER Item ADDING", "Allocations list item not found. Not INCREMENTED");
}
}
示例12: SetTaxonomyFields
/// <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 SetTaxonomyFields(ClientContext ctx, ListItem listItem,string FileContent,string ListId,string url)
{
FieldCollection _fields = listItem.ParentList.Fields;
ctx.Load(ctx.Web.AllProperties);
ctx.Load(_fields);
ctx.ExecuteQuery();
AppWebHelper hlp = new AppWebHelper(url,false);
List<GlobalSetting> settings = GetGlobalConfig(hlp);
LogHelper.Log(settings.Count.ToString());
var enabled = settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault();
bool KeywordCreationEnabled = Convert.ToBoolean(
settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault().value);
int KeywordRecognitionTreshold = Convert.ToInt32(
settings.Where(s => s.key == Constants.KeywordRecognitionTreshold).SingleOrDefault().value);
int KeywordCreationTreshold = Convert.ToInt32(
settings.Where(s => s.key == Constants.KeywordCreationTreshold).SingleOrDefault().value);
List<string> ConfiguredFields = hlp.ListTaxFields(ListId);
foreach(var _f in _fields)
{
if(ConfiguredFields.Contains(_f.Id.ToString()))
{
TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetById(_f.Id));
if(_f.InternalName != Constants.TaxFieldInternalName)
{
ctx.Load(_field);
ctx.ExecuteQuery();
Collection<Term> MatchingTerms = null;
MatchingTerms = AutoTaggingHelper.MatchingTerms(FileContent, ctx, _field.TermSetId, _field.AnchorId);
if (MatchingTerms.Count > 0)
{
LogHelper.Log("Updating taxfield " + _field.Title);
if (_field.AllowMultipleValues)
{
_field.SetFieldValueByCollection(listItem, MatchingTerms, 1033);
}
else
{
_field.SetFieldValueByTerm(listItem, MatchingTerms.First(), 1033);
}
listItem.Update();
ctx.ExecuteQuery();
}
}
else
{
TaxonomyTerms tt = new TaxonomyTerms(ctx);
string TextLanguage=
AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3;
StringBuilder EntKeyWordsValue = new StringBuilder();
Dictionary<string, int> tokens =
Tokenize(FileContent,
KeywordRecognitionTreshold,
TextLanguage);
StringBuilder TokenString = new StringBuilder();
foreach (KeyValuePair<string, int> token in tokens)
{
Guid KeywordId = TaxonomyTerms.GetKeyword(token.Key);
TokenString.AppendFormat("{0}|", token.Key);
if (KeywordId != Guid.Empty)
{
EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, KeywordId);
}
else
{
if (KeywordCreationEnabled && token.Value >= KeywordCreationTreshold &&
!AutoTaggingHelper.IsEmptyWord(token.Key.ToLowerInvariant(), TextLanguage,hlp))
{
Guid g = AddKeyWord(token.Key, ctx);
if (g != Guid.Empty)
{
EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, g);
}
}
}
}
LogHelper.Log(TokenString.ToString());
if (EntKeyWordsValue.ToString().Length > 0)
{
LogHelper.Log("keyword value " + EntKeyWordsValue.ToString(), LogSeverity.Error);
TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(ctx, string.Empty, _field);
col.PopulateFromLabelGuidPairs(EntKeyWordsValue.ToString());
_field.SetFieldValueByValueCollection(listItem, col);
listItem.Update();
ctx.ExecuteQuery();
//.........这里部分代码省略.........