Ejemplo n.º 1
0
        static void CreateExpenseSiteColumns()
        {
            fldExpenseCategory = clientContext.CastTo <FieldChoice>(CreateSiteColumn("ExpenseCategory", "Expense Category", "Choice"));
            string[] choicesExpenseCategory = ExpenseCategory.GetAll();
            fldExpenseCategory.Choices = choicesExpenseCategory;
            fldExpenseCategory.Update();
            clientContext.ExecuteQuery();


            fldExpenseDate = clientContext.CastTo <FieldDateTime>(CreateSiteColumn("ExpenseDate", "Expense Date", "DateTime"));;
            fldExpenseDate.DisplayFormat = DateTimeFieldFormatType.DateOnly;
            fldExpenseDate.Update();

            fldExpenseAmount = clientContext.CastTo <FieldCurrency>(CreateSiteColumn("ExpenseAmount", "Expense Amount", "Currency"));
            fldExpenseAmount.MinimumValue = 0;

            fldExpenseBudgetYear = clientContext.CastTo <FieldText>(CreateSiteColumn("ExpenseBudgetYear", "Budget Year", "Text"));

            fldExpenseBudgetQuarter = clientContext.CastTo <FieldText>(CreateSiteColumn("ExpenseBudgetQuarter", "Budget Quarter", "Text"));
            fldExpenseBudgetQuarter.Update();

            fldExpenseBudgetAmount = clientContext.CastTo <FieldCurrency>(CreateSiteColumn("ExpenseBudgetAmount", "Budget Amount", "Currency"));

            clientContext.ExecuteQuery();
        }
