コード例 #1
0
        protected virtual StoreModeData GetStoreMode(Guid id, Guid fileID)
        {
            StoreModeData result = null;
            DbCommand     dbCmd  = null;

            if (id != Guid.Empty || fileID != Guid.Empty)
            {
                dbCmd = this.SelectCommand;
                Database.SetParameterValue(dbCmd, "p_store_mode_id", id.ToString().ToUpper());
                Database.SetParameterValue(dbCmd, "p_physical_file_id", fileID.ToString().ToUpper());
            }
            else
            {
                dbCmd = GetNewStoreMode();
            }
            using (IDataReader reader = Database.ExecuteReader(dbCmd))
            {
                if (reader.Read())
                {
                    result = new StoreModeData();
                    FieldLookup lookup = this.EntityFactory.CreateFieldLookup(reader);
                    this.Adapter.SetEntityValue(result, reader, lookup);
                }
            }
            return(result);
        }
        /// <summary>
        /// get list array like "title@internalname@fileType"
        /// </summary>
        /// <param name="spcontext"></param>
        /// <param name="hidden">True contain Hidden field</param>
        /// <param name="listTitle"> listTitle</param>
        /// <returns></returns>
        public ArrayList getListFields(ClientContext spcontext, bool hidden, string listTitle)
        {
            ArrayList fieldArr = new ArrayList();

            if (!string.IsNullOrEmpty(listTitle))
            {
                var web        = spcontext.Web;
                var listFields = spcontext.LoadQuery(web.Lists.GetByTitle(listTitle).Fields);
                spcontext.ExecuteQuery();
                foreach (var field in listFields)
                {
                    // Field fields = field;
                    FieldProperty fpObj = new FieldProperty();
                    fpObj.title        = field.Title;
                    fpObj.internalName = field.InternalName;
                    fpObj.typeAsString = field.TypeAsString;
                    // var fieldInfo = field.Title + "@" + field.InternalName + "@" + field.TypeAsString;
                    //如果是Outlook类型,获取 查阅项源list GUID,及源字段内部名称
                    if (field.TypeAsString.Contains("ook"))
                    {
                        FieldLookup flp = field as FieldLookup;
                        if (flp != null)
                        {
                            //源list GUID
                            fpObj.lookupListID = flp.LookupList;
                            //   var listId = flp.LookupList;
                            //源字段 内部名称
                            fpObj.lookupFieldInterNalName = flp.LookupField;
                            //  var listField = flp.LookupField;
                            //显示名称@内部名称@字段类型@查阅项源list GUID@查阅项源字段内部名称
                            //   fieldInfo += "@" + listId + "@" + listFields;
                        }
                    }

                    //Filter readonly and hidden Fields ,Computed(内容类型)  Attachments(附件类型)
                    if (!field.ReadOnlyField && field.TypeAsString != "Computed" && field.TypeAsString != "Attachments")
                    {
                        if (!hidden)
                        {
                            if (!field.Hidden)
                            {
                                fieldArr.Add(fpObj);
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            fieldArr.Add(fpObj);
                        }
                    }
                }
            }


            return(fieldArr);
        }
コード例 #3
0
ファイル: FieldInformation.cs プロジェクト: rlocus/SP-MVC
 public FieldLookupInformation(FieldLookup field) : base(field)
 {
     AllowMultipleValues        = field.AllowMultipleValues;
     IsRelationship             = field.IsRelationship;
     RelationshipDeleteBehavior = (uint)field.RelationshipDeleteBehavior;
     LookupField    = field.LookupField;
     LookupList     = field.LookupList;
     LookupWebId    = field.LookupWebId;
     PrimaryFieldId = field.PrimaryFieldId;
 }
コード例 #4
0
        /// <summary>
        /// 遍历任务,
        /// </summary>
        private static void CheckTaskList()
        {
            string[] taskNames = System.Configuration.ConfigurationManager.AppSettings["TaskName"].Split(';');
            emailDespName = ConfigurationManager.AppSettings["emailDisplayName"];
            string emailTitle  = ConfigurationManager.AppSettings["emailTitle"];
            string emailBody   = ConfigurationManager.AppSettings["emailBody"].Replace(";", "<br>");
            string emailTitle1 = ConfigurationManager.AppSettings["emailTitle1"];
            string emailBody1  = ConfigurationManager.AppSettings["emailBody1"].Replace(";", "<br>");

            //任务对应的文档
            taskDocField  = ConfigurationManager.AppSettings["taskDocField"];
            clientContext = new ClientContext(siteUrl);
            Site site = clientContext.Site;
            Web  web  = clientContext.Web;

            clientContext.Load(site, s => s.Url);
            clientContext.Load(web, w => w.Title);

            foreach (string task in taskNames)
            {
                try
                {
                    List oList = web.Lists.GetByTitle(task);

                    clientContext.Load(oList, list => list.Title, list => list.DefaultDisplayFormUrl);
                    Field       f1    = oList.Fields.GetByInternalNameOrTitle(taskDocField);
                    FieldLookup field = clientContext.CastTo <FieldLookup>(f1);
                    //clientContext.Load(f1,f=>f.InternalName,f=>f.Id,f=>f.Title );
                    clientContext.Load(field);
                    clientContext.Load(oList.Fields);
                    clientContext.ExecuteQuery();
                    taskDocField = f1.InternalName;
                    CamlQuery oQuery = new CamlQuery();
                    DateTime  today  = DateTime.Today;
                    //任务开始通知
                    string xmlQuery = "<Eq><FieldRef Name='StartDate'/><Value Type='DateTime'>" + today.AddDays(1).ToString("yyyy-MM-dd") + "</Value></Eq>";
                    oQuery.ViewXml = "<View><Query><Where>" + xmlQuery + "</Where></Query></View>";
                    DealEmail(oList, oQuery, emailTitle, emailBody, site.Url + oList.DefaultDisplayFormUrl);

                    oQuery = new CamlQuery();
                    //任务结束通知
                    xmlQuery       = "<And> <Lt><FieldRef Name='StartDate' /> <Value Type='DateTime'>" + today.ToString("yyyy-MM-dd") + "</Value></Lt> <And><Gt><FieldRef Name='DueDate' /><Value Type='DateTime'>" + today.ToString("yyyy-MM-dd") + "</Value></Gt><Lt> <FieldRef Name='DueDate' /> <Value Type='DateTime'>" + today.AddDays(7).ToString("yyyy-MM-dd") + "</Value></Lt></And></And></Eq>";
                    oQuery.ViewXml = "<View><Query><Where>" + xmlQuery + "</Where></Query></View>";
                    DealEmail(oList, oQuery, emailTitle1, emailBody1, site.Url + oList.DefaultDisplayFormUrl);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                }
            }
        }
コード例 #5
0
        public override LogicFileInfoData FetchFileInfo(LogicFileInfoItemData fetchParam, DbTransaction trans)
        {
            LogicFileInfoData result = null;
            DbCommand         dbCmd  = this.FetchFileInfoCommand;

            this.Database.SetParameterValue(dbCmd, "p_logic_file_id", fetchParam.ID.ToString().ToUpper());
            this.Database.SetParameterValue(dbCmd, "p_physical_file_id", fetchParam.PhysicalFileID.ToString().ToUpper());
            if (fetchParam.Version > 0)
            {
                this.Database.SetParameterValue(dbCmd, "p_VERSION", fetchParam.Version);
            }
            this.Database.SetParameterValue(dbCmd, "p_with_physical_file", fetchParam.WithPhysicalFileInfo);
            IDataReader reader = null;

            if (trans != null)
            {
                reader = this.Database.ExecuteReader(dbCmd, trans);
            }
            else
            {
                reader = this.Database.ExecuteReader(dbCmd);
            }
            if (reader != null)
            {
                try
                {
                    if (reader.Read())
                    {
                        result = new LogicFileInfoData();
                        FieldLookup looup = this.EntityFactory.CreateFieldLookup(reader);
                        this.Adapter.SetEntityValue(result, reader, looup);
                        if (fetchParam.WithPhysicalFileInfo && reader.NextResult())
                        {
                            this.EntityFactory.BuildEntityCollection(result.PhysicalFileInfos, reader);
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
            return(result);
        }
コード例 #6
0
		private void ReadTerms(ITermsQuery termsQuery, JsonReader reader, JsonSerializer serializer)
		{
			reader.Read();
			if (reader.TokenType == JsonToken.StartObject)
			{
				var ef = new FieldLookup();
				var depth = reader.Depth;
				while (reader.Read() && reader.Depth >= depth && reader.Value != null)
				{
					var property = reader.Value as string;
					switch (property)
					{
						case "id":
							reader.Read();
							var id = serializer.Deserialize<Id>(reader);
							ef.Id = id;
							break;
						case "index":
							reader.Read();
							ef.Index = reader.Value as string;
							break;
						case "type":
							reader.Read();
							ef.Type = reader.Value as string;
							break;
						case "path":
							reader.Read();
							ef.Path = reader.Value as string;
							break;
						case "routing":
							reader.Read();
							ef.Routing = reader.Value as string;
							break;
					}
				}
				termsQuery.TermsLookup = ef;
			}
			else if (reader.TokenType == JsonToken.StartArray)
			{
				var values = JArray.Load(reader).Values<object>();
				termsQuery.Terms = values;
			}
		}
コード例 #7
0
ファイル: FakeProvider.cs プロジェクト: huytq1/smartCAML
        public async Task <List <KeyValuePair <string, string> > > GetLookupItems(FieldLookup lookup)
        {
            await Task.Factory.StartNew(() =>
            {
                System.Threading.Thread.Sleep(2000);
            });

            return(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("1", "Test 1"),
                new KeyValuePair <string, string>("4", "Test 4"),
                new KeyValuePair <string, string>("8", "Test 8"),
                new KeyValuePair <string, string>("3", "Test 3"),
                new KeyValuePair <string, string>("6", "Test 6"),
                new KeyValuePair <string, string>("7", "Test 7"),
                new KeyValuePair <string, string>("5", "Test 5"),
                new KeyValuePair <string, string>("2", "Test 2"),
                new KeyValuePair <string, string>("9", "Test 9")
            });
        }
コード例 #8
0
        /// <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();
        }
コード例 #9
0
ファイル: ComplexFields.cs プロジェクト: spdavid/SP2016
        public static void setupComplexListFields(ClientContext ctx)
        {
            Web root = ctx.Site.RootWeb;

            /////////////////////////////////////
            ////////// using xml ///////////////
            ////////////////////////////////////

            string pathToXML = AppDomain.CurrentDomain.BaseDirectory + "complexFields.xml";

            XDocument doc = XDocument.Load(pathToXML);

            List <XElement> LookupElements = doc.Root.Elements("Field").Where(e => e.Attribute("Type").Value == "Lookup").ToList();

            foreach (XElement element in LookupElements)
            {
                string listUrl = element.Attribute("List").Value;
                List   list    = ctx.Web.GetListByUrl(listUrl);
                element.Attribute("List").Value = list.Id.ToString();
            }
            root.CreateFieldsFromXMLString(doc.ToString());

            /////////////////////////////////////
            ////////// Using code ///////////////
            ////////////////////////////////////

            FieldCreationInformation fieldINfo = new FieldCreationInformation(FieldType.Lookup);

            fieldINfo.Id           = "{CC5820F0-60C9-4B9E-9CE9-C739AED70357}".ToGuid();
            fieldINfo.InternalName = "OD1_TryGoodBook2";
            fieldINfo.DisplayName  = "Good book 2";
            fieldINfo.Group        = "Custom Columns";

            FieldLookup lookupField = root.CreateField <FieldLookup>(fieldINfo);

            lookupField.LookupList = root.GetListByUrl("lists/books").Id.ToString();
            lookupField.Update();

            ctx.ExecuteQuery();
        }
コード例 #10
0
ファイル: ListManager.cs プロジェクト: picologic/spo-util
        private FieldLookupValue getLookupValue(string value, FieldLookup field)
        {
            var lookupList = _ctx.Web.Lists.GetById(new Guid(field.LookupList));
            var query      = new CamlQuery();

            query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='{0}'/><Value Type='Text'>{1}</Value></Eq></Where></Query></View>", field.LookupField, value);

            var items = lookupList.GetItems(query);

            _ctx.Load(items, i => i.Include(li => li.Id));
            _ctx.ExecuteQuery();

            if (items.Count == 0)
            {
                return(null);
            }

            var lv = new FieldLookupValue();

            lv.LookupId = items[0].Id;
            return(lv);
        }
コード例 #11
0
        private void SetLookupList(FieldLookup lookupField, Type lookupEntityType)
        {
            var lookupList = AttributeHelper.GetCustomAttributes <ListAttribute>(lookupEntityType, false).FirstOrDefault();

            if (lookupList != null)
            {
                var context = (ClientContext)lookupField.Context;

                List list = !string.IsNullOrEmpty(lookupList.Url)
                        ? context.Web.GetList($"{ Model.Context.SiteUrl.TrimEnd('/')}/{lookupList.Url.TrimStart('/')}")
                        : (!string.IsNullOrEmpty(lookupList.Title) ? context.Web.Lists.GetByTitle(lookupList.Title) : null);

                if (list != null)
                {
                    context.Load(list);
                    try
                    {
                        context.ExecuteQuery();
                    }
                    catch
                    {
                        list = null;
                    }
                    if (list != null)
                    {
                        if (!lookupField.IsPropertyAvailable("LookupList"))
                        {
                            lookupField.LookupList  = list.Id.ToString();
                            lookupField.LookupField = "Title";
                        }
                        else
                        {
                            lookupField.ReplaceLookupAttributes(lookupField.IsPropertyAvailable("LookupWebId") ? lookupField.LookupWebId : Guid.Empty, list.Id, "Title");
                        }
                    }
                }
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: prasannakadam/PnP
        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("");
        }
コード例 #13
0
        private void RegisterLookupReference(FieldLookup lookupField, ListItem listitem, object itemValue)
        {
            if (null != itemValue)
            {
                if (null == m_lookups)
                {
                    m_lookups = new Dictionary<string, LookupDataRef>();
                }

                FieldLookupValue[] value = itemValue as FieldLookupValue[];

                LookupDataRef lookupRef = null;
                if (!m_lookups.TryGetValue(lookupField.InternalName, out lookupRef))
                {
                    lookupRef = new LookupDataRef(lookupField);
                    m_lookups.Add(lookupField.InternalName, lookupRef);
                }
                lookupRef.ItemLookupValues.Add(listitem, itemValue);
            }
        }
コード例 #14
0
 public Task <List <KeyValuePair <string, string> > > GetLookupItems(FieldLookup lookup)
 {
     throw new NotImplementedException();
 }
コード例 #15
0
        public static void CreateOrdersList()
        {
            Console.WriteLine("Creating orders list...");

            if (CustomersListExists())
            {
                ListCreationInformation listInformationOrders = new ListCreationInformation();
                listInformationOrders.Title             = "Orders";
                listInformationOrders.Url               = "Lists/Orders";
                listInformationOrders.QuickLaunchOption = QuickLaunchOptions.On;
                listInformationOrders.TemplateType      = (int)ListTemplateType.GenericList;
                listOrders = site.Lists.Add(listInformationOrders);
                listOrders.OnQuickLaunch     = true;
                listOrders.EnableAttachments = false;
                listOrders.Update();
                clientContext.ExecuteQuery();

                clientContext.Load(listOrders.DefaultView.ViewFields);
                clientContext.ExecuteQuery();

                listOrders.DefaultView.ViewFields.RemoveAll();
                listOrders.DefaultView.ViewFields.Add("ID");
                listOrders.DefaultView.ViewFields.Add("Title");
                listOrders.DefaultView.Update();
                clientContext.ExecuteQuery();

                string      fldCustomerLookupXml = @"<Field Name='Customer' DisplayName='Customer' Type='Lookup' ></Field>";
                FieldLookup fldCustomerLookup    =
                    clientContext.CastTo <FieldLookup>(listOrders.Fields.AddFieldAsXml(fldCustomerLookupXml,
                                                                                       true,
                                                                                       AddFieldOptions.DefaultValue));

                // add cusotmer lookup field
                fldCustomerLookup.LookupField = "Title";
                fldCustomerLookup.LookupList  = listCustomers.Id.ToString();
                fldCustomerLookup.Indexed     = true;
                fldCustomerLookup.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Cascade;
                fldCustomerLookup.Update();

                // add order date field
                string        fldOrderDateXml = @"<Field Name='OrderDate' DisplayName='OrderDate' Type='DateTime' ></Field>";
                FieldDateTime fldOrderDate    =
                    clientContext.CastTo <FieldDateTime>(listOrders.Fields.AddFieldAsXml(fldOrderDateXml,
                                                                                         true,
                                                                                         AddFieldOptions.DefaultValue));
                fldOrderDate.DisplayFormat = DateTimeFieldFormatType.DateOnly;
                fldOrderDate.Update();

                // add order date field
                string        fldOrderAmountXml = @"<Field Name='OrderAmount' DisplayName='OrderAmount' Type='Currency' ></Field>";
                FieldCurrency fldOrderAmount    =
                    clientContext.CastTo <FieldCurrency>(listOrders.Fields.AddFieldAsXml(fldOrderAmountXml,
                                                                                         true,
                                                                                         AddFieldOptions.DefaultValue));
                fldOrderAmount.Update();

                clientContext.ExecuteQuery();

                clientContext.Load(listOrders);
                clientContext.ExecuteQuery();
            }
            else
            {
                Console.WriteLine("Cannot create Orders list because Customer list does not exist.");
            }
        }
コード例 #16
0
        public static void CreateOrderDetailsList()
        {
            Console.WriteLine("Creating order details list...");

            if (OrdersListExists())
            {
                ListCreationInformation listInformationOrderDetails = new ListCreationInformation();
                listInformationOrderDetails.Title             = "OrderDetails";
                listInformationOrderDetails.Url               = "Lists/OrderDetails";
                listInformationOrderDetails.QuickLaunchOption = QuickLaunchOptions.On;
                listInformationOrderDetails.TemplateType      = (int)ListTemplateType.GenericList;
                listOrderDetails = site.Lists.Add(listInformationOrderDetails);
                listOrderDetails.OnQuickLaunch     = true;
                listOrderDetails.EnableAttachments = false;
                listOrderDetails.Update();
                clientContext.ExecuteQuery();

                listOrderDetails.DefaultView.ViewFields.RemoveAll();
                listOrderDetails.DefaultView.ViewFields.Add("ID");
                listOrderDetails.DefaultView.Update();
                clientContext.ExecuteQuery();

                var fldTitle = listOrderDetails.Fields.GetByInternalNameOrTitle("Title");
                fldTitle.Required = false;
                fldTitle.Update();
                clientContext.ExecuteQuery();

                string      fldOrderLookupXml = @"<Field Name='OrderId' DisplayName='Order' Type='Lookup' ></Field>";
                FieldLookup fldOrderLookup    =
                    clientContext.CastTo <FieldLookup>(listOrderDetails.Fields.AddFieldAsXml(fldOrderLookupXml,
                                                                                             true,
                                                                                             AddFieldOptions.AddFieldInternalNameHint));

                // add cusotmer lookup field
                fldOrderLookup.LookupField = "ID";
                fldOrderLookup.LookupList  = listOrders.Id.ToString();
                fldOrderLookup.Indexed     = true;
                fldOrderLookup.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Cascade;
                fldOrderLookup.Update();

                // add quantity field
                string      fldQuantityXml = @"<Field Name='Quantity' DisplayName='Quantity' Type='Number' ></Field>";
                FieldNumber fldQuantity    =
                    clientContext.CastTo <FieldNumber>(listOrderDetails.Fields.AddFieldAsXml(fldQuantityXml,
                                                                                             true,
                                                                                             AddFieldOptions.DefaultValue));
                fldQuantity.Update();

                // add product field
                string    fldProductXml = @"<Field Name='Product' DisplayName='Product' Type='Text' ></Field>";
                FieldText fldProduct    =
                    clientContext.CastTo <FieldText>(listOrderDetails.Fields.AddFieldAsXml(fldProductXml,
                                                                                           true,
                                                                                           AddFieldOptions.DefaultValue));
                fldProduct.Update();

                string        fldSalesAmountXml = @"<Field Name='SalesAmount' DisplayName='SalesAmount' Type='Currency' ></Field>";
                FieldCurrency fldSalesAmount    =
                    clientContext.CastTo <FieldCurrency>(listOrderDetails.Fields.AddFieldAsXml(fldSalesAmountXml,
                                                                                               true,
                                                                                               AddFieldOptions.DefaultValue));
                fldSalesAmount.Update();

                clientContext.ExecuteQuery();

                //listOrderDetails.DefaultView.ViewFields.Remove("Title");
                listOrderDetails.DefaultView.Update();
                clientContext.ExecuteQuery();
            }
            else
            {
                Console.WriteLine("Cannot create OrderDetails list because Orders list does not exist.");
            }
        }
コード例 #17
0
        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();
        }
コード例 #18
0
        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;
                }
            }
        }
