Exemplo 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();
        }
Exemplo n.º 2
0
        public ActionResult EditItem(int id)
        {
            ClientContext clientContext = new ClientContext(SiteUrl);
            List          spList        = clientContext.Web.Lists.GetByTitle(ListName);

            clientContext.Load(spList);
            ListItem spListItem = spList.GetItemById(id);

            clientContext.Load(spListItem);
            clientContext.ExecuteQuery();

            string         Request_ID       = (String)spListItem[FieldId];
            string         Request_Details  = (String)spListItem[FieldDetails];
            string         Request_Status   = (String)spListItem[FieldStatus];
            var            dueDate          = spListItem[FieldDueDate];
            string         Request_Due_Date = dueDate != null ? ((DateTime)dueDate).ToShortDateString() : "";
            FieldUserValue Author           = (FieldUserValue)spListItem[FieldAuthor];
            string         Request_By       = Author.LookupValue;

            ViewBag.Request_ID       = Request_ID;
            ViewBag.Request_Details  = Request_Details;
            ViewBag.Request_Status   = Request_Status;
            ViewBag.Request_Due_Date = Request_Due_Date;
            ViewBag.Request_By       = Request_By;
            ViewBag.ID = id;

            // Getting choice fields from Request Status column
            FieldChoice choiceField = clientContext.CastTo <FieldChoice>(spList.Fields.GetByInternalNameOrTitle(FieldStatus));

            clientContext.Load(choiceField);
            clientContext.ExecuteQuery();
            ViewBag.Request_Status_Choices = choiceField.Choices;

            return(View());
        }
Exemplo n.º 3
0
        private static Field CreateChoiceField(FieldType fType, string displayName, string internalName, string fieldGroup, IEnumerable <KeyValuePair <string, string> > additionalAttributes, bool addToDefaultView, bool required, string[] choices)
        {
            Field field = null;

            if (web.FieldExistsByName(internalName))
            {
                field = web.Fields.GetByInternalNameOrTitle(internalName);
                field.DeleteObject();
                context.ExecuteQuery();
            }
            FieldCreationInformation fieldCi = new FieldCreationInformation(FieldType.Choice)
            {
                DisplayName      = displayName,
                InternalName     = internalName,
                AddToDefaultView = addToDefaultView,
                Required         = required,
                Id    = Guid.NewGuid(),
                Group = fieldGroup,
                AdditionalAttributes = additionalAttributes,
            };

            field = web.CreateField(fieldCi);

            FieldChoice fieldChoice = context.CastTo <FieldChoice>(web.Fields.GetByTitle(displayName));

            context.Load(fieldChoice);
            context.ExecuteQuery();

            fieldChoice.Choices = choices;
            fieldChoice.Update();
            context.Load(fieldChoice);
            context.ExecuteQuery();

            return(fieldChoice);
        }
Exemplo n.º 4
0
    /// <summary>
    /// Converts a field choice to a node.
    /// If field is variable, instead of creating a new node, returns an existing
    /// </summary>
    /// <param name="field"></param>
    /// <param name="rootNode"></param>
    /// <returns></returns>
    protected IntegerNode FieldToNode(FieldChoice field, RootNode rootNode)
    {
        HighlightableButton highlightableButton = (GameObjectHelper.HasComponent <HighlightableButton>(this.gameObject)) ? this.GetComponent <HighlightableButton>() : null;
        IntegerNode         fieldNode           = null;

        // If it is a variable, the variable has already been created
        // so we are going to search for it
        if (field.isVariable)
        {
            // When it is a variable, value will have its name
            ICodeNode variable = rootNode.SearchChildByName(field.value);
            if (variable != null && GameObjectHelper.CanBeCastedAs <IntegerNode>(variable))
            {
                fieldNode = (IntegerNode)variable;
            }
            else
            {
                throw new System.Exception("Expected " + field.value + " to be an integer node");
            }
        }
        // User has input a numeric value
        else
        {
            int value = int.Parse(field.value);
            fieldNode = new IntegerNode(null, value);
        }
        return(fieldNode);
    }
