public void DoesNotRecreateExistingFields()
        {
            ICategoryRepository categoryRepository;
            const string        categoryName = "category";

            List <FieldInfo> existingFields = new List <FieldInfo>();

            existingFields.Add(new FieldInfo("existingField1", FieldType.TextBox, "Existing field 1"));
            existingFields.Add(new FieldInfo("existingField2", FieldType.CheckBox, "Existing field 2"));

            using (Mocks.Record())
            {
                categoryRepository = Mocks.StrictMock <ICategoryRepository>();

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = existingFields.ToCustomFieldList();

                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Return(formSettings);
            }

            using (Mocks.Playback())
            {
                Migrator fm = new Migrator(categoryRepository, new PostRepository());
                fm.EnsureFields(categoryName, existingFields);
            }
        }
示例#2
0
    protected void UpdateFieldBTN_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(ExistingName.Text))
        {
            CustomFormSettings cfs = CustomFormSettings.Get(_category, false);

            CustomField cf = null;
            Guid        g  = new Guid(Request.QueryString["id"]);
            foreach (CustomField cfx in cfs.Fields)
            {
                if (cfx.Id == g)
                {
                    cf = cfx;
                    break;
                }
            }

            if (cf == null)
            {
                throw new Exception("Custom Field does not exist to be edited.");
            }

            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cfx in cfs.Fields)
                {
                    if (Util.AreEqualIgnoreCase(FieldName.Text.Trim(), cf.Name) && cfx.Id != cf.Id)
                    {
                        Message.Text = "Field Name already exists!";
                        Message.Type = StatusType.Error;
                        return;
                    }
                }
            }


            cf.Name        = ExistingName.Text;
            cf.Description = ExistingDescription.Text;
            if (cf.FieldType == FieldType.CheckBox)
            {
                cf.Checked = ExistingCheckBox.Checked;
            }
            else if (cf.FieldType == FieldType.List)
            {
                string[] lines =
                    ExistingListOptions.Text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                cf.ListOptions = new List <ListItemFormElement>();
                foreach (string line in lines)
                {
                    cf.ListOptions.Add(new ListItemFormElement(line.Trim(), line.Trim()));
                }
            }
            cf.Enabled = true;

            cfs.Save();

            Response.Redirect("~/graffiti-admin/site-options/custom-fields/?upd=" + cf.Id + "&category=" + _category.ToString());
        }
    }
示例#3
0
    protected void NewFieldBTN_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(FieldName.Text))
        {
            CustomFormSettings cfs = CustomFormSettings.Get(_category, false);
            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (Util.AreEqualIgnoreCase(FieldName.Text.Trim(), cf.Name))
                    {
                        Message.Text = "Field name already exists!";
                        Message.Type = StatusType.Error;
                        return;
                    }
                }
            }

            CustomField nfield = new CustomField();
            nfield.Name      = FieldName.Text;
            nfield.Enabled   = false;
            nfield.Id        = Guid.NewGuid();
            nfield.FieldType = (FieldType)Enum.Parse(typeof(FieldType), TypesOfField.SelectedValue);

            cfs.Name = _category.ToString();

            cfs.Add(nfield);

            cfs.Save();

            Response.Redirect("?new=true&id=" + nfield.Id + "&category=" + _category.ToString());
        }
    }
示例#4
0
        /// <summary>
        /// Creates fields in a category if they do not exist. Does not change any existing fields.
        /// </summary>
        /// <param name="categoryName">Name of the category.</param>
        /// <param name="fields">The fields.</param>
        internal void EnsureFields(string categoryName, List <FieldInfo> fields)
        {
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentOutOfRangeException("categoryName");
            }

            if (fields == null || fields.Count == 0)
            {
                // Nothing to to.
                return;
            }

            CustomFormSettings formSettings = _categoryRepository.GetFormSettings(categoryName);

            // Ensure that the fields exist.
            foreach (var field in fields)
            {
                FieldInfo   field1      = field;
                CustomField customField =
                    formSettings.Fields.Find(f => Util.AreEqualIgnoreCase(field1.FieldName, f.Name));

                if (customField != null)
                {
                    EnsureFieldDescription(field, formSettings);
                    continue;
                }

                CreateField(field, formSettings);
            }

            SortFields(fields, formSettings);
        }
示例#5
0
    private void LoadCustomFields()
    {
        CustomFormSettings csf = CustomFormSettings.Get(_category, false);

        if (csf.Fields != null && csf.Fields.Count > 0)
        {
            CustomFieldList.Visible = true;

            ExistingFields.DataSource = csf.Fields;
            ExistingFields.DataBind();
        }
        else
        {
            CustomFieldList.Visible = false;
        }

        if (Request.QueryString["upd"] != null)
        {
            CustomField temp = csf.Fields.Find(
                delegate(CustomField cf)
            {
                return(cf.Id == new Guid(Request.QueryString["upd"]));
            });

            Message.Text = "The custom field <strong>" + temp.Name + "</strong> was updated";
            Message.Type = StatusType.Success;
        }
    }
        private void SetUpRssCategories()
        {
            bool customFieldExists = false;
            CustomFormSettings cfs = CustomFormSettings.Get();

            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (Util.AreEqualIgnoreCase(categoryFieldName, cf.Name))
                    {
                        customFieldExists = true;
                        break;
                    }
                }
            }

            if (!customFieldExists)
            {
                CustomField nfield = new CustomField();
                nfield.Name        = categoryFieldName;
                nfield.Description = "Custom Categories you want to included in your RSS feed for your blog post.  Enter each on a new line and each item will be entered in a separate <category> element.  If you want to set a domain on the category element, add a dollar sign ($) after the category and then enter the domain value.";
                nfield.Enabled     = true;
                nfield.Id          = Guid.NewGuid();
                nfield.FieldType   = FieldType.TextArea;

                cfs.Name = "-1";
                cfs.Add(nfield);
                cfs.Save();
            }
        }
示例#7
0
        public void SaveFormSettings(CustomFormSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            settings.Save();
        }
        private void SetupCustomFields()
        {
            bool saveNeeded        = false;
            CustomFormSettings cfs = CustomFormSettings.Get();

            if (!DoesFieldExist(cfs.Fields, "Creator"))
            {
                cfs.Add(CreateCreatorsField("Creator", "Extension Creator"));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "Version"))
            {
                cfs.Add(CreateCustomField("Version", "Version", FieldType.TextBox));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "FileName"))
            {
                cfs.Add(CreateCustomField("FileName", "Download Url", FieldType.File));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "ImageLarge"))
            {
                cfs.Add(CreateCustomField("ImageLarge", "Large Image Url (max 602x200)", FieldType.File));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "RequiredMajorVersion"))
            {
                cfs.Add(CreateCustomField("RequiredMajorVersion", "Minimum Required Major Version #", FieldType.TextBox));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "RequiredMinorVersion"))
            {
                cfs.Add(CreateCustomField("RequiredMinorVersion", "Minimum Required Minor Version #", FieldType.TextBox));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "RequiresManualIntervention"))
            {
                cfs.Add(CreateCustomField("RequiresManualIntervention", "Requires Manual Intervention", FieldType.CheckBox));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "Price"))
            {
                cfs.Add(CreateCustomField("Price", "Price", FieldType.TextBox));
                saveNeeded = true;
            }
            if (!DoesFieldExist(cfs.Fields, "BuyUrl"))
            {
                cfs.Add(CreateCustomField("BuyUrl", "BuyUrl", FieldType.TextBox));
                saveNeeded = true;
            }

            if (saveNeeded)
            {
                cfs.Name = "-1";
                cfs.Save();
            }
        }