コード例 #19
0
        public object GetDisplayValue([NotNull] IRow row, int fieldIndex)
        {
            FieldLookup fieldLookup = _fieldLookupByIndex[fieldIndex];

            return(fieldLookup.GetDisplayValue(row));
        }
コード例 #20
0
        ///// <summary>
        ///// Handles the ItemAdded event by modifying the Description
        ///// field of the item.
        ///// </summary>
        ///// <param name="properties"></param>
        private void UpdateDefaultValuesAdding(SPRemoteEventProperties properties, SPRemoteEventResult result)
        {
            using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
            {
                if (clientContext != null)
                {
                    var    itemProperties   = properties.ItemEventProperties;
                    var    _userLoginName   = properties.ItemEventProperties.UserLoginName;
                    var    _afterProperites = itemProperties.AfterProperties;
                    string phase            = "";

                    List list = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
                    //ListItem item = list.GetItemById(properties.ItemEventProperties.ListItemId);
                    FieldCollection fields = list.Fields;
                    //clientContext.Load(item);
                    clientContext.Load(fields);
                    clientContext.ExecuteQuery();

                    string[] folderNameSplit = itemProperties.BeforeUrl.ToString().Split('/');
                    string   folderName      = folderNameSplit[folderNameSplit.Length - 2];
                    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();

                    FieldLookupValue flv = new FieldLookupValue();
                    foreach (ListItem li in litems)
                    {
                        string phaseItemCode = li["Title"].ToString().TrimEnd(')').Split('(').Last();
                        if (phaseItemCode == code)
                        {
                            if (itemProperties.AfterProperties.ContainsKey("Phase") && !String.IsNullOrEmpty(itemProperties.AfterProperties["Phase"].ToString()))
                            {
                                string[] stringSeparators = new string[] { ";#" };
                                if (itemProperties.AfterProperties["Phase"].ToString().Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries)[0] == li["ID"].ToString())
                                {
                                    break;
                                }
                            }

                            phase = li.Id + ";#" + li["Title"];
                            break;
                        }
                    }

                    result.ChangedItemProperties.Add("Phase", phase);
                    result.Status = SPRemoteEventServiceStatus.Continue;
                }
            }
        }
