Example #1
0
        /// <summary>
        /// Handles the SaveAndPublish event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// Sets the document's properties and if the page is valid continues to publish it, otherwise just saves a revision.
        /// </remarks>
        protected void Publish(object sender, EventArgs e)
        {
            //update UI and set document properties
            PerformSaveLogic();

            //the business logic here will check to see if the doc can actually be published and will return the
            // appropriate result so we can display the correct error messages (or success).
            var savePublishResult = _document.SaveAndPublishWithResult(UmbracoUser);

            ShowMessageForStatus(savePublishResult.Result);

            if (savePublishResult.Success)
            {
                _littPublishStatus.Text = string.Format("{0}: {1}<br/>", ui.Text("content", "lastPublished", UmbracoUser), _document.VersionDate.ToString());

                if (UmbracoUser.GetPermissions(_document.Path).IndexOf("U") > -1)
                {
                    _unPublish.Visible = true;
                }

                _documentHasPublishedVersion = _document.Content.HasPublishedVersion();
            }

            ClientTools.SyncTree(_document.Path, true);
        }
Example #2
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         ClientTools.SyncTree(_media.Path, false);
     }
 }
Example #3
0
        private void UpdateTreeNode()
        {
            var clientTools = new ClientTools(this.Page);

            clientTools
            .SyncTree(cType.Path, true);
        }
Example #4
0
        /// <summary>
        /// Handles the Save event for the ContentControl.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>
        /// This will set the document's properties and persist a new document revision
        /// </remarks>
        protected void Save(object sender, EventArgs e)
        {
            //NOTE: This is only here because we have to keep backwards compatibility with events in the ContentControl.
            // see: http://issues.umbraco.org/issue/U4-1660
            // in this case both Save and SaveAndPublish will fire when we are publishing but we only want to handle that once,
            // so if this is actually doing a publish, we'll exit and rely on the SaveAndPublish handler to do all the work.
            if (_cControl.DoesPublish)
            {
                return;
            }

            //update UI and set document properties
            PerformSaveLogic();

            //persist the document
            _document.Save();

            // Run Handler
            BusinessLogic.Actions.Action.RunActionHandlers(_document, ActionUpdate.Instance);

            ClientTools.ShowSpeechBubble(
                speechBubbleIcon.save, ui.Text("speechBubbles", "editContentSavedHeader", null),
                ui.Text("speechBubbles", "editContentSavedText", null));

            ClientTools.SyncTree(_document.Path, true);
        }
Example #5
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!m_ContentId.HasValue)
            {
                return;
            }

            if (!CheckUserValidation())
            {
                return;
            }

            // clear preview cookie
            // zb-00004 #29956 : refactor cookies names & handling
            StateHelper.Cookies.Preview.Clear();

            if (!IsPostBack)
            {
                BusinessLogic.Log.Add(BusinessLogic.LogTypes.Open, base.getUser(), _document.Id, "");
                ClientTools.SyncTree(_document.Path, false);
            }


            jsIds.Text = "var umbPageId = " + _document.Id.ToString() + ";\nvar umbVersionId = '" + _document.Version.ToString() + "';\n";
        }
Example #6
0
        protected void Save(object sender, System.EventArgs e)
        {
            // error handling test
            if (!Page.IsValid)
            {
                foreach (uicontrols.TabPage tp in tmp.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader          = ui.Text("errorHandling", "errorHeader");
                    tp.CloseCaption         = ui.Text("close");
                }
            }
            else if (Page.IsPostBack)
            {
                // hide validation summaries
                foreach (uicontrols.TabPage tp in tmp.GetPanels())
                {
                    tp.ErrorControl.Visible = false;
                }
            }
            _media.Save();

            this.updateDateLiteral.Text = _media.VersionDate.ToShortDateString() + " " + _media.VersionDate.ToShortTimeString();
            this.UpdateMediaFileLinksLiteral();

            _media.XmlGenerate(new XmlDocument());
            ClientTools.SyncTree(_media.Path, true);
        }
Example #7
0
 protected void Page_Load(object sender, System.EventArgs e)
 {
     //if (!IsPostBack)
     //{
     //    SyncPath.Text = _media.Path;
     //    newName.Text = _media.Text.Replace("'", "\\'");
     //}
     if (!IsPostBack)
     {
         ClientTools.SyncTree(_media.Path, false);
     }
 }
