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


C# ClientContext.CastTo方法代码示例

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


在下文中一共展示了ClientContext.CastTo方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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();
            }
        }
开发者ID:NicolajLarsen,项目名称:PnP,代码行数:33,代码来源:AutoTaggingHelper.cs

示例2: 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

示例3: CreateDefaultList

        public void CreateDefaultList(ClientContext context, Web web)
        {
            // Create a list
            var listInfo = new ListCreationInformation
            {
                Title = "Default List",
                TemplateType = (int)ListTemplateType.GenericList
            };
            var list = web.Lists.Add(listInfo);
            list.Description = "A default list that is provisioned.";
            list.EnableVersioning = true;
            list.Update();
            context.ExecuteQuery();

            // Add a field
            var field = list.Fields.AddFieldAsXml("<Field DisplayName='My Number1' Type='Number' />", true, AddFieldOptions.DefaultValue);
            var numberField = context.CastTo<FieldNumber>(field);
            numberField.MaximumValue = 1000;
            numberField.MinimumValue = 10;
            numberField.Update();

            // Add a second field
            var field2 = list.Fields.AddFieldAsXml("<Field DisplayName='My Number2' Type='Number' />", true, AddFieldOptions.DefaultValue);

            context.ExecuteQuery();
        }
开发者ID:mehrosu,项目名称:SPOEmulators,代码行数:26,代码来源:ProvisioningEngine.cs

示例4: GetWSSId

        /// <summary>
        /// Function to get the WssID for the Practice group, Area of law and Sub area of law terms
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="matterMetadata">Object containing meta data for Matter</param>
        /// <param name="fields">Field Collection object</param>
        /// <returns>An Object containing meta data for Matter</returns>
        internal static MatterMetadata GetWSSId(ClientContext clientContext, MatterMetadata matterMetadata, FieldCollection fields)
        {
            ClientResult<TaxonomyFieldValue> practiceGroupResult = clientContext.CastTo<TaxonomyField>
                (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnPracticeGroup))
                .GetFieldValueAsTaxonomyFieldValue(matterMetadata.PracticeGroupTerm.Id);
            ClientResult<TaxonomyFieldValue> areaOfLawResult = clientContext.CastTo<TaxonomyField>
                (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnAreaOfLaw))
                .GetFieldValueAsTaxonomyFieldValue(matterMetadata.AreaTerm.Id);
            ClientResult<TaxonomyFieldValue> subareaOfLawResult = clientContext.CastTo<TaxonomyField>
                (fields.GetByInternalNameOrTitle(ServiceConstantStrings.ContentTypeColumnSubareaOfLaw))
                .GetFieldValueAsTaxonomyFieldValue(matterMetadata.SubareaTerm.Id);
            clientContext.ExecuteQuery();

            matterMetadata.PracticeGroupTerm.WssId = practiceGroupResult.Value.WssId;
            matterMetadata.AreaTerm.WssId = areaOfLawResult.Value.WssId;
            matterMetadata.SubareaTerm.WssId = subareaOfLawResult.Value.WssId;
            return matterMetadata;
        }
开发者ID:MatthewSammut,项目名称:mattercenter,代码行数:25,代码来源:ProvisionHelperFunctionsUtility.cs

示例5: GetTaxonomyFieldValue

 public static TaxonomyFieldValue GetTaxonomyFieldValue(string termName, Field mmField, ClientContext clientContext)
 {
     //Ref: Steve Curran - http://sharepointfieldnotes.blogspot.com/2013_06_01_archive.html
     //Cast field to TaxonomyField to get its TermSetId
     TaxonomyField taxField = clientContext.CastTo<TaxonomyField>(mmField);
     //Get term ID from name and term set ID
     string termId = GetTermIdForTerm(termName, taxField.TermSetId, clientContext);
     if (!string.IsNullOrEmpty(termId))
     {
         //Set TaxonomyFieldValue
         TaxonomyFieldValue termValue = new TaxonomyFieldValue();
         termValue.Label = termName;
         termValue.TermGuid = termId;
         termValue.WssId = -1;
         return termValue;
     }
     return null;
 }
开发者ID:ALCBerry87,项目名称:SPO-Import-List-CSV,代码行数:18,代码来源:Program.cs

