Exemplo n.º 1
0
        private void CreateItemforForm()
        {
            FormWebPart wp = (FormWebPart)this.WebPart;

            List <BaseFieldControl> fields = new List <BaseFieldControl>();

            List <DesignDataSource> sources = new List <DesignDataSource>();

            if (!string.IsNullOrEmpty(wp.DataSourcesData))
            {
                sources = Utilities.DeserializeObject <List <DesignDataSource> >(wp.DataSourcesData);
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = SPContext.Current.Site;

                site.AllowUnsafeUpdates = true;
                foreach (DesignDataSource source in sources)
                {
                    fields    = new List <BaseFieldControl>();
                    SPWeb web = site.OpenWeb(new Guid(source.WebId));
                    web.AllowUnsafeUpdates           = true;
                    SPList list                      = web.Lists[new Guid(source.ListId)];
                    SPView view                      = list.GetView(new Guid(source.ViewId));
                    SPViewFieldCollection viewfields = view.ViewFields;

                    foreach (var viewfield in viewfields)
                    {
                        BaseFieldControl formField = (BaseFieldControl)FindControl(viewfield.ToString());
                        if (formField == null)
                        {
                            continue;
                        }

                        fields.Add(formField);
                    }

                    SPListItem item = list.Items.Add();

                    foreach (BaseFieldControl Fld in fields)
                    {
                        try
                        {
                            item[Fld.FieldName] = Fld.Value;
                        }
                        catch { };
                    }
                    UpdateUserInfo(item);

                    item.Update();

                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;
            });
        }
Exemplo n.º 2
0
        private static System.Type GetFieldRenderingControlType(SPField field)
        {
            if (field.FieldRenderingControl == null)
            {
                return(typeof(FormField));
            }
            BaseFieldControl fieldRenderingControl = field.FieldRenderingControl;

            if (fieldRenderingControl.GetType().Equals(typeof(RichTextField)))
            {
                return(typeof(NoteField));
            }
            return(fieldRenderingControl.GetType());
        }
Exemplo n.º 3
0
        private bool ValidateField(Control container, BaseFieldControl formControl)
        {
            bool valid = true;

            formControl.IsValid = true;
            List <Control> validators = FindValidators(container, formControl);

            foreach (BaseValidator validator in validators)
            {
                validator.Validate();
                if (!validator.IsValid)
                {
                    formControl.IsValid = validator.IsValid;
                    valid = validator.IsValid;
                }
            }
            return(valid);
        }
