Example #1
0
        /// <summary>
        /// Aplica el Metadato al listItem especificado.
        /// </summary>
        /// <param name="listItem"></param>
        /// <param name="site"></param>
        /// <param name="campo">Field Internal Name</param>
        /// <param name="valor">Term1/Term1Son/Term1GrandSon</param>
        /// <param name="lcid"></param>
        /// <returns></returns>
        public static void SetMetadata(ref SPListItem listItem, SPSite site, string campo, string valor, int lcid, bool multi)
        {
            TaxonomySession session   = new TaxonomySession(site);
            TaxonomyField   tagsField = (TaxonomyField)listItem.Fields.GetField(campo);
            TermStore       termStore = session.TermStores[tagsField.SspId];
            TermSet         termSet   = termStore.GetTermSet(tagsField.TermSetId);
            Term            termResult;

            if (multi)
            {
                ICollection <Term> termCol = new List <Term>();
                foreach (string term in valor.Split(';'))
                {
                    termResult = CrearNuevosTerminos(ref termStore, ref termSet, valor.Split('/'), lcid);
                    termCol.Add(termResult);
                }
                tagsField.SetFieldValue(listItem, termCol);
            }
            else
            {
                termResult = CrearNuevosTerminos(ref termStore, ref termSet, valor.Split('/'), lcid);
                tagsField.SetFieldValue(listItem, termResult);
            }
            listItem.SystemUpdate();
        }