示例6: ProvisionLists

        public static void ProvisionLists(ClientContext ctx)
        {
            //Create country list
            Console.WriteLine("Provisioning lists:");
            List countryList = null;
            if (!ctx.Web.ListExists("EmpCountry"))
            {
                Console.WriteLine("Country list...");
                countryList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpCountry", false, false, "Lists/EmpCountry", false);

                //Provision country list items
                ListItemCreationInformation newCountryCreationInfomation;
                newCountryCreationInfomation = new ListItemCreationInformation();
                ListItem newCountry = countryList.AddItem(newCountryCreationInfomation);
                newCountry["Title"] = "Belgium";
                newCountry.Update();
                newCountry = countryList.AddItem(newCountryCreationInfomation);
                newCountry["Title"] = "United States of America";
                newCountry.Update();
                newCountry = countryList.AddItem(newCountryCreationInfomation);
                newCountry["Title"] = "India";
                newCountry.Update();
                ctx.Load(countryList);
                ctx.ExecuteQueryRetry();
            }
            else
            {
                countryList = ctx.Web.GetListByUrl("Lists/EmpCountry");
                Console.WriteLine("Country list was already available");
            }

            List stateList = null;
            if (!ctx.Web.ListExists("EmpState"))
            {
                Console.WriteLine("State list...");
                stateList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpState", false, false, "Lists/EmpState", false);
                Field countryLookup = stateList.CreateField(@"<Field Type=""Lookup"" DisplayName=""Country"" ID=""{BDEF775C-AB4B-4E86-9FB8-0A2DE40FE832}"" Name=""Country""></Field>", false);
                ctx.Load(stateList);
                ctx.Load(countryLookup);
                ctx.Load(stateList.DefaultView, p => p.ViewFields);
                ctx.ExecuteQueryRetry();

                // Add field to default view               
                stateList.DefaultView.ViewFields.Add("Country");
                stateList.DefaultView.Update();
                ctx.ExecuteQueryRetry();

                // configure country lookup field
                FieldLookup countryField = ctx.CastTo<FieldLookup>(countryLookup);
                countryField.LookupList = countryList.Id.ToString();
                countryField.LookupField = "Title";
                countryField.Indexed = true;
                countryField.IsRelationship = true;
                countryField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Restrict;
                countryField.Update();
                ctx.ExecuteQueryRetry();

                //Provision state list items
                ListItemCreationInformation newStateCreationInfomation;
                newStateCreationInfomation = new ListItemCreationInformation();
                ListItem newState = stateList.AddItem(newStateCreationInfomation);
                newState["Title"] = "Washington";
                newState["Country"] = "2;#United States of America";
                newState.Update();
                newState = stateList.AddItem(newStateCreationInfomation);
                newState["Title"] = "Limburg";
                newState["Country"] = "1;#Belgium";
                newState.Update();
                newState = stateList.AddItem(newStateCreationInfomation);
                newState["Title"] = "Tennessee";
                newState["Country"] = "2;#United States of America";
                newState.Update();
                newState = stateList.AddItem(newStateCreationInfomation);
                newState["Title"] = "Karnataka";
                newState["Country"] = "3;#India";
                newState.Update();

                ctx.ExecuteQueryRetry();
            }
            else
            {
                countryList = ctx.Web.GetListByUrl("Lists/EmpState");
                Console.WriteLine("State list was already available");
            }

            List cityList = null;
            if (!ctx.Web.ListExists("EmpCity"))
            {
                Console.WriteLine("City list...");
                cityList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpCity", false, false, "Lists/EmpCity", false);
                Field stateLookup = cityList.CreateField(@"<Field Type=""Lookup"" DisplayName=""State"" ID=""{F55BED78-CAF9-4EDF-92B9-C46BDC032DD5}"" Name=""State""></Field>", false);
                ctx.Load(cityList);
                ctx.Load(stateLookup);
                ctx.Load(cityList.DefaultView, p => p.ViewFields);
                ctx.ExecuteQueryRetry();

                // Add field to default view               
                cityList.DefaultView.ViewFields.Add("State");
                cityList.DefaultView.Update();
                ctx.ExecuteQueryRetry();
//.........这里部分代码省略.........
开发者ID:modulexcite,项目名称:PnP-Transformation,代码行数:101,代码来源:SetupManager.cs

示例7: UpdateDefaultValues

        public void UpdateDefaultValues(ClientContext clientContext, Guid listId, int listItemId)
        {
            List list = clientContext.Web.Lists.GetById(listId);
            ListItem item = list.GetItemById(listItemId);
            FieldCollection fields = list.Fields;
            clientContext.Load(item);
            clientContext.Load(fields);
            clientContext.ExecuteQuery();

            if (item["Phase"] != null && !string.IsNullOrEmpty(item["Phase"].ToString()))
                return;

            string folderName = item["FileDirRef"].ToString().Split('/').Last();
            string code = folderName.Split('_').First();

            string lookupFieldName = "Phase";
            FieldLookup lookupField = clientContext.CastTo<FieldLookup>(fields.GetByInternalNameOrTitle(lookupFieldName));
            clientContext.Load(lookupField);
            clientContext.ExecuteQuery();

            Guid parentWeb = lookupField.LookupWebId;
            string parentListGUID = lookupField.LookupList;

            Web lookupListWeb = clientContext.Site.OpenWebById(parentWeb);
            List parentList = lookupListWeb.Lists.GetById(new Guid(parentListGUID));

            CamlQuery cq = new CamlQuery();
            cq.ViewXml = "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>";

            ListItemCollection litems = parentList.GetItems(cq);
            clientContext.Load(parentList);
            clientContext.Load(litems);
            clientContext.ExecuteQuery();

            foreach (ListItem li in litems)
            {
                string phaseItemCode = li["Title"].ToString().TrimEnd(')').Split('(').Last();
                if (phaseItemCode == code)
                {
                    string value = item.Id + ";#" + item["Title"];
                    if (item["Phase"] != null)
                    {
                        FieldLookupValue flv = (FieldLookupValue)item["Phase"];
                        string existingCode = flv.LookupValue.ToString().TrimEnd(')').Split('(').Last();
                        if (existingCode == code) break;
                    }

                    item["Phase"] = li.Id + ";#" + li["Title"];
                    item.Update();
                    clientContext.ExecuteQuery();
                    break;
                }
            }
        }
开发者ID:RapidCircle,项目名称:O365-DefaultValues,代码行数:54,代码来源:RemoteEventReceiverManager.cs

示例8: GetWSSId

 /// <summary>
 /// Function to get the WssID for all the managed columns that user has configured
 /// </summary>
 /// <param name="clientContext">SP client context</param>
 /// <param name="matterMetadata">Object containing meta data for Matter</param>
 /// <param name="fields">Field Collection object</param>
 /// <returns>An Object containing meta data for Matter</returns>
 private MatterMetadata GetWSSId(ClientContext clientContext, MatterMetadata matterMetadata, FieldCollection fields)
 {
     try
     {
         int levels = taxonomySettings.Levels;
         //For the number of levels that are configured, get the configured column name for each level and get the wssid and 
         //update the ManagedColumnTerms object with wssid
         for (int i = 1; i <= levels; i++)
         {
             string columnName = configuration.GetSection("ContentTypes").GetSection("ManagedColumns")["ColumnName" + i];
             ClientResult<TaxonomyFieldValue> managedColumnWSSId = clientContext.CastTo<TaxonomyField>
             (fields.GetByInternalNameOrTitle(columnName))
             .GetFieldValueAsTaxonomyFieldValue(matterMetadata.ManagedColumnTerms[columnName].Id);
             clientContext.ExecuteQuery();
             matterMetadata.ManagedColumnTerms[columnName].WssId = managedColumnWSSId.Value.WssId;
         }
         return matterMetadata;
     }
     catch(Exception ex)
     {
         customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
         throw ex;
     }
 }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:31,代码来源:SPContentTypes.cs

示例9: GetTaxonomyField

        public TaxonomyFieldValue GetTaxonomyField(ClientContext ctx, ListItem listItem, string fieldName, string term)
        {
            FieldCollection _fields = listItem.ParentList.Fields;
            ctx.Load(_fields);
            ctx.ExecuteQuery();

            TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(fieldName));
            ctx.Load(_field);
            ctx.ExecuteQuery();

            Guid _id = _field.TermSetId;
            string _termID = AutoTaggingHelper.GetTermIdByName(ctx, term, _id);

            var _termValue = new TaxonomyFieldValue()
            {
                Label = term,
                TermGuid = _termID,
                WssId = -1
            };

            return _termValue;


        }
开发者ID:NicolajLarsen,项目名称:PnP,代码行数:24,代码来源:AutoTaggingHelper.cs

示例10: MapMetadataColumns

        /// <summary>
        /// Function to map metadata columns with specific term set
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="fieldCol">Field Collection object</param>
        internal static void MapMetadataColumns(ClientContext clientContext, FieldCollection fieldCol)
        {
            string termsetName = ConfigurationManager.AppSettings["DefaultTermSetName"];
            string taxonomyFieldType = ConfigurationManager.AppSettings["TaxonomyFieldType"];
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
            TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
            TermSetCollection termSetCollection = termStore.GetTermSetsByName(termsetName, 1033);       // Setting LCID=1033, as the default language is English
            clientContext.Load(termStore);
            clientContext.Load(termSetCollection);
            clientContext.ExecuteQuery();
            string termStoreId = Convert.ToString(termStore.Id, CultureInfo.InvariantCulture);
            string termSetId = Convert.ToString(termSetCollection[0].Id, CultureInfo.InvariantCulture);

            TaxonomyField taxonomyField = null;
            foreach (Field field in fieldCol)
            {
                if (field.TypeAsString.Equals(taxonomyFieldType, StringComparison.OrdinalIgnoreCase))
                {
                    taxonomyField = clientContext.CastTo<TaxonomyField>(field);
                    taxonomyField.SspId = new Guid(termStoreId);
                    taxonomyField.TermSetId = new Guid(termSetId);
                    taxonomyField.AnchorId = Guid.Empty;
                    taxonomyField.Update();
                }
            }
        }
开发者ID:Microsoft,项目名称:mattercenter,代码行数:31,代码来源:CreateSiteColumns.cs

示例11: CreateLookUpField

        /// <summary>
        /// Creates lookup field for contextual help list
        /// </summary>
        /// <param name="clientcontext">Client Context</param>
        private static void CreateLookUpField(ClientContext clientcontext)
        {
            string sourceList = ConfigurationManager.AppSettings["ContextualHelpList1"];
            string lookupList = ConfigurationManager.AppSettings["ContextualHelpList2"];
            string lookupColumnName = ConfigurationManager.AppSettings["ContextualHelpLookUpColumnName"];
            List objSourceList = clientcontext.Web.Lists.GetByTitle(sourceList);
            List objLookupList = clientcontext.Web.Lists.GetByTitle(lookupList);
            clientcontext.Load(objSourceList);
            clientcontext.Load(objLookupList);
            clientcontext.ExecuteQuery();

            Field lookupFieldXML = objLookupList.Fields.AddFieldAsXml("<Field Type='" + "Lookup" + "' DisplayName='" + lookupColumnName + "' Name='" + lookupColumnName + "' />", true, AddFieldOptions.AddFieldToDefaultView);
            FieldLookup lookupField = clientcontext.CastTo<FieldLookup>(lookupFieldXML);
            lookupField.LookupList = objSourceList.Id.ToString();
            lookupField.LookupField = lookupColumnName;
            lookupFieldXML.Update();
            clientcontext.ExecuteQuery();
        }
开发者ID:RMSATS,项目名称:mattercenter,代码行数:22,代码来源:ConfigureLists.cs

示例12: AddValuesToChoiceColumn

        /// <summary>
        /// Creates choice field for contextual help list
        /// </summary>
        /// <param name="clientcontext">Client Context</param>
        private static void AddValuesToChoiceColumn(ClientContext clientcontext)
        {
            // Basic code to load the list
            Web myWeb = clientcontext.Web;
            clientcontext.Load(myWeb);
            List myList = myWeb.Lists.GetByTitle(ConfigurationManager.AppSettings["ContextualHelpSectionListName"]);
            FieldCollection allFields = myList.Fields;
            clientcontext.Load(allFields);
            clientcontext.ExecuteQuery();
            //The field must be cast to a FieldChoice using context.CastTo

            for (int iIterator = 0; iIterator < Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfColumns"], CultureInfo.InvariantCulture); iIterator++)   // For each list
            {
                string columnName = ConfigurationManager.AppSettings["ChoiceFieldColumnName" + iIterator];
                string choiceFields = ConfigurationManager.AppSettings["ChoiceFieldValues" + iIterator];
                string choiceFieldValue = string.Empty;

                string[] listChioceFields = choiceFields.Split(new string[] { "$|$" }, StringSplitOptions.RemoveEmptyEntries);
                for (int iCount = 0; iCount < listChioceFields.Length; iCount++) // Create columns inside list
                {
                    choiceFieldValue = string.Format(CultureInfo.InvariantCulture, "{0}<CHOICE>{1}</CHOICE>", choiceFieldValue, listChioceFields[iCount]);
                }
                choiceFieldValue = string.Format(CultureInfo.InvariantCulture, "<CHOICES>{0}</CHOICES>", choiceFieldValue);

                string choiceFieldDefaultvalue = string.Format(CultureInfo.InvariantCulture, "<Default>{0}</Default>", ConfigurationManager.AppSettings["DefaultChoiceField" + iIterator]);
                string choicefieldXml = "<Field Type='Choice' DisplayName='{0}' Required='FALSE' EnforceUniqueValues='FALSE' Format='Dropdown' FillInChoice='FALSE'> {1}{2}</Field>";
                Field choiceField = myList.Fields.AddFieldAsXml(string.Format(CultureInfo.InvariantCulture, choicefieldXml, columnName, choiceFieldDefaultvalue, choiceFieldValue), true, AddFieldOptions.DefaultValue);
                FieldNumber fldNumberTaskStatus = clientcontext.CastTo<FieldNumber>(choiceField);
                fldNumberTaskStatus.Update();
                clientcontext.ExecuteQuery();
            }
        }
开发者ID:RMSATS,项目名称:mattercenter,代码行数:36,代码来源:ConfigureLists.cs

示例13: UpdateDescription

        void UpdateDescription(ClientContext clientContext, Guid listId, int listItemId)
        {
            List list = clientContext.Web.Lists.GetById(listId);
            ListItem item = list.GetItemById(listItemId);
            ContentType itemContentType = item.ContentType;
            clientContext.Load(item);
            clientContext.Load(itemContentType);
            FieldCollection fields = list.Fields;
            clientContext.Load(fields);
            clientContext.ExecuteQuery();

            //if (!item.ContentType.Name.Equals("Rapid Delivery Document Set NL"))
            if(!item.ContentType.Id.ToString().StartsWith("0x0120D52000"))
                return;

            List<LookupFieldSet> lookupDefinitions = new List<LookupFieldSet>();

            LookupFieldSet lookupFieldDefinition = new LookupFieldSet();
            lookupFieldDefinition.LookupField = "BusinessConsultant";
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("BusinessConsultantFirstName", "FirstName"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("BusinessConsultantLastName", "Title"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("BusinessConsultantEmail", "Email"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("BusinessConsultantMobile", "CellPhone"));
            lookupDefinitions.Add(lookupFieldDefinition);

            lookupFieldDefinition = new LookupFieldSet();
            lookupFieldDefinition.LookupField = "FunctionalConsultant";
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("FunctionalConsultantFirstName", "FirstName"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("FunctionalConsultantLastName", "Title"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("FunctionalConsultantEmail", "Email"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("FunctionalConsultantMobile", "CellPhone"));
            lookupDefinitions.Add(lookupFieldDefinition);

            lookupFieldDefinition = new LookupFieldSet();
            lookupFieldDefinition.LookupField = "ProjectManager";
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("ProjectManagerFirstName", "FirstName"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("ProjectManagerLastName", "Title"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("ProjectManagerEmail", "Email"));
            lookupFieldDefinition.FieldMappings.Add(new LookupFieldMapping("ProjectManagerMobile", "CellPhone"));
            lookupDefinitions.Add(lookupFieldDefinition);

            Web lookupListWeb = null;
            List parentList = null;

            Dictionary<string, string> itemValues = new Dictionary<string, string>();
            foreach (var lookupDefinition in lookupDefinitions)
            {
                if (item[lookupDefinition.LookupField] == null) continue;
                FieldLookupValue itemField = item[lookupDefinition.LookupField] as FieldLookupValue;
                string lookupFieldValue = itemField.LookupValue;
                int lookupFieldId = itemField.LookupId;

                FieldLookup lookupField = clientContext.CastTo<FieldLookup>(fields.GetByInternalNameOrTitle(lookupDefinition.LookupField));
                clientContext.Load(lookupField);
                clientContext.ExecuteQuery();

                Guid parentWeb = lookupField.LookupWebId;
                string parentListGUID = lookupField.LookupList;

                if (lookupListWeb == null) lookupListWeb = clientContext.Site.OpenWebById(parentWeb);
                if (parentList == null)
                {
                    parentList = lookupListWeb.Lists.GetById(new Guid(parentListGUID));
                    clientContext.Load(parentList);
                    clientContext.ExecuteQuery();
                }

                ListItem lookupListItem = parentList.GetItemById(lookupFieldId);
                clientContext.Load(lookupListItem);
                clientContext.ExecuteQuery();

                foreach(var fieldMap in lookupDefinition.FieldMappings)
                {
                    if (item[fieldMap.ItemField] == null || !item[fieldMap.ItemField].ToString().Equals(lookupListItem[fieldMap.LookupListField].ToString()))
                    {
                        itemValues.Add(fieldMap.ItemField, lookupListItem[fieldMap.LookupListField].ToString());
                    }
                }
            }

            if (!itemValues.Any())
                return;

            foreach(KeyValuePair<string,string> itemValue in itemValues)
            {
                item[itemValue.Key] = itemValue.Value;
            }
            item.Update();
            clientContext.ExecuteQuery();
        }
开发者ID:RapidCircle,项目名称:O365-LookupFieldUpdater,代码行数:90,代码来源:RemoteEventReceiverManager.cs

示例14: Main

        static void Main()
        {
            string url = "http://intranet.wingtip.com";
              ClientContext clientContext = new ClientContext(url);

              Web site = clientContext.Web;
              clientContext.ExecuteQuery();

              ExceptionHandlingScope scope1 = new ExceptionHandlingScope(clientContext);
              using (scope1.StartScope()) {
            using (scope1.StartTry()) {
              site.Lists.GetByTitle("Teams").DeleteObject();
            }
            using (scope1.StartCatch()) { }
              }

              ExceptionHandlingScope scope2 = new ExceptionHandlingScope(clientContext);
              using (scope2.StartScope()) {
            using (scope2.StartTry()) {
              site.Lists.GetByTitle("Players").DeleteObject();
            }
            using (scope2.StartCatch()) { }
              }

              ListCreationInformation ciTeams = new ListCreationInformation();
              ciTeams.Title = "Teams";
              ciTeams.Url = "Lists/Teams";
              ciTeams.QuickLaunchOption = QuickLaunchOptions.On;
              ciTeams.TemplateType = (int)ListTemplateType.GenericList;

              List Teams = site.Lists.Add(ciTeams);
              Teams.EnableAttachments = false;
              Teams.Update();

              ListItem team1 = Teams.AddItem(new ListItemCreationInformation());
              team1["Title"] = "Boston Celtics";
              team1.Update();

              ListItem team2 = Teams.AddItem(new ListItemCreationInformation());
              team2["Title"] = "LA Lakers";
              team2.Update();

              clientContext.Load(Teams);
              clientContext.ExecuteQuery();

              ListCreationInformation ciPlayers = new ListCreationInformation();
              ciPlayers.Title = "Players";
              ciPlayers.Url = "Lists/Players";
              ciPlayers.QuickLaunchOption = QuickLaunchOptions.On;
              ciPlayers.TemplateType = (int)ListTemplateType.GenericList;

              List Players = site.Lists.Add(ciPlayers);
              Players.EnableAttachments = false;
              Players.Update();

              string fieldXML = @"<Field Name='Team' " +
                                "DisplayName='Team' " +
                                "Type='Lookup' > " +
                         "</Field>";

              FieldLookup lookup = clientContext.CastTo<FieldLookup>(Players.Fields.AddFieldAsXml(fieldXML, true, AddFieldOptions.DefaultValue));
              lookup.LookupField = "Title";
              lookup.LookupList = Teams.Id.ToString();
              lookup.Update();

              Console.WriteLine("ID: " + Teams.Id.ToString());

              clientContext.ExecuteQuery();
        }
开发者ID:CriticalPathTraining,项目名称:CBD365,代码行数:69,代码来源:Program.cs

示例15: GetFieldValues

        public static SharePointFieldMetadata GetFieldValues(string webFullUrl, string fieldTitle,
            string libraryTitle = "Documents")
        {
            SharePointFieldMetadata result;
            try
            {
                if (string.IsNullOrEmpty(webFullUrl) || string.IsNullOrEmpty(fieldTitle)) return null;

                var context = new ClientContext(webFullUrl);
                var web = context.Web;
                var list = web.Lists.GetByTitle(libraryTitle);
                var field = list.Fields.GetByInternalNameOrTitle(fieldTitle);
                var choiceField = context.CastTo<FieldChoice>(field);
                context.Load(field);
                context.ExecuteQuery();

                result = new SharePointFieldMetadata
                {
                    Choices = choiceField.Choices,
                    DefaultValue = choiceField.DefaultValue
                };
            }
            catch
            {
                result = new SharePointFieldMetadata();
            }
            return result;
        }
开发者ID:CuongDuongDuy,项目名称:SPLibraryMetadata,代码行数:28,代码来源:SharePointMetadataHelper.cs


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