コード例 #21
0
 public LookupDataRef(FieldLookup field)
 {
     this.Field = field;
     this.ItemLookupValues = new Dictionary<ListItem, object>();
 }
コード例 #22
0
        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();
        }
コード例 #23
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                var item = Identity.GetListItem(list);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
                if (Values != null)
                {
                    var fields =
                        ClientContext.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title,
                                                                    f => f.TypeAsString));
                    ClientContext.ExecuteQueryRetry();

                    Hashtable values = Values ?? new Hashtable();

                    foreach (var key in values.Keys)
                    {
                        var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                        if (field != null)
                        {
                            switch (field.TypeAsString)
                            {
                            case "User":
                            case "UserMulti":
                            {
                                List <FieldUserValue> userValues = new List <FieldUserValue>();

                                var value = values[key];
                                if (value == null)
                                {
                                    goto default;
                                }
                                if (value.GetType().IsArray)
                                {
                                    foreach (var arrayItem in (value as IEnumerable))
                                    {
                                        int userId;
                                        if (!int.TryParse(arrayItem.ToString(), out userId))
                                        {
                                            var user = SelectedWeb.EnsureUser(arrayItem as string);
                                            ClientContext.Load(user);
                                            ClientContext.ExecuteQueryRetry();
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = user.Id
                                                });
                                        }
                                        else
                                        {
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = userId
                                                });
                                        }
                                    }
                                    item[key as string] = userValues.ToArray();
                                }
                                else
                                {
                                    int userId;
                                    if (!int.TryParse(value as string, out userId))
                                    {
                                        var user = SelectedWeb.EnsureUser(value as string);
                                        ClientContext.Load(user);
                                        ClientContext.ExecuteQueryRetry();
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        };
                                    }
                                    else
                                    {
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = userId
                                        };
                                    }
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "TaxonomyFieldType":
                            case "TaxonomyFieldTypeMulti":
                            {
                                var value = Values[key];
                                if (value != null && value.GetType().IsArray)
                                {
                                    var taxSession = ClientContext.Site.GetTaxonomySession();
                                    var terms      = new List <KeyValuePair <Guid, string> >();
                                    foreach (var arrayItem in value as object[])
                                    {
                                        TaxonomyItem taxonomyItem;
                                        Guid         termGuid;
                                        if (!Guid.TryParse(arrayItem as string, out termGuid))
                                        {
                                            // Assume it's a TermPath
                                            taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(arrayItem as string);
                                        }
                                        else
                                        {
                                            taxonomyItem = taxSession.GetTerm(termGuid);
                                            ClientContext.Load(taxonomyItem);
                                            ClientContext.ExecuteQueryRetry();
                                        }
                                        terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name));
                                    }

                                    TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field);

                                    taxField.EnsureProperty(tf => tf.AllowMultipleValues);
                                    if (taxField.AllowMultipleValues)
                                    {
                                        var termValuesString = String.Empty;
                                        foreach (var term in terms)
                                        {
                                            termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#";
                                        }

                                        termValuesString = termValuesString.Substring(0, termValuesString.Length - 2);

                                        var newTaxFieldValue = new TaxonomyFieldValueCollection(ClientContext, termValuesString, taxField);
                                        taxField.SetFieldValueByValueCollection(item, newTaxFieldValue);
#if !ONPREMISES
                                        item.SystemUpdate();
#else
                                        item.Update();
#endif
                                        ClientContext.ExecuteQueryRetry();
                                    }
                                    else
                                    {
                                        WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                                    }
                                }
                                else
                                {
                                    Guid termGuid = Guid.Empty;

                                    var          taxSession   = ClientContext.Site.GetTaxonomySession();
                                    TaxonomyItem taxonomyItem = null;
                                    if (value != null && !Guid.TryParse(value as string, out termGuid))
                                    {
                                        // Assume it's a TermPath
                                        taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string);
                                    }
                                    else
                                    {
                                        if (value != null)
                                        {
                                            taxonomyItem = taxSession.GetTerm(termGuid);
                                            ClientContext.Load(taxonomyItem);
                                            ClientContext.ExecuteQueryRetry();
                                        }
                                    }

                                    TaxonomyField      taxField = ClientContext.CastTo <TaxonomyField>(field);
                                    TaxonomyFieldValue taxValue = new TaxonomyFieldValue();
                                    if (taxonomyItem != null)
                                    {
                                        taxValue.TermGuid = taxonomyItem.Id.ToString();
                                        taxValue.Label    = taxonomyItem.Name;
                                        taxField.SetFieldValueByValue(item, taxValue);
                                    }
                                    else
                                    {
                                        taxField.ValidateSetValue(item, null);
                                    }
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "Lookup":
                            case "LookupMulti":
                            {
                                var value = values[key];
                                if (value == null)
                                {
                                    goto default;
                                }
                                int[] multiValue;
                                if (value is Array)
                                {
                                    var arr = (object[])values[key];
                                    multiValue = new int[arr.Length];
                                    for (int i = 0; i < arr.Length; i++)
                                    {
                                        multiValue[i] = int.Parse(arr[i].ToString());
                                    }
                                }
                                else
                                {
                                    string valStr = values[key].ToString();
                                    multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray();
                                }

                                var newVals = multiValue.Select(id => new FieldLookupValue {
                                        LookupId = id
                                    }).ToArray();

                                FieldLookup lookupField = ClientContext.CastTo <FieldLookup>(field);
                                lookupField.EnsureProperty(lf => lf.AllowMultipleValues);
                                if (!lookupField.AllowMultipleValues && newVals.Length > 1)
                                {
                                    throw new Exception("Field " + field.InternalName + " does not support multiple values");
                                }

                                item[key as string] = newVals;
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            default:
                            {
                                item[key as string] = values[key];
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }
                            }
                        }
                        else
                        {
                            throw new Exception("Field not present in list");
                        }
                    }