Example #2
0
        //public static string GetUrl(this SPListItem item, string fieldName)
        //{
        //    object value = GetValue(item, fieldName);

        //    return GetUrl(value);
        //}

        //public static string GetUrl(this SPListItem item, Guid fieldId)
        //{
        //    object value = GetValue(item, fieldId);

        //    return GetUrl(value);
        //}

        //public static int GetRating(this SPListItem item, string fieldName)
        //{
        //    object value = GetValue(item, fieldName);

        //    return GetRating(value);
        //}

        //public static int GetRating(this SPListItem item, Guid fieldId)
        //{
        //    object value = GetValue(item, fieldId);

        //    return GetRating(value);
        //}

        //public static TaxonomyFieldValue GetTaxonomyValue(this SPListItem item, Guid fieldId)
        //{
        //    var value = item[fieldId];

        //    TaxonomyFieldValue ret = value != null
        //                                ? (TaxonomyFieldControl.GetTaxonomyValue(value.ToString())
        //                                   ?? new TaxonomyFieldValue(string.Empty))
        //                                : new TaxonomyFieldValue(string.Empty);

        //    return ret;
        //}

        //public static TaxonomyFieldValue GetTaxonomyValue(this SPListItem item, string fieldName)
        //{
        //    var value = item[fieldName];

        //    TaxonomyFieldValue ret = value != null
        //                                 ? (TaxonomyFieldControl.GetTaxonomyValue(value.ToString())
        //                                    ?? new TaxonomyFieldValue(string.Empty))
        //                                 : new TaxonomyFieldValue(string.Empty);

        //    return ret;
        //}

        //public static TaxonomyFieldValueCollection GetTaxonomyValues(this SPListItem item, Guid fieldId)
        //{
        //    var value = item[fieldId];

        //    TaxonomyFieldValueCollection ret = value != null
        //                                           ? (TaxonomyFieldControl.GetTaxonomyCollection(value.ToString())
        //                                              ?? new TaxonomyFieldValueCollection(string.Empty))
        //                                           : new TaxonomyFieldValueCollection(string.Empty);

        //    return ret;
        //}

        //public static TaxonomyFieldValueCollection GetTaxonomyValues(this SPListItem item, string fieldName)
        //{
        //    var value = item[fieldName];

        //    TaxonomyFieldValueCollection ret = value != null
        //                                           ? (TaxonomyFieldControl.GetTaxonomyCollection(value.ToString())
        //                                              ?? new TaxonomyFieldValueCollection(string.Empty))
        //                                           : new TaxonomyFieldValueCollection(string.Empty);

        //    return ret;
        //}

        //public static string GetTaxonomyLabel(this SPListItem item, Guid fieldId)
        //{
        //    return GetTaxonomyValue(item, fieldId).Label;
        //}

        //public static string GetTaxonomyLabel(this SPListItem item, string fieldName)
        //{
        //    return GetTaxonomyValue(item, fieldName).Label;
        //}

        //public static string[] GetTaxonomyLabels(this SPListItem item, Guid fieldId)
        //{
        //    return GetTaxonomyValues(item, fieldId).Where(@tax => tax.Label != null).Select(@tax => tax.Label).ToArray();
        //}

        //public static string[] GetTaxonomyLabels(this SPListItem item, string fieldName)
        //{
        //    return GetTaxonomyValues(item, fieldName).Where(@tax => tax.Label != null).Select(@tax => tax.Label).ToArray();
        //}

        public static void SetTaxonomyValue(this SPListItem item, string fieldName, string value, bool addIfDoesNotExist)
        {
            TaxonomyField taxonomyField = (TaxonomyField)item.Fields[fieldName];

            if (taxonomyField.AllowMultipleValues)
            {
                TaxonomyFieldValueCollection taxValue =
                    TaxonomyHelper.GetTaxonomyFieldValues(item.Web.Site, taxonomyField, new[] { value }, addIfDoesNotExist);
                taxonomyField.SetFieldValue(item, taxValue);
            }
            else
            {
                TaxonomyFieldValue taxValue = TaxonomyHelper.GetTaxonomyFieldValue(item.Web.Site, taxonomyField, value, addIfDoesNotExist);
                taxonomyField.SetFieldValue(item, taxValue);
            }
        }
        /// <summary>
        /// Updates a single-value managed metatada column
        /// </summary>
        /// <param name="taxonomyTerm"></param>
        /// <param name="item"></param>
        /// <param name="fieldToUpdate"></param>
        public static void UpdateMMField(string taxonomyTerm, SPListItem item, string fieldToUpdate)
        {
            //Get the metadata taxonomy field, a taxonomy session, the term store, and a collection of term sets in the store
            TaxonomyField   managedMetadataField = item.ParentList.Fields[fieldToUpdate] as TaxonomyField;
            Guid            tsId        = managedMetadataField.TermSetId;
            Guid            termStoreId = managedMetadataField.SspId;
            TaxonomySession tSession    = new TaxonomySession(item.ParentList.ParentWeb.Site);
            TermStore       tStore      = tSession.TermStores[termStoreId];
            TermSet         tSet        = tStore.GetTermSet(tsId);
            TermCollection  terms       = tSet.GetTerms(taxonomyTerm, false);
            Term            term        = null;

            //If term doesn't exist, create it in the term store
            if (terms.Count == 0)
            {
                Console.WriteLine("Creating term in managed metadata, {0}", taxonomyTerm);
                term = tSet.CreateTerm(taxonomyTerm, tStore.Languages[0]);
                tStore.CommitAll();
            }
            else
            {
                term = terms[0];
            }

            //Set the managed metadata field to the term retrieved from the term store
            managedMetadataField.SetFieldValue(item, term);
            item.Update();
        }
Example #4
0
 private void SetTaxonomyFieldValue(TermSet termSet, TaxonomyField taxField, SPListItem item, string value)
 {
     var terms = termSet.GetTerms(value, true, StringMatchOption.ExactMatch, 1, false);
     if (terms.Count > 0)
     {
         taxField.SetFieldValue(item, terms.First());
     }
 }
Example #5
0
        public static void SetTaxonomyValues(this SPListItem item, string fieldName, bool addIfDoesNotExist, params string[] values)
        {
            TaxonomyField taxonomyField = (TaxonomyField)item.Fields[fieldName];

            if (taxonomyField.AllowMultipleValues)
            {
                TaxonomyFieldValueCollection taxValue = TaxonomyHelper.GetTaxonomyFieldValues(item.Web.Site, taxonomyField, values, addIfDoesNotExist);
                taxonomyField.SetFieldValue(item, taxValue);
            }
            else
            {
                TaxonomyFieldValue taxValue = values != null && values.Length > 0
                                                  ? TaxonomyHelper.GetTaxonomyFieldValue(item.Web.Site, taxonomyField, values[0], addIfDoesNotExist)
                                                  : new TaxonomyFieldValue(taxonomyField);

                taxonomyField.SetFieldValue(item, taxValue);
            }
        }