Example #8
0
        protected void save_click(object sender, ImageClickEventArgs e)
        {
            // save prevalues;
            if (_prevalue != null)
            {
                _prevalue.Save();
            }

            dt.Text = txtName.Text;

            dt.DataType = f.DataType(new Guid(ddlRenderControl.SelectedValue));
            dt.Save();

            ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "dataTypeSaved", null), "");

            ClientTools.SyncTree(dt.Path, true);
        }
        protected void buttonRemoveProtection_Click(object sender, System.EventArgs e)
        {
            int pageId = int.Parse(helper.Request("nodeId"));

            p_setup.Visible = false;

            Access.RemoveProtection(pageId);

            feedback_text.Text = HttpUtility.HtmlEncode(ui.Text("publicAccess", "paIsRemoved", new cms.businesslogic.CMSNode(pageId).Text));
            p_feedback.Visible = true;

            var content = ApplicationContext.Current.Services.ContentService.GetById(pageId);

            //reloads the current node in the tree
            ClientTools.SyncTree(content.Path, true);
            //reloads the current node's children in the tree
            ClientTools.ReloadActionNode(false, true);
        }
        protected void buttonRemoveProtection_Click(object sender, System.EventArgs e)
        {
            int pageId = int.Parse(helper.Request("nodeId"));
            p_buttons.Visible = false;
            pane_advanced.Visible = false;
            pane_simple.Visible = false;

            Access.RemoveProtection(pageId);

            feedback.Text = ui.Text("publicAccess", "paIsRemoved", new cms.businesslogic.CMSNode(pageId).Text) + "</p><p><a href='#' onclick='" + ClientTools.Scripts.CloseModalWindow() + "'>" + ui.Text("closeThisWindow") + "</a>";

            var content = ApplicationContext.Current.Services.ContentService.GetById(pageId);
            //reloads the current node in the tree
            ClientTools.SyncTree(content.Path, true);
            //reloads the current node's children in the tree
            ClientTools.ReloadActionNode(false, true);
            feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success;
        }
        /// <summary>
        /// Save button in Umbraco menu
        /// </summary>
        /// <param name="sender">expects saveMenuImageButton object</param>
        /// <param name="e">expects ImageClickEventArgs</param>
        void saveMenuImageButton_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                var nameChanged      = this._relationType.Name != this.nameTextBox.Text.Trim();
                var aliasChanged     = this._relationType.Alias != this.aliasTextBox.Text.Trim();
                var directionChanged = this._relationType.IsBidirectional != (this.dualRadioButtonList.SelectedValue == "1");

                if (nameChanged || aliasChanged || directionChanged)
                {
                    string bubbleBody = string.Empty;

                    if (nameChanged)
                    {
                        bubbleBody += "Name, ";

                        this._relationType.Name = this.nameTextBox.Text.Trim();

                        // Refresh tree, as the name as changed
                        ClientTools.SyncTree(this._relationType.Id.ToString(), true);
                    }

                    if (directionChanged)
                    {
                        bubbleBody += "Direction, ";
                        this._relationType.IsBidirectional = this.dualRadioButtonList.SelectedValue == "1";
                    }

                    if (aliasChanged)
                    {
                        bubbleBody += "Alias, ";
                        this._relationType.Alias = this.aliasTextBox.Text.Trim();
                    }

                    bubbleBody = bubbleBody.Remove(bubbleBody.LastIndexOf(','), 1);
                    bubbleBody = bubbleBody + "Changed";

                    var relationService = Services.RelationService;
                    relationService.Save(this._relationType);

                    ClientTools.ShowSpeechBubble(speechBubbleIcon.save, "Relation Type Updated", bubbleBody);
                }
            }
        }
Example #12
0
        protected void Save(object sender, EventArgs e)
        {
            // do not continue saving anything if the page is invalid!
            // http://issues.umbraco.org/issue/U4-227
            if (!Page.IsValid)
            {
                foreach (uicontrols.TabPage tp in _contentControl.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader          = ui.Text("errorHandling", "errorHeader");
                    tp.CloseCaption         = ui.Text("close");
                }
            }
            else
            {
                if (Page.IsPostBack)
                {
                    // hide validation summaries
                    foreach (uicontrols.TabPage tp in _contentControl.GetPanels())
                    {
                        tp.ErrorControl.Visible = false;
                    }
                }

                //The value of the properties has been set on IData through IDataEditor in the ContentControl
                //so we need to 'retrieve' that value and set it on the property of the new IContent object.
                //NOTE This is a workaround for the legacy approach to saving values through the DataType instead of the Property
                //- (The DataType shouldn't be responsible for saving the value - especically directly to the db).
                foreach (var item in _contentControl.DataTypes)
                {
                    _media.getProperty(item.Key).Value = item.Value.Data.Value;
                }

                _media.Save();

                this._updateDateLiteral.Text = _media.VersionDate.ToShortDateString() + " " + _media.VersionDate.ToShortTimeString();
                this.UpdateMediaFileLinksLiteral();

                _media.XmlGenerate(new XmlDocument());
                ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editMediaSaved"), ui.Text("editMediaSavedText"));
                ClientTools.SyncTree(_media.Path, true);
            }
        }