#if !ONPREMISES
                    if (SystemUpdate)
                    {
                        item.SystemUpdate();
                    }
                    else
                    {
                        item.Update();
                    }
#else
                    item.Update();
#endif
                    ClientContext.Load(item);
                    ClientContext.ExecuteQueryRetry();
                }
                WriteObject(item);
            }
        }
コード例 #24
0
        public static void SetFieldValues(this ListItem item, Hashtable valuesToSet, Cmdlet cmdlet)
        {
            // xxx: return early if hashtable is empty to save getting fields?

            var itemValues = new List <FieldUpdateValue>();

            var context = item.Context as ClientContext;
            var list    = item.ParentList;

            context.Web.EnsureProperty(w => w.Url);

            var clonedContext = context.Clone(context.Web.Url);
            var web           = clonedContext.Web;

            var fields =
                context.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title,
                                                      f => f.TypeAsString));

            context.ExecuteQueryRetry();

            Hashtable values = valuesToSet ?? new Hashtable();

            foreach (var key in values.Keys)
            {
                var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                if (field != null)
                {
                    switch (field.TypeAsString)
                    {
                    case "User":
                    case "UserMulti":
                    {
                        List <FieldUserValue> userValues = new List <FieldUserValue>();

                        var value = values[key];
                        if (value == null)
                        {
                            goto default;
                        }
                        if (value is string && string.IsNullOrWhiteSpace(value + ""))
                        {
                            goto default;
                        }
                        if (value.GetType().IsArray)
                        {
                            foreach (var arrayItem in (value as IEnumerable))
                            {
                                int userId;
                                if (!int.TryParse(arrayItem.ToString(), out userId))
                                {
                                    var user = web.EnsureUser(arrayItem as string);
                                    clonedContext.Load(user);
                                    clonedContext.ExecuteQueryRetry();
                                    userValues.Add(new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        });
                                }
                                else
                                {
                                    userValues.Add(new FieldUserValue()
                                        {
                                            LookupId = userId
                                        });
                                }
                            }
                            itemValues.Add(new FieldUpdateValue(key as string, userValues.ToArray(), null));
                        }
                        else
                        {
                            int userId;
                            if (!int.TryParse(value as string, out userId))
                            {
                                var user = web.EnsureUser(value as string);
                                clonedContext.Load(user);
                                clonedContext.ExecuteQueryRetry();
                                itemValues.Add(new FieldUpdateValue(key as string, new FieldUserValue()
                                    {
                                        LookupId = user.Id
                                    }));
                            }
                            else
                            {
                                itemValues.Add(new FieldUpdateValue(key as string, new FieldUserValue()
                                    {
                                        LookupId = userId
                                    }));
                            }
                        }
                        break;
                    }

                    case "TaxonomyFieldType":
                    case "TaxonomyFieldTypeMulti":
                    {
                        var value = values[key];
                        if (value != null && value.GetType().IsArray)
                        {
                            var taxSession = clonedContext.Site.GetTaxonomySession();
                            var terms      = new List <KeyValuePair <Guid, string> >();
                            foreach (var arrayItem in value as object[])
                            {
                                TaxonomyItem taxonomyItem;
                                Guid         termGuid;
                                if (!Guid.TryParse(arrayItem as string, out termGuid))
                                {
                                    // Assume it's a TermPath
                                    taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(arrayItem as string);
                                }
                                else
                                {
                                    taxonomyItem = taxSession.GetTerm(termGuid);
                                    clonedContext.Load(taxonomyItem);
                                    clonedContext.ExecuteQueryRetry();
                                }
                                terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name));
                            }

                            TaxonomyField taxField = context.CastTo <TaxonomyField>(field);
                            taxField.EnsureProperty(tf => tf.AllowMultipleValues);
                            if (taxField.AllowMultipleValues)
                            {
                                var termValuesString = String.Empty;
                                foreach (var term in terms)
                                {
                                    termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#";
                                }

                                termValuesString = termValuesString.Substring(0, termValuesString.Length - 2);

                                var newTaxFieldValue = new TaxonomyFieldValueCollection(context, termValuesString, taxField);
                                itemValues.Add(new FieldUpdateValue(key as string, newTaxFieldValue, field.TypeAsString));
                            }
                            else
                            {
                                cmdlet.WriteWarning(@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                            }
                        }
                        else
                        {
                            Guid termGuid = Guid.Empty;

                            var          taxSession   = clonedContext.Site.GetTaxonomySession();
                            TaxonomyItem taxonomyItem = null;
                            if (value != null && !Guid.TryParse(value as string, out termGuid))
                            {
                                // Assume it's a TermPath
                                taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(value as string);
                            }
                            else
                            {
                                if (value != null)
                                {
                                    taxonomyItem = taxSession.GetTerm(termGuid);
                                    clonedContext.Load(taxonomyItem);
                                    clonedContext.ExecuteQueryRetry();
                                }
                            }

                            TaxonomyField      taxField = context.CastTo <TaxonomyField>(field);
                            TaxonomyFieldValue taxValue = new TaxonomyFieldValue();
                            if (taxonomyItem != null)
                            {
                                taxValue.TermGuid = taxonomyItem.Id.ToString();
                                taxValue.Label    = taxonomyItem.Name;
                                itemValues.Add(new FieldUpdateValue(key as string, taxValue, field.TypeAsString));
                            }
                            else
                            {
                                taxField.ValidateSetValue(item, null);
                            }
                        }
                        break;
                    }

                    case "Lookup":
                    case "LookupMulti":
                    {
                        var value = values[key];
                        if (value == null)
                        {
                            goto default;
                        }
                        int[] multiValue;
                        if (value is Array)
                        {
                            var arr = (object[])values[key];
                            multiValue = new int[arr.Length];
                            for (int i = 0; i < arr.Length; i++)
                            {
                                multiValue[i] = int.Parse(arr[i].ToString());
                            }
                        }
                        else
                        {
                            string valStr = values[key].ToString();
                            multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray();
                        }

                        var newVals = multiValue.Select(id => new FieldLookupValue {
                                LookupId = id
                            }).ToArray();

                        FieldLookup lookupField = context.CastTo <FieldLookup>(field);
                        lookupField.EnsureProperty(lf => lf.AllowMultipleValues);
                        if (!lookupField.AllowMultipleValues && newVals.Length > 1)
                        {
                            throw new Exception("Field " + field.InternalName + " does not support multiple values");
                        }
                        itemValues.Add(new FieldUpdateValue(key as string, newVals));
                        break;
                    }

                    default:
                    {
                        itemValues.Add(new FieldUpdateValue(key as string, values[key]));
                        break;
                    }
                    }
                }
                else
                {
                    throw new PSInvalidOperationException($"Field {key} not present in list.");
                }
            }
            if (item != null && !item.ServerObjectIsNull.Value)
            {
                var specialFields = new[] { "Author", "Editor", "Created", "Modified" };
                // check if we are setting editor or author fields
                if (itemValues.Any(i => specialFields.Contains(i.Key)))
                {
                    foreach (var field in specialFields)
                    {
                        if (itemValues.FirstOrDefault(i => i.Key == field) == null)
                        {
                            if (item.FieldValues.TryGetValue(field, out object fieldValue))
                            {
                                itemValues.Add(new FieldUpdateValue(field, fieldValue));
                            }
                        }
                    }
                }
            }

            foreach (var itemValue in itemValues)
            {
                if (string.IsNullOrEmpty(itemValue.FieldTypeString))
                {
                    item[itemValue.Key] = itemValue.Value;
                }
                else
                {
                    switch (itemValue.FieldTypeString)
                    {
                    case "TaxonomyFieldTypeMulti":
                    {
                        var field    = fields.FirstOrDefault(f => f.InternalName == itemValue.Key as string || f.Title == itemValue.Key as string);
                        var taxField = context.CastTo <TaxonomyField>(field);
                        if (itemValue.Value is TaxonomyFieldValueCollection)
                        {
                            taxField.SetFieldValueByValueCollection(item, itemValue.Value as TaxonomyFieldValueCollection);
                        }
                        else
                        {
                            taxField.SetFieldValueByValue(item, itemValue.Value as TaxonomyFieldValue);
                        }
                        break;
                    }

                    case "TaxonomyFieldType":
                    {
                        var field    = fields.FirstOrDefault(f => f.InternalName == itemValue.Key as string || f.Title == itemValue.Key as string);
                        var taxField = context.CastTo <TaxonomyField>(field);
                        taxField.SetFieldValueByValue(item, itemValue.Value as TaxonomyFieldValue);
                        break;
                    }
                    }
                }
            }
        }