Exemplo n.º 5
0
        /// <summary>
        /// Adds the role.
        /// </summary>
        /// <param name="role">The role.</param>
        /// <returns></returns>
        public ActionStatus AddRole(string role)
        {
            lock (Padlock)
            {
                ActionStatus status = new ActionStatus();
                try
                {
                    if (!string.IsNullOrWhiteSpace(role))
                    {
                        List <NameValueData> roleMasterData = this.GetAllRoles();
                        if (roleMasterData.Where(m => m.Value.ToUpper().Trim() == role.ToUpper().Trim()).Any())
                        {
                            status.IsSucceed = false;
                            status.Messages.Add("This Role is already exists.");
                            return(status);
                        }
                        else
                        {
                            List roleMaster = this.web.Lists.GetByTitle(Masters.ROLEMASTER);
                            ListItemCreationInformation info = new ListItemCreationInformation();
                            ListItem listItem = roleMaster.AddItem(info);
                            listItem["Role"] = role;
                            listItem.Update();
                            this.context.ExecuteQuery();

                            List        emplist     = this.web.Lists.GetByTitle(Masters.APPROVERMASTER);
                            Field       rolefield   = emplist.Fields.GetByTitle("Role");
                            FieldChoice fieldChoice = this.context.CastTo <FieldChoice>(rolefield);
                            this.context.Load(fieldChoice);
                            this.context.ExecuteQuery();

                            List <string> options = new List <string>(fieldChoice.Choices);
                            options.Add(role);
                            fieldChoice.Choices = options.ToArray();
                            fieldChoice.Update();
                            this.context.ExecuteQuery();

                            //  this.CreateSPGroup(role);

                            status.IsSucceed = true;
                            status.ExtraData = role;
                            status.Messages.Add("Role added Successfully.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    status.IsSucceed = false;
                    status.Messages.Add("Sorry! Error while Adding Role.");

                    Logger.Error("Error while adding role name =" + role + " Message =" + ex.Message + " StackTrace = " + ex.StackTrace);
                }
                return(status);
            }
        }
Exemplo n.º 6
0
        public string[] GetAvailableChoicesFromField <T>(string propertyName)
        {
            string listTitle      = EntityHelper.GetDisplayNameFromEntitiyType(typeof(T));
            List   sharePointList = _clientContext.Web.Lists.GetByTitle(listTitle);

            _clientContext.Load(sharePointList);
            _clientContext.ExecuteQuery();

            var property = typeof(T).GetProperty(propertyName);

            FieldChoice choiceField = _clientContext.CastTo <FieldChoice>(_awecsomeField.GetFieldDefinition(sharePointList, property));

            _clientContext.Load(choiceField, q => q.Choices);
            _clientContext.ExecuteQuery();

            return(choiceField.Choices);
        }
Exemplo n.º 7
0
    public List <BloxValidationError> ValidateOperator()
    {
        List <BloxValidationError> errors = new List <BloxValidationError>();
        FieldChoice field1 = getSwitcherValue(Value1Switcher);
        FieldChoice field2 = getSwitcherValue(Value2Switcher);

        // if one of the fields is empty
        if (string.IsNullOrWhiteSpace(field1.value) || string.IsNullOrWhiteSpace(field2.value))
        {
            errors.Add(new BloxValidationError()
            {
                ErrorMessage = BloxValidationErrorMessages.OPERATOR_BLOX_NO_VALUE,
                TargetBlox   = this
            });
        }

        return(errors);
    }
 public HttpResponseMessage GetFieldsValues(string fieldName)
 {
     try
     {
         using (var ctx = new ClientContext(webUrl))
         {
             Field       field     = ctx.Web.Lists.GetByTitle(listTitle).Fields.GetByInternalNameOrTitle(fieldName);
             FieldChoice fldChoice = ctx.CastTo <FieldChoice>(field);
             ctx.Load(fldChoice, f => f.Choices);
             ctx.ExecuteQuery();
             return(Request.CreateResponse(HttpStatusCode.OK, fldChoice.Choices));
         }
     }
     catch (Exception ex)
     {
         // return the error back
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the questionnaire category.
        /// </summary>
        /// <returns>Question category</returns>
        public static List <string> GetQuestionnaireCategory()
        {
            var category = new List <string> {
                "None"
            };
            var web = Context.Web;

            Context.Load(web, w => w.AvailableFields);
            Context.ExecuteQuery();
            var         collFields = web.AvailableFields;
            FieldChoice choice     = Enumerable.FirstOrDefault(from field in collFields where field.InternalName == "QuestionCategory" select Context.CastTo <FieldChoice>(field));

            if (choice != null)
            {
                category.AddRange(choice.Choices);
            }

            return(category);
        }
        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();
        }
Exemplo n.º 11
0
        public static void CreateCarContetType(ClientContext ctx)
        {
            string VehicleContentType = "0x0100567A676ED8534670A79990FADE68DE47";
            string carContentType     = "0x0100567A676ED8534670A79990FADE68DE4700DC042CAC4BCA4EDFB9334B39999E4576";

            if (!ctx.Web.ContentTypeExistsById(VehicleContentType))
            {
                ctx.Web.CreateContentType("Vehicle", VehicleContentType, "Davids Content Types");
            }

            if (!ctx.Web.ContentTypeExistsById(carContentType))
            {
                ctx.Web.CreateContentType("Car", carContentType, "Davids Content Types");
            }

            Guid carModleFieldId = "{6DAD1B3E-A841-4E35-8B00-0E68E269C1F5}".ToGuid();

            if (!ctx.Web.FieldExistsById(carModleFieldId))
            {
                FieldCreationInformation modleFieldInfo = new FieldCreationInformation(FieldType.Text);
                modleFieldInfo.Id           = carModleFieldId;
                modleFieldInfo.InternalName = "F_CarModel";
                modleFieldInfo.DisplayName  = "Car Model";
                modleFieldInfo.Group        = "Davids Fields";

                ctx.Web.CreateField(modleFieldInfo);
            }

            ctx.Web.AddFieldToContentTypeById(carContentType, carModleFieldId.ToString());

            Guid carYearFieldId = "{AB76F05D-FC5F-4456-989D-F435BBF39230}".ToGuid();

            if (!ctx.Web.FieldExistsById(carYearFieldId))
            {
                FieldCreationInformation yearFieldInfo = new FieldCreationInformation(FieldType.Number);
                yearFieldInfo.Id           = carYearFieldId;
                yearFieldInfo.InternalName = "F_CarYear";
                yearFieldInfo.DisplayName  = "Car Year";
                yearFieldInfo.Group        = "Davids Fields";

                ctx.Web.CreateField(yearFieldInfo);
            }

            ctx.Web.AddFieldToContentTypeById(carContentType, carYearFieldId.ToString());

            Guid carColorFieldId = "{3A2B1887-ABBF-4EDB-BCCC-11CF48A279EA}".ToGuid();

            if (!ctx.Web.FieldExistsById(carColorFieldId))
            {
                FieldCreationInformation colorFieldInfo = new FieldCreationInformation(FieldType.Choice);
                colorFieldInfo.Id           = carColorFieldId;
                colorFieldInfo.InternalName = "F_CarColor";
                colorFieldInfo.DisplayName  = "Car Color";
                colorFieldInfo.Group        = "Davids Fields";

                FieldChoice field = ctx.Web.CreateField <FieldChoice>(colorFieldInfo);
                field.Choices      = new string[] { "Green", "Blue", "Red" };
                field.DefaultValue = "Green";
                field.Update();
                ctx.ExecuteQuery();
            }
            ctx.Web.AddFieldToContentTypeById(carContentType, carColorFieldId.ToString());
            ctx.Web.CreateList(ListTemplateType.GenericList, "Cars", false, true, "lists/cars", true);
            ctx.Web.AddContentTypeToListById("Cars", carContentType, true);
        }
Exemplo n.º 12
0
 public FieldChoiceInformation(FieldChoice field) : base(field)
 {
     EditFormat = (uint)field.EditFormat;
 }
Exemplo n.º 13
0
        static void UploadFile(ClientContext clientContext, DataTable data, String fileName)
        {
            string Reason       = "";
            string UploadStatus = "";
            string FilePath     = "";
            List   list         = clientContext.Web.Lists.GetByTitle(Constant.RootFolder);

            clientContext.Load(list);
            clientContext.ExecuteQuery();
            Folder newFolder = list.RootFolder;

            clientContext.Load(newFolder);
            clientContext.ExecuteQuery();
            foreach (DataRow row in data.Rows)  //here feteching the all rows from datatble
            {
                bool flag  = true;
                long bytes = 0;
                try
                {
                    FilePath = row[0].ToString();
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(FilePath);
                    string             FileType = fileInfo.Extension;
                    //try
                    //{
                    if (fileInfo.Exists)                             //read the file size
                    {
                        bytes = fileInfo.Length;
                    }
                    else
                    {
                        throw new EX.FileNotFoundException("File not found");
                    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    UploadStatus = "Failed";
                    //    Reason = "File not exist on given path";
                    //    flag = false;
                    //}
                    if (flag == true && (bytes < 10000000)) //checking the file size before upload & file size is given range or not
                    {
                        int    FileNameStarts        = FilePath.LastIndexOf("\\");
                        string Filename              = FilePath.Substring(FileNameStarts + 1); //spliting the file name from file path
                        string CreatedBy             = row[1].ToString();                      //adding the column to the files
                        string depart                = row[2].ToString();
                        string Status                = (row[3]).ToString();
                        FileCreationInformation File = new FileCreationInformation(); //Uploading the file to sharepoint library
                        File.Content   = System.IO.File.ReadAllBytes(FilePath);
                        File.Url       = Filename;
                        File.Overwrite = true;
                        File fileToUpload = newFolder.Files.Add(File);
                        clientContext.Load(fileToUpload);
                        clientContext.ExecuteQuery();
                        var newItem = fileToUpload.ListItemAllFields;   //creating the column items to the file
                        newItem["CreatedByThisFile"] = CreatedBy.ToString();
                        newItem["Size"]        = fileToUpload.Length;
                        newItem["Departement"] = depart;
                        Microsoft.SharePoint.Client.Field field = list.Fields.GetByInternalNameOrTitle("Status"); //here reading the status of the file
                        clientContext.Load(field);
                        clientContext.ExecuteQuery();
                        FieldChoice fieldChoices = clientContext.CastTo <FieldChoice>(field);
                        string[]    StatusArray  = Status.Split(',');
                        string      finalyStatus = "";
                        for (int count = 0; count < StatusArray.Length; count++)
                        {
                            if (fieldChoices.Choices.Contains(StatusArray[count]))
                            {
                                if (count == StatusArray.Length - 1)
                                {
                                    finalyStatus = StatusArray[count];
                                }
                                else
                                {
                                    finalyStatus = StatusArray[count] + ";";
                                }
                            }
                        }
                        newItem["Status"]     = finalyStatus;
                        newItem["TypeOfFile"] = FileType.ToString();
                        newItem.Update();
                        clientContext.ExecuteQuery();
                        // Console.WriteLine(Filename+" is Done");
                        UploadStatus = "Success";
                        Reason       = "";
                    }
                    else if (flag)
                    {
                        throw new Exception("File Size to high");
                        //Reason = "File size is to high";
                        //UploadStatus = "Failed";
                    }
                    //after taking the all fields from file then update the excel sheet througth datatble
                }
                catch (EX.FileNotFoundException ex)
                {
                    UploadStatus = "Failed";
                    Reason       = ex.Message;
                    LogClass.RecordException(ex);
                }
                catch (Exception ex)
                {
                    UploadStatus = "Failed";
                    Reason       = ex.Message;
                    LogClass.RecordException(ex);
                }
                UpdateDataTable(FilePath, Reason, UploadStatus);
            }
        }
Exemplo n.º 14
0
        private bool UpdatLibraryData(DataRow row)
        {
            try
            {
                string Listname   = "MyDocuments";
                List   list       = ClientCntx.Web.Lists.GetByTitle(Listname);
                string FileName   = row[Settings.FilePath].ToString();
                string FileStatus = row[Settings.FileStatus].ToString();
                string CreatedBy  = row[Settings.CreatedBy].ToString();
                string Department = row[Settings.Department].ToString();

                System.IO.FileInfo Fileinfo = new System.IO.FileInfo(FileName);
                User user = SiteUsers.GetByEmail(CreatedBy);
                ClientCntx.Load(user);
                ClientCntx.ExecuteQuery();

                if (Fileinfo.Exists)
                {
                    double Filesize = (Fileinfo.Length / 1e+6);
                    FileSize = Filesize + "mb";
                    if (Fileinfo.Length < Settings.MaxSIze && Fileinfo.Length > Settings.MinSize)
                    {
                        ListItem DepartmentItem             = GetDepartment(Department);
                        FileCreationInformation Fcreateinfo = new FileCreationInformation();
                        Fcreateinfo.Url       = Fileinfo.Name;
                        Fcreateinfo.Content   = System.IO.File.ReadAllBytes(FileName);
                        Fcreateinfo.Overwrite = true;
                        File FileToUpload = list.RootFolder.Files.Add(Fcreateinfo);
                        ClientCntx.Load(list);
                        ClientCntx.ExecuteQuery();

                        try
                        {
                            ListItem Listitem = FileToUpload.ListItemAllFields;

                            Field       field  = list.Fields.GetByTitle("FIle_Status");
                            FieldChoice choice = ClientCntx.CastTo <FieldChoice>(field);
                            ClientCntx.Load(choice);
                            ClientCntx.ExecuteQuery();
                            string[] MyStatus     = FileStatus.ToUpper().Split(',');
                            string   StatusUpload = string.Empty;
                            for (int choicecount = 0; choicecount < MyStatus.Length; choicecount++)
                            {
                                if (choice.Choices.Contains(MyStatus[choicecount].Trim()))
                                {
                                    if (choicecount == MyStatus.Length - 1)
                                    {
                                        StatusUpload = StatusUpload + MyStatus[choicecount];
                                    }
                                    else
                                    {
                                        StatusUpload = StatusUpload + MyStatus[choicecount] + ";";
                                    }
                                }
                            }

                            Listitem["File_Type"]       = System.IO.Path.GetExtension(FileName);
                            Listitem["FIle_Status"]     = StatusUpload;
                            Listitem["FileCreatedBy"]   = user.Title;
                            Listitem["Department_Name"] = DepartmentItem.Id;
                            Listitem.Update();
                            ClientCntx.ExecuteQuery();
                            Reason = "NA";
                            Status = true;
                        }
                        catch (Exception ex)
                        {
                            Reason = "Department not found";
                            Console.WriteLine("Department not found");
                            WriteToLog.WriteToLogs(ex);
                        }
                    }
                    else
                    {
                        if (Fileinfo.Length < Settings.MinSize)
                        {
                            Reason = "File size is Less than Required file size";
                            Console.WriteLine(Reason);
                        }
                        else
                        {
                            Reason = "File size is more than Required file size";
                            Console.WriteLine(Reason);
                        }
                    }
                }
                else
                {
                    Reason = "File Does not exist";

                    Console.WriteLine(Reason);
                }
            }
            catch (Exception ex)
            {
                Reason   = "User Does not exist";
                FileSize = "";
                Status   = false;
                WriteToLog.WriteToLogs(ex);
            }

            return(Status);
        }
Exemplo n.º 15
0
        /***********************Uploading Data and Files in Specific List Library*******************/
        public static void UploadFilesAndData(ClientContext clientContext, System.Data.DataTable dataTable)
        {
            Application App1 = new Application();
            //if (System.IO.File.Exists(@"D:\FileUploadData.xlsx"))
            //{
            //    Console.WriteLine("Exists file");
            //}

            Workbook WorkBook1 = (Microsoft.Office.Interop.Excel.Workbook)(App1.Workbooks._Open(ApplicationConfiguration.LocalFilePath + DiskFilePath, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                                                                                                System.Reflection.Missing.Value, System.Reflection.Missing.Value));

            //int NumberOfWorkbooks = App1.Workbooks.Count;
            Microsoft.Office.Interop.Excel.Worksheet Sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)WorkBook1.Worksheets[1];
            //int NumberOfSheets = WorkBook1.Worksheets.Count;

            try
            {
                if (dataTable.Rows.Count > 0)
                {
                    Console.WriteLine("-------------------Uploading file--------------------");

                    List ExcelFile = clientContext.Web.Lists.GetByTitle("FileUpload");
                    clientContext.Load(ExcelFile);
                    clientContext.ExecuteQuery();

                    Console.WriteLine("List name " + ExcelFile.Title + " desc :" + ExcelFile.Description);

                    /**************Get All Users of Site**************/
                    UserCollection SiteUsers = clientContext.Web.SiteUsers;
                    clientContext.Load(SiteUsers);
                    clientContext.ExecuteQuery();

                    for (int Count = 0; Count < dataTable.Rows.Count; Count++)
                    {
                        try
                        {
                            if (Count > -1)
                            {
                                string LocalFilePath  = dataTable.Rows[Count]["FilePath"].ToString();
                                string StatusList     = dataTable.Rows[Count]["Status"].ToString();
                                string CreatedByEmail = dataTable.Rows[Count]["Created By"].ToString();
                                string Department     = dataTable.Rows[Count]["Dept"].ToString();
                                string UploadStatus   = dataTable.Rows[Count]["Upload Status"].ToString();
                                string Reason         = dataTable.Rows[Count]["Reason"].ToString();
                                long   SizeOfFile     = new System.IO.FileInfo(LocalFilePath.Replace(@"\\", @"\")).Length;

                                /****************Get All Users for that site*************/
                                User CreatedUserObj = SiteUsers.GetByEmail(CreatedByEmail);
                                clientContext.Load(CreatedUserObj);
                                clientContext.ExecuteQuery();

                                /****************Get All Departments from Department List and filter the data*************/
                                List DepartmentList = clientContext.Web.Lists.GetByTitle("Department");
                                clientContext.Load(DepartmentList);
                                clientContext.ExecuteQuery();

                                CamlQuery DepartmentQuery = new CamlQuery();
                                DepartmentQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Department'/><Value Type = 'Text'>" + Department.Trim() + "</Value></Eq></Where></Query><RowLimit></RowLimit></View> ";

                                //var fs = new FileStream(filepath, FileMode.Open);
                                try
                                {
                                    ListItemCollection GetDepartmentByName = DepartmentList.GetItems(DepartmentQuery);
                                    clientContext.Load(GetDepartmentByName);
                                    clientContext.ExecuteQuery();
                                    if (GetDepartmentByName != null && GetDepartmentByName.Count > 0)
                                    {
                                        if (SizeOfFile > 100 && SizeOfFile < 2097150)
                                        {
                                            FileCreationInformation FileToUpload = new FileCreationInformation();
                                            FileToUpload.Content   = System.IO.File.ReadAllBytes(LocalFilePath.Replace(@"\\", @"\"));
                                            FileToUpload.Overwrite = true;
                                            FileToUpload.Url       = Path.Combine("FileUpload/", Path.GetFileName(LocalFilePath.Replace(@"\\", @"\")));
                                            Microsoft.SharePoint.Client.File UploadFile = ExcelFile.RootFolder.Files.Add(FileToUpload);

                                            clientContext.Load(UploadFile);
                                            clientContext.ExecuteQuery();

                                            ListItem UploadItem = UploadFile.ListItemAllFields;

                                            Field Choice = ExcelFile.Fields.GetByInternalNameOrTitle("Status");
                                            clientContext.Load(Choice);
                                            clientContext.ExecuteQuery();
                                            FieldChoice StatusFieldChoice = clientContext.CastTo <FieldChoice>(Choice);
                                            clientContext.Load(StatusFieldChoice);
                                            clientContext.ExecuteQuery();
                                            string[] StatusArray            = StatusList.Split(',');
                                            string   StatusPutSelectedValue = string.Empty;
                                            for (int statusCount = 0; statusCount < StatusArray.Length; statusCount++)
                                            {
                                                if (StatusFieldChoice.Choices.Contains(StatusArray[statusCount]))
                                                {
                                                    if (statusCount == StatusArray.Length - 1)
                                                    {
                                                        StatusPutSelectedValue += StatusArray[statusCount];
                                                    }
                                                    else
                                                    {
                                                        StatusPutSelectedValue += StatusArray[statusCount] + ";";
                                                    }
                                                }
                                            }

                                            UploadItem["CreatedBy"]  = CreatedUserObj.Title;
                                            UploadItem["SizeOfFile"] = SizeOfFile;
                                            UploadItem["FileType"]   = Path.GetExtension(LocalFilePath.Replace(@"\\", @"\"));
                                            UploadItem["Status"]     = StatusPutSelectedValue;
                                            UploadItem["Dept"]       = GetDepartmentByName[0].Id.ToString();;

                                            UploadItem.Update();
                                            clientContext.ExecuteQuery();
                                            Sheet1.Cells[Count + 2, 5] = "Success";
                                            Sheet1.Cells[Count + 2, 6] = "N/A";
                                        }
                                        else
                                        {
                                            Console.WriteLine("File : " + Path.GetFileName(LocalFilePath.Replace(@"\\", @"\")) + " could not be uploaded since file size is not in range");
                                            Sheet1.Cells[Count + 2, 5] = "Error";
                                            Sheet1.Cells[Count + 2, 6] = "File Size Exceeds Specified Range";
                                            /*************Create Custom Exception Object**********/
                                            ApplicationCustomException FileSizeException = new ApplicationCustomException("File Size Exceeds Specified Range");
                                            ErrorWriteToLog.WriteToLogFile(FileSizeException);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Department Not Found in Department List");
                                        Sheet1.Cells[Count + 2, 5] = "Error";
                                        Sheet1.Cells[Count + 2, 6] = "Department Not Found in Department List";
                                        /*************Create Custom Exception Object**********/
                                        ApplicationCustomException DepartmentNotFoundException = new ApplicationCustomException("File Size Exceeds Specified Range");
                                        ErrorWriteToLog.WriteToLogFile(DepartmentNotFoundException);
                                    }
                                }
                                catch (Exception exe)
                                {
                                    Console.WriteLine("Exception : " + exe.Message);
                                    ErrorWriteToLog.WriteToLogFile(exe);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception : " + ex);
                            Sheet1.Cells[Count + 2, 5] = "Error";
                            Sheet1.Cells[Count + 2, 6] = ex.Message;
                            ErrorWriteToLog.WriteToLogFile(ex);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine("Exception :" + ee.Message);
                ErrorWriteToLog.WriteToLogFile(ee);
            }

            WorkBook1.Save();

            WorkBook1.Close(true, ApplicationConfiguration.LocalFilePath + DiskFilePath, System.Reflection.Missing.Value);
            App1.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(App1);

            Marshal.ReleaseComObject(Sheet1);
            Marshal.ReleaseComObject(WorkBook1);
            Marshal.ReleaseComObject(App1);
        }
Exemplo n.º 16
0
        ///// <summary>
        ///// Creates the sp group.
        ///// </summary>
        ///// <param name="role">The role.</param>
        //private void CreateSPGroup(string role)
        //{
        //    try
        //    {
        //        Group addgroup = null;
        //        try
        //        {
        //            addgroup = this.context.Web.SiteGroups.GetByName(role);
        //            this.context.Load(addgroup);
        //            this.context.ExecuteQuery();
        //        }
        //        catch
        //        {
        //            Logger.Error(role + " Group not found.Creating Group now.");
        //            addgroup = null;
        //        }

        //        if (addgroup == null)
        //        {
        //            //this.web.BreakRoleInheritance(true, false);
        //            User owner = this.web.EnsureUser("*****@*****.**");
        //            //   User member = this.web.EnsureUser("*****@*****.**");

        //            GroupCreationInformation groupCreationInfo = new GroupCreationInformation();
        //            groupCreationInfo.Title = role;
        //            groupCreationInfo.Description = "Group Name : " + role;

        //            Group group = this.web.SiteGroups.Add(groupCreationInfo);
        //            group.Owner = owner;
        //            //  group.Users.AddUser(member);
        //            group.Update();
        //            this.context.ExecuteQuery();

        //            // Get the Role Definition (Permission Level)
        //            var customFullControlRoleDefinition = this.web.RoleDefinitions.GetByName("Contribute");
        //            this.context.Load(customFullControlRoleDefinition);
        //            this.context.ExecuteQuery();

        //            // Add it to the Role Definition Binding Collection
        //            RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(this.context);
        //            collRDB.Add(this.web.RoleDefinitions.GetByName("Contribute"));

        //            // Bind the Newly Created Permission Level to the new User Group
        //            this.web.RoleAssignments.Add(group, collRDB);

        //            this.context.Load(group);
        //            this.context.ExecuteQuery();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.Error("Error while adding Group name =" + role + " Message =" + ex.Message + " StackTrace = " + ex.StackTrace);
        //    }
        //}

        ///// <summary>
        ///// Deletes the sp group.
        ///// </summary>
        ///// <param name="role">The role.</param>
        //private void DeleteSPGroup(string role)
        //{
        //    Group deletegroup = null;
        //    try
        //    {
        //        deletegroup = this.context.Web.SiteGroups.GetByName(role);
        //        this.context.Load(deletegroup);
        //        this.context.ExecuteQuery();
        //    }
        //    catch
        //    {
        //        Logger.Error(role + " Group could not found in sharepoint Group.");
        //        deletegroup = null;
        //    }
        //    try
        //    {
        //        if (deletegroup != null)
        //        {
        //            this.web.RoleAssignments.GetByPrincipal(deletegroup).DeleteObject();
        //            this.web.Update();
        //            this.context.ExecuteQuery();

        //            GroupCollection groupColl = this.web.SiteGroups;
        //            groupColl.Remove(deletegroup);
        //            this.context.ExecuteQuery();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Logger.Error("Error while deleting Group name =" + role + " Message =" + ex.Message + " StackTrace = " + ex.StackTrace);
        //    }
        //}

        /// <summary>
        /// Deletes the role.
        /// </summary>
        /// <param name="roleID">The role identifier.</param>
        /// <returns></returns>
        public ActionStatus DeleteRole(int roleID)
        {
            ActionStatus status = new ActionStatus();

            try
            {
                string roleName = string.Empty;
                if (roleID > 0)
                {
                    List     roleMaster = this.web.Lists.GetByTitle(Masters.ROLEMASTER);
                    ListItem item       = roleMaster.GetItemById(roleID);
                    this.context.Load(item);
                    this.context.ExecuteQuery();
                    if (item != null)
                    {
                        roleName = Convert.ToString(item["Role"]);

                        List      emplist      = this.web.Lists.GetByTitle(Masters.APPROVERMASTER);
                        CamlQuery camlEmpQuery = new CamlQuery();
                        camlEmpQuery.ViewXml = @"<View>
                                       <Query>
                                           <Where>
                                              <Eq>
                                                 <FieldRef Name='Role' />
                                                 <Value Type='Choice'>" + roleName + @"</Value>
                                              </Eq>
                                           </Where>
                                        </Query>
                                   </View>";
                        ListItemCollection empitems = emplist.GetItems(camlEmpQuery);
                        this.context.Load(empitems);
                        this.context.ExecuteQuery();
                        if (empitems != null && empitems.Count > 0)
                        {
                            status.IsSucceed = false;
                            status.Messages.Add("You can't delete this role because " + empitems.Count + " employee(s) are already assigned to this role.To delete this role please remove/reassign the other role to employee(s).");
                        }
                        else if (empitems == null || empitems.Count == 0)
                        {
                            List      screenMapMaster = this.web.Lists.GetByTitle(ICCPListNames.ROLESCREENMAPPING);
                            CamlQuery camlQuery       = new CamlQuery();
                            camlQuery.ViewXml = @"<View>
                                       <Query>
                                           <Where>
                                              <Eq>
                                                 <FieldRef Name='RoleID' />
                                                 <Value Type='Lookup'>" + roleName + @"</Value>
                                              </Eq>
                                           </Where>
                                        </Query>
                                   </View>";
                            ListItemCollection items = screenMapMaster.GetItems(camlQuery);
                            this.context.Load(items);
                            this.context.ExecuteQuery();
                            if (items != null && items.Count > 0)
                            {
                                foreach (ListItem deleteitem in items.ToList())
                                {
                                    deleteitem.DeleteObject();
                                }
                                this.context.ExecuteQuery();
                            }
                            if (items != null && items.Count == 0)
                            {
                                item.DeleteObject();
                                this.context.ExecuteQuery();
                                Field       rolefield   = emplist.Fields.GetByTitle("Role");
                                FieldChoice fieldChoice = this.context.CastTo <FieldChoice>(rolefield);
                                this.context.Load(fieldChoice);
                                this.context.ExecuteQuery();

                                List <string> options = new List <string>(fieldChoice.Choices);
                                options.Remove(roleName);
                                fieldChoice.Choices = options.ToArray();
                                fieldChoice.Update();
                                this.context.ExecuteQuery();

                                // this.DeleteSPGroup(Convert.ToString(roleName));

                                status.IsSucceed = true;
                                status.Messages.Add("Role Deleted Successfully.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status.IsSucceed = true;
                status.Messages.Add("Sorry! Error while delete Role.");
                Logger.Error("Error while delete role having roleId =" + roleID + " Message =" + ex.Message + " StackTrace = " + ex.StackTrace);
            }
            return(status);
        }
        public async Task <IActionResult> Save(IFormCollection form)
        {
            try
            {
                JObject parameters = form.ToJObject();
                string  recordID   = parameters.GetValue("RecordId").ToString();
                if (recordID != null)
                {
                    Record r = await db.Records.Include(m => m.TextData).ThenInclude(td => td.FormField)
                               .Include(u => u.NumericData).ThenInclude(td => td.FormField)
                               .Include(u => u.BooleanData).ThenInclude(td => td.FormField)
                               .Include(u => u.Form).ThenInclude(m => m.FormFormFields).ThenInclude(fff => fff.FormField)
                               .Include(u => u.Form).ThenInclude(m => m.FormFormFields).ThenInclude(fff => fff.FormField).ThenInclude(mo => mo.PublicMotherFormField)
                               .Where(m => m.RecordId == new Guid(recordID)).FirstOrDefaultAsync();

                    foreach (FormField ff in r.Form.FormFormFields.Select(fff => fff.FormField))
                    {
                        if (ff.FieldTypeId == FieldTypeEnum.Text)
                        {
                            if (parameters.GetValue("Field_" + ff.FormFieldId) != null)
                            {
                                string   newValue = parameters.GetValue("Field_" + ff.FormFieldId).ToString();
                                TextData td       = r.TextData.Where(m => m.FormField.FormFieldId == ff.FormFieldId).FirstOrDefault();
                                if (td == null)
                                {
                                    td = new TextData()
                                    {
                                        FormField = ff, Record = r, Id = Guid.NewGuid(), Value = newValue
                                    };
                                    r.TextData.Add(td);
                                    db.Entry(td).State = EntityState.Added;
                                    db.Entry(r).State  = EntityState.Modified;
                                }
                                else
                                {
                                    td.Value           = newValue;
                                    db.Entry(td).State = EntityState.Modified;
                                }
                            }
                        }
                        else if (ff.FieldTypeId == FieldTypeEnum.DateTime)
                        {
                            if (parameters.GetValue("Field_" + ff.FormFieldId) != null)
                            {
                                string   newValue = parameters.GetValue("Field_" + ff.FormFieldId).ToString();
                                DateTime myDT;
                                myDT = DateTime.ParseExact(newValue.Replace("{0:", " ").Replace("}", ""), formats, CultureInfo.InvariantCulture, DateTimeStyles.None);


                                string zulu = myDT
                                              .ToString("yyyy-MM-ddTHH\\:mm\\:sszzz");

                                TextData td = r.TextData.Where(m => m.FormField.FormFieldId == ff.FormFieldId).FirstOrDefault();
                                if (td == null)
                                {
                                    td = new TextData()
                                    {
                                        FormField = ff, Record = r, Id = Guid.NewGuid(), Value = zulu
                                    };
                                    r.TextData.Add(td);
                                    db.Entry(td).State = EntityState.Added;
                                    db.Entry(r).State  = EntityState.Modified;
                                }
                                else
                                {
                                    td.Value           = zulu;
                                    db.Entry(td).State = EntityState.Modified;
                                }
                            }
                        }
                        else if (ff.FieldTypeId == FieldTypeEnum.Choice)
                        {
                            if (parameters.GetValue("Field_" + ff.FormFieldId) != null)
                            {
                                string newValue = parameters.GetValue("Field_" + ff.FormFieldId).ToString();
                                await db.Entry(ff).Collection(m => m.FieldChoices).LoadAsync();

                                FieldChoice fc = ff.FieldChoices.Where(m => m.Text == newValue).FirstOrDefault();
                                if (ff.PublicMotherFormField != null)
                                {
                                    await db.Entry(ff.PublicMotherFormField).Collection(m => m.FieldChoices).LoadAsync();

                                    fc = ff.PublicMotherFormField.FieldChoices.Where(m => m.Text == newValue).FirstOrDefault();
                                }
                                TextData td = r.TextData.Where(m => m.FormField.FormFieldId == ff.FormFieldId).FirstOrDefault();
                                if (td == null)
                                {
                                    td = new TextData()
                                    {
                                        FormField = ff, Record = r, Id = Guid.NewGuid(), Value = newValue, FieldChoice = fc
                                    };
                                    r.TextData.Add(td);
                                    db.Entry(td).State = EntityState.Added;
                                    db.Entry(r).State  = EntityState.Modified;
                                }
                                else
                                {
                                    td.Value           = newValue;
                                    td.FieldChoice     = fc;
                                    db.Entry(td).State = EntityState.Modified;
                                }
                            }
                        }
                        else if (ff.FieldTypeId == FieldTypeEnum.Boolean)
                        {
                            if (parameters.GetValue("Field_" + ff.FormFieldId) != null)
                            {
                                bool        newValue = (bool)parameters.GetValue("Field_" + ff.FormFieldId).ToObject <bool>();
                                BooleanData bd       = r.BooleanData.Where(m => m.FormField.FormFieldId == ff.FormFieldId).FirstOrDefault();
                                if (bd == null)
                                {
                                    bd = new BooleanData()
                                    {
                                        FormField = ff, Record = r, Id = Guid.NewGuid(), Value = newValue
                                    };
                                    r.BooleanData.Add(bd);
                                    db.Entry(bd).State = EntityState.Added;
                                    db.Entry(r).State  = EntityState.Modified;
                                }
                                else
                                {
                                    bd.Value           = newValue;
                                    db.Entry(bd).State = EntityState.Modified;
                                }
                            }
                        }
                    }

                    User user = Helpers.UserHelper.GetCurrentUser(User, db);

                    ChangeLog cl = new ChangeLog()
                    {
                        Log = user.UserId + " changed the record", User = user
                    };
                    ChangeLogRecord clr = new ChangeLogRecord()
                    {
                        Record = r, ChangeLog = cl
                    };
                    if (r.RecordChangeLogs == null)
                    {
                        r.RecordChangeLogs = new List <ChangeLogRecord>();
                    }
                    r.RecordChangeLogs.Add(clr);

                    await db.SaveChangesAsync();
                }
                return(Content("OK"));
            }
            catch (Exception e)
            {
                return(Content(e.ToString()));;
            }
        }
Exemplo n.º 18
0
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();
              Console.WriteLine("Creating site columns");

              fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
              fieldProductCode.EnforceUniqueValues = true;
              fieldProductCode.Indexed = true;
              fieldProductCode.Required = true;
              fieldProductCode.Update();
              clientContext.ExecuteQuery();
              clientContext.Load(fieldProductCode);
              clientContext.ExecuteQuery();

              fieldProductListPrice = clientContext.CastTo<FieldCurrency>(CreateSiteColumn("ProductListPrice", "List Price", "Currency"));

              fieldProductCategory = clientContext.CastTo<FieldChoice>(CreateSiteColumn("ProductCategory", "Product Category", "Choice"));
              string[] choicesProductCategory = { "Action Figures", "Arts and Crafts", "Vehicles and Remote Control" };
              fieldProductCategory.Choices = choicesProductCategory;
              fieldProductCategory.Update();
              clientContext.ExecuteQuery();

              fieldProductColor = clientContext.CastTo<FieldChoice>(CreateSiteColumn("ProductColor", "Product Color", "Choice"));
              string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
              fieldProductColor.Choices = choicesProductColor;
              fieldProductColor.Update();
              clientContext.ExecuteQuery();

              fieldMinimumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));

              fieldMaximumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
        }
Exemplo n.º 19
0
        public static void CreateBookCT(ClientContext ctx)
        {
            string bookCT = "0x01000E870749A9444905BB8A362E475B0798";

            Web web = ctx.Site.RootWeb;

            //web.GetListByTitle("Books2").DeleteObject();
            //ctx.ExecuteQuery();
            //web.DeleteContentTypeById(bookCT);

            if (!web.ContentTypeExistsById(bookCT))
            {
                web.CreateContentType("David Books", bookCT, "Davids ContentType");
            }

            string bookTypeFieldId = "{DBB24705-0DEA-4C4F-8C2A-95CB6F0DE25E}";

            if (!web.FieldExistsById(new Guid(bookTypeFieldId)))
            {
                FieldCreationInformation info = new FieldCreationInformation(FieldType.Choice);
                info.Id           = bookTypeFieldId.ToGuid();
                info.InternalName = "DAV_BookType";
                info.DisplayName  = "Book Type";
                info.Group        = "Tims Columns";


                FieldChoice field = web.CreateField <FieldChoice>(info);
                field.Choices = new string[] { "Romance", "Drama", "Horror", "Thriller" };
                field.Update();
                ctx.ExecuteQuery();
            }


            string authorFieldId = "{D6996667-0BEA-4C9F-9904-DEB21CC5AA84}";

            if (!web.FieldExistsById(new Guid(authorFieldId)))
            {
                FieldCreationInformation info = new FieldCreationInformation(FieldType.Text);
                info.Id           = authorFieldId.ToGuid();
                info.InternalName = "DAV_Author";
                info.DisplayName  = "Author";
                info.Group        = "Tims Columns";


                Field field = web.CreateField(info);
            }

            string releaseDateFieldId = "{84716863-06CA-4D31-BAA0-7D099FC501E7}";

            if (!web.FieldExistsById(new Guid(releaseDateFieldId)))
            {
                FieldCreationInformation info = new FieldCreationInformation(FieldType.DateTime);
                info.Id           = releaseDateFieldId.ToGuid();
                info.InternalName = "DAV_Realesedate";
                info.DisplayName  = "ReleaseDate";
                info.Group        = "Tims Columns";


                FieldDateTime field = web.CreateField <FieldDateTime>(info);
                field.DisplayFormat = DateTimeFieldFormatType.DateOnly;
                field.Update();
                ctx.ExecuteQuery();
            }


            string descriptionDateFieldId = "{4BD3F599-4D5C-412D-8431-6ECD36AEB015}";

            // web.RemoveFieldById(descriptionDateFieldId);

            if (!web.FieldExistsById(new Guid(descriptionDateFieldId)))
            {
                FieldCreationInformation info = new FieldCreationInformation(FieldType.Note);
                info.Id           = descriptionDateFieldId.ToGuid();
                info.InternalName = "DAV_description";
                info.DisplayName  = "Description";
                info.Group        = "Tims Columns";
                info.Required     = true;
                FieldMultiLineText field = web.CreateField <FieldMultiLineText>(info);

                field.RichText       = true;
                field.NumberOfLines  = 10;
                field.AllowHyperlink = true;
                field.Update();
                ctx.ExecuteQuery();
            }

            web.AddFieldToContentTypeById(bookCT, bookTypeFieldId);
            web.AddFieldToContentTypeById(bookCT, authorFieldId);
            web.AddFieldToContentTypeById(bookCT, releaseDateFieldId);
            web.AddFieldToContentTypeById(bookCT, descriptionDateFieldId, true);


            if (!web.ListExists("Books2"))
            {
                List list = web.CreateList(ListTemplateType.GenericList, "Books2", false, urlPath: "lists/books2", enableContentTypes: true);
                list.AddContentTypeToListById(bookCT, true);

                View listView = list.DefaultView;
                listView.ViewFields.Add("DAV_BookType");
                listView.ViewFields.Add("DAV_Author");
                listView.ViewFields.Add("DAV_Realesedate");
                listView.ViewFields.Add("DAV_description");
                listView.Update();
                ctx.ExecuteQueryRetry();
            }

            List bookList = web.GetListByTitle("Books2");

            ListItem item = bookList.AddItem(new ListItemCreationInformation());

            item["Title"]           = "MistBorn";
            item["DAV_BookType"]    = "Fantasy";
            item["DAV_Author"]      = "Brandon Sanderson";
            item["DAV_Realesedate"] = DateTime.Parse("2001-02-12");
            item["DAV_description"] = "This is a decription \n\n is this a new line?";

            item.Update();
            ctx.ExecuteQuery();


            //ListItemCollection items = bookList.GetItems(CamlQuery.CreateAllItemsQuery());
            //ctx.Load(items);
            //ctx.ExecuteQuery();
        }