Ejemplo n.º 2
0
        public static void SetUp(ClientContext ctx)
        {
            Web    root      = ctx.Site.RootWeb;
            string pathToXML = AppDomain.CurrentDomain.BaseDirectory + "CVContentType.xml";

            root.CreateFieldsFromXMLFile(pathToXML);
            root.CreateContentTypeFromXMLFile(pathToXML);

            List CVs = null;

            if (root.ListExists("CV's"))
            {
                CVs = root.GetListByTitle("CV's");
            }
            else
            {
                CVs = root.CreateList(ListTemplateType.DocumentLibrary, "CV's", true, true, "CVS", true);
            }

            CVs.AddContentTypeToListByName("CV", true);
            CVs.RemoveContentTypeByName("Document");

            FieldText titleField = CVs.GetFieldById <FieldText>("{fa564e0f-0c70-4ab9-b863-0177e6ddd247}".ToGuid());

            titleField.Title = "CV Description";
            titleField.Update();
            ctx.ExecuteQuery();

            AddViewFields(ctx, CVs);



            string query = @"<OrderBy>
            <FieldRef Name='Modified' Ascending='FALSE' />
                </OrderBy>
                <Where>
                    <And>
                        <Eq>
                            <FieldRef Name='CV_bool' />
                            <Value Type='Boolean' >1</Value>
                        </Eq>
                        <Gt>
                            <FieldRef Name='Created' />
                            <Value Type='DateTime' >2017-01-01T00:00:00Z</Value>
                        </Gt>
                    </And>
                </Where>
                    ";

            CVs.CreateView("Active CV's 2", ViewType.Html, new string[] { "Title", "CV_Picture", "CV_Person" }, 10, false, query);
        }
        public static void CreateListColumn()
        {
            var clientContext = Helper.GetClientContext();

            List oList = clientContext.Web.Lists.GetByTitle(listName);

            //Number DataType Column
            Field       numberField = oList.Fields.AddFieldAsXml("<Field DisplayName='Age' Type='Number' />", true, AddFieldOptions.DefaultValue);
            FieldNumber fieldNumber = clientContext.CastTo <FieldNumber>(numberField);

            fieldNumber.MaximumValue = 100;
            fieldNumber.MinimumValue = 35;
            fieldNumber.Update();
            clientContext.Load(fieldNumber);

            // //Single Line Of Text DataType Column
            Field     textField = oList.Fields.AddFieldAsXml("<Field DisplayName='SingleLine' Type='Text' />", true, AddFieldOptions.DefaultValue);
            FieldText fieldText = clientContext.CastTo <FieldText>(textField);

            fieldText.Update();
            clientContext.Load(fieldText);

            //Multi Line Of Text DataType Column
            Field multiLineField = oList.Fields.AddFieldAsXml("<Field DisplayName='MultiLine' Type='Note' />", true, AddFieldOptions.DefaultValue);
            FieldMultiLineText fieldmultiLineText = clientContext.CastTo <FieldMultiLineText>(multiLineField);

            fieldmultiLineText.Update();
            clientContext.Load(fieldmultiLineText);

            //Multi Line Rich Text DataType Column
            Field multiLineRichTextField = oList.Fields.AddFieldAsXml("<Field DisplayName='Multi Line RichText' Type='Note' />", true, AddFieldOptions.DefaultValue);
            FieldMultiLineText fieldmultiLineRichText = clientContext.CastTo <FieldMultiLineText>(multiLineRichTextField);

            fieldmultiLineRichText.AllowHyperlink = true;
            fieldmultiLineRichText.RichText       = true;
            fieldmultiLineRichText.Update();
            fieldmultiLineRichText.UpdateAndPushChanges(true);
            clientContext.Load(fieldmultiLineRichText);

            //An enhanced multi line text field
            string schemaRichTextField        = "<Field Type='Note' Name='EnhancedmultiLine' StaticName='EnhancedmultiLine' DisplayName = 'Enhanced multiLine' NumLines = '6' RichText = 'TRUE' RichTextMode = 'FullHtml' IsolateStyles = 'TRUE' Sortable = 'FALSE' /> ";
            Field  multilineenhancedTextField = oList.Fields.AddFieldAsXml(schemaRichTextField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(multilineenhancedTextField);

            // DropDown Choice
            string schemaChoiceFieldDDL = "<Field Type='Choice' DisplayName='ChoiceDDL' Name='ChoiceDDL' StaticName='ChoiceDDL' Format = 'Dropdown' >"
                                          + "<Default>Option 2</Default>"
                                          + "<CHOICES>"
                                          + "    <CHOICE>Option 2</CHOICE>"
                                          + "    <CHOICE>Option 3</CHOICE>"
                                          + "</CHOICES>"
                                          + "</Field>";

            Field       choiceDDLField = oList.Fields.AddFieldAsXml(schemaChoiceFieldDDL, true, AddFieldOptions.AddFieldInternalNameHint);
            FieldChoice fieldChoice    = clientContext.CastTo <FieldChoice>(choiceDDLField);

            fieldChoice.Required = true;
            fieldChoice.Update();
            clientContext.Load(fieldChoice);


            //Radio buttons
            string schemaRadioChoiceField = "<Field Type='Choice' Name='ChoiceRadio' StaticName='ChoiceRadio' DisplayName = 'Choice Radio' Format = 'RadioButtons' > "
                                            + "<Default>Opt Radio 3</Default>"
                                            + "<CHOICES>"
                                            + "    <CHOICE>Opt Radio 1</CHOICE>"
                                            + "    <CHOICE>Opt Radio 2</CHOICE>"
                                            + "    <CHOICE>Opt Radio 3</CHOICE>"
                                            + "</CHOICES>"
                                            + "</Field>";
            Field choiceField = oList.Fields.AddFieldAsXml(schemaRadioChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceField);

            //Checkboxes
            string schemaMultiChoiceField = "<Field Type='MultiChoice' Name='ChoiceMulti' StaticName='ChoiceMulti' DisplayName = 'Choice Multi' > "
                                            + "<Default>MultiChoice 2</Default>"
                                            + "<CHOICES>"
                                            + "    <CHOICE>MultiChoice 1</CHOICE>"
                                            + "    <CHOICE>MultiChoice 2</CHOICE>"
                                            + "    <CHOICE>MultiChoice 3</CHOICE>"
                                            + "</CHOICES>"
                                            + "</Field>";
            Field choiceMultiChoiceField = oList.Fields.AddFieldAsXml(schemaMultiChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceMultiChoiceField);

            //Fill In option
            string schemaFillInChoiceField = "<Field Type='Choice' DisplayName='Fill In Choice' Name='FillInChoice' StaticName='FillInChoice' Format = 'Dropdown' FillInChoice = 'TRUE' > "
                                             + "<Default>My Choices Data will come here</Default>"
                                             + "<CHOICES>"
                                             + "    <CHOICE>FillInChoice 1</CHOICE>"
                                             + "    <CHOICE>FillInChoice 2</CHOICE>"
                                             + "    <CHOICE>FillInChoice 3</CHOICE>"
                                             + "</CHOICES>"
                                             + "</Field>";
            Field choiceFillInChoiceField = oList.Fields.AddFieldAsXml(schemaFillInChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceFillInChoiceField);

            //Picture field

            string schemaPictureField = "<Field Type='URL' Name='EmployeePicture' StaticName='EmployeePicture' DisplayName = 'Employee Picture' Format = 'Image' /> ";
            Field  pictureField       = oList.Fields.AddFieldAsXml(schemaPictureField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(pictureField);

            //URL field

            string schemaUrlField = "<Field Type='URL' Name='BlogUrl' StaticName='BlogUrl' DisplayName='Blog URL' Format='Hyperlink'/>";
            Field  urlField       = oList.Fields.AddFieldAsXml(schemaUrlField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(urlField);
            clientContext.ExecuteQuery();

            // Lookup field

            List countryList = clientContext.Web.Lists.GetByTitle("Countries");

            clientContext.Load(countryList, c => c.Id);
            clientContext.ExecuteQuery();


            // //define the relationship with the lookup field, in that case the field needs to be indexed:
            // string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = '{B5E2D800F-E739-401F-983F-B40984B70273}' ShowField = 'Title' RelationshipDeleteBehavior = 'Restrict' Indexed = 'TRUE' /> ";
            //string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = 'Countries' ShowField = 'Title' RelationshipDeleteBehavior = 'Restrict' Indexed = 'TRUE' /> ";
            string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = '" + countryList.Id + "' ShowField = 'Title' /> ";
            Field  lookupField       = oList.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.AddFieldInternalNameHint);

            lookupField.Update();
            clientContext.Load(lookupField);

            //// multi-select lookup field
            string schemaMultiLookupField = "<Field Type='LookupMulti' Name='Country' StaticName='Country' DisplayName='Country' List = '" + countryList.Id + "' ShowField = 'Title' Mult = 'TRUE' /> ";
            //string schemaMultiLookupField = "<Field Type='LookupMulti' Name='Country' StaticName='Country' DisplayName='Country' List = 'Countries' ShowField = 'Title' Mult = 'TRUE' /> ";
            Field lookupFieldmulti = oList.Fields.AddFieldAsXml(schemaMultiLookupField, true, AddFieldOptions.AddFieldInternalNameHint);

            lookupFieldmulti.Update();
            clientContext.Load(lookupFieldmulti);


            ////Ref: https://karinebosch.wordpress.com/my-articles/creating-fields-using-csom/

            // //User Field
            string schemaUserField = "<Field Type='User' Name='UserName' StaticName='UserName' DisplayName='User Name' />";
            Field  userField       = oList.Fields.AddFieldAsXml(schemaUserField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(userField);

            ////User Field multiple
            //string schemaUserGroupField = "<Field Type='UserMulti' Name='EmployeeName' StaticName='EmployeeName' DisplayName='Employee Name' UserSelectionMode = 'PeopleOnly' UserSelectionScope = '7' Mult = 'TRUE' /> ";
            string schemaUserGroupField = "<Field Type='UserMulti' Name='EmployeeName' StaticName='EmployeeName' DisplayName='Employee Name' UserSelectionMode = 'PeopleAndGroups' UserSelectionScope = '7' Mult = 'TRUE' /> ";
            Field  userGroupField       = oList.Fields.AddFieldAsXml(schemaUserGroupField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(userGroupField);

            ////boolean field

            string schemaBooleanField = "<Field Type='Boolean' Name='Married' StaticName='Married' DisplayName='Married'> <Default>1</Default> </Field>";
            Field  booleanField       = oList.Fields.AddFieldAsXml(schemaBooleanField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(booleanField);

            ////DateTime Field

            //Date only field
            string schemaBirthDate = "<Field Type='DateTime' Name='BirthDate' StaticName='BirthDate' DisplayName = 'Birth date' Format = 'DateOnly'> <Default>[Today]</Default></Field>";
            Field  birthDateField  = oList.Fields.AddFieldAsXml(schemaBirthDate, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(birthDateField);

            ////Date and time field
            string schemaArrivalField = "<Field Type='DateTime' Name='ArrivalDateTime' StaticName='ArrivalDateTime' DisplayName = 'Arrival' Format = 'DateTime'> <Default>[Now]</Default></Field>";
            Field  DateTimeField      = oList.Fields.AddFieldAsXml(schemaArrivalField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(DateTimeField);

            ////hidden field

            string schemaHiddenTextField = "<Field Type='Text' Name='HiddenField' StaticName='HiddenField' DisplayName='Hidden Field' Hidden='TRUE' />";
            Field  hiddenTextField       = oList.Fields.AddFieldAsXml(schemaHiddenTextField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(hiddenTextField);

            //indexed field // Not Working as of now

            //Field f = oList.Fields.GetByInternalNameOrTitle("ID");
            //clientContext.Load(f);
            //clientContext.ExecuteQuery();
            //f.Indexed = true;
            //f.Update();

            //Managed Metadata field

            Guid termStoreId = Guid.Empty;
            Guid termSetId   = Guid.Empty;

            GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId);

            // Single selection Taxonomy field
            string schemaTaxonomyField = "<Field Type='TaxonomyFieldType' Name='TaxonomyField' StaticName='TaxonomyField' DisplayName = 'Taxonomy Field' /> ";
            Field  taxonomyFieldSingle = oList.Fields.AddFieldAsXml(schemaTaxonomyField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(taxonomyFieldSingle);

            // Retrieve the field as a Taxonomy Field
            TaxonomyField taxonomyField = clientContext.CastTo <TaxonomyField>(taxonomyFieldSingle);

            taxonomyField.SspId          = termStoreId;
            taxonomyField.TermSetId      = termSetId;
            taxonomyField.TargetTemplate = String.Empty;
            taxonomyField.AnchorId       = Guid.Empty;
            taxonomyField.Update();

            // Multi selection Taxonomy field

            string schemaTaxonomyFieldMulti = "<Field Type='TaxonomyFieldTypeMulti' Name='TaxonomyFieldMulti' StaticName='TaxonomyFieldMulti' DisplayName = 'Taxonomy Field Multi' Mult = 'TRUE' /> ";
            Field  taxonomyFieldMulti       = oList.Fields.AddFieldAsXml(schemaTaxonomyFieldMulti, false, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(taxonomyFieldMulti);

            // Retrieve the field as a Taxonomy Field
            TaxonomyField taxonomyField1 = clientContext.CastTo <TaxonomyField>(taxonomyFieldMulti);

            taxonomyField1.SspId          = termStoreId;
            taxonomyField1.TermSetId      = termSetId;
            taxonomyField1.TargetTemplate = String.Empty;
            taxonomyField1.AnchorId       = Guid.Empty;
            taxonomyField1.Update();


            clientContext.ExecuteQuery();

            //Calculated field

            // Not Working

            //string formula = "<Formula>=Age&amp;\"\"&amp;SingleLine&amp;\"(id:\"&amp;ID&amp;\"\"</Formula>"
            //                  + "<FieldRefs>"
            //                  + "<FieldRef Name='Age' />"
            //                  + "<FieldRef Name='SingleLine' />"
            //                  + "<FieldRef Name='ID' />"
            //                  + "</FieldRefs>";

            //string schemaCalculatedField = "<Field Type='Calculated' Name='CalculatedField' StaticName='CalculatedField' DisplayName = 'Calculated Field' ResultType = 'Text' Required = 'TRUE' ReadOnly = 'TRUE' > " + formula + " </ Field > ";
            //Field fullNameField = oList.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddFieldInternalNameHint);
            //clientContext.ExecuteQuery();

            string fieldXml = "<Field Name='CalculatedField_Year' StaticName='CalculatedField_Year' DisplayName='CalculatedField Year' Type='Text' ReadOnly = 'TRUE'>"
                              + "<DefaultFormula>=CONCATENATE(YEAR(Today))</DefaultFormula>"
                              + "</Field>";
            Field field = oList.Fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.DefaultValue);

            clientContext.ExecuteQuery();
        }
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult result = new SPRemoteEventResult();

            //get the host web url
            Uri hostUrl = properties.AppEventProperties.HostWebFullUrl;

            //get the operation context so we can figure out the host URL for this service, from
            //which we can get the Authority for a client context
            System.ServiceModel.OperationContext oc = System.ServiceModel.OperationContext.Current;

            Uri localUrl = null;

            //UPDATE:  THIS CODE WORKED FINE FOR WHEN YOU USE THE WEB APP CREATED BY VS.NET
            //FOR THE SHAREPOINT APP, BUT IT BREAKS WHEN YOU DEPLOY TO A REAL IIS SERVER
            //BECAUSE YOU END UP GETTING TWO BASEADDRESSES, BUT NOT WITH THE RIGHT SCHEME.
            //FOR EXAMPLE, THE FIRST ONE IS THE ADDRESS OF THIS HOST BUT WITH THE HTTP SCHEME.
            //THE SECOND ONE IS HTTPS, BUT THE HOST NAME IS THE FQDN OF THE SERVER.  SINCE
            //SHAREPOINT DOESN'T RECOGNIZE THAT AS THE ENDPOINT IT TRUSTS FOR THIS CODE, IT BLOWS
            //UP WHEN RUNNING THE CODE BELOW AND THE WHOLE THING FAILS

            #region Code That Breaks In IIS
            ////now enumerate through the Host base addresses and look for the SSL connection
            //foreach (Uri u in oc.Host.BaseAddresses)
            //{
            //    if (u.Scheme.ToLower() == "https")
            //    {
            //        localUrl = u;
            //        break;
            //    }
            //}
            #endregion

            //assume first base address is ours, which it has been so far
            if (oc.Host.BaseAddresses.Count > 0)
            {
                localUrl = oc.Host.BaseAddresses[0];
            }

            //make sure we found our local URL
            if (localUrl != null)
            {
                //using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false))
                using (ClientContext ctx = TokenHelper.GetClientContextWithContextToken(hostUrl.ToString(), properties.ContextToken, localUrl.Authority))
                {
                    if (ctx != null)
                    {
                        //try to retrieve the list first to see if it exists
                        List l = ctx.Web.Lists.GetByTitle(LIST_NAME);
                        ctx.Load(l);

                        //have to put in a try block because of course it throw an exception if
                        //list doesn't exist
                        try
                        {
                            ctx.ExecuteQuery();
                        }
                        catch (Exception noListEx)
                        {
                            //look to see if the exception is that the list doesn't exist
                            if (noListEx.Message.ToLower().Contains("does not exist"))
                            {
                                //code here to create list
                                Web web = ctx.Web;

                                ListCreationInformation ci = new ListCreationInformation();
                                ci.Title             = LIST_NAME;
                                ci.TemplateType      = (int)ListTemplateType.GenericList;
                                ci.QuickLaunchOption = QuickLaunchOptions.Off;

                                l             = web.Lists.Add(ci);
                                l.Description = "List for tracking events with the Event Planner Social App";

                                Field fldEventName   = l.Fields.AddFieldAsXml("<Field DisplayName='EventName' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                Field fldSiteUrl     = l.Fields.AddFieldAsXml("<Field DisplayName='SiteUrl' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                Field fldTwitterTags = l.Fields.AddFieldAsXml("<Field DisplayName='TwitterTags' Type='Text' />", true, AddFieldOptions.DefaultValue);

                                Field         fldEventDate = l.Fields.AddFieldAsXml("<Field DisplayName='EventDate' Type='DateTime' />", true, AddFieldOptions.DefaultValue);
                                FieldDateTime dtEventDate  = ctx.CastTo <FieldDateTime>(fldEventDate);
                                dtEventDate.DisplayFormat = DateTimeFieldFormatType.DateOnly;
                                dtEventDate.Update();

                                Field     fldGraphID = l.Fields.AddFieldAsXml("<Field DisplayName='ObjectGraphID' Type='Text' />", true, AddFieldOptions.DefaultValue);
                                FieldText txtGraphID = ctx.CastTo <FieldText>(fldGraphID);
                                txtGraphID.Indexed = true;
                                txtGraphID.Update();

                                l.Hidden = true;
                                l.Update();

                                try
                                {
                                    //this creates the list
                                    ctx.ExecuteQuery();

                                    //all of the rest of this is to remove the list from the "Recent" list that appears
                                    //in sites by default, which is really a set of navigation links

                                    //get the site and root web, where the navigation lives
                                    Site s  = ctx.Site;
                                    Web  rw = s.RootWeb;

                                    //get the QuickLaunch navigation, which is where the Recent nav lives
                                    ctx.Load(rw, x => x.Navigation, x => x.Navigation.QuickLaunch);
                                    ctx.ExecuteQuery();

                                    //now extract the Recent navigation node from the collection
                                    var vNode = from NavigationNode nn in rw.Navigation.QuickLaunch
                                                where nn.Title == "Recent"
                                                select nn;

                                    NavigationNode nNode = vNode.First <NavigationNode>();

                                    //now we need to get the child nodes of Recent, that's where our list should be found
                                    ctx.Load(nNode.Children);
                                    ctx.ExecuteQuery();

                                    var vcNode = from NavigationNode cn in nNode.Children
                                                 where cn.Title == LIST_NAME
                                                 select cn;

                                    //now that we have the node representing our list, delete it
                                    NavigationNode cNode = vcNode.First <NavigationNode>();
                                    cNode.DeleteObject();

                                    ctx.ExecuteQuery();
                                }
                                catch (Exception newListFailEx)
                                {
                                    Debug.WriteLine("Creation of new list failed: " + newListFailEx.Message);
                                }
                            }
                        }

                        //okay, so if we're here then the list should exist, and we should be good to go at this point
                    }
                }
            }


            #region OOB Template Code
            //using (ClientContext clientContext = TokenHelper.CreateAppEventClientContext(properties, false))
            //{
            //    if (clientContext != null)
            //    {
            //        clientContext.Load(clientContext.Web);
            //        clientContext.ExecuteQuery();
            //    }
            //}
            #endregion

            return(result);
        }
        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.");
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Lanza el proceso de creación de nuevas columnas
        /// </summary>
        /// <returns></returns>
        public bool CreateColumns()
        {
            bool result          = true;
            List list            = null;
            bool continueProcess = true;

            if (ConectionSiteOK)
            {
                if (SPFields.Count > 0)
                {
                    foreach (SPFields infoField in SPFields)
                    {
                        continueProcess = true;
                        try
                        {
                            list = site.Web.Lists.GetByTitle(infoField.ListName);
                        }
                        catch (Exception ex)
                        {
                            SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                            continueProcess = false;
                        }

                        if (continueProcess)
                        {
                            //Configuramos...
                            switch (infoField.Column)
                            {
                            case TypeColumn.LineOfText:
                                //Linea de texto
                                Field newField1 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField1.StaticName  = infoField.ColumnName;
                                newField1.Description = infoField.Description;

                                if (infoField.FieldText != null)
                                {
                                    FieldText fldText = site.CastTo <FieldText>(newField1);
                                    fldText.Required            = infoField.FieldText.ContainInformation;
                                    fldText.EnforceUniqueValues = infoField.FieldText.UniqueValues;
                                    fldText.MaxLength           = infoField.FieldText.MaxLength;
                                    fldText.DefaultValue        = infoField.FieldText.DefaultValue;
                                    if (infoField.FieldText.UniqueValues)
                                    {
                                        fldText.Indexed = true;
                                    }
                                    fldText.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Multiline:
                                //Varias líneas de texto
                                Field newField2 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField2.StaticName  = infoField.ColumnName;
                                newField2.Description = infoField.Description;

                                if (infoField.FieldMultiText != null)
                                {
                                    FieldMultiLineText fldMultiLine = site.CastTo <FieldMultiLineText>(newField2);
                                    fldMultiLine.Required      = infoField.FieldMultiText.ContainInformation;
                                    fldMultiLine.NumberOfLines = infoField.FieldMultiText.NumLines;
                                    fldMultiLine.RichText      = infoField.FieldMultiText.RichText;
                                    fldMultiLine.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Choice:
                                //Eleccion
                                Field newField3 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField3.StaticName  = infoField.ColumnName;
                                newField3.Description = infoField.Description;

                                if (infoField.FieldChoice != null)
                                {
                                    FieldMultiChoice fldChoice = site.CastTo <FieldMultiChoice>(newField3);
                                    fldChoice.Required            = infoField.FieldChoice.ContainInformation;
                                    fldChoice.EnforceUniqueValues = infoField.FieldChoice.UniqueValues;
                                    fldChoice.DefaultValue        = infoField.FieldChoice.DefaultValue;
                                    if (infoField.FieldChoice.UniqueValues)
                                    {
                                        fldChoice.Indexed = true;
                                    }
                                    fldChoice.Choices = infoField.FieldChoice.Options;
                                    fldChoice.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Number:
                                //Numero
                                Field newField4 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField4.StaticName  = infoField.ColumnName;
                                newField4.Description = infoField.Description;

                                if (infoField.FieldNumber != null)
                                {
                                    FieldNumber fldNumber = site.CastTo <FieldNumber>(newField4);
                                    fldNumber.ShowAsPercentage = infoField.FieldNumber.ShowAsPercentaje;
                                    if (infoField.FieldNumber.MinValue != 0)
                                    {
                                        fldNumber.MinimumValue = infoField.FieldNumber.MinValue;
                                    }
                                    if (infoField.FieldNumber.MaxValue != 0)
                                    {
                                        fldNumber.MaximumValue = infoField.FieldNumber.MaxValue;
                                    }

                                    fldNumber.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Lookup:
                                if (infoField.FieldLookup != null)
                                {
                                    string required = "FALSE";
                                    if (infoField.FieldLookup.ContainInformation)
                                    {
                                        required = "TRUE";
                                    }

                                    try
                                    {
                                        List sourceList = site.Web.Lists.GetByTitle(infoField.FieldLookup.LookupList);
                                        site.Load(sourceList);

                                        List destinationList = site.Web.Lists.GetByTitle(infoField.ListName);
                                        site.Load(destinationList);

                                        site.ExecuteQuery();

                                        Field LookUpField = destinationList.Fields.AddFieldAsXml(string.Format(schemaXMLLookUp, infoField.Type, infoField.ColumnName, required, sourceList.Id, infoField.FieldLookup.LookupField), true, AddFieldOptions.DefaultValue);
                                        LookUpField.Description = infoField.Description;
                                        LookUpField.Update();
                                    }
                                    catch (Exception ex)
                                    {
                                        SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                                        continueProcess = false;
                                    }
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.UsersAndGroups:
                                Field newField5 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField5.StaticName  = infoField.ColumnName;
                                newField5.Description = infoField.Description;

                                if (infoField.FieldUserGroup != null)
                                {
                                    FieldUser fldUser = site.CastTo <FieldUser>(newField5);
                                    fldUser.Required = infoField.FieldUserGroup.ContainInformation;
                                    switch (infoField.FieldUserGroup.UserSelectionMode)
                                    {
                                    case TypeUserSelectionMode.PeopleOnly:
                                        fldUser.SelectionMode = FieldUserSelectionMode.PeopleOnly;
                                        break;

                                    case TypeUserSelectionMode.PeopleAndGroups:
                                        fldUser.SelectionMode = FieldUserSelectionMode.PeopleAndGroups;
                                        break;
                                    }

                                    if (infoField.FieldUserGroup.MultiUser)
                                    {
                                        fldUser.AllowMultipleValues = true;
                                    }

                                    if (!string.IsNullOrEmpty(infoField.FieldUserGroup.UsersFromGroup))
                                    {
                                        Group group = site.Web.SiteGroups.GetByName(infoField.FieldUserGroup.UsersFromGroup);

                                        try
                                        {
                                            site.Load(group);
                                            site.ExecuteQuery();
                                        }
                                        catch (Exception ex)
                                        {
                                            SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Warning));
                                            group = null;
                                        }

                                        if (group != null)
                                        {
                                            fldUser.SelectionGroup = group.Id;
                                        }
                                    }

                                    fldUser.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }

                                break;
                            }

                            //Añadimos...
                            if (continueProcess)
                            {
                                try
                                {
                                    site.ExecuteQuery();
                                }
                                catch (Exception ex)
                                {
                                    SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                                }
                            }
                        }

                        list = null;
                    }
                }
                else
                {
                    SHPExecOperationsErrors.Add(GetInfoError("Creación de columnas (CreateColumns)", "No se han indicado campos a crear", "", TypeError.Warning));
                    result = false;
                }
            }
            else
            {
                SHPExecOperationsErrors.Add(GetInfoError("Creación de columnas (CreateColumns)", "No se ha establecido conexión con el site", "", TypeError.Warning));
                result = false;
            }

            SPFields.Clear();

            return(result);
        }