コード例 #25
0
        public static ListItem UpdateListItem(ListItem item, Hashtable valuesToSet, ListItemUpdateType updateType, Action <string> warningCallback, Action <string, string> terminatingError)
        {
            var itemValues = new List <FieldUpdateValue>();

            var context = item.Context as ClientContext;
            var list    = item.ParentList;

            context.Web.EnsureProperty(w => w.Url);

            var clonedContext = context.Clone(context.Web.Url);
            var web           = clonedContext.Web;

            var fields =
                context.LoadQuery(list.Fields.Include(f => f.InternalName, f => f.Title,
                                                      f => f.TypeAsString));

            context.ExecuteQueryRetry();

            Hashtable values = valuesToSet ?? new Hashtable();

            foreach (var key in values.Keys)
            {
                var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                if (field != null)
                {
                    switch (field.TypeAsString)
                    {
                    case "User":
                    case "UserMulti":
                    {
                        List <FieldUserValue> userValues = new List <FieldUserValue>();

                        var value = values[key];
                        if (value == null)
                        {
                            goto default;
                        }
                        if (value is string && string.IsNullOrWhiteSpace(value + ""))
                        {
                            goto default;
                        }
                        if (value.GetType().IsArray)
                        {
                            foreach (var arrayItem in (value as IEnumerable))
                            {
                                int userId;
                                if (!int.TryParse(arrayItem.ToString(), out userId))
                                {
                                    var user = web.EnsureUser(arrayItem as string);
                                    clonedContext.Load(user);
                                    clonedContext.ExecuteQueryRetry();
                                    userValues.Add(new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        });
                                }
                                else
                                {
                                    userValues.Add(new FieldUserValue()
                                        {
                                            LookupId = userId
                                        });
                                }
                            }
                            itemValues.Add(new FieldUpdateValue(key as string, userValues.ToArray(), null));
                        }
                        else
                        {
                            int userId;
                            if (!int.TryParse(value as string, out userId))
                            {
                                var user = web.EnsureUser(value as string);
                                clonedContext.Load(user);
                                clonedContext.ExecuteQueryRetry();
                                itemValues.Add(new FieldUpdateValue(key as string, new FieldUserValue()
                                    {
                                        LookupId = user.Id
                                    }));
                            }
                            else
                            {
                                itemValues.Add(new FieldUpdateValue(key as string, new FieldUserValue()
                                    {
                                        LookupId = userId
                                    }));
                            }
                        }
                        break;
                    }

                    case "TaxonomyFieldType":
                    case "TaxonomyFieldTypeMulti":
                    {
                        var value = values[key];
                        if (value != null && value.GetType().IsArray)
                        {
                            var taxSession = clonedContext.Site.GetTaxonomySession();
                            var terms      = new List <KeyValuePair <Guid, string> >();
                            foreach (var arrayItem in value as object[])
                            {
                                TaxonomyItem taxonomyItem;
                                Guid         termGuid;
                                if (!Guid.TryParse(arrayItem as string, out termGuid))
                                {
                                    // Assume it's a TermPath
                                    taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(arrayItem as string);
                                }
                                else
                                {
                                    taxonomyItem = taxSession.GetTerm(termGuid);
                                    clonedContext.Load(taxonomyItem);
                                    clonedContext.ExecuteQueryRetry();
                                }
                                terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name));
                            }

                            TaxonomyField taxField = context.CastTo <TaxonomyField>(field);
                            taxField.EnsureProperty(tf => tf.AllowMultipleValues);
                            if (taxField.AllowMultipleValues)
                            {
                                var termValuesString = String.Empty;
                                foreach (var term in terms)
                                {
                                    termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#";
                                }

                                termValuesString = termValuesString.Substring(0, termValuesString.Length - 2);

                                var newTaxFieldValue = new TaxonomyFieldValueCollection(context, termValuesString, taxField);
                                itemValues.Add(new FieldUpdateValue(key as string, newTaxFieldValue, field.TypeAsString));
                            }
                            else
                            {
                                warningCallback?.Invoke($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                            }
                        }
                        else
                        {
                            Guid termGuid = Guid.Empty;

                            var          taxSession   = clonedContext.Site.GetTaxonomySession();
                            TaxonomyItem taxonomyItem = null;
                            if (value != null && !Guid.TryParse(value as string, out termGuid))
                            {
                                // Assume it's a TermPath
                                taxonomyItem = clonedContext.Site.GetTaxonomyItemByPath(value as string);
                            }
                            else
                            {
                                if (value != null)
                                {
                                    taxonomyItem = taxSession.GetTerm(termGuid);
                                    clonedContext.Load(taxonomyItem);
                                    clonedContext.ExecuteQueryRetry();
                                }
                            }

                            TaxonomyField      taxField = context.CastTo <TaxonomyField>(field);
                            TaxonomyFieldValue taxValue = new TaxonomyFieldValue();
                            if (taxonomyItem != null)
                            {
                                taxValue.TermGuid = taxonomyItem.Id.ToString();
                                taxValue.Label    = taxonomyItem.Name;
                                itemValues.Add(new FieldUpdateValue(key as string, taxValue, field.TypeAsString));
                            }
                            else
                            {
                                taxField.ValidateSetValue(item, null);
                            }
                        }
                        break;
                    }

                    case "Lookup":
                    case "LookupMulti":
                    {
                        var value = values[key];
                        if (value == null)
                        {
                            goto default;
                        }
                        int[] multiValue;
                        if (value is Array)
                        {
                            var arr = (object[])values[key];
                            multiValue = new int[arr.Length];
                            for (int i = 0; i < arr.Length; i++)
                            {
                                multiValue[i] = int.Parse(arr[i].ToString());
                            }
                        }
                        else
                        {
                            string valStr = values[key].ToString();
                            multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray();
                        }

                        var newVals = multiValue.Select(id => new FieldLookupValue {
                                LookupId = id
                            }).ToArray();

                        FieldLookup lookupField = context.CastTo <FieldLookup>(field);
                        lookupField.EnsureProperty(lf => lf.AllowMultipleValues);
                        if (!lookupField.AllowMultipleValues && newVals.Length > 1)
                        {
                            throw new Exception("Field " + field.InternalName + " does not support multiple values");
                        }
                        itemValues.Add(new FieldUpdateValue(key as string, newVals));
                        break;
                    }

                    default:
                    {
                        itemValues.Add(new FieldUpdateValue(key as string, values[key]));
                        break;
                    }
                    }
                }
                else
                {
                    terminatingError?.Invoke($"Field {key} not present in list.", "FIELDNOTINLIST");
                }
            }
            foreach (var itemValue in itemValues)
            {
                if (string.IsNullOrEmpty(itemValue.FieldTypeString))
                {
                    item[itemValue.Key] = itemValue.Value;
                }
                else
                {
                    switch (itemValue.FieldTypeString)
                    {
                    case "TaxonomyFieldTypeMulti":
                    {
                        var field    = fields.FirstOrDefault(f => f.InternalName == itemValue.Key as string || f.Title == itemValue.Key as string);
                        var taxField = context.CastTo <TaxonomyField>(field);
                        taxField.SetFieldValueByValueCollection(item, itemValue.Value as TaxonomyFieldValueCollection);
                        break;
                    }

                    case "TaxonomyFieldType":
                    {
                        var field    = fields.FirstOrDefault(f => f.InternalName == itemValue.Key as string || f.Title == itemValue.Key as string);
                        var taxField = context.CastTo <TaxonomyField>(field);
                        taxField.SetFieldValueByValue(item, itemValue.Value as TaxonomyFieldValue);
                        break;
                    }
                    }
                }
            }