示例#9
0
        public void DeleteField(CustomFormSettings settings, string fieldName)
        {
            CustomField field = settings.Fields.Find(cf => cf.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));

            if (field != null)
            {
                settings.Fields.Remove(field);
                settings.Save();
            }
        }
示例#10
0
        public CustomFormSettings GetFormSettings(string categoryName)
        {
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentOutOfRangeException("categoryName");
            }

            Category category = GetCategory(categoryName);

            return(CustomFormSettings.Get(category));
        }
示例#11
0
        void CreateField(FieldInfo field, CustomFormSettings formSettings)
        {
            CustomField newField = new CustomField
            {
                Id          = Guid.NewGuid(),
                Enabled     = true,
                Name        = field.FieldName,
                FieldType   = field.FieldType,
                Description = field.Description
            };

            _categoryRepository.AddField(formSettings, newField);
        }
        public void ShouldSetDescriptionForExistingFieldsIfEmpty()
        {
            ICategoryRepository categoryRepository;
            const string        categoryName = "category";

            List <FieldInfo> existingFields = new List <FieldInfo>();

            existingFields.Add(new FieldInfo("existingField1", FieldType.TextBox, "User-defined description"));
            existingFields.Add(new FieldInfo("existingField2", FieldType.CheckBox, String.Empty));

            List <FieldInfo> newFields = new List <FieldInfo>();

            newFields.Add(new FieldInfo("existingField1", FieldType.TextBox, "Field description 1"));
            newFields.Add(new FieldInfo("existingField2", FieldType.CheckBox, "Field description 2"));

            using (Mocks.Record())
            {
                categoryRepository = Mocks.StrictMock <ICategoryRepository>();

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = existingFields.ToCustomFieldList();
                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Return(formSettings);

                List <CustomField> expectedFormSettings = new List <CustomField>();
                expectedFormSettings.Add(existingFields.ToCustomFieldList()[0]);
                expectedFormSettings.Add(newFields.ToCustomFieldList()[1]);

                categoryRepository.SaveFormSettings(null);
                LastCall.Constraints(Is.Matching((CustomFormSettings cfs) =>
                {
                    for (int i = 0; i < cfs.Fields.Count; i++)
                    {
                        CustomField field         = cfs.Fields[i];
                        CustomField expectedField = expectedFormSettings[i];
                        if (expectedField.Name != field.Name || expectedField.Description != field.Description ||
                            expectedField.FieldType != field.FieldType)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }));
            }

            using (Mocks.Playback())
            {
                Migrator fm = new Migrator(categoryRepository, new PostRepository());
                fm.EnsureFields(categoryName, newFields);
            }
        }
示例#13
0
        public void AddField(CustomFormSettings settings, CustomField field)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            settings.Add(field);
            settings.Save();
        }
        public void ShouldCreateNewFieldsAndLeaveExistingFieldsIntact()
        {
            ICategoryRepository categoryRepository;
            const string        categoryName = "category";

            List <FieldInfo> existingFields = new List <FieldInfo>();

            existingFields.Add(new FieldInfo("existingField1", FieldType.TextBox, "Existing field 1"));
            existingFields.Add(new FieldInfo("existingField2", FieldType.CheckBox, "Existing field 2"));

            List <FieldInfo> newFields = new List <FieldInfo>();

            newFields.Add(new FieldInfo("newField1", FieldType.TextBox, "New field 1"));
            newFields.Add(new FieldInfo("newField2", FieldType.CheckBox, "New field 2"));

            using (Mocks.Record())
            {
                categoryRepository = Mocks.StrictMock <ICategoryRepository>();

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = existingFields.ToCustomFieldList();
                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Return(formSettings);

                foreach (FieldInfo field in newFields)
                {
                    categoryRepository.AddField(null, null);

                    FieldInfo field1 = field;
                    LastCall.Constraints(Is.Same(formSettings),
                                         Is.Matching(
                                             (CustomField f) =>
                                             f.Name == field1.FieldName && f.FieldType == field1.FieldType &&
                                             f.Description == field1.Description));
                }
            }

            using (Mocks.Playback())
            {
                List <FieldInfo> merged = new List <FieldInfo>();
                merged.AddRange(newFields);
                merged.AddRange(existingFields);

                Migrator fm = new Migrator(categoryRepository, new PostRepository());
                fm.EnsureFields(categoryName, merged);
            }
        }
示例#15
0
        void EnsureFieldDescription(FieldInfo field, CustomFormSettings formSettings)
        {
            CustomField customField =
                formSettings.Fields.Find(f => Util.AreEqualIgnoreCase(field.FieldName, f.Name));

            if (!customField.Description.IsNullOrEmpty())
            {
                return;
            }

            if (String.Equals(customField.Description, field.Description, StringComparison.Ordinal))
            {
                return;
            }

            customField.Description = field.Description;
            _categoryRepository.SaveFormSettings(formSettings);
        }
示例#16
0
    protected void lbDelete_Command(object sender, CommandEventArgs args)
    {
        string id = args.CommandArgument.ToString();

        CustomFormSettings cfs = CustomFormSettings.Get(_category, false);

        CustomField temp = cfs.Fields.Find(delegate(CustomField cf) { return(cf.Id == new Guid(id)); });

        if (temp != null)
        {
            cfs.Fields.Remove(temp);
        }

        cfs.Save();

        LoadCustomFields();
        Message.Text = "The custom field <b>" + temp.Name + "</b> was deleted.";
        Message.Type = StatusType.Success;
    }
示例#17
0
        /// <summary>
        /// Sorts the fields according the order of the fields in the <paramref name="fields"/> list.
        /// </summary>
        /// <param name="fields">The fields.</param>
        /// <param name="formSettings">The form settings.</param>
        void SortFields(List <FieldInfo> fields, CustomFormSettings formSettings)
        {
            string[] fieldNames = fields.ConvertAll(field => field.FieldName).ToArray();

            formSettings.Fields.Sort(delegate(CustomField x, CustomField y)
            {
                if (Array.IndexOf(fieldNames, x.Name) < Array.IndexOf(fieldNames, y.Name))
                {
                    return(-1);
                }

                if (Array.IndexOf(fieldNames, x.Name) > Array.IndexOf(fieldNames, y.Name))
                {
                    return(1);
                }

                return(0);
            });
        }
示例#18
0
        /// <summary>
        /// Deletes fields in a category.
        /// </summary>
        /// <param name="categoryName">Name of the category.</param>
        /// <param name="fieldNames">The fields to delete.</param>
        void DeleteFields(string categoryName, ICollection <string> fieldNames)
        {
            if (String.IsNullOrEmpty(categoryName))
            {
                throw new ArgumentOutOfRangeException("categoryName");
            }

            if (fieldNames == null || fieldNames.Count == 0)
            {
                // Nothing to do.
                return;
            }

            CustomFormSettings formSettings = _categoryRepository.GetFormSettings(categoryName);

            foreach (string field in fieldNames)
            {
                _categoryRepository.DeleteField(formSettings, field);
            }
        }