Example #6
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Control control     = null;
                    string controlValue = null;

                    foreach (SPListItem listItem in selectedListItems)
                    {
                        listItem.ParentList.ParentWeb.AllowUnsafeUpdates = true;
                        foreach (SPField field in fieldsToUpdate)
                        {
                            control      = phDynamicFormControls.FindControl(string.Format("ctrl_{0}", field.InternalName));
                            controlValue = GetControlValue(control);

                            if (control != null && GetControlValue(control) != string.Empty)
                            {
                                if (control.GetType().Equals(typeof(Microsoft.SharePoint.Taxonomy.TaxonomyWebTaggingControl)))
                                {
                                    TaxonomyField fld = (TaxonomyField)field;
                                    if (fld.AllowMultipleValues)
                                    {
                                        var values = new TaxonomyFieldValueCollection(field);
                                        values.PopulateFromLabelGuidPairs(controlValue);
                                        fld.SetFieldValue(listItem, values);
                                    }
                                }
                                else
                                {
                                    listItem[field.Id] = controlValue;
                                }
                            }
                        }
                        listItem.Update();
                        listItem.ParentList.ParentWeb.AllowUnsafeUpdates = false;
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.Instance.Error("Error while saving fields during batch moving.", ex, DiagnosticsCategories.eCaseSearch);
            }

            //show any error messages that we have
            lblErrors.Text = errorMessages == null ? null : errorMessages.ToString();

            if (errorMessages == null || errorMessages.Length == 0)
            {
                //close the modal
                Response.Write(string.Format(CultureInfo.InvariantCulture, "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, '{0}');</script>", selectedLists.Count));
                Response.Flush();
                Response.End();
            }
        }
Example #7
0
        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            // Get the workflow context for the workflow activity.
            NWWorkflowContext ctx = NWWorkflowContext.GetContext(
                this.__Context,
                new Guid(this.__ListId),
                this.__ListItem.Id,
                this.WorkflowInstanceId,
                this);

            string resolvedFieldValue = ctx.AddContextDataToString(this.TaxFieldValue);
            string resolvedListID     = ctx.AddContextDataToString(this.lookupList);
            int    resolvedItemID     = int.Parse(ctx.AddContextDataToString(this.itemID));

            base.LogProgressStart(ctx);

            Nintex.Workflow.Diagnostics.EventLogger.Log(
                "Updating '" + TaxonomyFieldName + "' Value '" + TaxFieldValue + "' ",
                Microsoft.SharePoint.Administration.TraceSeverity.Verbose,
                _ErrorSource);

            try
            {
                SPList             list               = ctx.Web.Lists.GetList(new Guid(resolvedListID), false);
                SPListItem         item               = list.GetItemById(resolvedItemID);
                TaxonomyField      taxonomyField      = list.Fields[TaxonomyFieldName] as TaxonomyField;
                TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);

                String[] TermValues = resolvedFieldValue.Split('|');
                if (TermValues[0].Length > 0)
                {
                    // value|GUID
                    if (TermValues.Length == 2)
                    {
                        taxonomyFieldValue.Label    = TermValues[0];
                        taxonomyFieldValue.TermGuid = TermValues[1];
                    }
                    taxonomyField.SetFieldValue(item, taxonomyFieldValue);
                    item.SystemUpdate(false);
                }
            }
            catch (Exception ex)
            {
                Nintex.Workflow.Diagnostics.EventLogger.Log(
                    "Error occured while updating '" + TaxonomyFieldName + "' Value '" + resolvedFieldValue + "' " + ex.Message,
                    Microsoft.SharePoint.Administration.TraceSeverity.Unexpected,
                    _ErrorSource);
            }

            base.LogProgressEnd(ctx, executionContext);
            return(ActivityExecutionStatus.Closed);
        }