#if !ONPREMISES
            switch (updateType)
            {
            case ListItemUpdateType.Update:
            {
                item.Update();
                break;
            }

            case ListItemUpdateType.SystemUpdate:
            {
                item.SystemUpdate();
                break;
            }

            case ListItemUpdateType.UpdateOverwriteVersion:
            {
                item.UpdateOverwriteVersion();
                break;
            }
            }
#else
            item.Update();
#endif
            context.Load(item);
            context.ExecuteQueryRetry();
            return(item);
        }
コード例 #26
0
        private static void UpdateMappingsAtDestination(Dictionary<int, MasterItemMapping> itemMappings, IEnumerable<ListItem> destinationItems, FieldLookup destinationLookup, ClientContext destinationContext)
        {
            Console.WriteLine("Updating lookup values ...");

            int batchedItems = 0;
            foreach (var destinationItem in destinationItems.Where(item => itemMappings.ContainsKey(item.Id)))
            {
                var mapping = itemMappings[destinationItem.Id];

                if(!mapping.DestinationLookupIds.Any() || !mapping.SourceLookupIds.Any())
                    continue;

                var creator = LookupValueHandlerFactory.Create(destinationLookup.FieldTypeKind);
                object value = destinationLookup.AllowMultipleValues ? mapping.DestinationLookupIds.Select(creator.Create).ToArray()
                                   : creator.Create(mapping.DestinationLookupIds.First());
                destinationItem[destinationLookup.InternalName] = value;
                destinationItem.Update();
                batchedItems++;

                if(batchedItems % BatchSize == 0)
                {
                    destinationContext.ExecuteQuery();
                    batchedItems = 0;
                }
            }

            if(batchedItems > 0)
            {
                destinationContext.ExecuteQuery();
            }
        }