示例#19
0
        void ga_AfterNewUser(IGraffitiUser user, EventArgs e)
        {
            // If users are added or updated, refresh the list of available creators in the custom dropdown field

            CustomFormSettings cfs = CustomFormSettings.Get();

            if (cfs.Fields == null || cfs.Fields.Count == 0)
            {
                SetupCustomFields();
            }
            else
            {
                CustomField creatorField = cfs.Fields.Find(field => Util.AreEqualIgnoreCase(field.Name, "Creator"));
                if (creatorField != null)
                {
                    UpdateCreatorsFieldOptions(creatorField);
                    cfs.Name = "-1";
                    cfs.Save();
                }
            }
        }
        public void CreatesNewFields()
        {
            ICategoryRepository categoryRepository;
            const string        categoryName = "category";

            List <FieldInfo> newFields = new List <FieldInfo>();

            newFields.Add(new FieldInfo("newField1", FieldType.TextBox, "New field 1"));
            newFields.Add(new FieldInfo("newField2", FieldType.CheckBox, "New field 2"));

            using (Mocks.Record())
            {
                categoryRepository = Mocks.StrictMock <ICategoryRepository>();

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = new List <CustomField>();
                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Return(formSettings);

                foreach (FieldInfo field in newFields)
                {
                    categoryRepository.AddField(formSettings, new CustomField());

                    FieldInfo field1 = field;
                    LastCall.Constraints(Is.Same(formSettings),
                                         Is.Matching(
                                             (CustomField f) =>
                                             f.Name == field1.FieldName && f.FieldType == field1.FieldType &&
                                             f.Description == field1.Description));
                }
            }

            using (Mocks.Playback())
            {
                Migrator fm = new Migrator(categoryRepository, new PostRepository());
                fm.EnsureFields(categoryName, newFields);
            }
        }
示例#21
0
        private void SetupGeoRSS()
        {
            if (!EnableGeoRSS)
            {
                return;
            }

            bool customFieldExists = false;
            CustomFormSettings cfs = CustomFormSettings.Get();

            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (Util.AreEqualIgnoreCase(_geoRSSCustomFieldName, cf.Name))
                    {
                        customFieldExists = true;
                        break;
                    }
                }
            }

            if (!customFieldExists)
            {
                CustomField nfield = new CustomField();
                nfield.Name        = _geoRSSCustomFieldName;
                nfield.Description = "The geographic location of this post in the format lattitude longitude. If no location is entered, the default location set in the Blog Extensions Plugin will be used.";
                nfield.Enabled     = true;
                nfield.Id          = Guid.NewGuid();
                nfield.FieldType   = FieldType.TextBox;

                cfs.Name = "-1";
                cfs.Add(nfield);
                cfs.Save();
            }
        }
示例#22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        LiHyperLink.SetNameToCompare(Context, "settings");

        _category = int.Parse(Request.QueryString["category"] ?? "-1");

        if (Request.QueryString["id"] != null)
        {
            if (Request.QueryString["new"] != null)
            {
                if (!IsPostBack)
                {
                    Message.Text = "Your field was successfully added.";
                    Message.Type = StatusType.Success;
                }
            }

            if (!IsPostBack)
            {
                Cancel_Edit.NavigateUrl = "?category=" + _category.ToString();

                Master.FindControl("SideBarRegion").Visible = false;

                CustomFormSettings csf = CustomFormSettings.Get(_category, false);

                CustomField cf = null;
                Guid        g  = new Guid(Request.QueryString["id"]);
                foreach (CustomField cfx in csf.Fields)
                {
                    if (cfx.Id == g)
                    {
                        cf = cfx;
                        break;
                    }
                }

                if (cf != null)
                {
                    FormViews.SetActiveView(EditFieldView);

                    ExistingName.Text        = cf.Name;
                    ExistingDescription.Text = cf.Description;

                    if (cf.FieldType == FieldType.CheckBox)
                    {
                        CheckboxRegion.Visible   = true;
                        ExistingCheckBox.Checked = cf.Checked;
                    }
                    else if (cf.FieldType == FieldType.List)
                    {
                        ListRegion.Visible = true;
                        if (cf.ListOptions != null && cf.ListOptions.Count > 0)
                        {
                            foreach (ListItemFormElement li in cf.ListOptions)
                            {
                                ExistingListOptions.Text += (li.Text + "\n");
                            }
                        }
                    }
                }
            }
        }
        else
        {
            if (!IsPostBack)
            {
                Master.FindControl("SideBarRegion").Visible = true;

                if (_category != -1)
                {
                    Category c = new Category(_category);
                    lblCategory.Text = c.Name;
                }
                else
                {
                    lblCategory.Text = "Global";
                }

                LoadCategories();

                LoadCustomFields();
            }
        }
    }