Exemplo n.º 4
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (this.item.Fields.ContainsField(this.FieldName))
         {
             this.baseControl = this.item.Fields[this.FieldName].FieldRenderingControl;
             WebPartManager currentWebPartManager = WebPartManager.GetCurrentWebPartManager(this.Page);
             if (currentWebPartManager.DisplayMode == WebPartManager.DesignDisplayMode)
             {
                 this.baseControl.ControlMode = SPControlMode.Edit;
             }
             this.Controls.Add(this.baseControl);
         }
     }
     catch (Exception)
     {
     }
 }
        public static BaseFieldControl GetFieldControlByName(
            String fieldNameToFind, SPFormContext formContext, string clientID)
        {
            foreach (Control control in formContext.FieldControlCollection)
            {
                if (control is BaseFieldControl)
                {
                    BaseFieldControl baseField = (BaseFieldControl)control;
                    String           fieldName = baseField.FieldName;
                    if ((fieldName == fieldNameToFind) &&
                        (GetIteratorByFieldControl(baseField).ClientID == clientID))
                    {
                        return(baseField);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 6
0
        internal static BaseFieldControl GetFieldControlByName(BaseFieldControl thisfield, String fieldNameToSearch)
        {
            String iteratorId = GetIteratorByFieldControl(thisfield).ClientID;

            foreach (IValidator validator in thisfield.Page.Validators)
            {
                if (validator is BaseFieldControl)
                {
                    BaseFieldControl baseField = (BaseFieldControl)validator;
                    if (baseField.FieldName == fieldNameToSearch &&
                        GetIteratorByFieldControl(baseField).ClientID == iteratorId)
                    {
                        return(baseField);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 7
0
 static string sufix(BaseFieldControl field)
 {
     if (field is BaseTextField)
     {
         return("_ctl00_TextField");
     }
     else if (field is LookupField)
     {
         return("_Lookup");
     }
     else if (field is BooleanField)
     {
         return("_ctl00_BooleanField");
     }
     else
     {
         return(string.Empty);
     }
 }
Exemplo n.º 8
0
        internal List <BaseFieldControl> FieldList(WebPart webpart)
        {
            FormWebPart wp = (FormWebPart)webpart;

            List <BaseFieldControl> fields = new List <BaseFieldControl>();

            List <DesignDataSource> sources = new List <DesignDataSource>();

            if (!string.IsNullOrEmpty(wp.DataSourcesData))
            {
                sources = Utilities.DeserializeObject <List <DesignDataSource> >(wp.DataSourcesData);
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = SPContext.Current.Site;

                foreach (DesignDataSource source in sources)
                {
                    SPWeb web   = site.OpenWeb(new Guid(source.WebId));
                    SPList list = web.Lists[new Guid(source.ListId)];
                    SPView view = list.GetView(new Guid(source.ViewId));
                    SPViewFieldCollection viewfields = view.ViewFields;

                    foreach (var viewfield in viewfields)
                    {
                        BaseFieldControl formField = (BaseFieldControl)FindControl(viewfield.ToString());
                        //formField.ControlMode = Microsoft.SharePoint.WebControls.SPControlMode.Display;
                        if (formField == null)
                        {
                            continue;
                        }

                        fields.Add(formField);
                    }
                }
            });

            return(fields);
        }
        // from Microsoft.SharePoint.Publishing.WebServices.SharepointPublishingToolboxService
        /// <summary>
        /// Gets the type of the field rendering control.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <returns></returns>
        internal static Type GetFieldRenderingControlType(this SPField field)
        {
            // Exception for the PublishingStartDate and the PublishingEndDate fields which require Context to retrieve the FieldRenderingControl
            if (field.InternalName.Equals("PublishingStartDate") || field.InternalName.Equals("PublishingExpirationDate"))
            {
                return(typeof(PublishingScheduleFieldControl));
            }

            if (field.FieldRenderingControl == null)
            {
                return(typeof(FormField));
            }

            BaseFieldControl fieldRenderingControl = field.FieldRenderingControl;

            if (!fieldRenderingControl.GetType().Equals(typeof(RichTextField)))
            {
                return(fieldRenderingControl.GetType());
            }

            return(typeof(NoteField));
        }
Exemplo n.º 10
0
        private static bool CheckFromUIValue(string fieldName, Enums.Operator op, string value, SPFormContext formContext, string clientID)
        {
            BaseFieldControl field = ValidationInjector.GetFieldControlByName(fieldName, formContext, clientID);

            // to manage the rich field UI text
            if (field is RichTextField)
            {
                string fieldVaue = ((RichTextField)field).HiddenInput.Value;

                switch (op)
                {
                case Enums.Operator.Equal:
                    return(fieldVaue.Equals(value));

                case Enums.Operator.NotEqual:
                    return(!fieldVaue.Equals(value));

                case Enums.Operator.Contains:
                    return(fieldVaue.Contains(value));

                case Enums.Operator.NotContains:
                    return(!fieldVaue.Contains(value));

                default:
                    return(false);
                }
            }
            else
            {
                if (field is LookupField)
                {
                    LookupField l = field as LookupField;
                    String      v = l.Value.ToString();
                }

                return(MatchItemValueBasedOnOperatorAndValueType(op, value, field.Value, field.Field.FieldValueType));
            }
        }
Exemplo n.º 11
0
        private void AddFormControl(SPField field, SPListItem listItem, SPList list, SPWeb spWeb)
        {
            // our table row
            HtmlTableRow  newRow      = new HtmlTableRow();
            HtmlTableCell lblCell     = new HtmlTableCell();
            HtmlTableCell controlCell = new HtmlTableCell();

            // our form control types
            TaxonomyWebTaggingControl taxonomyControl = null;
            BaseFieldControl          webControl      = null;
            DateTimeControl           dateTimeControl = null;

            using (SPSite site = list.ParentWeb.Site)
            {
                using (SPWeb web = site.OpenWeb(spWeb.ID))
                {
                    if (field.FieldRenderingControl != null && !skipField(field))
                    {
                        //add our label to the table
                        System.Web.UI.WebControls.Label newLabel = new System.Web.UI.WebControls.Label();
                        newLabel.Width = Unit.Pixel(150);
                        newLabel.Text  = field.Title;
                        lblCell.Controls.Add(newLabel);
                        newRow.Cells.Add(lblCell);

                        try
                        {
                            switch (field.FieldRenderingControl.GetType().Name)
                            {
                            case ("DateTimeField"):
                                dateTimeControl          = new DateTimeControl();
                                dateTimeControl.DateOnly = true;
                                dateTimeControl.ID       = string.Format("ctrl_{0}", field.InternalName);
                                break;

                            case ("TaxonomyFieldControl"):
                                TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site);
                                var             store   = session.TermStores[0];

                                taxonomyControl            = new TaxonomyWebTaggingControl();
                                taxonomyControl.IsMulti    = true;
                                taxonomyControl.IsAddTerms = true;
                                taxonomyControl.TermSetId.Add(session.TermStores[0].Id);
                                taxonomyControl.ID          = string.Format("ctrl_{0}", field.InternalName);
                                taxonomyControl.FieldName   = field.Title;
                                taxonomyControl.FieldId     = field.Id.ToString();
                                taxonomyControl.SSPList     = ((TaxonomyField)field).SspId.ToString();
                                taxonomyControl.AnchorId    = ((TaxonomyField)field).AnchorId;
                                taxonomyControl.TermSetList = ((TaxonomyField)field).TermSetId.ToString();
                                break;

                            default:
                                webControl             = field.FieldRenderingControl;
                                webControl.ID          = string.Format("ctrl_{0}", field.InternalName);
                                webControl.ControlMode = SPControlMode.New;
                                webControl.ListId      = list.ID;
                                webControl.FieldName   = field.InternalName;
                                SPContext Context = SPContext.GetContext(HttpContext.Current, list.Items.GetItemById(listItem.ID).ID, list.ID, web);
                                webControl.RenderContext = Context;
                                webControl.ItemContext   = Context;
                                break;
                            }

                            //add our new row with controls to our placeholder
                            phDynamicFormControls.Controls.Add(newRow);
                            // add the cell into our row
                            newRow.Cells.Add(controlCell);
                            // add the row to the table
                            phDynamicFormControls.Controls.Add(newRow);
                            if (webControl != null)
                            {
                                controlCell.Controls.Add(webControl);
                            }
                            else if (taxonomyControl != null)
                            {
                                controlCell.Controls.Add(taxonomyControl);
                            }
                            else if (dateTimeControl != null)
                            {
                                controlCell.Controls.Add(dateTimeControl);
                            }
                        }
                        catch (Exception ex)
                        { }
                    }
                }
            }
        }
Exemplo n.º 12
0
 internal static ListFieldIterator GetIteratorByFieldControl(BaseFieldControl fieldControl)
 {
     return((Microsoft.SharePoint.WebControls.ListFieldIterator)fieldControl.Parent.Parent.Parent.Parent.Parent);
 }
Exemplo n.º 13
0
        internal static List <ListItem> GetAvailableValues(CascadingLookupField f, BaseFieldControl thisfield)
        {
            List <ListItem>   _v    = null;
            List <SPListItem> items = new List <SPListItem>();
            Guid fId = new Guid(f.LookupField);

            SPList lookupList = SPContext.Current.Web.Lists[new Guid(f.LookupList)];

            try
            {
                if (f.QueryFilter != null)
                {
                    SPQuery query = new SPQuery();
                    query.Query = f.QueryFilter.Query;

                    Regex regex = new Regex(@"\[(.[^\[\]]+)");

                    foreach (string coluna in regex.Matches(query.Query).OfType <Match>().Select(m => m.Groups[1].Value)
                             .Where(m => m.ToUpper() != "HOJE" && m.ToUpper() != "EU"))
                    {
                        BaseFieldControl ctr = GetFieldControlByName(thisfield, coluna);

                        if (!(ctr is MultipleCascadingLookupFieldControl) && !(ctr is CascadingLookupFieldControl) && ctr.Controls[0] != null)
                        {
                            if (ctr.Controls[0] is ListControl)
                            {
                                (ctr.Controls[0] as ListControl).AutoPostBack = true;
                            }
                            else if (ctr.Controls[0] is TextBox)
                            {
                                (ctr.Controls[0] as TextBox).AutoPostBack = true;
                            }
                        }

                        string value = string.Empty;

                        if (ctr != null)
                        {
                            if (ctr.Value is SPFieldLookupValue)
                            {
                                value = ((SPFieldLookupValue)ctr.Value).LookupId.ToString();
                            }
                            else
                            {
                                value = ctr.Value.ToString();
                            }
                        }
                        else if (SPContext.Current.ListItem != null)
                        {
                            value = SPContext.Current.ListItem[coluna].ToString();
                        }

                        query.Query = query.Query.Replace(string.Format("[{0}]", coluna), value);
                    }

                    items = lookupList.GetItems(query).OfType <SPListItem>().ToList();
                }
                else
                {
                    items = lookupList.Items.OfType <SPListItem>().ToList();
                }
            }
            catch { }
            //if (items.Count <= 0) { items = lookupList.Items.OfType<SPListItem>().ToList(); }
            try
            {
                if (items.Count > 0)
                {
                    _v = items
                         .Cast <SPListItem>()
                         .Where(e => e[e.Fields[fId].InternalName] != null)
                         .Select(e => new ListItem((
                                                       e.Fields[fId].GetFieldValueAsText(e[fId])), e.ID.ToString()))
                         .ToList <ListItem>();
                }
            }
            catch { }
            return(_v);
        }
		public static SPListItemVersion GetRequestedVersion(BaseFieldControl fieldControl)
		{
			string s = fieldControl.Page.Request.QueryString["VersionNo"];

			if (s != null)
			{
				try
				{
					int versionId = Int32.Parse(s);
					return fieldControl.ListItem.Versions.GetVersionFromID(versionId);
				}
				catch
				{
					return null;
				}
			}
			else
			{
				// No version specified so return 
				// most current version
				return fieldControl.ListItem.Versions[0];
			}
		}
        public string GetValueFromProperty(SPField field, string fieldStatus, SPControlMode controlMode, bool isViewOrAlert)
        {
            SPList  currentList;
            SPItem  currentItem;
            SPField currentField;

            if (isViewOrAlert)
            {
                currentList  = field.ParentList;
                currentField = field;
            }
            else
            {
                BaseFieldControl webControl = field.FieldRenderingControl;
                currentList  = webControl.List;
                currentItem  = webControl.Item;
                currentField = webControl.Field;

                Guid?  currentListId    = webControl.ListId;
                int?   currentItemIdInt = webControl.ItemId;
                string currentItemId    = webControl.Field.Id.ToString();
                string currentValue     = webControl.ItemFieldValue == null ? "" : webControl.ItemFieldValue.ToString();
            }


            StringBuilder propertyValue = new StringBuilder();

            propertyValue.Append(Definitions.prefix + Definitions.separator);
            propertyValue.Append(currentList.ID + Definitions.separator);
            propertyValue.Append(currentField.Id + Definitions.separator);
            propertyValue.Append(controlMode.ToString() + Definitions.separator);
            propertyValue.Append(fieldStatus);

            //SPGuys_ListId_FieldId_FormMode_ReadOnly Hidden
            string propertyFromWeb = propertyValue.ToString();

            //SPGuys_b9a223e1-58da-4608-aaf4-0a0c2f1d6b0e_fa564e0f-0c70-4ab9-b863-0177e6ddd247_New_Hidden   title
            //SPGuys_b9a223e1-58da-4608-aaf4-0a0c2f1d6b0e_6e180dd1-762e-46a0-8ffd-7925b70e699e_New_ReadOnly   people

            if (propertyFromWeb.Contains(SPBuiltInFieldId.LinkTitle.ToString()))
            {
                propertyFromWeb = propertyFromWeb.Replace(SPBuiltInFieldId.LinkTitle.ToString(), SPBuiltInFieldId.Title.ToString());
            }

            if (propertyFromWeb.Contains(SPBuiltInFieldId.LinkTitleNoMenu.ToString()))
            {
                propertyFromWeb = propertyFromWeb.Replace(SPBuiltInFieldId.LinkTitleNoMenu.ToString(), SPBuiltInFieldId.Title.ToString());
            }

            //Toto tu je kvoli tomu ze ked volam priamo tuto metodu na zistenie detailov pre ListField.aspx
            if (currentSite == null)
            {
                currentSite = SPContext.Current.Site;
                currentWeb  = SPContext.Current.Web;
            }

            if (currentSite.RootWeb.AllProperties[propertyFromWeb] != null)
            {
                //Musim replacovat \\\\ aj ked do property ulozim len \\ ale on tam doplni \\ potrebujem to mat v stave sp2010\\Administrator nie sp2010\\\\Administrator
                //return currentSite.RootWeb.AllProperties[propertyFromWeb].ToString().Replace("\\\\", "\\");

                return(currentSite.RootWeb.AllProperties[propertyFromWeb].ToString()); //Tu sa to zapisuje inak preto nam to nie je treba replacovat
            }

            return(String.Empty);
        }
 protected override void OnInit(EventArgs e)
 {
     //Check whether there in a SPContext, and if this is a List Item
     if (SPContext.Current != null && SPContext.Current.ListItem != null)
     {
         //Check whether the current content type is or inherits from the Page content type
         SPContentTypeId pageContentTypeId = SPContext.Current.Web.AvailableContentTypes["Page"].Id;
         SPContentTypeId currentItemTypeId = SPContext.Current.ListItem.ContentTypeId;
         if (currentItemTypeId.Equals(pageContentTypeId) || currentItemTypeId.IsChildOf(pageContentTypeId))
         {
             //Get the PageHolderMain content place holder control
             ContentPlaceHolder placeHolderMain = (ContentPlaceHolder)this.Page.Master.FindControl("PlaceHolderMain");
             if (placeHolderMain != null)
             {
                 //Check whether the current item is a publishing page and is a New item or in Edit mode
                 if ((PublishingPage.IsPublishingPage(SPContext.Current.ListItem)) &&
                     (SPContext.Current.FormContext.FormMode == SPControlMode.Edit ||
                      SPContext.Current.FormContext.FormMode == SPControlMode.New))
                 {
                     //Get the custom column
                     SPField demoCustomColumn;
                     try
                     {
                         demoCustomColumn = SPContext.Current.ListItem.Fields["DemoCustomColumn"];
                     }
                     catch
                     {
                         demoCustomColumn = null;
                     }
                     if (demoCustomColumn != null)
                     {
                         //We have a page, in edit or new mode, with the demoCustomColumn.
                         //So render the custom field control
                         BaseFieldControl demoCustomColumnControl = demoCustomColumn.FieldRenderingControl;
                         demoCustomColumnControl.ID = demoCustomColumn.InternalName;
                         placeHolderMain.Controls.Add(new LiteralControl("<div class=\"edit-mode-panel\">"));
                         placeHolderMain.Controls.Add(demoCustomColumnControl);
                         placeHolderMain.Controls.Add(new LiteralControl("</div>"));
                     }
                 }
                 else if ((PublishingPage.IsPublishingPage(SPContext.Current.ListItem)) &&
                          (SPContext.Current.FormContext.FormMode == SPControlMode.Display))
                 {
                     //Get the custom column
                     SPField demoCustomColumn;
                     try
                     {
                         demoCustomColumn = (SPFieldText)SPContext.Current.ListItem.Fields["DemoCustomColumn"];
                     }
                     catch
                     {
                         demoCustomColumn = null;
                     }
                     if (demoCustomColumn != null)
                     {
                         //We have a page, in display mode, with the demoCustomColumn.
                         //So render the value of the field. You can add custom rendering markup
                         //here. In this case, the <div> tag renders the text in red.
                         placeHolderMain.Controls.Add(new LiteralControl("<div style=\"color: red;\">"));
                         placeHolderMain.Controls.Add(new LiteralControl(SPContext.Current.ListItem["DemoCustomColumn"].ToString()));
                         placeHolderMain.Controls.Add(new LiteralControl("</div>"));
                     }
                 }
             }
         }
     }
     base.OnInit(e);
 }
Exemplo n.º 17
0
        protected override void CreateChildControls()
        {
            _FieldRenderingControl = _Field.FieldRenderingControl ;
            _FieldRenderingControl.ControlMode = SPControlMode.New;
            this.Controls.Add(_FieldRenderingControl);

            this.ChildControlsCreated = true;
        }
 public static void SetValidationError(
     BaseFieldControl fieldControl, String errorMessage)
 {
     fieldControl.ErrorMessage = errorMessage;
     fieldControl.IsValid      = false;
 }
Exemplo n.º 19
0
        public override void CreateWebPartChildControls()
        {
            bool       authenticated = HttpContext.Current.User.Identity.IsAuthenticated;
            SPListItem item          = SPContext.Current.ListItem;

            try
            {
                int versionId = 0;
                NameValueCollection queryString = HttpContext.Current.Request.QueryString;

                foreach (string key in queryString.AllKeys)
                {
                    if (key != null && key == "PageVersion")
                    {
                        versionId = int.Parse(queryString[key]);
                        break;
                    }
                }
                if (versionId > 0 && !authenticated)
                {
                    SPListItemVersionCollection versions = item.Versions;

                    foreach (SPListItemVersion version in versions)
                    {
                        if (version.VersionId == versionId)
                        {
                            Field = version.Fields[FieldName];
                        }
                    }
                }
            }
            catch { };

            if (item != null)
            {
                try
                {
                    if (Field == null)
                    {
                        Field = item.Fields[FieldName];
                    }

                    if (Field != null)
                    {
                        BaseFieldControl FieldColumnControl = Field.FieldRenderingControl;
                        if (FieldColumnControl != null)
                        {
                            if (FieldColumnControl.ItemContext.FormContext.FormMode != SPControlMode.Invalid)
                            {
                                FieldColumnControl.ItemContext.FormContext.EnableInputFieldLabels = false;
                                FieldColumnControl.InputFieldLabel = string.Empty;
                                FieldColumnControl.ID = Field.InternalName;
                            }

                            if (inEditMode)
                            {
                                FieldColumnControl.ControlMode = SPControlMode.Edit;
                            }
                            else
                            {
                                FieldColumnControl.ControlMode = SPControlMode.Display;
                            }
                        }
                        this.Controls.Add(FieldColumnControl);
                        this.Title = Field.Title;
                    }
                }
                catch (ArgumentException)
                {
                    if (this.DesignMode)
                    {
                        this.Title = "Unknown PagePart";
                        this.Controls.Add(new LiteralControl("The Field for this PagePart is not found"));
                    }
                }
            }

            //base.CreateWebPartChildControls();
        }
Exemplo n.º 20
0
 public static void SetValidationError(
     BaseFieldControl fieldControl, String errorMessage)
 {
     fieldControl.ErrorMessage = errorMessage;
     fieldControl.IsValid = false;
 }
Exemplo n.º 21
0
     GetIteratorByFieldControl(BaseFieldControl fieldControl)
 {
     return (Microsoft.SharePoint.WebControls.ListFieldIterator)
         fieldControl.Parent.Parent.Parent.Parent.Parent;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Button ClickEvent will cause a PostBack and will try to save all values to corresponding
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnOk_Click(object sender, EventArgs e)
        {
            using (new SPMonitoredScope("SP2010 BatchEdit Process Field Values"))
            {
                try
                {
                    _fieldValues = new List <KeyValuePair <Guid, string> >();
                    foreach (Control control in pnlFields.Controls)
                    {
                        if (control.GetType().Equals(typeof(DateTimeField)))
                        {
                            BaseFieldControl taxControl = (DateTimeField)control;
                            if (taxControl.Value != null)
                            {
                                _fieldValues.Add(new KeyValuePair <Guid, string>(taxControl.Field.Id, taxControl.Value.ToString()));
                            }
                        }
                        else
                        {
                            var taggingControl = control as TaxonomyWebTaggingControl;
                            if (taggingControl != null)
                            {
                                TaxonomyWebTaggingControl taxControl = taggingControl;
                                if (!string.IsNullOrEmpty(taxControl.Text))
                                {
                                    _fieldValues.Add(new KeyValuePair <Guid, string>(new Guid(taxControl.FieldId), taxControl.Text));
                                }
                            }
                            else if (control.GetType().IsSubclassOf(typeof(BaseFieldControl)))
                            {
                                BaseFieldControl fieldControl = (BaseFieldControl)control;
                                if (!string.IsNullOrEmpty(fieldControl.Value as string))
                                {
                                    _fieldValues.Add(new KeyValuePair <Guid, string>(fieldControl.Field.Id, fieldControl.Value as string));
                                }
                            }
                        }
                    }

                    string webId  = Request["web"];
                    string listId = Request["source"];
                    string items  = Request["items"];

                    using (SPWeb web = SPContext.Current.Site.OpenWeb(new Guid(webId)))
                    {
                        SPList sourceLibrary = web.Lists[new Guid(listId)];

                        string[] itemids = items.Trim('|').Split('|');

                        foreach (string itemid in itemids)
                        {
                            try
                            {
                                SPListItem item = sourceLibrary.GetItemById(int.Parse(itemid));

                                if (item.Folder != null)
                                {
                                    TraverseListFolder(item.Folder);
                                }
                                else
                                {
                                    UpdateListItem(item);
                                }
                            }
                            catch (Exception ex)
                            {
                                _messages += ex.Message + "<br/>";
                                SPCriticalTraceCounter.AddDataToScope(67, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _messages += ex.Message + "<br/>";
                    SPCriticalTraceCounter.AddDataToScope(68, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
                }
            }

            if (string.IsNullOrEmpty(_messages))
            {
                Page.Response.Clear();
                Page.Response.Write(string.Format(CultureInfo.InvariantCulture,
                                                  "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, 'Items updated');</script>"));
                Page.Response.End();
            }
            else
            {
                // Log all messages again. (we could also use this
                SPCriticalTraceCounter.AddDataToScope(67, "SP2010 BatchEdit", 1, _messages);

                lblMessages.Text = "Unfortunately there was an error updating the items with the provided values, a system administrator can use the message below to check upon this error, please provide them with it. <br />" + _messages;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Generates the form containing all the fields
        /// </summary>
        private void LoadForm()
        {
            try
            {
                using (new SPMonitoredScope("SP2010 BatchEdit Get Fields (and default values)"))
                {
                    string webId  = Request["web"];
                    string listId = Request["source"];

                    using (SPWeb web = SPContext.Current.Site.OpenWeb(new Guid(webId)))
                    {
                        SPList list = web.Lists[new Guid(listId)];

                        foreach (SPField field in list.Fields)
                        {
                            if (field.ShowInNewForm.GetValueOrDefault(true) && field.FieldRenderingControl != null && (field.ShowInEditForm ?? field.CanBeDisplayedInEditForm))
                            {
                                string lblText = field.Title;
                                if (field.Required)
                                {
                                    lblText += " *";
                                }

                                pnlFields.Controls.Add(new System.Web.UI.WebControls.Label {
                                    Text = lblText
                                });
                                pnlFields.Controls.Add(new Literal {
                                    Text = "<br/>"
                                });

                                try
                                {
                                    if (!field.FieldRenderingControl.GetType().Equals(typeof(TaxonomyFieldControl)))
                                    {
                                        BaseFieldControl editControl = field.FieldRenderingControl;
                                        editControl.ID = "fld_" + field.Id.ToString().Replace("-", "_"); // fix for Lookup picker
                                        Trace.Write(field.Id.ToString());
                                        editControl.ControlMode   = SPControlMode.New;
                                        editControl.ListId        = list.ID;
                                        editControl.FieldName     = field.InternalName;
                                        editControl.RenderContext = SPContext.GetContext(HttpContext.Current, list.DefaultView.ID, list.ID, web);

                                        pnlFields.Controls.Add(editControl);
                                    }

                                    else
                                    {
                                        var session = new TaxonomySession(field.ParentList.ParentWeb.Site);

                                        var taxonomyControl = new TaxonomyWebTaggingControl
                                        {
                                            IsMulti    = true,
                                            IsAddTerms = true,
                                            ID         = "fld_" + field.Id,
                                            FieldName  = field.Title,
                                            FieldId    = field.Id.ToString()
                                        };

                                        taxonomyControl.TermSetId.Add(session.TermStores[0].Id);
                                        taxonomyControl.SSPList     = ((TaxonomyField)field).SspId.ToString();
                                        taxonomyControl.AnchorId    = ((TaxonomyField)field).AnchorId;
                                        taxonomyControl.TermSetList = ((TaxonomyField)field).TermSetId.ToString();
                                        pnlFields.Controls.Add(taxonomyControl);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    SPCriticalTraceCounter.AddDataToScope(66, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
                                }

                                pnlFields.Controls.Add(new Literal {
                                    Text = "<br/><br/>"
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SPCriticalTraceCounter.AddDataToScope(66, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
            }
        }
Exemplo n.º 24
0
        public void Validate()
        {
            FieldValidations allFieldVals = FieldValidations.LoadFieldValidations(GetConfigFile(Constants.ConfigFile.FieldValidationFile));

            if (base.ControlMode != SPControlMode.Display && allFieldVals != null)
            {
                #region Test data
                //allFieldVals.Add(new FieldValidation(new Field("Title"), Enums.ValidationRule.Column, Enums.Operator.Equal, "adil", "error for adil", "", Enums.Operator.None));
                //allFieldVals.Add(new FieldValidation(new Field("Status"), Enums.ValidationRule.Column, Enums.Operator.Contains, "Start", "error for start", "", Enums.Operator.None));
                //allFieldVals.Add(new FieldValidation(new Field("Title"), Enums.ValidationRule.Pattern, Enums.Operator.Equal, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", "not valid email", "pc\\pdadmin", Enums.Operator.Equal));
                //allFieldVals.Add(new FieldValidation(new Field("Predecessors"), Enums.ValidationRule.Column, Enums.Operator.Contains, "adil", "contains adil", "pc\\pdadmin", Enums.Operator.Equal));
                #endregion

                bool isErroredField = false;
                foreach (FieldValidation v in allFieldVals)
                {
                    if (ConditionEvaluator.EvaluateFromUIValue(v.Conditions, _formContext, ClientID) && PrincipalEvaluator.Check(v.ForSPPrinciples, v.BySPPrinciplesOperator))
                    {
                        BaseFieldControl field = ValidationInjector.GetFieldControlByName(v.OnField.SPName, _formContext, ClientID);

                        if (field != null)
                        {
                            switch (v.Rule)
                            {
                            case Enums.ValidationRule.Column:
                                if (ValidationInjector.InvalidColumnValue(field.Value, v.ByRuleOperator, v.Value.ToString(), field.Field.FieldValueType))
                                {
                                    ValidationInjector.SetValidationError(field, v.ErrorMsg); isErroredField = true;
                                }
                                break;

                            case Enums.ValidationRule.length:
                                int length = (field.Value == null ? 0 : field.Value.ToString().Length);
                                if (ValidationInjector.InvalidLengthValue(length, v.ByRuleOperator, v.Value.ToString()))
                                {
                                    ValidationInjector.SetValidationError(field, v.ErrorMsg); isErroredField = true;
                                }
                                break;

                            case Enums.ValidationRule.Pattern:
                                if (ValidationInjector.InvalidPatternValue((field.Value ?? "").ToString(), v.Value.ToString()))
                                {
                                    ValidationInjector.SetValidationError(field, v.ErrorMsg); isErroredField = true;
                                }
                                break;
                            }
                        }

                        if (allTabs != null)
                        {
                            string tabname = allTabs.GetTabNameOfField(v.OnField.SPName);
                            if (isErroredField && !string.IsNullOrEmpty(tabname))
                            {
                                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "SLFE_UpdatePanelHelper", string.Concat(new string[]
                                {
                                    "<script type='text/javascript'>g_SLFEUpdatePanelHelper='",
                                    this.updatePanelIterator.ClientID,
                                    "';\r\ng_RequestResultTabsInfoHidden = '",
                                    this.RequestResultTabsInfoHidden.ClientID,
                                    "';\r\nSys.WebForms.PageRequestManager.getInstance().add_pageLoaded(SLFE_OnClientResponseEnded);\r\n</script>"
                                }));
                                this.Page.ClientScript.RegisterStartupScript(base.GetType(), "SLFE_CallFirstSelectTab", "<script type='text/javascript'>SLFE_SelectTab('" + allTabs.GetTabNameOfField(v.OnField.SPName) + "')</script>");
                            }
                        }
                    }
                }
            }
        }