コード例 #27
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(SelectedWeb);
            }
            if (list != null)
            {
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        SelectedWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                if (ContentType != null)
                {
                    ContentType ct = null;
                    if (ContentType.ContentType == null)
                    {
                        if (ContentType.Id != null)
                        {
                            ct = SelectedWeb.GetContentTypeById(ContentType.Id, true);
                        }
                        else if (ContentType.Name != null)
                        {
                            ct = SelectedWeb.GetContentTypeByName(ContentType.Name, true);
                        }
                    }
                    else
                    {
                        ct = ContentType.ContentType;
                    }
                    if (ct != null)
                    {
                        ct.EnsureProperty(w => w.StringId);

                        item["ContentTypeId"] = ct.StringId;
                        item.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values != null)
                {
                    Hashtable values = Values ?? new Hashtable();
                    // Load all list fields and their types
                    var fields = ClientContext.LoadQuery(list.Fields.Include(f => f.Id, f => f.InternalName, f => f.Title, f => f.TypeAsString));
                    ClientContext.ExecuteQueryRetry();

                    foreach (var key in values.Keys)
                    {
                        var field = fields.FirstOrDefault(f => f.InternalName == key as string || f.Title == key as string);
                        if (field != null)
                        {
                            switch (field.TypeAsString)
                            {
                            case "User":
                            case "UserMulti":
                            {
                                var userValues = new List <FieldUserValue>();

                                var value = values[key];
                                if (value.GetType().IsArray)
                                {
                                    foreach (var arrayItem in value as object[])
                                    {
                                        int userId;
                                        if (!int.TryParse(arrayItem as string, out userId))
                                        {
                                            var user = SelectedWeb.EnsureUser(arrayItem as string);
                                            ClientContext.Load(user);
                                            ClientContext.ExecuteQueryRetry();
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = user.Id
                                                });
                                        }
                                        else
                                        {
                                            userValues.Add(new FieldUserValue()
                                                {
                                                    LookupId = userId
                                                });
                                        }
                                    }
                                    item[key as string] = userValues.ToArray();
                                }
                                else
                                {
                                    int userId;
                                    if (!int.TryParse(value as string, out userId))
                                    {
                                        var user = SelectedWeb.EnsureUser(value as string);
                                        ClientContext.Load(user);
                                        ClientContext.ExecuteQueryRetry();
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = user.Id
                                        };
                                    }
                                    else
                                    {
                                        item[key as string] = new FieldUserValue()
                                        {
                                            LookupId = userId
                                        };
                                    }
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "TaxonomyFieldType":
                            case "TaxonomyFieldTypeMulti":
                            {
                                var value = values[key];
                                if (value.GetType().IsArray)
                                {
                                    var taxSession = ClientContext.Site.GetTaxonomySession();
                                    var terms      = new List <KeyValuePair <Guid, string> >();
                                    foreach (var arrayItem in value as object[])
                                    {
                                        TaxonomyItem taxonomyItem;
                                        Guid         termGuid = Guid.Empty;
                                        if (!Guid.TryParse(arrayItem as string, out termGuid))
                                        {
                                            // Assume it's a TermPath
                                            taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(arrayItem as string);
                                        }
                                        else
                                        {
                                            taxonomyItem = taxSession.GetTerm(termGuid);
                                            ClientContext.Load(taxonomyItem);
                                            ClientContext.ExecuteQueryRetry();
                                        }



                                        terms.Add(new KeyValuePair <Guid, string>(taxonomyItem.Id, taxonomyItem.Name));
                                    }

                                    TaxonomyField taxField = ClientContext.CastTo <TaxonomyField>(field);

                                    taxField.EnsureProperty(tf => tf.AllowMultipleValues);

                                    if (taxField.AllowMultipleValues)
                                    {
                                        var termValuesString = String.Empty;
                                        foreach (var term in terms)
                                        {
                                            termValuesString += "-1;#" + term.Value + "|" + term.Key.ToString("D") + ";#";
                                        }

                                        termValuesString = termValuesString.Substring(0, termValuesString.Length - 2);

                                        var newTaxFieldValue = new TaxonomyFieldValueCollection(ClientContext, termValuesString, taxField);
                                        taxField.SetFieldValueByValueCollection(item, newTaxFieldValue);
#if !ONPREMISES
                                        item.SystemUpdate();
#else
                                        item.Update();
#endif
                                        ClientContext.ExecuteQueryRetry();
                                    }
                                    else
                                    {
                                        WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                                    }
                                }
                                else
                                {
                                    Guid termGuid = Guid.Empty;
                                    if (!Guid.TryParse(value as string, out termGuid))
                                    {
                                        // Assume it's a TermPath
                                        var taxonomyItem = ClientContext.Site.GetTaxonomyItemByPath(value as string);
                                        termGuid = taxonomyItem.Id;
                                    }
                                    item[key as string] = termGuid.ToString();
                                }
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            case "Lookup":
                            case "LookupMulti":
                            {
                                int[] multiValue;
                                if (values[key] is Array)
                                {
                                    var arr = (object[])values[key];
                                    multiValue = new int[arr.Length];
                                    for (int i = 0; i < arr.Length; i++)
                                    {
                                        multiValue[i] = int.Parse(arr[i].ToString());
                                    }
                                }
                                else
                                {
                                    string valStr = values[key].ToString();
                                    multiValue = valStr.Split(',', ';').Select(int.Parse).ToArray();
                                }

                                var newVals = multiValue.Select(id => new FieldLookupValue {
                                        LookupId = id
                                    }).ToArray();

                                FieldLookup lookupField = ClientContext.CastTo <FieldLookup>(field);
                                lookupField.EnsureProperty(lf => lf.AllowMultipleValues);
                                if (!lookupField.AllowMultipleValues && newVals.Length > 1)
                                {
                                    WriteWarning($@"You are trying to set multiple values in a single value field. Skipping values for field ""{field.InternalName}""");
                                }

                                item[key as string] = newVals;
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }

                            default:
                            {
                                item[key as string] = values[key];
#if !ONPREMISES
                                item.SystemUpdate();
#else
                                item.Update();
#endif
                                break;
                            }
                            }
                        }
                        else
                        {
                            ThrowTerminatingError(new ErrorRecord(new Exception("Field not present in list"), "FIELDNOTINLIST", ErrorCategory.InvalidData, key));
                        }
                    }
                }

                item.Update();
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
コード例 #28
0
ファイル: ListManager.cs プロジェクト: picologic/spo-util
        private void populateItem(ListItem item, Row row, IDictionary <string, string> fieldMap, IDictionary <string, string> defaults, FieldCollection fields)
        {
            // helper
            Action <string, string> setField = (fieldName, val) => {
                if (!string.IsNullOrWhiteSpace(val))
                {
                    // check if we need to convert value
                    var field = fields.Where(x => x.InternalName == fieldName).First();
                    switch (field.FieldTypeKind)
                    {
                    case FieldType.DateTime:
                        DateTime dtVal;
                        if (!DateTime.TryParse(val, out dtVal))
                        {
                            double dblVal;
                            if (double.TryParse(val, out dblVal))
                            {
                                dtVal = DateTime.FromOADate(dblVal);
                            }
                            else
                            {
                                throw new Exception("Could not parse " + val + " as DateTime");
                            }
                        }

                        item[fieldName] = dtVal;
                        break;

                    case FieldType.URL:
                        if (!val.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) &&
                            !val.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
                        {
                            val = "http://" + val;
                        }
                        item[fieldName] = val;
                        break;

                    case FieldType.Lookup:
                        FieldLookup lookup = (FieldLookup)field;
                        item[fieldName] = getLookupValue(val, lookup);
                        break;

                    case FieldType.Currency:
                        double dbVal;
                        if (double.TryParse(val, out dbVal))
                        {
                            item[fieldName] = dbVal;
                        }
                        else
                        {
                            Console.WriteLine("Could not convert {0} to currency", val);
                        }
                        break;

                    case FieldType.Text:
                        FieldText tfield = (FieldText)field;
                        if (val.Length > tfield.MaxLength)
                        {
                            val = val.Substring(0, tfield.MaxLength);
                            Console.WriteLine("Truncating value for {0}", tfield.Title);
                        }
                        item[fieldName] = val;
                        break;

                    default:
                        item[fieldName] = val;
                        break;
                    }
                }
            };

            foreach (var colname in fieldMap.Keys)
            {
                var fieldName = fieldMap[colname];
                if (fieldName == "")    // if empty, it doesn't exist in target list so skip
                {
                    continue;
                }

                var val = "";
                if (row.ColumnNames.Contains(colname))
                {
                    val = row.GetValueOrEmpty(colname);
                }

                if (string.IsNullOrWhiteSpace(val) && defaults.ContainsKey(colname))
                {
                    val = defaults[colname];
                }

                setField(fieldName, val);
            }
        }
コード例 #29
0
        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();

                // configure state lookup field
                FieldLookup stateField = ctx.CastTo <FieldLookup>(stateLookup);
                stateField.LookupList                 = stateList.Id.ToString();
                stateField.LookupField                = "Title";
                stateField.Indexed                    = true;
                stateField.IsRelationship             = true;
                stateField.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Restrict;
                stateField.Update();
                ctx.ExecuteQueryRetry();

                //Provision city list items
                ListItemCreationInformation newCityCreationInfomation;
                newCityCreationInfomation = new ListItemCreationInformation();
                ListItem newCity = cityList.AddItem(newCityCreationInfomation);
                newCity["Title"] = "Bree";
                newCity["State"] = "2;#Limburg";
                newCity.Update();
                newCity          = cityList.AddItem(newCityCreationInfomation);
                newCity["Title"] = "Redmond";
                newCity["State"] = "1;#Washington";
                newCity.Update();
                newCity          = cityList.AddItem(newCityCreationInfomation);
                newCity["Title"] = "Franklin";
                newCity["State"] = "3;#Tennessee";
                newCity.Update();
                newCity          = cityList.AddItem(newCityCreationInfomation);
                newCity["Title"] = "Bangalore";
                newCity["State"] = "4;#Karnataka";
                newCity.Update();

                ctx.ExecuteQueryRetry();
            }
            else
            {
                cityList = ctx.Web.GetListByUrl("Lists/EmpCity");
                Console.WriteLine("City list was already available");
            }

            List designationList = null;

            if (!ctx.Web.ListExists("EmpDesignation"))
            {
                Console.WriteLine("Designation list...");
                designationList = ctx.Web.CreateList(ListTemplateType.GenericList, "EmpDesignation", false, false, "Lists/EmpDesignation", false);
                ctx.Load(designationList);
                ctx.ExecuteQueryRetry();

                //Provision designation list items
                ListItemCreationInformation newDesignationCreationInfomation;
                newDesignationCreationInfomation = new ListItemCreationInformation();
                ListItem newDesignation = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Service Engineer";
                newDesignation.Update();
                newDesignation          = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Service Engineer II";
                newDesignation.Update();
                newDesignation          = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Senior Service Engineer";
                newDesignation.Update();
                newDesignation          = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Principal Service Engineer";
                newDesignation.Update();
                newDesignation          = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Program Manager";
                newDesignation.Update();
                newDesignation          = designationList.AddItem(newDesignationCreationInfomation);
                newDesignation["Title"] = "Senior Program Manager";
                newDesignation.Update();

                ctx.ExecuteQueryRetry();
            }
            else
            {
                designationList = ctx.Web.GetListByUrl("Lists/EmpDesignation");
                Console.WriteLine("Designation list was already available");
            }

            List empAttachmentsList = null;

            if (!ctx.Web.ListExists("EmpAttachments"))
            {
                Console.WriteLine("EmpAttachments list...");
                empAttachmentsList = ctx.Web.CreateList(ListTemplateType.DocumentLibrary, "EmpAttachments", false, false, "Lists/EmpAttachments", false);
                ctx.Load(empAttachmentsList);
                ctx.ExecuteQueryRetry();

                empAttachmentsList.CreateField(@"<Field Type=""Text"" DisplayName=""AttachmentID"" ID=""{E6FAC176-F466-4174-9785-7FB9611CBC00}"" Name=""AttachmentID""></Field>", false);
                empAttachmentsList.Update();
                ctx.Load(empAttachmentsList.DefaultView, p => p.ViewFields);
                ctx.ExecuteQueryRetry();

                // Add fields to view
                empAttachmentsList.DefaultView.ViewFields.Add("AttachmentID");
                empAttachmentsList.DefaultView.Update();
                ctx.ExecuteQueryRetry();
            }
            else
            {
                empAttachmentsList = ctx.Web.GetListByUrl("Lists/EmpAttachments");
                Console.WriteLine("EmpAttachments list was already available");
            }

            List employeeList = null;

            if (!ctx.Web.ListExists("Employees"))
            {
                Console.WriteLine("Employee list...");
                employeeList = ctx.Web.CreateList(ListTemplateType.GenericList, "Employees", false, false, "Lists/Employees", false);
                ctx.Load(employeeList);
                ctx.ExecuteQueryRetry();

                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Number"" ID=""{0FFF75B6-0E57-46BE-84D7-E5225A55E914}"" Name=""EmpNumber""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""UserID"" ID=""{D3199531-C091-4359-8CDE-86FB3924F65E}"" Name=""UserID""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Manager"" ID=""{B7E2F4D9-AEA2-40DB-A354-94EEDAFEF35E}"" Name=""EmpManager""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Designation"" ID=""{AB230804-C137-4ED8-A6D6-722037BDDA3D}"" Name=""Designation""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Location"" ID=""{2EE32832-5EF0-41D0-8CD3-3DE7B9616C21}"" Name=""Location""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""Skills"" ID=""{89C02660-822D-4F41-881D-1D533C56017E}"" Name=""Skills""></Field>", false);
                employeeList.CreateField(@"<Field Type=""Text"" DisplayName=""AttachmentID"" ID=""{53A31281-1C25-4D00-B785-40C71D37AE7B}"" Name=""AttachmentID""></Field>", false);
                employeeList.Update();
                ctx.Load(employeeList.DefaultView, p => p.ViewFields);
                ctx.ExecuteQueryRetry();

                // Add fields to view
                employeeList.DefaultView.ViewFields.Add("EmpNumber");
                employeeList.DefaultView.ViewFields.Add("UserID");
                employeeList.DefaultView.ViewFields.Add("EmpManager");
                employeeList.DefaultView.ViewFields.Add("Designation");
                employeeList.DefaultView.ViewFields.Add("Location");
                employeeList.DefaultView.ViewFields.Add("Skills");
                employeeList.DefaultView.ViewFields.Add("AttachmentID");
                employeeList.DefaultView.Update();
                ctx.ExecuteQueryRetry();
            }
            else
            {
                employeeList = ctx.Web.GetListByUrl("Lists/Employees");
                Console.WriteLine("Employee list was already available");
            }
        }