Example #8
0
 private void SetTaxonomyFieldMultiValue(TermSet termSet, TaxonomyField taxField, SPListItem item, List<string> fieldValues)
 {
     var fieldTerms = new List<Term>();
     foreach (var value in fieldValues)
     {
         var terms = termSet.GetTerms(value, true);
         if (terms.Count > 0)
         {
             terms.ToList().ForEach(t => fieldTerms.Add(t));
         }
     }
     taxField.SetFieldValue(item, fieldTerms);
 }
Example #9
0
 private static void AplicarTermino(Term term, string grupo, string path, SPListItem item, Term tGrupo, int orden)
 {
     try
     {
         TaxonomyField campo = (TaxonomyField)item.Fields.GetField(field);
         List <Term>   terms = new List <Term>();
         ObtenerTerminosAplicados(term, path, item, tGrupo, terms);
         if (terms.Count > 0)
         {
             campo.SetFieldValue(item, terms);
         }
         else
         {
             campo.SetFieldValue(item, tGrupo);
         }
         item.SystemUpdate();
         logProceso.WriteLine(orden + " " + path + " " + term.GetPath() + ";" + grupo);
     }
     catch (Exception ex)
     {
         logProceso.WriteLine("Error aplicando el metadato: " + path + " " + term.GetPath() + ";" + grupo + " " + ex.Message);
     }
 }
        /// <summary>
        /// Updates a multi-value managed metatada column
        /// </summary>
        /// <param name="taxonomyTerms"></param>
        /// <param name="item"></param>
        /// <param name="fieldToUpdate"></param>
        public static void UpdateMultiMMField(string[] taxonomyTerms, SPListItem item, string fieldToUpdate)
        {
            //Get the metadata taxonomy field, a taxonomy session, the term store, and a collection of term sets in the store
            TaxonomyField   multipleManagedMetadataField = item.ParentList.Fields[fieldToUpdate] as TaxonomyField;
            Guid            tsId        = multipleManagedMetadataField.TermSetId;
            Guid            termStoreId = multipleManagedMetadataField.SspId;
            TaxonomySession tSession    = new TaxonomySession(item.ParentList.ParentWeb.Site);
            TermStore       tStore      = tSession.TermStores[termStoreId];
            TermSet         tSet        = tStore.GetTermSet(tsId);
            TaxonomyFieldValueCollection termCollection = new TaxonomyFieldValueCollection(multipleManagedMetadataField);

            //Loop through each value being added to the metadata field
            foreach (string t in taxonomyTerms)
            {
                TermCollection terms = tSet.GetTerms(t, false);
                Term           term  = null;
                //If there are no matching terms in the term store, create one
                if (terms.Count == 0)
                {
                    Console.WriteLine("Creating term in managed metadata, {0}", t);
                    term = tSet.CreateTerm(t, tStore.Languages[0]);
                    tStore.CommitAll();
                }
                else
                {
                    term = terms[0];
                }

                //Add the current term to a term collection
                TaxonomyFieldValue termValue = new TaxonomyFieldValue(multipleManagedMetadataField);
                termValue.TermGuid = term.Id.ToString();
                termValue.Label    = term.Name;
                termCollection.Add(termValue);
            }

            //Add the term collection to the metadata field
            multipleManagedMetadataField.SetFieldValue(item, termCollection);
            item.Update();
        }