Example #13
0
        protected void save_click(object sender, ImageClickEventArgs e)
        {
            // save prevalues;
            if (_prevalue != null)
            {
                _prevalue.Save();
            }

            dt.Text = txtName.Text;

            dt.DataType = f.DataType(new Guid(ddlRenderControl.SelectedValue));
            dt.Save();

            System.Web.HttpRuntime.Cache.Remove(string.Format("UmbracoDataTypeDefinition{0}", dt.UniqueId));

            ClientTools.ShowSpeechBubble(BasePages.BasePage.speechBubbleIcon.save, ui.Text("speechBubbles", "dataTypeSaved", null), "");

            ClientTools.SyncTree(dt.Path, true);
        }
Example #14
0
        void save_Click(object sender, EventArgs e)
        {
            foreach (TextBox t in languageFields)
            {
                //check for null but allow empty string!
                // http://issues.umbraco.org/issue/U4-1931
                if (t.Text != null)
                {
                    currentItem.setValue(int.Parse(t.ID), t.Text);
                }
            }

            labelChangeKey.Text = ""; // reset error text
            var newKey = boxChangeKey.Text;

            if (string.IsNullOrWhiteSpace(newKey) == false && newKey != currentItem.key)
            {
                // key already exists, save but inform
                if (Dictionary.DictionaryItem.hasKey(newKey) == true)
                {
                    labelChangeKey.Text = ui.Text("dictionaryItem", "changeKeyError", newKey, currentUser);
                    boxChangeKey.Text   = currentItem.key; // reset key
                }
                else
                {
                    // set the new key
                    currentItem.setKey(newKey);

                    // update the title with the new key
                    Panel1.title.InnerHtml = ui.Text("editdictionary") + ": " + newKey;

                    // sync the content tree
                    var path = BuildPath(currentItem);
                    ClientTools.SyncTree(path, true);
                }
            }
            txt.Text = "<br/><p>" + ui.Text("dictionaryItem", "description", currentItem.key, currentUser) + "</p><br/>";
            ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "dictionaryItemSaved"), "");
        }
Example #15
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _macro = Services.MacroService.GetById(Convert.ToInt32(Request.QueryString["macroID"]));

            if (IsPostBack == false)
            {
                ClientTools
                .SyncTree("-1," + _macro.Id, false);

                PopulateFieldsOnLoad(_macro);

                // Load elements from macro
                MacroPropertyBind();

                PopulatePartialViewFiles();

                // Load usercontrols
                PopulateUserControls(IOHelper.MapPath(SystemDirectories.UserControls));
                userControlList.Items.Insert(0, new ListItem("Browse usercontrols on server...", string.Empty));
            }
        }
Example #16
0
        protected void Save(object sender, EventArgs e)
        {
            // error handling test
            if (Page.IsValid == false)
            {
                foreach (uicontrols.TabPage tp in _cControl.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader          = ui.Text("errorHandling", "errorButDataWasSaved");
                    tp.CloseCaption         = ui.Text("close");
                }
            }
            else if (Page.IsPostBack)
            {
                // hide validation summaries
                foreach (uicontrols.TabPage tp in _cControl.GetPanels())
                {
                    tp.ErrorControl.Visible = false;
                }
            }

            // Update name if it has not changed and is not empty
            if (_cControl.NameTxt != null && _document.Text != _cControl.NameTxt.Text && !_cControl.NameTxt.Text.IsNullOrWhiteSpace())
            {
                //_refreshTree = true;
                _document.Text = _cControl.NameTxt.Text;
                //newName.Text = _document.Text;
            }


            if (_dpRelease.DateTime > new DateTime(1753, 1, 1) && _dpRelease.DateTime < new DateTime(9999, 12, 31))
            {
                _document.ReleaseDate = _dpRelease.DateTime;
            }
            else
            {
                _document.ReleaseDate = new DateTime(1, 1, 1, 0, 0, 0);
            }
            if (_dpExpire.DateTime > new DateTime(1753, 1, 1) && _dpExpire.DateTime < new DateTime(9999, 12, 31))
            {
                _document.ExpireDate = _dpExpire.DateTime;
            }
            else
            {
                _document.ExpireDate = new DateTime(1, 1, 1, 0, 0, 0);
            }

            // Update default template
            if (_ddlDefaultTemplate.SelectedIndex > 0)
            {
                _document.Template = int.Parse(_ddlDefaultTemplate.SelectedValue);
            }
            else
            {
                if (new DocumentType(_document.ContentType.Id).allowedTemplates.Length == 0)
                {
                    _document.RemoveTemplate();
                }
            }

            //The value of the properties has been set on IData through IDataEditor in the ContentControl
            //so we need to 'retrieve' that value and set it on the property of the new IContent object.
            //NOTE This is a workaround for the legacy approach to saving values through the DataType instead of the Property
            //- (The DataType shouldn't be responsible for saving the value - especically directly to the db).
            foreach (var item in _cControl.DataTypes)
            {
                _document.getProperty(item.Key).Value = item.Value.Data.Value;
            }
            // Run Handler
            BusinessLogic.Actions.Action.RunActionHandlers(_document, ActionUpdate.Instance);
            _document.Save();

            // Update the update date
            _dp.Text = _document.UpdateDate.ToShortDateString() + " " + _document.UpdateDate.ToShortTimeString();

            if (_cControl.DoesPublish == false)
            {
                ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editContentSavedHeader", null), ui.Text("speechBubbles", "editContentSavedText", null));
            }

            ClientTools.SyncTree(_document.Path, true);
        }