コード例 #30
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            // CSOM provision for DependentLookupFieldDefinition does not update these props
            // seems to be a by design SharePoin issue
            // https://github.com/SubPointSolutions/spmeta2/issues/753

            this.SkipAllowMultipleValuesValidation = true;
            this.SkipFieldTypeValidation           = true;
            this.SkipLookupFieldValidation         = true;

            this.ModelHost = modelHost;

            base.DeployModel(modelHost, model);

            var definition       = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull());
            var spObject         = GetField(modelHost, definition);
            var typedField       = spObject.Context.CastTo <FieldLookup>(spObject);
            var typedDefinition  = model.WithAssertAndCast <DependentLookupFieldDefinition>("model", value => value.RequireNotNull());
            var typedFieldAssert = ServiceFactory.AssertService.NewAssert(model, typedDefinition, typedField);

            var context = spObject.Context;

            typedFieldAssert.SkipProperty(m => m.RelationshipDeleteBehavior, "DependentLookupFieldDefinition");

            // binding
            var fields = FieldLookupService.GetFieldCollection(this.ModelHost);

            FieldLookup primaryLookupField = null;

            if (typedDefinition.PrimaryLookupFieldId.HasGuidValue())
            {
                primaryLookupField = FieldLookupService.GetFieldAs <FieldLookup>(fields, typedDefinition.PrimaryLookupFieldId.Value, null, null);
                typedFieldAssert.ShouldNotBeNull(primaryLookupField);

                typedFieldAssert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.PrimaryLookupFieldId);
                    var isValid = primaryLookupField.Id == new Guid(typedField.PrimaryFieldId);

                    return(new PropertyValidationResult {
                        Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid
                    });
                });
            }
            else
            {
                typedFieldAssert.SkipProperty(m => m.PrimaryLookupFieldId, "PrimaryLookupFieldId is NULL. Skipping.");
            }

            if (!string.IsNullOrEmpty(typedDefinition.PrimaryLookupFieldInternalName))
            {
                primaryLookupField = FieldLookupService.GetFieldAs <FieldLookup>(fields, null, typedDefinition.PrimaryLookupFieldInternalName, null);
                typedFieldAssert.ShouldNotBeNull(primaryLookupField);

                typedFieldAssert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.PrimaryLookupFieldInternalName);
                    var isValid = primaryLookupField.Id == new Guid(typedField.PrimaryFieldId);

                    return(new PropertyValidationResult {
                        Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid
                    });
                });
            }
            else
            {
                typedFieldAssert.SkipProperty(m => m.PrimaryLookupFieldInternalName, "PrimaryLookupFieldInternalName is NULL. Skipping.");
            }

            if (!string.IsNullOrEmpty(typedDefinition.PrimaryLookupFieldTitle))
            {
                primaryLookupField = FieldLookupService.GetFieldAs <FieldLookup>(fields, null, null, typedDefinition.PrimaryLookupFieldTitle);
                typedFieldAssert.ShouldNotBeNull(primaryLookupField);

                typedFieldAssert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(m => m.PrimaryLookupFieldTitle);
                    var isValid = primaryLookupField.Id == new Guid(typedField.PrimaryFieldId);

                    return(new PropertyValidationResult {
                        Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid
                    });
                });
            }
            else
            {
                typedFieldAssert.SkipProperty(m => m.PrimaryLookupFieldTitle, "PrimaryLookupFieldInternalName is NULL. Skipping.");
            }
        }