Example #11
0
        private static void updateFromAD(Dictionary <string, Guid> indexedTaxonomy, TermSet termSet, string ldapServerUrl, string principalCID, SPListItem item, SPFieldUser staffUserId)
        {
            var chalmerUserId = staffUserId.GetFieldValue(item[Constants.ChalmersID].ToString()) as SPFieldUserValue;

            if (chalmerUserId != null)
            {
                string username = chalmerUserId.User.LoginName;
                LoggingService.WriteTrace(EventSeverity.Information, "Got username: "******"UserLoginName has claims: " + userLoginName, LogCategory.ChalmersPublicWeb);
                }

                if (!string.IsNullOrEmpty(userLoginName))
                {
                    ADuser aduser = new ADuser(userLoginName)
                    {
                        LdapServerUrl   = ldapServerUrl,
                        GivenName       = string.Empty,
                        SN              = string.Empty,
                        Mail            = string.Empty,
                        Organisation    = string.Empty,
                        TelephoneNumber = string.Empty,
                        OtherTelephone  = string.Empty
                    };


#if DEBUG
                    string value = ConfigurationFile.GetGonfigurationFile(Chalmers.PublicWeb.Core.Constants.ConfigurationFilePath).GetSettingValue("StaffSyncCID");
                    if (value.ToLower().Contains(aduser.CID.ToLower().Replace("net\\", string.Empty)))
                    {
                        string x = "asdf";
                        System.Diagnostics.Debug.Print(x.ToString());
                    }
#endif

                    LoggingService.WriteTrace(EventSeverity.Information, "aduser CID = " + aduser.CID, LogCategory.ChalmersPublicWeb);
                    string domain = WebConfigurationManager.AppSettings["CurrentDomain"];

                    if (string.IsNullOrEmpty(domain))
                    {
                        aduser.ADDomainName = @"net\";
                    }
                    else
                    {
                        aduser.ADDomainName = domain + @"\";
                    }

                    if (aduser.CID.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        aduser.CIDWithoutDomain = aduser.CID.Remove(0, aduser.CID.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);
                        #if DEBUG
                        if (aduser.CIDWithoutDomain.ToString().ToLower().Equals("kain") ||
                            aduser.CIDWithoutDomain.ToString().ToLower().Equals("anderska"))
                        {
                            string x = aduser.CIDWithoutDomain.ToString();
                            System.Diagnostics.Debug.Print(x);
                        }
                        #endif
                    }
                    List <Term>   terms        = null;
                    TaxonomyField managedField = null;
                    aduser = ADUserProfile.GetUserProfileFromAD(aduser);

                    if (aduser != null)
                    {
                        bool adUnitsHaveChanged = taxFieldChanged(indexedTaxonomy, termSet, item, aduser, ref terms, ref managedField);
                        System.Text.StringBuilder phoneNumbers = new System.Text.StringBuilder();
                        if (!string.IsNullOrEmpty(aduser.TelephoneNumber))
                        {
                            phoneNumbers.Append(aduser.TelephoneNumber);
                        }
                        if (phoneNumbers.Length > 0 && !string.IsNullOrEmpty(aduser.OtherTelephone))
                        {
                            phoneNumbers.Append(", ");
                        }
                        if (!string.IsNullOrEmpty(aduser.OtherTelephone))
                        {
                            phoneNumbers.Append(aduser.OtherTelephone);
                        }

                        if (
                            hasUpdatedValues(item, aduser, phoneNumbers) ||
                            DateTime.Now.DayOfWeek == DayOfWeek.Saturday ||
                            adUnitsHaveChanged ||
                            (aduser.CID.Equals(principalCID))
                            )
                        {
                            item["EduPersonOrcid"]      = aduser.EduPersonOrcid;
                            item["FieldStaffGivenname"] = aduser.GivenName;
                            item["FieldStaffLastName"]  = aduser.SN;
                            item["FieldStaffFullName"]  = aduser.GivenName + " " + aduser.SN;
                            item["Title"] = aduser.GivenName + " " + aduser.SN;
                            item["FieldStaffOrganisation"] = aduser.Organisation;
                            item["FieldStaffTelephone"]    = phoneNumbers.ToString();
                            item["OfficeRoomNumber"]       = aduser.OfficeRoomNumber;
                            item["OfficeStreet"]           = aduser.OfficeStreet;
                            item["OfficeFloorNumber"]      = aduser.OfficeFloorNumber;

                            setEmail(principalCID, item, aduser);

                            if (adUnitsHaveChanged)
                            {
                                if (terms == null)
                                {
                                    terms = new List <Term>();
                                }
                                managedField.SetFieldValue(item, terms);
                            }

                            trySaveChanges(item, aduser);
                        }
                    }
                }
            }
        }