Example #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
            {
                createdPackage = CreatedPackage.GetById(int.Parse(Request.QueryString["id"]));
                pack           = createdPackage.Data;

                /* CONTENT */

                cp = new ContentPicker();
                content.Controls.Add(cp);

                if (string.IsNullOrEmpty(pack.PackagePath) == false)
                {
                    packageUmbFile.Text = " &nbsp; <a href='" + Page.ResolveClientUrl(pack.PackagePath) + "'>Download</a>";
                }
                else
                {
                    packageUmbFile.Text = "<em>This package is not published</em>";
                }

                if (Page.IsPostBack == false)
                {
                    ClientTools
                    .SyncTree("-1,created," + createdPackage.Data.Id, false);

                    packageAuthorName.Text  = pack.Author;
                    packageAuthorUrl.Text   = pack.AuthorUrl;
                    packageLicenseName.Text = pack.License;
                    packageLicenseUrl.Text  = pack.LicenseUrl;
                    packageName.Text        = pack.Name;
                    packageReadme.Text      = pack.Readme;
                    packageVersion.Text     = pack.Version;
                    packageUrl.Text         = pack.Url;
                    iconUrl.Text            = pack.IconUrl;
                    umbracoVersion.Text     = pack.UmbracoVersion != null?pack.UmbracoVersion.ToString(3) : string.Empty;

                    /*ACTIONS XML*/
                    tb_actions.Text = pack.Actions;

                    cp.Value = pack.ContentNodeId.ToString();

                    //startNode.Value = pack.ContentNodeId.ToString();

                    packageContentSubdirs.Checked = pack.ContentLoadChildNodes;


                    /*TEMPLATES */
                    var nTemplates = Services.FileService.GetTemplates();
                    //Template[] umbTemplates = Template.GetAllAsList().ToArray();
                    foreach (var tmp in nTemplates)
                    {
                        ListItem li = new ListItem(tmp.Name, tmp.Id.ToString());

                        if (pack.Templates.Contains(tmp.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        templates.Items.Add(li);
                    }

                    /* DOC TYPES */
                    // fixme - media types? member types?
                    var nContentTypes = Services.ContentTypeService.GetAll();
                    //DocumentType[] docs = DocumentType.GetAllAsList().ToArray();
                    foreach (var dc in nContentTypes)
                    {
                        ListItem li = new ListItem(dc.Name, dc.Id.ToString());
                        if (pack.Documenttypes.Contains(dc.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        documentTypes.Items.Add(li);
                    }

                    /*Stylesheets */
                    var sheets = Services.FileService.GetStylesheets();
                    foreach (var st in sheets)
                    {
                        if (string.IsNullOrEmpty(st.Name) == false)
                        {
                            var li = new ListItem(st.Alias, st.Name);
                            if (pack.Stylesheets.Contains(st.Name))
                            {
                                li.Selected = true;
                            }
                            stylesheets.Items.Add(li);
                        }
                    }

                    /* MACROS */
                    var nMacros = Services.MacroService.GetAll();
                    //Macro[] umbMacros = Macro.GetAll();
                    foreach (var m in nMacros)
                    {
                        ListItem li = new ListItem(m.Name, m.Id.ToString());
                        if (pack.Macros.Contains(m.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        macros.Items.Add(li);
                    }

                    /*Langauges */
                    var nLanguages = Services.LocalizationService.GetAllLanguages();
                    //Language[] umbLanguages = Language.getAll;
                    foreach (var l in nLanguages)
                    {
                        ListItem li = new ListItem(l.CultureName, l.Id.ToString());
                        if (pack.Languages.Contains(l.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        languages.Items.Add(li);
                    }

                    /*Dictionary Items*/
                    var umbDictionary = Services.LocalizationService.GetRootDictionaryItems();
                    foreach (var d in umbDictionary)
                    {
                        string liName   = d.ItemKey;
                        var    children = Services.LocalizationService.GetDictionaryItemChildren(d.Key);
                        if (children.Any())
                        {
                            liName += " <small>(Including all child items)</small>";
                        }

                        var li = new ListItem(liName, d.Id.ToString());

                        if (pack.DictionaryItems.Contains(d.Id.ToString()))
                        {
                            li.Selected = true;
                        }

                        dictionary.Items.Add(li);
                    }

                    //TODO: Fix this with the new services and apis! and then remove since this should all be in angular

                    ///*Data types */
                    //cms.businesslogic.datatype.DataTypeDefinition[] umbDataType = cms.businesslogic.datatype.DataTypeDefinition.GetAll();

                    // sort array by name
                    //Array.Sort(umbDataType, delegate(cms.businesslogic.datatype.DataTypeDefinition umbDataType1, cms.businesslogic.datatype.DataTypeDefinition umbDataType2)
                    //{
                    //    return umbDataType1.Text.CompareTo(umbDataType2.Text);
                    //});

                    //foreach (cms.businesslogic.datatype.DataTypeDefinition umbDtd in umbDataType)
                    //{

                    //    ListItem li = new ListItem(umbDtd.Text, umbDtd.Id.ToString());

                    //    if (pack.DataTypes.Contains(umbDtd.Id.ToString()))
                    //        li.Selected = true;

                    //    cbl_datatypes.Items.Add(li);
                    //}

                    /* FILES */
                    packageFilesRepeater.DataSource = pack.Files;
                    packageFilesRepeater.DataBind();

                    packageControlPath.Text = pack.LoadControl;
                }
                else
                {
                    ClientTools
                    .SyncTree("-1,created," + createdPackage.Data.Id, true);
                }
            }
        }
Example #18
0
        public UploadResponse ProcessUploadRequest(HttpContext context)
        {
            int parentNodeId;

            if (int.TryParse(context.Request["parentNodeId"], out parentNodeId) && context.Request.Files.Count > 0)
            {
                try
                {
                    var parentNode = new Media(parentNodeId);
                    // Check FilePath
                    if (!string.IsNullOrEmpty(context.Request["path"]))
                    {
                        var pathParts = context.Request["path"].Trim('/').Split('/');

                        foreach (var pathPart in pathParts)
                        {
                            if (!string.IsNullOrEmpty(pathPart))
                            {
                                parentNode = GetOrCreateFolder(parentNode, pathPart);
                            }
                        }
                        parentNodeId = parentNode.Id;
                    }

                    // Check whether to replace existing
                    var  parsed          = false;
                    bool replaceExisting = (context.Request["replaceExisting"] == "1" || (bool.TryParse(context.Request["replaceExisting"], out parsed) && parsed));

                    // loop through uploaded files
                    for (var j = 0; j < context.Request.Files.Count; j++)
                    {
                        // get the current file
                        var uploadFile = context.Request.Files[j];

                        // if there was a file uploded
                        if (uploadFile.ContentLength > 0)
                        {
                            // Ensure we get the filename without the path in IE in intranet mode
                            // http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie
                            var fileName = uploadFile.FileName;
                            if (fileName.LastIndexOf(@"\") > 0)
                            {
                                fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                            }

                            fileName = Umbraco.Core.IO.IOHelper.SafeFileName(fileName);

                            var postedMediaFile = new PostedMediaFile
                            {
                                FileName        = fileName,
                                DisplayName     = context.Request["name"],
                                ContentType     = uploadFile.ContentType,
                                ContentLength   = uploadFile.ContentLength,
                                InputStream     = uploadFile.InputStream,
                                ReplaceExisting = replaceExisting
                            };

                            // Get concrete MediaFactory
                            var factory = MediaFactory.GetMediaFactory(parentNodeId, postedMediaFile, AuthenticatedUser);

                            // Handle media Item
                            var media = factory.HandleMedia(parentNodeId, postedMediaFile, AuthenticatedUser);
                        }
                    }

                    var scripts = new ClientTools(new Page());
                    scripts.SyncTree(parentNode.Path, true);

                    // log succes
                    Log.Add(LogTypes.New, parentNodeId, "Succes");
                }
                catch (Exception e)
                {
                    // log error
                    Log.Add(LogTypes.Error, parentNodeId, e.ToString());
                }
            }
            else
            {
                // log error
                Log.Add(LogTypes.Error, -1, "Parent node id is in incorrect format");
            }



            return(new UploadResponse());
        }
Example #19
0
        protected void Save(object sender, System.EventArgs e)
        {
            // error handling test
            if (!Page.IsValid)
            {
                foreach (uicontrols.TabPage tp in cControl.GetPanels())
                {
                    tp.ErrorControl.Visible = true;
                    tp.ErrorHeader          = ui.Text("errorHandling", "errorButDataWasSaved");
                    tp.CloseCaption         = ui.Text("close");
                }
            }
            else if (Page.IsPostBack)
            {
                // hide validation summaries
                foreach (uicontrols.TabPage tp in cControl.GetPanels())
                {
                    tp.ErrorControl.Visible = false;
                }
            }
            //Audit trail...
            BusinessLogic.Log.Add(BusinessLogic.LogTypes.Save, base.getUser(), _document.Id, "");

            // Update name
            if (_document.Text != cControl.NameTxt.Text)
            {
                //_refreshTree = true;
                _document.Text = cControl.NameTxt.Text;
                //newName.Text = _document.Text;
            }


            if (dpRelease.DateTime > new DateTime(1753, 1, 1) && dpRelease.DateTime < new DateTime(9999, 12, 31))
            {
                _document.ReleaseDate = dpRelease.DateTime;
            }
            else
            {
                _document.ReleaseDate = new DateTime(1, 1, 1, 0, 0, 0);
            }
            if (dpExpire.DateTime > new DateTime(1753, 1, 1) && dpExpire.DateTime < new DateTime(9999, 12, 31))
            {
                _document.ExpireDate = dpExpire.DateTime;
            }
            else
            {
                _document.ExpireDate = new DateTime(1, 1, 1, 0, 0, 0);
            }

            // Update default template
            if (ddlDefaultTemplate.SelectedIndex > 0)
            {
                _document.Template = int.Parse(ddlDefaultTemplate.SelectedValue);
            }
            else
            {
                if (new DocumentType(_document.ContentType.Id).allowedTemplates.Length == 0)
                {
                    _document.RemoveTemplate();
                }
            }



            // Run Handler
            BusinessLogic.Actions.Action.RunActionHandlers(_document, ActionUpdate.Instance);
            _document.Save();

            // Update the update date
            dp.Text = _document.UpdateDate.ToShortDateString() + " " + _document.UpdateDate.ToShortTimeString();

            if (!cControl.DoesPublish)
            {
                ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editContentSavedHeader", null), ui.Text("speechBubbles", "editContentSavedText", null));
            }

            ClientTools.SyncTree(_document.Path, true);
        }
Example #20
0
        protected void ValidateAndSave_Click(object sender, EventArgs e)
        {
            if (IsPropertyMappingValid())
            {
                // For all properties to be mapped, save the values to a temporary list
                var propertyMappings = SavePropertyMappings();

                // Get flag for if content already published
                var wasPublished = _content.Published;

                // Change the document type passing flag to clear the properties
                var newContentType = GetSelectedDocumentType();
                _content.ChangeContentType(newContentType, true);

                // Set the template if one has been selected
                if (NewTemplateList.SelectedItem != null)
                {
                    var templateId = int.Parse(NewTemplateList.SelectedItem.Value);
                    if (templateId > 0)
                    {
                        _content.Template = ApplicationContext.Current.Services.FileService.GetTemplate(templateId);
                    }
                }

                // Set the property values
                var propertiesMappedMessageBuilder = new StringBuilder("<ul>");
                foreach (var propertyMapping in propertyMappings)
                {
                    propertiesMappedMessageBuilder.AppendFormat("<li>{0} {1} {2}</li>",
                                                                propertyMapping.FromName, global::umbraco.ui.Text("changeDocType", "to"), propertyMapping.ToName);
                    _content.SetValue(propertyMapping.ToAlias, propertyMapping.Value);
                }
                propertiesMappedMessageBuilder.Append("</ul>");

                // Save
                var user = global::umbraco.BusinessLogic.User.GetCurrent();
                ApplicationContext.Current.Services.ContentService.Save(_content, user.Id);

                // Publish if the content was already published
                if (wasPublished)
                {
                    ApplicationContext.Current.Services.ContentService.Publish(_content, user.Id);
                }

                // Sync the tree
                ClientTools.SyncTree(_content.Path, true);

                // Reload the page if the content was already being viewed
                ClientTools.ReloadContentFrameUrlIfPathLoaded("/editContent.aspx?id=" + _content.Id);

                // Display success message
                SuccessMessage.Text          = global::umbraco.ui.Text("changeDocType", "successMessage").Replace("[new type]", "<strong>" + newContentType.Name + "</strong>");
                PropertiesMappedMessage.Text = propertiesMappedMessageBuilder.ToString();
                if (wasPublished)
                {
                    ContentPublishedMessage.Text    = global::umbraco.ui.Text("changeDocType", "contentRepublished");
                    ContentPublishedMessage.Visible = true;
                }
                else
                {
                    ContentPublishedMessage.Visible = false;
                }
                SuccessPlaceholder.Visible               = true;
                SaveAndCancelPlaceholder.Visible         = false;
                ValidationPlaceholder.Visible            = false;
                ChangeDocTypePane.Visible                = false;
                ChangeDocTypePropertyMappingPane.Visible = false;
            }
            else
            {
                ValidationPlaceholder.Visible = true;
            }
        }
Example #21
0
        protected void protect_Click(object sender, CommandEventArgs e)
        {
            if (string.IsNullOrEmpty(errorPagePicker.Value) || errorPagePicker.Value == "-1")
            {
                cv_errorPage.IsValid = false;
            }

            if (string.IsNullOrEmpty(loginPagePicker.Value) || loginPagePicker.Value == "-1")
            {
                cv_loginPage.IsValid = false;
            }

            //reset
            SimpleLoginNameValidator.IsValid = true;

            var provider = MembershipProviderExtensions.GetMembersMembershipProvider();

            if (Page.IsValid)
            {
                int pageId = int.Parse(helper.Request("nodeId"));

                if (e.CommandName == "simple")
                {
                    var memberLogin = simpleLogin.Visible ? simpleLogin.Text : SimpleLoginLabel.Text;

                    var member = provider.GetUser(memberLogin, false);
                    if (member == null)
                    {
                        var tempEmail = "u" + Guid.NewGuid().ToString("N") + "@example.com";

                        // this needs to work differently depending on umbraco members or external membership provider
                        if (provider.IsUmbracoMembershipProvider() == false)
                        {
                            member = provider.CreateUser(memberLogin, simplePassword.Text, tempEmail);
                        }
                        else
                        {
                            //if it's the umbraco membership provider, then we need to tell it what member type to create it with
                            if (MemberType.GetByAlias(Constants.Conventions.MemberTypes.SystemDefaultProtectType) == null)
                            {
                                MemberType.MakeNew(BusinessLogic.User.GetUser(0), Constants.Conventions.MemberTypes.SystemDefaultProtectType);
                            }
                            var castedProvider = provider.AsUmbracoMembershipProvider();
                            MembershipCreateStatus status;
                            member = castedProvider.CreateUser(Constants.Conventions.MemberTypes.SystemDefaultProtectType,
                                                               memberLogin, simplePassword.Text, tempEmail, null, null, true, null, out status);
                            if (status != MembershipCreateStatus.Success)
                            {
                                SimpleLoginNameValidator.IsValid      = false;
                                SimpleLoginNameValidator.ErrorMessage = "Could not create user: "******"Could not create user: "******"__umbracoRole_" + member.UserName;
                    if (Roles.RoleExists(simpleRoleName) == false)
                    {
                        Roles.CreateRole(simpleRoleName);
                    }
                    if (Roles.IsUserInRole(member.UserName, simpleRoleName) == false)
                    {
                        Roles.AddUserToRole(member.UserName, simpleRoleName);
                    }

                    Access.ProtectPage(true, pageId, int.Parse(loginPagePicker.Value), int.Parse(errorPagePicker.Value));
                    Access.AddMembershipRoleToDocument(pageId, simpleRoleName);
                    Access.AddMembershipUserToDocument(pageId, member.UserName);
                }
                else if (e.CommandName == "advanced")
                {
                    Access.ProtectPage(false, pageId, int.Parse(loginPagePicker.Value), int.Parse(errorPagePicker.Value));

                    foreach (ListItem li in _memberGroups.Items)
                    {
                        if (("," + _memberGroups.Value + ",").IndexOf("," + li.Value + ",", StringComparison.Ordinal) > -1)
                        {
                            Access.AddMembershipRoleToDocument(pageId, li.Value);
                        }
                        else
                        {
                            Access.RemoveMembershipRoleFromDocument(pageId, li.Value);
                        }
                    }
                }

                feedback.Text = ui.Text("publicAccess", "paIsProtected", new cms.businesslogic.CMSNode(pageId).Text) + "</p><p><a href='#' onclick='" + ClientTools.Scripts.CloseModalWindow() + "'>" + ui.Text("closeThisWindow") + "</a>";

                p_buttons.Visible     = false;
                pane_advanced.Visible = false;
                pane_simple.Visible   = false;
                var content = ApplicationContext.Current.Services.ContentService.GetById(pageId);
                //reloads the current node in the tree
                ClientTools.SyncTree(content.Path, true);
                //reloads the current node's children in the tree
                ClientTools.ReloadActionNode(false, true);
                feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success;
            }
        }
        public UploadResponse ProcessUploadRequest(HttpContext context)
        {
            int parentNodeId;

            if (int.TryParse(context.Request["parentNodeId"], out parentNodeId) && context.Request.Files.Count > 0)
            {
                try
                {
                    var parentNode = new Media(parentNodeId);
                    // Check FilePath
                    if (!string.IsNullOrEmpty(context.Request["path"]))
                    {
                        var pathParts = context.Request["path"].Trim('/').Split('/');

                        foreach (var pathPart in pathParts.Where(part => string.IsNullOrWhiteSpace(part) == false))
                        {
                            parentNode = GetOrCreateFolder(parentNode, pathPart);
                        }

                        parentNodeId = parentNode.Id;
                    }

                    // Check whether to replace existing
                    bool parsed;
                    var  replaceExisting = (context.Request["replaceExisting"] == "1" || (bool.TryParse(context.Request["replaceExisting"], out parsed) && parsed));

                    // loop through uploaded files
                    for (var j = 0; j < context.Request.Files.Count; j++)
                    {
                        // get the current file
                        var uploadFile = context.Request.Files[j];

                        //Are we allowed to upload this?
                        var ext = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.') + 1).ToLower();
                        if (UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext))
                        {
                            LogHelper.Warn <MediaUploader>("Cannot upload file " + uploadFile.FileName + ", it is not approved in `disallowedUploadFiles` in ~/config/UmbracoSettings.config");
                            continue;
                        }

                        using (var inputStream = uploadFile.InputStream)
                        {
                            // if there was a file uploded
                            if (uploadFile.ContentLength > 0)
                            {
                                // Ensure we get the filename without the path in IE in intranet mode
                                // http://stackoverflow.com/questions/382464/httppostedfile-filename-different-from-ie
                                var fileName = uploadFile.FileName;
                                if (fileName.LastIndexOf(@"\") > 0)
                                {
                                    fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                                }

                                fileName = Umbraco.Core.IO.IOHelper.SafeFileName(fileName);

                                var postedMediaFile = new PostedMediaFile
                                {
                                    FileName        = fileName,
                                    DisplayName     = context.Request["name"],
                                    ContentType     = uploadFile.ContentType,
                                    ContentLength   = uploadFile.ContentLength,
                                    InputStream     = inputStream,
                                    ReplaceExisting = replaceExisting
                                };

                                // Get concrete MediaFactory
                                var factory = MediaFactory.GetMediaFactory(parentNodeId, postedMediaFile, AuthenticatedUser);

                                // Handle media Item
                                var media = factory.HandleMedia(parentNodeId, postedMediaFile, AuthenticatedUser);
                            }
                        }
                    }

                    var scripts = new ClientTools(new Page());
                    scripts.SyncTree(parentNode.Path, true);

                    // log succes
                    LogHelper.Info <MediaUploader>(string.Format("Success uploading to parent {0}", parentNodeId));
                }
                catch (Exception e)
                {
                    // log error
                    LogHelper.Error <MediaUploader>(string.Format("Error uploading to parent {0}", parentNodeId), e);
                }
            }
            else
            {
                // log error
                LogHelper.Warn <MediaUploader>(string.Format("Parent node id is in incorrect format: {0}", parentNodeId));
            }

            return(new UploadResponse());
        }
Example #23
0
        void Save_Click(object sender, EventArgs e)
        {
            Page.Validate();

            ClientTools
            .SyncTree("-1," + _macro.Id.ToInvariantString(), true);     //true forces the reload


            var tempCachePeriod = cachePeriod.Text;

            if (tempCachePeriod == string.Empty)
            {
                tempCachePeriod = "0";
            }

            SetMacroValuesFromPostBack(_macro, Convert.ToInt32(tempCachePeriod), macroUserControl.Text, SelectedPartialView.Text);

            // save elements
            // this is oh so completely broken
            var aliases = new Dictionary <string, string>();

            foreach (RepeaterItem item in macroProperties.Items)
            {
                var macroPropertyId       = (HtmlInputHidden)item.FindControl("macroPropertyID");
                var macroElementName      = (TextBox)item.FindControl("macroPropertyName");
                var macroElementAlias     = (TextBox)item.FindControl("macroPropertyAlias");
                var macroElementSortOrder = (TextBox)item.FindControl("macroPropertySortOrder");
                var macroElementType      = (DropDownList)item.FindControl("macroPropertyType");

                var prop      = _macro.Properties.Values.Single(x => x.Id == int.Parse(macroPropertyId.Value));
                var sortOrder = 0;
                int.TryParse(macroElementSortOrder.Text, out sortOrder);

                var alias = macroElementAlias.Text.Trim();
                if (prop.Alias != alias) // changing the alias
                {
                    // use a temp alias to avoid collision if eg swapping aliases
                    var tempAlias = Guid.NewGuid().ToString("N").Substring(0, 8);
                    aliases[tempAlias] = alias;
                    alias = tempAlias;
                }

                _macro.Properties.UpdateProperty(
                    prop.Alias,
                    macroElementName.Text.Trim(),
                    sortOrder,
                    macroElementType.SelectedValue,
                    alias);
            }

            // now apply the real aliases, should not collide
            foreach (var kvp in aliases)
            {
                _macro.Properties.UpdateProperty(kvp.Key, newAlias: kvp.Value);
            }

            Services.MacroService.Save(_macro);

            ClientTools.ShowSpeechBubble(SpeechBubbleIcon.Save, "Macro saved", "");

            MacroPropertyBind();
        }