示例#23
0
        private void AddEventFields(Category eventCategory)
        {
            bool eventDateFieldExists = false;
            bool startTimeFieldExists = false;
            bool endTimeFieldExists   = false;
            bool startDateFieldExists = false;
            bool endDateFieldExists   = false;

            CustomFormSettings cfs = CustomFormSettings.Get(eventCategory, false);

            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (!eventDateFieldExists && Util.AreEqualIgnoreCase(eventDateFieldName, cf.Name))
                    {
                        eventDateFieldExists = true;
                    }
                    if (!startTimeFieldExists && Util.AreEqualIgnoreCase(startTimeFieldName, cf.Name))
                    {
                        startTimeFieldExists = true;
                    }
                    if (!endTimeFieldExists && Util.AreEqualIgnoreCase(endTimeFieldName, cf.Name))
                    {
                        endTimeFieldExists = true;
                    }
                    if (!startDateFieldExists && Util.AreEqualIgnoreCase(startDateFieldName, cf.Name))
                    {
                        startDateFieldExists = true;
                    }
                    if (!endDateFieldExists && Util.AreEqualIgnoreCase(endDateFieldName, cf.Name))
                    {
                        endDateFieldExists = true;
                    }

                    if (eventDateFieldExists && startTimeFieldExists && endTimeFieldExists && endDateFieldExists && startDateFieldExists)
                    {
                        break;
                    }
                }
            }

            if (!eventDateFieldExists)
            {
                CustomField dateField = new CustomField();
                dateField.Name        = eventDateFieldName;
                dateField.Description = "The date that the event takes place on";
                dateField.Enabled     = true;
                dateField.Id          = Guid.NewGuid();
                dateField.FieldType   = FieldType.Date;

                cfs.Name = eventCategory.Id.ToString();
                cfs.Add(dateField);
                cfs.Save();
            }

            if (!startTimeFieldExists)
            {
                CustomField startField = new CustomField();
                startField.Name        = startTimeFieldName;
                startField.Description = "The time that the event starts";
                startField.Enabled     = true;
                startField.Id          = Guid.NewGuid();
                startField.FieldType   = FieldType.TextBox;

                cfs.Name = eventCategory.Id.ToString();
                cfs.Add(startField);
                cfs.Save();
            }

            if (!endTimeFieldExists)
            {
                CustomField endField = new CustomField();
                endField.Name        = endTimeFieldName;
                endField.Description = "The time that the event ends";
                endField.Enabled     = true;
                endField.Id          = Guid.NewGuid();
                endField.FieldType   = FieldType.TextBox;

                cfs.Name = eventCategory.Id.ToString();
                cfs.Add(endField);
                cfs.Save();
            }

            if (!startDateFieldExists)
            {
                CustomField startDateField = new CustomField();
                startDateField.Name        = startDateFieldName;
                startDateField.Description = "The start date for the event";
                startDateField.Enabled     = true;
                startDateField.Id          = Guid.NewGuid();
                startDateField.FieldType   = FieldType.Date;

                cfs.Name = eventCategory.Id.ToString();
                cfs.Add(startDateField);
                cfs.Save();
            }

            if (!endDateFieldExists)
            {
                CustomField endDateField = new CustomField();
                endDateField.Name        = endDateFieldName;
                endDateField.Description = "The end date for the event";
                endDateField.Enabled     = true;
                endDateField.Id          = Guid.NewGuid();
                endDateField.FieldType   = FieldType.Date;

                cfs.Name = eventCategory.Id.ToString();
                cfs.Add(endDateField);
                cfs.Save();
            }
        }
        public void ShouldDeleteChangedFields()
        {
            ICategoryRepository categoryRepository;
            IPostRepository     postRepository;
            IMemento            newState;
            IMemento            oldState;
            const string        categoryName = "category";

            using (Mocks.Record())
            {
                oldState = Mocks.StrictMock <IMemento>();
                Expect.Call(oldState.CategoryName).Return(categoryName);
                Expect.Call(oldState.Fields).Repeat.AtLeastOnce().Return(new Dictionary <Guid, FieldInfo>
                {
                    {
                        new Guid("{28E2469B-E568-4406-832D-3AD3F1EBE214}"),
                        new FieldInfo("oldFieldName",
                                      FieldType.TextBox,
                                      "Description")
                    }
                });

                newState = Mocks.StrictMock <IMemento>();
                Expect.Call(newState.CategoryName).Return(categoryName);
                Expect.Call(newState.Fields).Repeat.AtLeastOnce().Return(new Dictionary <Guid, FieldInfo>
                {
                    {
                        new Guid("{28E2469B-E568-4406-832D-3AD3F1EBE214}"),
                        new FieldInfo("newFieldName",
                                      FieldType.TextBox,
                                      "Description")
                    }
                });

                categoryRepository = Mocks.StrictMock <ICategoryRepository>();
                Category targetCategory = new Category {
                    Id = int.MaxValue, Name = categoryName
                };
                Expect.Call(categoryRepository.GetCategory(categoryName)).Repeat.AtLeastOnce().Return(targetCategory);

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = new List <CustomField>();
                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Repeat.AtLeastOnce().Return(formSettings);

                categoryRepository.AddField(null, null);
                LastCall.Constraints(Is.Same(formSettings), Is.Matching((CustomField f) => f.Name == "newFieldName"));

                categoryRepository.DeleteField(null, null);
                LastCall.Constraints(Is.Same(formSettings), Is.Equal("oldFieldName"));

                // No posts to migrate.
                postRepository = Mocks.StrictMock <IPostRepository>();
                Expect.Call(postRepository.GetByCategory(categoryName)).Return(new PostCollection());
            }

            using (Mocks.Playback())
            {
                Migrator fm = new Migrator(categoryRepository, postRepository);
                fm.Migrate(new MigrationInfo(oldState, newState));
            }
        }