Example #12
0
        static void ImportTemplate(SPList list)
        {
            TaxonomySession taxonomySession = new TaxonomySession(list.ParentWeb.Site, updateCache: true);

            // STEP 1: Load the TermSet objects for the SPField objects.
            Dictionary <string, TermSetLookup> termSetsByInternalName = new Dictionary <string, TermSetLookup>(StringComparer.OrdinalIgnoreCase);

            foreach (SPField field in list.Fields)
            {
                // Alternatively, the code could also support taxonomy fields that can take multiple values here.
                if (field.TypeAsString != "TaxonomyFieldType")
                {
                    continue;
                }

                TaxonomyField taxonomyField = field as TaxonomyField;
                if (taxonomyField == null)
                {
                    continue;
                }

                TermStore termStore = taxonomySession.TermStores[taxonomyField.SspId];
                TermSet   termSet   = termStore.GetTermSet(taxonomyField.TermSetId);
                termSetsByInternalName.Add(field.InternalName, new TermSetLookup(termSet));
            }

            // STEP 2: Load the Excel file.
            Dictionary <string, ExcelRow> excelRowsByUrl = new Dictionary <string, ExcelRow>(StringComparer.OrdinalIgnoreCase);

            // Parse the input file.
            Log("Reading AutomatedTagging.csv...");

            using (StreamReader streamReader = new StreamReader("AutomatedTagging.csv"))
            {
                if (!streamReader.ReadLine().Contains("Filename"))
                {
                    throw new InvalidOperationException("Invalid file format; header is missing");
                }

                int lineNumber = 1;
                for (; ;)
                {
                    string line = streamReader.ReadLine();
                    ++lineNumber;
                    if (line == null)
                    {
                        break;
                    }

                    string[] csvValues = ParseCsvLine(line);
                    if (csvValues == null)
                    {
                        throw new InvalidOperationException("[line " + lineNumber + "]: Syntax error");
                    }

                    if (csvValues.Length < 1)
                    {
                        continue;
                    }

                    ExcelRow excelRow = new ExcelRow(csvValues[0], lineNumber);
                    for (int i = 2; i + 1 < csvValues.Length;)
                    {
                        string key = csvValues[i++].Trim();
                        if (key == "")
                        {
                            break;
                        }

                        string value = csvValues[i++].Trim();
                        if (value == "")
                        {
                            break;
                        }

                        SPField       field         = list.Fields.GetFieldByInternalName(key);
                        TermSetLookup termSetLookup = termSetsByInternalName[key];
                        Guid          termId        = termSetLookup.GetTermId(value);

                        excelRow.Pairs.Add(new KeyValuePair <string, Guid>(field.InternalName, termId));
                    }

                    excelRowsByUrl.Add(excelRow.ListItemUrl, excelRow);
                }
            }

            // STEP 3: Update the list items.
            ContentIterator contentIterator = new ContentIterator();

            contentIterator.ProcessListItems(list,
                                             delegate(SPListItem listItem)
            {
                ExcelRow excelRow;
                if (!excelRowsByUrl.TryGetValue(listItem.Url, out excelRow))
                {
                    return;
                }

                excelRow.Processed = true;

                bool updated = false;
                foreach (KeyValuePair <string, Guid> pair in excelRow.Pairs)
                {
                    TaxonomyField taxonomyField = (TaxonomyField)listItem.Fields.GetFieldByInternalName(pair.Key);

                    TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);
                    taxonomyFieldValue.TermGuid           = pair.Value.ToString();

                    TaxonomyFieldValue oldValue = listItem[taxonomyField.Id] as TaxonomyFieldValue;
                    if (oldValue == null || oldValue.TermGuid != taxonomyFieldValue.TermGuid)
                    {
                        taxonomyField.SetFieldValue(listItem, taxonomyFieldValue);
                        updated = true;
                    }
                }

                if (updated)
                {
                    Log("Updating item: " + listItem.Url);
                    listItem.Update();
                }
            },
                                             delegate(SPListItem listItem, Exception e)
            {
                Log("Error processing item " + listItem.Url
                    + ": " + e.Message);
                return(true);
            }
                                             );

            // Were any items missed?
            Log("");
            List <ExcelRow> missedRows = excelRowsByUrl.Values.Where(row => !row.Processed).ToList();

            if (missedRows.Count > 0)
            {
                Log("Failed to match these rows");
                foreach (ExcelRow row in missedRows)
                {
                    Log("  " + row.ListItemUrl);
                }
            }
        }