示例#25
0
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType != "POST" || !context.Request.IsAuthenticated)
            {
                return;
            }

            IGraffitiUser user = GraffitiUsers.Current;

            if (user == null)
            {
                return;
            }

            if (!RolePermissionManager.CanViewControlPanel(user))
            {
                return;
            }

            context.Response.ContentType = "text/plain";


            switch (context.Request.QueryString["command"])
            {
            case "deleteComment":

                Comment c = new Comment(context.Request.Form["commentid"]);

                if (RolePermissionManager.GetPermissions(c.Post.CategoryId, GraffitiUsers.Current).Publish)
                {
                    Comment.Delete(context.Request.Form["commentid"]);
                    context.Response.Write("success");
                }

                break;

            case "deleteCommentWithStatus":

                Comment c1 = new Comment(context.Request.Form["commentid"]);

                if (RolePermissionManager.GetPermissions(c1.Post.CategoryId, GraffitiUsers.Current).Publish)
                {
                    Comment.Delete(context.Request.Form["commentid"]);
                    context.Response.Write("The comment was deleted. <a href=\"javascript:void(0);\" onclick=\"Comments.unDelete('" +
                                           new Urls().AdminAjax + "'," + context.Request.Form["commentid"] +
                                           "); return false;\">Undo?</a>");
                }
                break;

            case "unDelete":
                Comment c2 = new Comment(context.Request.Form["commentid"]);

                if (RolePermissionManager.GetPermissions(c2.Post.CategoryId, GraffitiUsers.Current).Publish)
                {
                    Comment comment = new Comment(context.Request.Form["commentid"]);
                    comment.IsDeleted = false;
                    comment.Save();
                    context.Response.Write("The comment was un-deleted. You may need to refresh the page to see it");
                }
                break;

            case "approve":
                Comment c3 = new Comment(context.Request.Form["commentid"]);

                if (RolePermissionManager.GetPermissions(c3.Post.CategoryId, GraffitiUsers.Current).Publish)
                {
                    Comment cmt = new Comment(context.Request.Form["commentid"]);
                    cmt.IsDeleted   = false;
                    cmt.IsPublished = true;
                    cmt.Save();
                    context.Response.Write("The comment was un-deleted and/or approved. You may need to refresh the page to see it");
                }
                break;

            case "deletePost":
                try
                {
                    Post postToDelete = new Post(context.Request.Form["postid"]);

                    Permission perm = RolePermissionManager.GetPermissions(postToDelete.CategoryId, user);

                    if (GraffitiUsers.IsAdmin(user) || perm.Publish)
                    {
                        postToDelete.IsDeleted = true;
                        postToDelete.Save(user.Name, DateTime.Now);

                        //Post.Delete(context.Request.Form["postid"]);
                        //ZCache.RemoveByPattern("Posts-");
                        //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                        context.Response.Write("The post was deleted. <a href=\"javascript:void(0);\" onclick=\"Posts.unDeletePost('" +
                                               new Urls().AdminAjax + "'," + context.Request.Form["postid"] +
                                               "); return false;\">Undo?</a>");
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "unDeletePost":
                Post p = new Post(context.Request.Form["postid"]);
                p.IsDeleted = false;
                p.Save();
                //ZCache.RemoveByPattern("Posts-");
                //ZCache.RemoveCache("Post-" + context.Request.Form["postid"]);
                //context.Response.Write("The post was un-deleted. You may need to fresh the page to see it");
                break;

            case "permanentDeletePost":
                Post tempPost = new Post(context.Request.Form["postid"]);
                Post.DestroyDeletedPost(tempPost.Id);
                context.Response.Write(tempPost.Title);
                break;

            case "createdWidget":
                string widgetID    = context.Request.Form["id"];
                var    the_widgets = Widgets.GetAvailableWidgets();
                Widget widget      = null;
                foreach (WidgetDescription wia in the_widgets)
                {
                    if (wia.UniqueId == widgetID)
                    {
                        widget = Widgets.Create(wia.WidgetType);
                        break;
                    }
                }

                context.Response.Write(widget.Id.ToString());

                break;

            case "updateWidgetsOrder":

                try
                {
                    string listID = context.Request.Form["id"];
                    string list   = "&" + context.Request.Form["list"];

                    Widgets.ReOrder(listID, list);

                    //StreamWriter sw = new StreamWriter(context.Server.MapPath("~/widgets.txt"), true);
                    //sw.WriteLine(DateTime.Now);
                    //sw.WriteLine();
                    //sw.WriteLine(context.Request.Form["left"]);
                    //sw.WriteLine(context.Request.Form["right"]);
                    //sw.WriteLine(context.Request.Form["queue"]);
                    //sw.WriteLine();
                    //sw.Close();

                    context.Response.Write("Saved!");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "deleteWidget":

                string deleteID = context.Request.Form["id"];
                Widgets.Delete(deleteID);
                context.Response.Write("The widget was removed!");

                break;

            case "createTextLink":
                DynamicNavigationItem di = new DynamicNavigationItem();
                di.NavigationType = DynamicNavigationType.Link;
                di.Text           = context.Request.Form["text"];
                di.Href           = context.Request.Form["href"];
                di.Id             = Guid.NewGuid();
                NavigationSettings.Add(di);
                context.Response.Write(di.Id);

                break;

            case "deleteTextLink":
                Guid g = new Guid(context.Request.Form["id"]);
                NavigationSettings.Remove(g);
                context.Response.Write("Success");
                break;

            case "reOrderNavigation":
                try
                {
                    string navItems = "&" + context.Request.Form["navItems"];
                    NavigationSettings.ReOrder(navItems);
                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "addNavigationItem":


                try
                {
                    if (context.Request.Form["type"] == "Post")
                    {
                        Post navPost = Post.FetchByColumn(Post.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                        DynamicNavigationItem item = new DynamicNavigationItem();
                        item.PostId         = navPost.Id;
                        item.Id             = navPost.UniqueId;
                        item.NavigationType = DynamicNavigationType.Post;
                        NavigationSettings.Add(item);
                        context.Response.Write("Success");
                    }
                    else if (context.Request.Form["type"] == "Category")
                    {
                        Category navCategory       = Category.FetchByColumn(Category.Columns.UniqueId, new Guid(context.Request.Form["id"]));
                        DynamicNavigationItem item = new DynamicNavigationItem();
                        item.CategoryId     = navCategory.Id;
                        item.Id             = navCategory.UniqueId;
                        item.NavigationType = DynamicNavigationType.Category;
                        NavigationSettings.Add(item);
                        context.Response.Write("Success");
                    }
                }
                catch (Exception exp)
                {
                    context.Response.Write(exp.Message);
                }

                break;

            case "reOrderPosts":
                try
                {
                    var   posts = new Dictionary <int, Post>();
                    Query query = Post.CreateQuery();
                    query.AndWhere(Post.Columns.CategoryId, int.Parse(context.Request.QueryString["id"]));
                    foreach (Post post in PostCollection.FetchByQuery(query))
                    {
                        posts[post.Id] = post;
                    }

                    string postOrder   = context.Request.Form["posts"];
                    int    orderNumber = 1;
                    foreach (string sId in postOrder.Split('&'))
                    {
                        Post post = null;
                        posts.TryGetValue(int.Parse(sId), out post);
                        if (post != null && post.SortOrder != orderNumber)
                        {
                            post.SortOrder = orderNumber;
                            post.Save();
                        }

                        orderNumber++;
                    }

                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "reOrderHomePosts":
                try
                {
                    var   posts = new Dictionary <int, Post>();
                    Query query = Post.CreateQuery();
                    query.AndWhere(Post.Columns.IsHome, true);
                    foreach (Post post in PostCollection.FetchByQuery(query))
                    {
                        posts[post.Id] = post;
                    }

                    string postOrder   = context.Request.Form["posts"];
                    int    orderNumber = 1;
                    foreach (string sId in postOrder.Split('&'))
                    {
                        Post post = null;
                        posts.TryGetValue(int.Parse(sId), out post);
                        if (post != null && post.HomeSortOrder != orderNumber)
                        {
                            post.HomeSortOrder = orderNumber;
                            post.Save();
                        }

                        orderNumber++;
                    }

                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "categoryForm":

                int selectedCategory = int.Parse(context.Request.QueryString["category"] ?? "-1");
                int postId           = int.Parse(context.Request.QueryString["post"] ?? "-1");
                NameValueCollection nvcCustomFields;
                if (postId > 0)
                {
                    nvcCustomFields = new Post(postId).CustomFields();
                }
                else
                {
                    nvcCustomFields = new NameValueCollection();
                }

                CustomFormSettings cfs = CustomFormSettings.Get(selectedCategory);

                if (cfs.HasFields)
                {
                    foreach (CustomField cf in cfs.Fields)
                    {
                        if (context.Request.Form[cf.Id.ToString()] != null)
                        {
                            nvcCustomFields[cf.Name] = context.Request.Form[cf.Id.ToString()];
                        }
                    }

                    context.Response.Write(cfs.GetHtmlForm(nvcCustomFields, (postId < 1)));
                }
                else
                {
                    context.Response.Write("");
                }

                break;

            case "toggleEventStatus":

                try
                {
                    EventDetails ed = Events.GetEvent(context.Request.QueryString["t"]);
                    ed.Enabled = !ed.Enabled;

                    if (ed.Enabled)
                    {
                        ed.Event.EventEnabled();
                    }
                    else
                    {
                        ed.Event.EventDisabled();
                    }

                    Events.Save(ed);

                    context.Response.Write(ed.Enabled ? "Enabled" : "Disabled");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "buildMainFeed":
                try
                {
                    FileInfo mainFeedFileInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/Feed/Default.aspx"));

                    if (!mainFeedFileInfo.Directory.Exists)
                    {
                        mainFeedFileInfo.Directory.Create();
                    }

                    using (StreamWriter sw = new StreamWriter(mainFeedFileInfo.FullName, false))
                    {
                        sw.WriteLine("<%@ Page Language=\"C#\" Inherits=\"Graffiti.Core.RSS\" %>");
                        sw.Close();
                    }

                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                    return;
                }

                break;

            case "removeFeedData":
                try
                {
                    FeedManager.RemoveFeedData();
                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;

            case "buildCategoryPages":

                try
                {
                    CategoryCollection cc = new CategoryController().GetCachedCategories();
                    foreach (Category cat in cc)
                    {
                        cat.WritePages();
                    }


                    context.Response.Write("Success");
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                    return;
                }

                break;

            case "buildPages":

                try
                {
                    Query q = Post.CreateQuery();
                    q.PageIndex = Int32.Parse(context.Request.Form["p"]);
                    q.PageSize  = 20;
                    q.OrderByDesc(Post.Columns.Id);

                    PostCollection pc = PostCollection.FetchByQuery(q);
                    if (pc.Count > 0)
                    {
                        foreach (Post postToWrite in pc)
                        {
                            postToWrite.WritePages();
                            foreach (string tagName in Util.ConvertStringToList(postToWrite.TagList))
                            {
                                if (!string.IsNullOrEmpty(tagName))
                                {
                                    Tag.WritePage(tagName);
                                }
                            }
                        }

                        context.Response.Write("Next");
                    }
                    else
                    {
                        context.Response.Write("Success");
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                    return;
                }


                break;

            case "importPosts":

                try
                {
                    Post newPost = new Post();
                    newPost.Title = HttpContext.Current.Server.HtmlDecode(context.Request.Form["subject"]);

                    string postName = HttpContext.Current.Server.HtmlDecode(context.Request.Form["name"]);

                    PostCollection pc = new PostCollection();

                    if (!String.IsNullOrEmpty(postName))
                    {
                        Query q = Post.CreateQuery();
                        q.AndWhere(Post.Columns.Name, Util.CleanForUrl(postName));
                        pc.LoadAndCloseReader(q.ExecuteReader());
                    }

                    if (pc.Count > 0)
                    {
                        newPost.Name   = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                        newPost.Status = (int)PostStatus.Draft;
                    }
                    else if (String.IsNullOrEmpty(postName))
                    {
                        newPost.Name   = "[RENAME ME - " + Guid.NewGuid().ToString().Substring(0, 7) + "]";
                        newPost.Status = (int)PostStatus.Draft;
                    }
                    else
                    {
                        newPost.Name   = postName;
                        newPost.Status = (int)PostStatus.Publish;
                    }

                    if (String.IsNullOrEmpty(newPost.Title))
                    {
                        newPost.Title = newPost.Name;
                    }


                    newPost.PostBody       = HttpContext.Current.Server.HtmlDecode(context.Request.Form["body"]);
                    newPost.CreatedOn      = Convert.ToDateTime(context.Request.Form["createdon"]);
                    newPost.CreatedBy      = context.Request.Form["author"];
                    newPost.ModifiedBy     = context.Request.Form["author"];
                    newPost.TagList        = context.Request.Form["tags"];
                    newPost.ContentType    = "text/html";
                    newPost.CategoryId     = Convert.ToInt32(context.Request.Form["category"]);
                    newPost.UserName       = context.Request.Form["author"];
                    newPost.EnableComments = true;
                    newPost.Published      = Convert.ToDateTime(context.Request.Form["createdon"]);
                    newPost.IsPublished    = Convert.ToBoolean(context.Request.Form["published"]);

                    // this was causing too many posts to be in draft status.
                    // updated text on migrator to flag users to just move their content/binary directory
                    // into graffiti's root
                    //if (context.Request.Form["method"] == "dasBlog")
                    //{
                    //    if (newPost.Body.ToLower().Contains("/content/binary/"))
                    //        newPost.Status = (int)PostStatus.Draft;
                    //}

                    newPost.Save(GraffitiUsers.Current.Name);

                    int postid = Convert.ToInt32(context.Request.Form["postid"]);

                    IMigrateFrom temp = null;

                    switch (context.Request.Form["method"])
                    {
                    case "CS2007Database":

                        CS2007Database db = new CS2007Database();
                        temp = db;

                        break;

                    case "Wordpress":

                        Wordpress wp = new Wordpress();
                        temp = wp;

                        break;

                    case "BlogML":

                        BlogML bml = new BlogML();
                        temp = bml;

                        break;

                    case "CS21Database":
                        CS21Database csDb = new CS21Database();
                        temp = csDb;

                        break;

                    case "dasBlog":
                        dasBlog dasb = new dasBlog();
                        temp = dasb;

                        break;
                    }

                    var comments = temp.GetComments(postid);

                    foreach (MigratorComment cmnt in comments)
                    {
                        Comment ct = new Comment();
                        ct.PostId         = newPost.Id;
                        ct.Body           = cmnt.Body;
                        ct.Published      = cmnt.PublishedOn;
                        ct.IPAddress      = cmnt.IPAddress;
                        ct.WebSite        = cmnt.WebSite;
                        ct.Email          = string.IsNullOrEmpty(cmnt.Email) ? "" : cmnt.Email;
                        ct.Name           = string.IsNullOrEmpty(cmnt.UserName) ? "" : cmnt.UserName;
                        ct.IsPublished    = cmnt.IsPublished;
                        ct.IsTrackback    = cmnt.IsTrackback;
                        ct.SpamScore      = cmnt.SpamScore;
                        ct.DontSendEmail  = true;
                        ct.DontChangeUser = true;

                        ct.Save();

                        Comment ctemp = new Comment(ct.Id);
                        ctemp.DontSendEmail  = true;
                        ctemp.DontChangeUser = true;
                        ctemp.Body           = HttpContext.Current.Server.HtmlDecode(ctemp.Body);
                        ctemp.Save();
                    }

                    if (newPost.Status == (int)PostStatus.Publish)
                    {
                        context.Response.Write("Success" + context.Request.Form["panel"]);
                    }
                    else
                    {
                        context.Response.Write("Warning" + context.Request.Form["panel"]);
                    }
                }
                catch (Exception ex)
                {
                    context.Response.Write(context.Request.Form["panel"] + ":" + ex.Message);
                }

                break;

            case "saveHomeSortStatus":

                SiteSettings siteSettings = SiteSettings.Get();
                siteSettings.UseCustomHomeList = bool.Parse(context.Request.Form["ic"]);
                siteSettings.Save();
                context.Response.Write("Success");

                break;

            case "checkCategoryPermission":

                try
                {
                    int        catID          = Int32.Parse(context.Request.QueryString["category"]);
                    string     permissionName = context.Request.QueryString["permission"];
                    Permission perm           = RolePermissionManager.GetPermissions(catID, user);

                    bool permissionResult = false;
                    switch (permissionName)
                    {
                    case "Publish":
                        permissionResult = perm.Publish;
                        break;

                    case "Read":
                        permissionResult = perm.Read;
                        break;

                    case "Edit":
                        permissionResult = perm.Edit;
                        break;
                    }

                    context.Response.Write(permissionResult.ToString().ToLower());
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                }
                break;
            }
        }
示例#26
0
    protected void publish_return_click(object sender, EventArgs e)
    {
        try
        {
            if (!IsValid)
            {
                return;
            }

            IGraffitiUser user = GraffitiUsers.Current;

            ListItem catItem = CategoryList.SelectedItem;
            if (catItem.Value == "-1" && String.IsNullOrEmpty(newCategory.Text))
            {
                SetMessage("Please enter a name for the new Category.", StatusType.Error);
                return;
            }

            string extenedBody = txtContent_extend.Text;
            string postBody    = txtContent.Text;

            if (string.IsNullOrEmpty(postBody))
            {
                SetMessage("Please enter a post body.", StatusType.Warning);
                return;
            }

            Category c = new Category();

            if (catItem.Value == "-1")
            {
                try
                {
                    Category temp = new Category();
                    temp.Name = newCategory.Text;
                    temp.Save();

                    c = temp;

                    CategoryController.Reset();
                }
                catch (Exception ex)
                {
                    SetMessage("The category could not be created. Reason: " + ex.Message, StatusType.Error);
                }
            }
            else
            {
                c = new CategoryController().GetCachedCategory(Int32.Parse(catItem.Value), false);
            }

            string pid = Request.QueryString["id"];
            Post   p   = pid == null ? new Post() : new Post(pid);

            if (p.IsNew)
            {
                p["where"] = "web";

                p.UserName = user.Name;

                if (Request.Form["dateChangeFlag"] == "true")
                {
                    p.Published = PublishDate.DateTime;
                }
                else
                {
                    p.Published = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet);
                }
            }
            else
            {
                p.Published = PublishDate.DateTime;
            }

            p.ModifiedOn = DateTime.Now.AddHours(SiteSettings.Get().TimeZoneOffSet);

            p.PostBody = postBody;
            if (string.IsNullOrEmpty(extenedBody) || extenedBody == "<p></p>" || extenedBody == "<p>&nbsp;</p>" ||
                extenedBody == "<br />\r\n")
            {
                p.ExtendedBody = null;
            }
            else
            {
                p.ExtendedBody = extenedBody;
            }

            p.Title           = Server.HtmlEncode(txtTitle.Text);
            p.EnableComments  = EnableComments.Checked;
            p.Name            = txtName.Text;
            p.TagList         = txtTags.Text.Trim();
            p.ContentType     = "text/html";
            p.CategoryId      = c.Id;
            p.Notes           = txtNotes.Text;
            p.ImageUrl        = postImage.Text;
            p.MetaKeywords    = Server.HtmlEncode(txtKeywords.Text.Trim());
            p.MetaDescription = Server.HtmlEncode(txtMetaScription.Text.Trim());
            p.IsHome          = HomeSortOverride.Checked;
            p.PostStatus      = (PostStatus)Enum.Parse(typeof(PostStatus), Request.Form[PublishStatus.UniqueID]);

            CustomFormSettings cfs = CustomFormSettings.Get(c);
            if (cfs.HasFields)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (cf.FieldType == FieldType.CheckBox && Request.Form[cf.Id.ToString()] == null)
                    {
                        p[cf.Name] = null;                         // false.ToString();
                    }
                    else if (cf.FieldType == FieldType.DateTime && Request.Form[cf.Id.ToString()].IndexOf("_") > -1)
                    {
                        p[cf.Name] = null;
                    }
                    else
                    {
                        p[cf.Name] = Request.Form[cf.Id.ToString()];
                    }
                }
            }

            if (HasDuplicateName(p))
            {
                SetMessage("A post in the selected category already exists with the same name.", StatusType.Error);
                return;
            }

            PostRevisionManager.CommitPost(p, user, FeaturedSite.Checked, FeaturedCategory.Checked);

            string CatQuery = (Request.QueryString["category"] == null)
                                                  ? null
                                                  : (p.Status == 1) ? "&category=" + p.CategoryId : "&category=" + Request.QueryString["category"];
            string AuthQuery = (Request.QueryString["author"] == null) ? null : "&author=" + Request.QueryString["author"];
            Response.Redirect("~/graffiti-admin/posts/" + "?id=" + p.Id + "&status=" + p.Status + CatQuery + AuthQuery);
        }
        catch (Exception ex)
        {
            SetMessage("Your post could not be saved. Reason: " + ex.Message, StatusType.Error);
        }
    }
示例#27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        NameValueCollection nvcCustomFields = null;
        IGraffitiUser       user            = GraffitiUsers.Current;
        bool isAdmin                     = GraffitiUsers.IsAdmin(user);
        CategoryController cc            = new CategoryController();
        Category           uncategorized = cc.GetCachedCategory(CategoryController.UncategorizedName, false);
        Post post = null;

        if (Request.QueryString["id"] != null)
        {
            post = new Post(Request.QueryString["id"]);
        }

        ProcessCategoryDropdownList(cc, isAdmin, uncategorized);

        if (!IsPostBack)
        {
            ClientScripts.RegisterScriptsForDateTimeSelector(this);
            Util.CanWriteRedirect(Context);

            SetDefaultFormValues(isAdmin);

            if (Request.QueryString["nid"] != null)
            {
                post = new Post(Request.QueryString["nid"]);
                if (post.IsLoaded)
                {
                    if (isAdmin)
                    {
                        SetMessage("Your post was saved. View: <a href=\"" + post.Url + "\">" + post.Title + "</a>.", StatusType.Success);
                    }
                    else
                    {
                        SetMessage(
                            "Your post was saved. However, since you do not have permission to publish new content, it will need to be approved before it is viewable.",
                            StatusType.Success);
                    }
                    FormWrapper.Visible = false;
                }
            }


            if (post != null)
            {
                bool isOriginalPublished  = post.IsPublished;
                int  currentVersionNumber = post.Version;

                VersionStoreCollection vsc = VersionStore.GetVersionHistory(post.Id);

                if (vsc.Count > 0)
                {
                    var the_Posts = new List <Post>();
                    foreach (VersionStore vs in vsc)
                    {
                        the_Posts.Add(ObjectManager.ConvertToObject <Post>(vs.Data));
                    }

                    the_Posts.Add(post);

                    the_Posts.Sort(delegate(Post p1, Post p2) { return(Comparer <int> .Default.Compare(p2.Version, p1.Version)); });


                    string versionHtml =
                        "<div style=\"width: 280px; overflow: hidden; padding: 6px 0; border-bottom: 1px solid #ccc;\"><b>Revision {0}</b> ({1})<div>by {2}</div><div style=\"font-style: italic;\">{3}</div></div>";
                    string versionText = "Revision {0}";
                    foreach (Post px in the_Posts)
                    {
                        VersionHistory.Items.Add(
                            new DropDownListItem(
                                string.Format(versionHtml, px.Version, px.ModifiedOn.ToString("dd-MMM-yyyy"),
                                              GraffitiUsers.GetUser(px.ModifiedBy).ProperName, px.Notes),
                                string.Format(versionText, px.Version), px.Version.ToString()));
                    }


                    int versionToEdit = Int32.Parse(Request.QueryString["v"] ?? "-1");
                    if (versionToEdit > -1)
                    {
                        foreach (Post px in the_Posts)
                        {
                            if (px.Version == versionToEdit)
                            {
                                post = px;

                                // add logic to change category if it was deleted here
                                CategoryCollection cats = new CategoryController().GetCachedCategories();
                                Category           temp = cats.Find(
                                    delegate(Category c) { return(c.Id == post.CategoryId); });

                                if (temp == null && post.CategoryId != 1)
                                {
                                    post.CategoryId = uncategorized.Id;
                                    SetMessage(
                                        "The category ID on this post revision could not be located. It has been marked as Uncategorized. ",
                                        StatusType.Warning);
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        post = the_Posts[0];
                    }

                    VersionHistoryArea.Visible            = true;
                    VersionHistory.SelectedValue          = post.Version.ToString();
                    VersionHistory.Attributes["onchange"] = "window.location = '" +
                                                            VirtualPathUtility.ToAbsolute("~/graffiti-admin/posts/write/") +
                                                            "?id=" + Request.QueryString["id"] +
                                                            "&v=' + this.options[this.selectedIndex].value;";
                }


                if (post.Id > 0)
                {
                    nvcCustomFields = post.CustomFields();

                    txtTitle.Text            = Server.HtmlDecode(post.Title);
                    txtContent.Text          = post.PostBody;
                    txtContent_extend.Text   = post.ExtendedBody;
                    txtTags.Text             = post.TagList;
                    txtName.Text             = Util.UnCleanForUrl(post.Name);
                    EnableComments.Checked   = post.EnableComments;
                    PublishDate.DateTime     = post.Published;
                    txtNotes.Text            = post.Notes;
                    postImage.Text           = post.ImageUrl;
                    FeaturedSite.Checked     = (post.Id == SiteSettings.Get().FeaturedId);
                    FeaturedCategory.Checked = (post.Id == post.Category.FeaturedId);
                    txtKeywords.Text         = Server.HtmlDecode(post.MetaKeywords ?? string.Empty);
                    txtMetaScription.Text    = Server.HtmlDecode(post.MetaDescription ?? string.Empty);
                    HomeSortOverride.Checked = post.IsHome;

                    ListItem li = CategoryList.Items.FindByValue(post.CategoryId.ToString());
                    if (li != null)
                    {
                        CategoryList.SelectedIndex = CategoryList.Items.IndexOf(li);
                    }
                    else
                    {
                        CategoryList.SelectedIndex =
                            CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(uncategorized.Id.ToString()));
                    }

                    li = PublishStatus.Items.FindByValue(post.Status.ToString());
                    if (li != null && post.Status != (int)PostStatus.PendingApproval &&
                        post.Status != (int)PostStatus.RequiresChanges)
                    {
                        PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li);
                    }
                    else if (post.Status == (int)PostStatus.PendingApproval || post.Status == (int)PostStatus.RequiresChanges)
                    {
                        // turn published on if it is in req changes
                        ListItem li2 = PublishStatus.Items.FindByValue(Convert.ToString((int)PostStatus.Publish));
                        if (li2 != null)
                        {
                            PublishStatus.SelectedIndex = PublishStatus.Items.IndexOf(li2);
                        }
                    }

                    if (post.Version != currentVersionNumber && !isOriginalPublished)
                    {
                        SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning);
                    }
                    else if (post.Version != currentVersionNumber && isOriginalPublished)
                    {
                        SetMessage(
                            "The post your are editing has been published. However, the revision you are editing has not been published.",
                            StatusType.Warning);
                    }
                    else if (!isOriginalPublished)
                    {
                        SetMessage("You are editing an unpublished revision of this post.", StatusType.Warning);
                    }
                }
                else
                {
                    FormWrapper.Visible = false;
                    SetMessage("The post with the id " + Request.QueryString["id"] + " could not be found.", StatusType.Warning);
                }
            }
            else
            {
                ListItem liUncat = CategoryList.Items.FindByText(CategoryController.UncategorizedName);
                if (liUncat != null)
                {
                    CategoryList.SelectedIndex = CategoryList.Items.IndexOf(liUncat);
                }
            }
        }

        if (FormWrapper.Visible)
        {
            NavigationConfirmation.RegisterPage(this);
            NavigationConfirmation.RegisterControlForCancel(Publish_Button);

            Page.ClientScript.RegisterStartupScript(GetType(),
                                                    "Writer-Page-StartUp",
                                                    "$(document).ready(function() { var eBody = $('#extended_body')[0]; " +
                                                    (!string.IsNullOrEmpty(txtContent_extend.Text)
                                                                         ? "eBody.style.position = 'static'; eBody.style.visibility = 'visible';"
                                                                         : "eBody.style.position = 'absolute'; eBody.style.visibility = 'hidden';") +
                                                    "categoryChanged($('#" + CategoryList.ClientID +
                                                    "')[0]); Publish_Status_Change();});", true);

            Page.ClientScript.RegisterHiddenField("dateChangeFlag", "false");
        }

        CustomFormSettings cfs = CustomFormSettings.Get(int.Parse(CategoryList.SelectedItem.Value));

        if (cfs.HasFields)
        {
            if (nvcCustomFields == null)
            {
                nvcCustomFields = new NameValueCollection();
                foreach (CustomField cf in cfs.Fields)
                {
                    if (Request.Form[cf.Id.ToString()] != null)
                    {
                        nvcCustomFields[cf.Name] = Request.Form[cf.Id.ToString()];
                    }
                }
            }

            bool isNewPost = (post != null) && (post.Id < 1);
            the_CustomFields.Text = cfs.GetHtmlForm(nvcCustomFields, isNewPost);
        }
        else
        {
            CustomFieldsTab.Tab.Enabled = false;
            the_CustomFields.Text       = "";
        }

        PublishStatus.Attributes.Add("onchange", "Publish_Status_Change();");
    }
        private void AddNewsFields(Category newsCategory)
        {
            bool startDateFieldExists = false;
            bool endDateFieldExists   = false;
            bool priorityFieldExists  = false;

            CustomFormSettings cfs = CustomFormSettings.Get(newsCategory, false);

            if (cfs.Fields != null && cfs.Fields.Count > 0)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (!startDateFieldExists && Util.AreEqualIgnoreCase(startDateFieldName, cf.Name))
                    {
                        startDateFieldExists = true;
                    }
                    if (!endDateFieldExists && Util.AreEqualIgnoreCase(endDateFieldName, cf.Name))
                    {
                        endDateFieldExists = true;
                    }
                    if (!priorityFieldExists && Util.AreEqualIgnoreCase(priorityFieldName, cf.Name))
                    {
                        priorityFieldExists = true;
                    }

                    if (endDateFieldExists && startDateFieldExists && priorityFieldExists)
                    {
                        break;
                    }
                }
            }

            if (!startDateFieldExists)
            {
                CustomField startDateField = new CustomField();
                startDateField.Name        = startDateFieldName;
                startDateField.Description = "The first date to show the news item";
                startDateField.Enabled     = true;
                startDateField.Id          = Guid.NewGuid();
                startDateField.FieldType   = FieldType.Date;

                cfs.Name = newsCategory.Id.ToString();
                cfs.Add(startDateField);
                cfs.Save();
            }

            if (!endDateFieldExists)
            {
                CustomField endDateField = new CustomField();
                endDateField.Name        = endDateFieldName;
                endDateField.Description = "The last date to show the news item";
                endDateField.Enabled     = true;
                endDateField.Id          = Guid.NewGuid();
                endDateField.FieldType   = FieldType.Date;

                cfs.Name = newsCategory.Id.ToString();
                cfs.Add(endDateField);
                cfs.Save();
            }

            if (!priorityFieldExists)
            {
                CustomField priorityField = new CustomField();
                priorityField.Name        = priorityFieldName;
                priorityField.Description = "Priority of the news item. Higher priority displays first";
                priorityField.Enabled     = true;
                priorityField.Id          = Guid.NewGuid();
                priorityField.FieldType   = FieldType.List;
                priorityField.ListOptions = new List <ListItemFormElement>();
                priorityField.ListOptions.Add(new ListItemFormElement("Low", "1"));
                priorityField.ListOptions.Add(new ListItemFormElement("Normal", "2", true));
                priorityField.ListOptions.Add(new ListItemFormElement("High", "3"));

                cfs.Name = newsCategory.Id.ToString();
                cfs.Add(priorityField);
                cfs.Save();
            }
        }