Example #13
0
        private void WriteTagsToFolksonomyColumn(IEnumerable <string> tags, SPListItem item, TaxonomyField column)
        {
            if (!column.IsTermSetValid)
            {
                return;
            }
            if (!column.Open)
            {
                return;
            }

            var session = new TaxonomySession(item.Web.Site);
            var mms     = session.TermStores[column.SspId];
            var ts      = mms.GetTermSet(column.TermSetId);

            if (!ts.IsOpenForTermCreation)
            {
                return;
            }

            var  addedTerms = new List <Term>();
            bool hasChanges = false;

            foreach (var tag in tags)
            {
                if (tag.Length > MAX_LENGTH)
                {
                    continue;
                }

                var validTag = GetValidTermName(tag);

                Term matchingTerm;

                if (column.IsKeyword)
                {
                    matchingTerm = mms.GetTerms(validTag, false, StringMatchOption.ExactMatch, 1, true).FirstOrDefault();
                }
                else
                {
                    matchingTerm = ts.GetTerms(validTag, false, StringMatchOption.ExactMatch, 1, true).FirstOrDefault();
                }

                if (matchingTerm == null)
                {
                    matchingTerm = ts.CreateTerm(validTag, mms.WorkingLanguage);
                    hasChanges   = true;
                }

                if (!addedTerms.Contains(matchingTerm))
                {
                    addedTerms.Add(matchingTerm);
                }
            }

            if (hasChanges)
            {
                mms.CommitAll();
            }
            if (addedTerms.Count > 0)
            {
                if (column.AllowMultipleValues)
                {
                    column.SetFieldValue(item, addedTerms, mms.WorkingLanguage);
                }
                else
                {
                    column.SetFieldValue(item, addedTerms.First());
                }
            }
        }
Example #14
0
        public static void AddDataTableToList(DataTable dt, SPList list, bool systemUpdate = false, bool doNotFireEvents = false)
        {
            if (dt == null)
            {
                return;
            }

            foreach (DataRow dr in dt.Rows)
            {
                SPListItem item = list.AddItem();

                string[] attachments = null;

                foreach (DataColumn col in dt.Columns)
                {
                    if (col.ReadOnly)
                    {
                        continue;
                    }

                    if (col.DataType == typeof(TaxonomyFieldValue))
                    {
                        TaxonomyField taxonomyField = (TaxonomyField)list.Fields.GetField(col.ColumnName);
                        taxonomyField.SetFieldValue(item, (TaxonomyFieldValue)(Convert.IsDBNull(dr[col]) ? new TaxonomyFieldValue(taxonomyField) : dr[col]));
                    }
                    else if (col.DataType == typeof(TaxonomyFieldValueCollection))
                    {
                        TaxonomyField taxonomyField = (TaxonomyField)list.Fields.GetField(col.ColumnName);
                        taxonomyField.SetFieldValue(item, (TaxonomyFieldValueCollection)(Convert.IsDBNull(dr[col]) ? new TaxonomyFieldValueCollection(taxonomyField) : dr[col]));
                    }
                    else if (col.ColumnName == "Attachments")
                    {
                        if (!Convert.IsDBNull(dr[col]))
                        {
                            attachments = dr[col].ToString().Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                        }
                    }
                    else
                    {
                        item[col.ColumnName] = Convert.IsDBNull(dr[col]) ? null : dr[col];
                    }
                }

                if (attachments != null)
                {
                    foreach (string attachment in attachments)
                    {
                        if (!string.IsNullOrEmpty(attachment))
                        {
                            item.AttachFile(attachment.Trim(), false, true);
                        }
                    }
                }

                if (systemUpdate)
                {
                    if (doNotFireEvents)
                    {
                        RunWithDisabledEvent(item.SystemUpdate);
                    }

                    item.SystemUpdate();
                }
                else
                {
                    if (doNotFireEvents)
                    {
                        RunWithDisabledEvent(item.Update);
                    }

                    item.Update();
                }
            }
        }