Пример #1
0
        /// <summary>
        /// Handles POST operations. Parameters come from request stream.
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="portalContext"></param>
        /// <param name="odataReq"></param>
        internal void WriteOperationResult(Stream inputStream, PortalContext portalContext, ODataRequest odataReq)
        {
            object response = null;
            var    content  = ODataHandler.LoadContentByVersionRequest(odataReq.RepositoryPath);

            if (content == null)
            {
                throw new ContentNotFoundException(string.Format(SNSR.GetString("$Action,ErrorContentNotFound"), odataReq.RepositoryPath));
            }

            var action = ODataHandler.ActionResolver.GetAction(content, odataReq.Scenario, odataReq.PropertyName, null, null);

            if (action == null)
            {
                // check if this is a versioning action (e.g. a checkout)
                SavingAction.AssertVersioningAction(content, odataReq.PropertyName, true);

                throw new InvalidContentActionException(InvalidContentActionReason.UnknownAction, content.Path, null, odataReq.PropertyName);
            }

            if (action.Forbidden || (action.GetApplication() != null && !action.GetApplication().Security.HasPermission(PermissionType.RunApplication)))
            {
                throw new InvalidContentActionException("Forbidden action: " + odataReq.PropertyName);
            }

            var parameters = GetOperationParameters(action, inputStream);

            response = action.Execute(content, parameters);

            var responseAsContent = response as Content;

            if (responseAsContent != null)
            {
                WriteSingleContent(responseAsContent, portalContext);
                return;
            }

            int count;

            response = ProcessOperationResponse(response, portalContext, odataReq, out count);
            WriteOperationResult(response, portalContext, odataReq, count);
        }
Пример #2
0
        private static object GetIdentity(Node node)
        {
            if (node == null)
            {
                throw new ArgumentException("Identity not found");
            }

            string domain = null; //TODO: domain
            var    kind   = node is User ? SnIdentityKind.User : node is Group ? SnIdentityKind.Group : SnIdentityKind.OrganizationalUnit;

            return(new Dictionary <string, object>
            {
                { "id", node.Id },
                { "path", node.Path },
                { "name", node.Name },
                { "displayName", SNSR.GetString(node.DisplayName) },
                { "domain", domain },
                { "kind", kind.ToString().ToLower() }
            });
        }
Пример #3
0
        /// <summary>
        /// Constructor of taglist.
        /// </summary>
        public TagList()
        {
            InnerControlID = "InnerTagListBox";

            var user = Context.User.Identity as User;

            _adminMode = (Group.Administrators.Members.Where(n => n.Id == user.Id)).FirstOrDefault() != null;

            _tbTagList = new TextBox {
                ID = InnerControlID
            };
            _errorLabel = new Label {
                ID = "InnerErrorLabel"
            };
            _btnAddTag = new Button {
                ID = "btnAddTag", Text = SNSR.GetString(SNSR.FieldControls.TagList_AddTag), OnClientClick = "return false;"
            };
            _taglist          = new TagCollection();
            _searchPath       = "";
            _searchFilterName = "TagFilter";
        }
Пример #4
0
        // =============================================================================== Public methods
        /// <summary>
        /// Returns markup in a short format - for comments
        /// </summary>
        /// <returns></returns>
        public string GetShortMarkup()
        {
            if (Count == 0)
            {
                return(string.Empty);
            }

            string markup = string.Empty;

            if (Count == 1)
            {
                markup = SNSR.GetString(SNSR.Wall.OnePerson);
            }

            if (Count > 1)
            {
                markup = string.Format(SNSR.GetString(SNSR.Wall.NPeople), Count);
            }

            return(string.Format("<a {1}>{0}</a>", markup, _likeListLinkParams));
        }
Пример #5
0
        /// <summary>
        /// Handles POST operations. Parameters come from request stream.
        /// </summary>
        internal async Task WritePostOperationResultAsync(HttpContext httpContext, ODataRequest odataReq, IConfiguration appConfig)
        {
            var content = ODataMiddleware.LoadContentByVersionRequest(odataReq.RepositoryPath, httpContext);

            if (content == null)
            {
                throw new ContentNotFoundException(string.Format(SNSR.GetString("$Action,ErrorContentNotFound"), odataReq.RepositoryPath));
            }

            var action = ODataMiddleware.ActionResolver.GetAction(content, odataReq.Scenario, odataReq.PropertyName, null, null, httpContext, appConfig);

            if (action == null)
            {
                // check if this is a versioning action (e.g. a checkout)
                SavingAction.AssertVersioningAction(content, odataReq.PropertyName, true);

                throw new InvalidContentActionException(InvalidContentActionReason.UnknownAction, content.Path, null, odataReq.PropertyName);
            }

            if (action.Forbidden || (action.GetApplication() != null && !action.GetApplication().Security.HasPermission(PermissionType.RunApplication)))
            {
                throw new InvalidContentActionException("Forbidden action: " + odataReq.PropertyName);
            }

            var response = action is ODataOperationMethodExecutor odataAction
            ? (odataAction.IsAsync ? await odataAction.ExecuteAsync(content) : action.Execute(content))
            : action.Execute(content, await GetOperationParametersAsync(action, httpContext, odataReq));

            if (response is Content responseAsContent)
            {
                await WriteSingleContentAsync(responseAsContent, httpContext)
                .ConfigureAwait(false);

                return;
            }

            response = ProcessOperationResponse(response, odataReq, httpContext, out var count);
            await WriteOperationResultAsync(response, httpContext, odataReq, count)
            .ConfigureAwait(false);
        }
Пример #6
0
        internal static object GetIdentity(Node node)
        {
            if (node == null)
            {
                throw new ArgumentException("Identity not found");
            }

            var seeOnly = !node.Security.HasPermission(PermissionType.Open);

            string         domain = null;
            string         avatar = null;
            SnIdentityKind kind;

            if (node is User userNode)
            {
                kind   = SnIdentityKind.User;
                domain = seeOnly ? null : userNode.Domain;
                avatar = seeOnly ? null : userNode.AvatarUrl;
            }
            else if (node is Group groupNode)
            {
                kind   = SnIdentityKind.Group;
                domain = seeOnly ? null : groupNode.Domain?.Name;
            }
            else
            {
                kind = SnIdentityKind.OrganizationalUnit;
            }

            return(new Dictionary <string, object>
            {
                { "id", node.Id },
                { "path", node.Path },
                { "name", node.Name },
                { "displayName", seeOnly ? node.Name : SNSR.GetString(node.DisplayName) },
                { "domain", domain },
                { "kind", kind.ToString().ToLower() },
                { "avatar", avatar }
            });
        }
Пример #7
0
        public ActionResult GetLikeList(string itemId, string contextPath, string rnd)
        {
            if (!HasPermission())
            {
                return(Json(SNSR.GetString(SNSR.Wall.PleaseLogIn), JsonRequestBehavior.AllowGet));
            }

            SetCurrentWorkspace(contextPath);
            var id = PostInfo.GetIdFromClientId(itemId);

            // create like markup
            var likeInfo = new LikeInfo(id);
            var likelist = new StringBuilder();

            foreach (var likeitem in likeInfo.LikeUsers)
            {
                var likeuser = likeitem as User;
                likelist.Append(WallHelper.GetLikeListItemMarkup(likeuser));
            }

            return(Json(likelist.ToString(), JsonRequestBehavior.AllowGet));
        }
Пример #8
0
        public static string GetLikeList(Content content, string itemId, string rnd)
        {
            if (!HasPermission())
            {
                return(JsonConvert.SerializeObject(SNSR.GetString(Compatibility.SR.Wall.PleaseLogIn)));
            }

            SetCurrentWorkspace(content.Path);
            var id = PostInfo.GetIdFromClientId(itemId);

            // create like markup
            var likeInfo = new LikeInfo(id);
            var likelist = new StringBuilder();

            foreach (var likeitem in likeInfo.LikeUsers)
            {
                var likeuser = likeitem as User;
                likelist.Append(WallHelper.GetLikeListItemMarkup(likeuser));
            }

            return(likelist.ToString());
        }
Пример #9
0
        // =============================================================================== Constructors
        public static PostInfo CreateFromCommentOrLike(Node commentOrLike)
        {
            var targetContent = commentOrLike.Parent.Parent;

            // comment likes should not appear, only content likes
            if (targetContent.NodeType.Name == "Comment")
            {
                return(null);
            }

            var postInfo = new PostInfo();

            postInfo.CreationDate = commentOrLike.CreationDate;
            postInfo.CreatedBy    = commentOrLike.CreatedBy as User;
            //postInfo.Action = commentOrLike.NodeType.Name == "Comment" ? "commented on a Content" : "likes a Content";
            postInfo.Action        = SNSR.GetString(commentOrLike.NodeType.Name == "Comment" ? SNSR.Wall.CommentedOnAContent : SNSR.Wall.LikesAContent);
            postInfo.Id            = targetContent.Id;
            postInfo.Path          = targetContent.Path;
            postInfo.ClientId      = postInfo.Id.ToString();
            postInfo.Type          = PostType.BigPost;
            postInfo.SharedContent = targetContent;
            return(postInfo);
        }
Пример #10
0
        /// <summary>
        /// Returns markup in a long format - for posts
        /// </summary>
        /// <returns></returns>
        public string GetLongMarkup()
        {
            if (Count == 0)
            {
                return(string.Empty);
            }

            string markup = string.Empty;

            if (iLike && Count == 1)
            {
                markup = SNSR.GetString(SNSR.Wall.YouLikeThis);
            }

            if (iLike && Count == 2)
            {
                markup = string.Format(WallHelper.GetXmlDecodedString(SNSR.GetString(SNSR.Wall.YouAndAnotherLikesThis)), _likeListLinkParams);
            }

            if (iLike && Count > 2)
            {
                markup = string.Format(WallHelper.GetXmlDecodedString(SNSR.GetString(SNSR.Wall.YouAndOthersLikesThis)), Count - 1, _likeListLinkParams);
            }

            if (!iLike && Count == 1)
            {
                markup = string.Format(WallHelper.GetXmlDecodedString(SNSR.GetString(SNSR.Wall.OnePersonLikesThis)), _likeListLinkParams);
            }

            if (!iLike && Count > 1)
            {
                markup = string.Format(WallHelper.GetXmlDecodedString(SNSR.GetString(SNSR.Wall.MorePersonLikeThis)), Count, _likeListLinkParams);
            }

            return(markup);
        }
Пример #11
0
 public static void ThrowNotFound(string contentNameOrPath = null)
 {
     throw new HttpException(404, SNSR.GetString(SNSR.Exceptions.HttpAction.NotFound_1, contentNameOrPath ?? string.Empty));
 }
Пример #12
0
        private void BuildContentView(string contentTypeName, Node parent, ViewMode viewMode)
        {
            var viewPath = string.Empty;

            #region creates container)
            if (_container == null)
            {
                CreateContainer();
            }
            else
            {
                _container.Controls.Clear();
                //this.Controls.Remove(_container);
            }

            if (this._container.Parent == null)
            {
                this.Controls.Add(this._container);
            }
            #endregion

            #region creates new content or loads an existing one
            // when we are in InlineNew creates an empty content
            if (viewMode == ViewMode.InlineNew)
            {
                if (!string.IsNullOrEmpty(contentTypeName) && !((GenericContent)PortalContext.Current.ContextNode).IsAllowedChildType(contentTypeName))
                {
                    var ct = ContentType.GetByName(contentTypeName);
                    this._errorMessage = string.Format(SNSR.GetString("SingleContentPortlet", "TypeIsNotAllowed"), ct != null ? Content.Create(ct).DisplayName : contentTypeName);
                    ShowSimpleErrorMessage();
                    return;
                }

                _content = SNC.Content.CreateNew(contentTypeName, parent, string.Empty);
            }

            // when the portlet is in browse, edit, inlineedit states, loads the content
            if (viewMode == ViewMode.Browse ||
                viewMode == ViewMode.Edit ||
                viewMode == ViewMode.InlineEdit)
            {
                Node node = Node.LoadNode(this.AbsoulteContentPath);

                // check if can select a single node (ie smartfolderex)
                ICustomSingleNode singleNode = node as ICustomSingleNode;

                // select single node
                if (singleNode != null)
                {
                    node = singleNode.SelectedItem();
                }

                if (node == null)
                {
                    _content = null;
                }
                else
                {
                    _content = SNC.Content.Create(node);
                }
            }

            #endregion

            if (viewMode == ViewMode.InlineEdit || viewMode == ViewMode.Edit)
            {
                this._displayMode = GetViewModeName(ViewMode.Edit);
            }

            // if content does not exist stop creating controls.
            if (_content == null)
            {
                this._errorMessage = String.Format(HttpContext.GetGlobalResourceObject("SingleContentPortlet", "PathNotFound") as string, AbsoulteContentPath);
                return;
            }

            #region checks validity

            // if content is not valid, exit the method, and an empty contol will be shown to the user.
            if (this.ValidationSetting != ValidationOption.DontCheckValidity)
            {
                //Use cache setting for deciding if we need to check content expiration.
                //This code will not run if the user is in one of the administrator groups.
                //Equivalent to: !PortalContext.IsInAdminGroup(User.Current, AdminGroupPaths)
                if (PortalContext.Current.LoggedInUserCacheEnabled)
                {
                    _validitySetting = GetValiditySetting(_content);
                    if (_validitySetting != null)
                    {
                        // User has been set the ValidationSetting,
                        // and checks the content will be displayed or not.
                        // if the content is not visible, just return (and don't do anything else)
                        // otherwise the content processing will be going on.
                        switch (this.ValidationSetting)
                        {
                        case ValidationOption.ShowAllValid:
                            if (!_validitySetting.ShowAllValidContent)
                            {
                                return;
                            }
                            break;

                        case ValidationOption.ShowValidButArchived:
                            if (!_validitySetting.ShowValidAndArchived)
                            {
                                return;
                            }
                            break;

                        case ValidationOption.ShowValidButNotArchived:
                            if (!_validitySetting.ShowValidAndNotArchived)
                            {
                                return;
                            }
                            break;

                        case ValidationOption.DontCheckValidity:        // not used
                        default:
                            break;
                        }
                    }
                }
            }
            #endregion


            viewPath = GetViewPath();


            // try to create ContentView which contains all webcontrols of the content
            try
            {
                if (this.UseUrlPath)
                {
                    _contentView = ContentView.Create(_content, this.Page, viewMode, String.IsNullOrEmpty(this.ContentViewPath) ? viewPath : this.ContentViewPath);
                }
                else
                {
                    _contentView = ContentView.Create(_content, this.Page, viewMode, viewPath);
                }

                _container.Controls.Remove(_contentView);
            }
            catch (Exception e) //logged
            {
                Logger.WriteException(e);
                this._errorMessage = String.Format("Message: {0} {1} Source: {2} {3} StackTrace: {4} {5}", e.Message, Environment.NewLine, e.Source, Environment.NewLine, e.StackTrace, Environment.NewLine);
                return;
            }

            _contentView.UserAction           += _contentView_UserAction;
            _contentView.CommandButtonsAction += _contentView_CommandButtonsAction;
            _container.Controls.Add(_contentView);
        }
Пример #13
0
        /// <summary>
        /// Overrided for proper saving method:
        /// - Blacklist checking + error indication
        /// - New and old tag population and merging
        /// - Handling admin and normal user mode
        /// </summary>
        /// <returns>String for a longtext field (Tags) wich can be stored in the usual way on the content.</returns>
        public override object GetData()
        {
            _bannedTagsList.Clear();
            ClearWarning();
            _tagListString = string.Empty;
            var newTags = _tbTagList.Text.Trim(_splitChars).Split(_splitChars).ToList();

            newTags.RemoveAll(i => string.IsNullOrEmpty(i));

            var oldTags = new List <string>();

            if (!_adminMode)
            {
                foreach (var tag in _taglist)
                {
                    if (!IsBlacklisted(tag.Name))
                    {
                        _tagListString += tag.Name + _splitChars[0];
                        if (!oldTags.Contains(tag.Name))
                        {
                            oldTags.Add(tag.Name);
                        }
                    }
                    else
                    {
                        _bannedTagsList.Add(tag.Name);
                    }
                }
            }
            foreach (var tag in newTags)
            {
                if (!oldTags.Contains(tag) && !IsBlacklisted(tag))
                {
                    _tagListString += tag + _splitChars[0];
                }
                else if (IsBlacklisted(tag))
                {
                    _bannedTagsList.Add(tag);
                }
            }

            _taglist.Clear();
            _tbTagList.Text = string.Empty;
            if (_bannedTagsList.Count > 0)
            {
                var msgbody = "\n";
                var msgEnd  = SNSR.GetString(SR.FieldControls.TagList_BlacklistedTag);
                if (_bannedTagsList.Count > 1)
                {
                    msgEnd = SNSR.GetString(SR.FieldControls.TagList_BlacklistedTags);
                }
                foreach (var tag in _bannedTagsList)
                {
                    msgbody += tag + ", ";
                }
                DisplayWarning(msgbody.TrimEnd(' ', ',') + msgEnd);
                _bannedTagsList.Clear();
            }
            SetTagList(_tagListString.Split(_splitChars));
            return(_tagListString.ToLower());
        }
Пример #14
0
 protected void ThrowForbidden()
 {
     throw new HttpException(404, SNSR.GetString(SNSR.Exceptions.HttpAction.Forbidden_1, TargetNode == null ? string.Empty : TargetNode.Name));
 }
Пример #15
0
 internal static void ResourceNotFound()
 {
     throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ResourceNotFound), ODataExceptionCode.ResourceNotFound);
 }
Пример #16
0
 internal static void ContentAlreadyExists(PortalContext portalContext, string path)
 {
     throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ContentAlreadyExists_1, path), ODataExceptionCode.ContentAlreadyExists);
 }
Пример #17
0
 public PostInfo(Node node)
 {
     CreationDate  = node.CreationDate;
     CreatedBy     = node.CreatedBy as User;
     Text          = node.GetProperty <string>("Description");
     Details       = node.GetProperty <string>("PostDetails");
     JournalId     = node.GetProperty <int>("JournalId"); // journal's id to leave out item from wall if post already exists
     Id            = node.Id;
     Path          = node.Path;
     ClientId      = Id.ToString();
     Type          = (PostType)node.GetProperty <int>("PostType");
     SharedContent = node.GetReference <Node>("SharedContent");
     if (SharedContent != null)
     {
         LastPath = SharedContent.Path;
         var ws = ContentRepository.Workspaces.Workspace.GetWorkspaceWithWallForNode(node);
         if (ws != null)
         {
             Action = string.Format("{2} <a href='{0}'>{1}</a>", ws.Path, Content.Create(ws).DisplayName, SNSR.GetString(SNSR.Wall.What_To));
         }
     }
 }
Пример #18
0
        public override object Execute(Content content, params object[] parameters)
        {
            //optional destination
            var destination = parameters != null && parameters.Length > 0 ? (string)parameters[0] : null;

            //optional new name parameter
            var addNewName = parameters != null && parameters.Length > 1 && parameters[1] != null ? (bool)parameters[1] : (bool?)null;

            var tb = content.ContentHandler as TrashBag;

            if (tb == null)
            {
                throw new InvalidContentActionException("The resource content must be a trashbag.");
            }

            if (string.IsNullOrEmpty(destination))
            {
                destination = tb.OriginalPath;
            }

            try
            {
                if (addNewName.HasValue)
                {
                    TrashBin.Restore(tb, destination, addNewName.Value);
                }
                else
                {
                    TrashBin.Restore(tb, destination);
                }
            }
            catch (RestoreException rex)
            {
                string msg;

                switch (rex.ResultType)
                {
                case RestoreResultType.ExistingName:
                    msg = SNSR.GetString(SNSR.Exceptions.OData.RestoreExistingName);
                    break;

                case RestoreResultType.ForbiddenContentType:
                    msg = SNSR.GetString(SNSR.Exceptions.OData.RestoreForbiddenContentType);
                    break;

                case RestoreResultType.NoParent:
                    msg = SNSR.GetString(SNSR.Exceptions.OData.RestoreNoParent);
                    break;

                case RestoreResultType.PermissionError:
                    msg = SNSR.GetString(SNSR.Exceptions.OData.RestorePermissionError);
                    break;

                default:
                    msg = rex.Message;
                    break;
                }

                throw new Exception(msg);
            }

            return(null);
        }
Пример #19
0
 public static void ThrowForbidden(string contentNameOrPath = null)
 {
     throw new HttpException(403, SNSR.GetString(SNSR.Exceptions.HttpAction.Forbidden_1, contentNameOrPath ?? string.Empty));
 }
Пример #20
0
        public PostInfo(JournalItem journalItem, string lastPath)
        {
            IsJournal    = true;
            LastPath     = lastPath;
            CreationDate = journalItem.When;
            var backspIndex = journalItem.Who.IndexOf('\\');

            if (backspIndex != -1)
            {
                var domain = journalItem.Who.Substring(0, backspIndex);
                var name   = journalItem.Who.Substring(backspIndex + 1);
                CreatedBy = User.Load(domain, name);
            }

            var what    = journalItem.What.ToLower();
            var typeStr = string.Empty;

            // type & type string
            if (what == "created")
            {
                Type    = PostType.JournalCreated;
                typeStr = SNSR.GetString(Compatibility.SR.Wall.What_Created);
            }
            else if (what == "modified")
            {
                Type    = PostType.JournalModified;
                typeStr = SNSR.GetString(Compatibility.SR.Wall.What_Modified);
            }
            else if (what == "deleted" || what == "deletedphysically")
            {
                Type    = PostType.JournalDeletedPhysically;
                typeStr = SNSR.GetString(Compatibility.SR.Wall.What_Deleted);
            }
            else if (what == "moved")
            {
                Type    = PostType.JournalMoved;
                typeStr = SNSR.GetString(Compatibility.SR.Wall.What_Moved);
            }
            else if (what == "copied")
            {
                Type    = PostType.JournalCopied;
                typeStr = SNSR.GetString(Compatibility.SR.Wall.What_Copied);
            }
            else
            {
                throw new SnNotSupportedException(String.Format("Processing '{0}' journal type is not supported", what));
            }

            var displyaName       = SenseNetResourceManager.Current.GetString(journalItem.DisplayName);
            var targetDisplayName = SenseNetResourceManager.Current.GetString(journalItem.TargetDisplayName);

            Text = Type == PostType.JournalCopied || Type == PostType.JournalMoved ?
                   string.Format("{0} <a href='{1}'>{2}</a> {5} <a href='{3}'>{4}</a>", typeStr, "{{path}}", displyaName, journalItem.TargetPath, targetDisplayName, SNSR.GetString(Compatibility.SR.Wall.What_To)) :
                   string.Format("{0} <a href='{1}'>{2}</a>", typeStr, "{{path}}", displyaName);

            JournalId = journalItem.Id; // journal's id to leave out item from wall if post already exists
            Id        = journalItem.Id;
            ClientId  = "J" + Id.ToString();
            Path      = lastPath;

            // details
            switch (Type)
            {
            case PostType.JournalModified:
                Details = journalItem.Details;
                break;

            case PostType.JournalMoved:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.SourcePath), journalItem.TargetPath, SNSR.GetString(Compatibility.SR.Wall.Source), SNSR.GetString(Compatibility.SR.Wall.Target));
                break;

            case PostType.JournalCopied:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.Wherewith), journalItem.TargetPath, SNSR.GetString(Compatibility.SR.Wall.Source), SNSR.GetString(Compatibility.SR.Wall.Target));
                break;

            default:
                break;
            }
        }
Пример #21
0
        protected void BuildResultScreen(RestoreException rex)
        {
            ClearControls();

            if (this.RestoreResult == RestoreResultType.Nonedefined)
            {
                return;
            }

            var trashBag = GetContextNode() as TrashBag;

            if (trashBag == null)
            {
                return;
            }

            var view         = this.InfoViewPath;
            var messageTitle = string.Empty;
            var messageDesc  = string.Empty;

            switch (this.RestoreResult)
            {
            case RestoreResultType.UnknownError:
                view = this.ErrorViewPath;
                break;
            }

            var c = Page.LoadControl(view);

            if (c == null)
            {
                return;
            }

            this.Controls.Add(c);

            if (rex != null)
            {
                //build UI info from the exception
                var folderName = string.IsNullOrEmpty(rex.ContentPath) ?
                                 "{folder}" : RepositoryPath.GetFileNameSafe(RepositoryPath.GetParentPath(rex.ContentPath));
                var contentName = string.IsNullOrEmpty(rex.ContentPath) ?
                                  "{content}" : RepositoryPath.GetFileNameSafe(rex.ContentPath);

                switch (rex.ResultType)
                {
                case RestoreResultType.Nonedefined:
                case RestoreResultType.UnknownError:
                    messageTitle = rex.Message;
                    messageDesc  = rex.ToString();
                    break;

                case RestoreResultType.PermissionError:
                    messageTitle = "Not enough permissions to complete the operation";
                    messageDesc  = rex.Message;
                    break;

                case RestoreResultType.ForbiddenContentType:
                    messageTitle = "Cannot restore this type of content to the selected target";
                    break;

                case RestoreResultType.ExistingName:
                    messageTitle = "Content with this name already exists in the folder " + folderName;
                    messageDesc  =
                        string.Format(
                            "You can restore it with a new name (<strong>{0}</strong>) or please choose a different destination",
                            contentName);
                    break;

                case RestoreResultType.NoParent:
                    messageTitle = "Destination folder is missing";
                    messageDesc  = "Please choose a different destination";
                    break;
                }
            }

            if (this.MessageControl != null)
            {
                this.MessageControl.ButtonsAction += MessageControl_ButtonsAction;

                if (this.NewNameButton != null)
                {
                    this.NewNameButton.Command += MessageControl_ButtonsAction;
                }

                if (this.MessageLabel != null)
                {
                    this.MessageLabel.Text = messageTitle;
                }

                if (this.MessageDescLabel != null)
                {
                    this.MessageDescLabel.Text = messageDesc;
                }
            }

            if (this.ContentLabel != null)
            {
                var lc = trashBag.DeletedContent;
                if (lc != null)
                {
                    this.ContentLabel.Text = HttpUtility.HtmlEncode(SNSR.GetString(lc.DisplayName));
                }
            }

            ShowHideControls();
        }
Пример #22
0
        private void BindEvents()
        {
            if (MessageControl == null)
            {
                return;
            }

            MessageControl.ButtonsAction += MessageControlButtonsAction;

            // switching visibility of the controls on and off within the user control

            var gContent  = ContextNode as GenericContent;
            var bag       = ContextNode as TrashBag;
            var title     = gContent == null ? ContextNode.Name : SNSR.GetString(gContent.DisplayName);
            var isInTrash = ContentsAreInTrash();

            var folder = bag == null ? ContextNode as IFolder : bag.DeletedContent as IFolder;

            if (folder == null)
            {
                SetLabel(MessageControl, "DeleteOneLabel", title, ContextNode.ParentPath);
            }
            else
            {
                SetLabel(MessageControl, "DeleteFolderLabel", title, ContextNode.ParentPath);
            }


            TrashBin trashBin = null;

            try
            {
                trashBin = TrashBin.Instance;
            }
            catch (SenseNetSecurityException)
            {
                // trashbin is not accessible due to lack of permissions
            }

            if (trashBin == null)   // trashbin ain't available
            {
                MessageControl.Errors.Add("Trashbin node not found under /Root/Trash, trashbin functionality unavailable.");
                ToggleControlVisibility(MessageControl, "PermanentDeleteLabel", true);
                ToggleControlVisibility(MessageControl, "BinEnabledLabel", false);
                ToggleControlVisibility(MessageControl, "PermanentDeleteCheckBox", false);
            }
            else
            {   // trashbin is available
                var nodesInTreeCount = GetNodesInTreeCount();

                bool?trashDisabled = !ContentsAreTrashable();

                if (gContent != null)
                {
                    ToggleControlVisibility(MessageControl, "BinDisabledGlobalLabel", !trashBin.IsActive);

                    if (isInTrash)
                    {
                        ToggleControlVisibility(MessageControl, "BinEnabledLabel", false);
                        ToggleControlVisibility(MessageControl, "PermanentDeleteCheckBox", false);
                        ToggleControlVisibility(MessageControl, "BinNotConfiguredLabel", false);
                        ToggleControlVisibility(MessageControl, "PermanentDeleteLabel", true);
                        ToggleControlVisibility(MessageControl, "PurgeFromTrashLabel", true);
                        ToggleControlVisibility(MessageControl, "TooMuchContentLabel", false);
                    }
                    else if (trashBin.BagCapacity == 0 || trashBin.BagCapacity > nodesInTreeCount)
                    {
                        if (trashDisabled.Value)
                        {
                            ToggleControlVisibility(MessageControl, "BinEnabledLabel", false);
                            ToggleControlVisibility(MessageControl, "BinNotConfiguredLabel", trashBin.IsActive);
                            ToggleControlVisibility(MessageControl, "PermanentDeleteLabel", true);
                        }
                        else
                        {
                            ToggleControlVisibility(MessageControl, "BinEnabledLabel", trashBin.IsActive);
                            ToggleControlVisibility(MessageControl, "PermanentDeleteCheckBox", trashBin.IsActive);
                            ToggleControlVisibility(MessageControl, "BinNotConfiguredLabel", false);
                            ToggleControlVisibility(MessageControl, "PermanentDeleteLabel", !trashBin.IsActive);
                        }
                    }
                    else
                    {
                        // too much content flow
                        ToggleControlVisibility(MessageControl, "BinEnabledLabel", false);
                        ToggleControlVisibility(MessageControl, "PermanentDeleteCheckBox", false);
                        ToggleControlVisibility(MessageControl, "BinNotConfiguredLabel", trashDisabled.Value && trashBin.IsActive);
                        ToggleControlVisibility(MessageControl, "PermanentDeleteLabel", true);
                        ToggleControlVisibility(MessageControl, "TooMuchContentLabel", !trashDisabled.Value && trashBin.IsActive);
                    }
                }
                else
                {
                    MessageControl.Errors.Add("System Message: You can't delete a content which is not derived from GenericContent.");
                }
            }
        }
Пример #23
0
        public static BatchActionResponse MoveBatch(Content content, string targetPath, object[] paths)
        {
            var targetNode = Node.LoadNode(targetPath);

            if (targetNode == null)
            {
                throw new ContentNotFoundException(targetPath);
            }

            var results          = new List <object>();
            var errors           = new List <ErrorContent>();
            var identifiers      = paths.Select(NodeIdentifier.Get).ToList();
            var foundIdentifiers = new List <NodeIdentifier>();
            var nodes            = Node.LoadNodes(identifiers);

            foreach (var node in nodes)
            {
                try
                {
                    // Collect already found identifiers in a separate list otherwise the error list
                    // would contain multiple errors for the same content.
                    foundIdentifiers.Add(NodeIdentifier.Get(node));

                    node.MoveTo(targetNode);
                    results.Add(new { node.Id, node.Path, node.Name });
                }
                catch (Exception e)
                {
                    //TODO: we should log only relevant exceptions here and skip
                    // business logic-related errors, e.g. lack of permissions or
                    // existing target content path.
                    SnLog.WriteException(e);

                    errors.Add(new ErrorContent
                    {
                        Content = new { node?.Id, node?.Path, node?.Name },
                        Error   = new Error
                        {
                            Code          = "NotSpecified",
                            ExceptionType = e.GetType().FullName,
                            InnerError    = new StackInfo {
                                Trace = e.StackTrace
                            },
                            Message = new ErrorMessage
                            {
                                Lang  = System.Globalization.CultureInfo.CurrentUICulture.Name.ToLower(),
                                Value = e.Message
                            }
                        }
                    });
                }
            }

            // iterating through the missing identifiers and making error items for them
            errors.AddRange(identifiers.Where(id => !foundIdentifiers.Exists(f => f.Id == id.Id || f.Path == id.Path))
                            .Select(missing => new ErrorContent
            {
                Content = new { missing?.Id, missing?.Path },
                Error   = new Error
                {
                    Code          = "ResourceNotFound",
                    ExceptionType = "ContentNotFoundException",
                    InnerError    = null,
                    Message       = new ErrorMessage
                    {
                        Lang  = System.Globalization.CultureInfo.CurrentUICulture.Name.ToLower(),
                        Value = string.Format(SNSR.GetString(SNSR.Exceptions.OData.ErrorContentNotFound),
                                              missing?.Path)
                    }
                }
            }));

            return(BatchActionResponse.Create(results, errors, results.Count + errors.Count));
        }
Пример #24
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event. Parents CreateChildControls() logic moved here for processing
        /// data of input renderer.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (!string.IsNullOrEmpty(QueryTemplate))
            {
                foreach (var param in HttpContext.Current.Request.Params.AllKeys)
                {
                    if (this.QueryTemplate.Contains("%" + param + "%"))
                    {
                        _hasUrlInput = true;
                        break;
                    }
                }

                foreach (var key in HttpContext.Current.Request.Form.AllKeys)
                {
                    var controlName = string.Empty;
                    if (key.Contains('$'))
                    {
                        controlName = key.Remove(0, key.LastIndexOf('$') + 1);
                    }
                    if (QueryTemplate.Contains("%" + controlName + "%"))
                    {
                        _hasFormInput = true;
                        break;
                    }
                }
            }

            Exception controlException = null;

            if (_hasFormInput || HttpContext.Current.Request.QueryString.ToString().Contains(Math.Abs((PortalContext.Current.ContextNodePath + this.ID).GetHashCode()).ToString()) || _hasUrlInput)
            {
                try
                {
                    this.GetQueryFilter();  // initialize query filter to see if query is invalid for empty search
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    controlException = new InvalidContentQueryException(this.QueryTemplate, innerException: ex);
                }

                var errorPanel = this.FindControlRecursive(EmptyQueryErrorPanelID);
                if (errorPanel != null)
                {
                    errorPanel.Visible = _invalidQuery;
                }
                if (_invalidQuery)
                {
                    return;
                }

                Content rootContent = null;

                try
                {
                    rootContent = GetModel() as Content;
                    if (rootContent != null)
                    {
                        rootContent.ChildrenDefinition.AllChildren = AllChildren;
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    if (controlException == null)
                    {
                        controlException = ex;
                    }
                }

                var model = new ParametricSearchViewModel
                {
                    State            = State,
                    SearchParameters = _searchParams.Select(searchParam => new SearchParameter {
                        Name = searchParam.Key, Value = searchParam.Value
                    }).
                                       ToArray()
                };

                try
                {
                    var childCount = 0;
                    if (rootContent != null)
                    {
                        try
                        {
                            childCount = rootContent.Children.Count();
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteException(ex);
                            if (controlException == null)
                            {
                                controlException = ex;
                            }
                        }
                    }

                    try
                    {
                        model.Pager = GetPagerModel(childCount, State, string.Empty);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteException(ex);
                        if (controlException == null)
                        {
                            controlException = ex;
                        }

                        //in case of error, set dummy pager model
                        model.Pager = new PagerModel(0, State, string.Empty);
                    }

                    model.Content = rootContent;

                    if (RenderingMode == RenderMode.Xslt)
                    {
                        XmlModelData = model.ToXPathNavigator();
                    }
                    else if (RenderingMode == RenderMode.Ascx || RenderingMode == RenderMode.Native)
                    {
                        if (CanCache && Cacheable && IsInCache)
                        {
                            return;
                        }

                        var viewPath = RenderingMode == RenderMode.Native
                                           ? "/root/Global/Renderers/ContentCollectionView.ascx"
                                           : Renderer;

                        Control presenter = null;

                        try
                        {
                            presenter = Page.LoadControl(viewPath);
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteException(ex);
                            if (controlException == null)
                            {
                                controlException = ex;
                            }
                        }

                        if (presenter != null)
                        {
                            var ccView = presenter as ContentCollectionView;
                            if (ccView != null)
                            {
                                ccView.Model = model;
                            }

                            if (rootContent != null)
                            {
                                var itemlist = presenter.FindControl(ContentListID);
                                if (itemlist != null)
                                {
                                    try
                                    {
                                        ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemlist,
                                                                                                            rootContent.Children);
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.WriteException(ex);
                                        if (controlException == null)
                                        {
                                            controlException = ex;
                                        }
                                    }
                                }
                            }

                            var itemPager = presenter.FindControl("ContentListPager");
                            if (itemPager != null)
                            {
                                try
                                {
                                    ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemPager,
                                                                                                        model.Pager.PagerActions);
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteException(ex);
                                    if (controlException == null)
                                    {
                                        controlException = ex;
                                    }
                                }
                            }

                            Controls.Add(presenter);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    if (controlException == null)
                    {
                        controlException = ex;
                    }
                }
            }

            try
            {
                if (controlException != null)
                {
                    BuildErrorMessage(controlException);
                }
            }
            catch (Exception ex)
            {
                var errorText = SNSR.GetString(SNSR.Portlets.ContentCollection.ErrorLoadingContentView, HttpUtility.HtmlEncode(ex.Message));

                this.Controls.Clear();
                this.Controls.Add(new LiteralControl(errorText));
            }

            ChildControlsCreated = true;
        }
Пример #25
0
        internal void WriteContentProperty(String path, string propertyName, bool rawValue, PortalContext portalContext, ODataRequest req)
        {
            var content = ODataHandler.LoadContentByVersionRequest(path);

            if (content == null)
            {
                ODataHandler.ContentNotFound(portalContext.OwnerHttpContext, path);
                return;
            }

            if (propertyName == ODataHandler.PROPERTY_ACTIONS)
            {
                var backUrl = portalContext.BackUrl;

                //Get actions without back url: let the client append the back parameter,
                //as we are in a service here that does not know about the redirect url.
                var snActions = ODataHandler.ActionResolver.GetActions(content, req.Scenario, string.IsNullOrEmpty(backUrl) ? null : backUrl);

                var actions = snActions.Where(a => a.IsHtmlOperation).Select(a => new ODataActionItem
                {
                    Name           = a.Name,
                    DisplayName    = SNSR.GetString(a.Text),
                    Icon           = a.Icon,
                    Index          = a.Index,
                    Url            = a.Uri,
                    IncludeBackUrl = a.GetApplication() == null ? 0 : (int)a.GetApplication().IncludeBackUrl,
                    ClientAction   = a is ClientAction && !string.IsNullOrEmpty(((ClientAction)a).Callback),
                    Forbidden      = a.Forbidden
                });
                WriteActionsProperty(portalContext, actions.ToArray(), rawValue);
                return;
            }

            Field field;

            if (content.Fields.TryGetValue(propertyName, out field))
            {
                var refField = field as ReferenceField;
                if (refField != null)
                {
                    var refFieldSetting = refField.FieldSetting as ReferenceFieldSetting;
                    var isMultiRef      = true;
                    if (refFieldSetting != null)
                    {
                        isMultiRef = refFieldSetting.AllowMultiple == true;
                    }
                    if (isMultiRef)
                    {
                        WriteMultiRefContents(refField.GetData(), portalContext, req);
                    }
                    else
                    {
                        WriteSingleRefContent(refField.GetData(), portalContext);
                    }
                }
                else if (!rawValue)
                {
                    WriteSingleContent(portalContext, new Dictionary <string, object> {
                        { propertyName, field.GetData() }
                    });
                }
                else
                {
                    WriteRaw(field.GetData(), portalContext);
                }
            }
            else
            {
                //ResourceNotFound(content, propertyName);
                WriteOperationResult(portalContext, req);
            }
        }
Пример #26
0
        protected virtual void BuildResultView()
        {
            Content   rootContent      = null;
            Exception controlException = null;

            try
            {
                // Elevation: it should be possible to search for content
                // under a folder where the user does not have explicit
                // permissions but on one of the child content may have.
                using (new SystemAccount())
                {
                    rootContent = GetModel() as Content;
                }

                if (rootContent != null)
                {
                    rootContent.ChildrenDefinition.AllChildren = AllChildren;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                controlException = ex;
            }

            var model = new ContentCollectionViewModel {
                State = this.State
            };

            var childCount = 0;

            if (rootContent != null)
            {
                try
                {
                    childCount = rootContent.Children.Count();
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    if (controlException == null)
                    {
                        controlException = ex;
                    }
                }
            }

            try
            {
                model.Pager   = GetPagerModel(childCount, State, string.Empty);
                model.Content = rootContent;
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                if (controlException == null)
                {
                    controlException = ex;
                }

                //in case of error, set dummy pager model
                model.Pager = new PagerModel(0, State, string.Empty);
            }

            try
            {
                if (RenderingMode == RenderMode.Xslt)
                {
                    XmlModelData = model.ToXPathNavigator();
                }
                else
                {
                    var viewPath = RenderingMode == RenderMode.Native
                                       ? "/root/Global/Renderers/ContentCollectionView.ascx"
                                       : Renderer;

                    Control presenter = null;

                    try
                    {
                        presenter = Page.LoadControl(viewPath);
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteException(ex);
                        if (controlException == null)
                        {
                            controlException = ex;
                        }
                    }

                    if (presenter != null)
                    {
                        Controls.Add(presenter);
                        PresenterClientId = presenter.ClientID;

                        var ccView = presenter as ContentCollectionView;
                        if (ccView != null)
                        {
                            ccView.Model = model;
                        }

                        if (rootContent != null)
                        {
                            var itemlist = presenter.FindControl(ContentListID);
                            if (itemlist != null)
                            {
                                try
                                {
                                    ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemlist,
                                                                                                        rootContent.
                                                                                                        Children);
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteException(ex);
                                    if (controlException == null)
                                    {
                                        controlException = ex;
                                    }
                                }
                            }
                            itemlist = presenter.FindControl("ViewDatasource");
                            if (itemlist != null)
                            {
                                try
                                {
                                    ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemlist,
                                                                                                        rootContent.Children);
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteException(ex);
                                    if (controlException == null)
                                    {
                                        controlException = ex;
                                    }
                                }
                            }
                        }

                        var itemPager = presenter.FindControl("ContentListPager");
                        if (itemPager != null)
                        {
                            try
                            {
                                ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemPager,
                                                                                                    model.Pager.PagerActions);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteException(ex);
                                if (controlException == null)
                                {
                                    controlException = ex;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                if (controlException == null)
                {
                    controlException = ex;
                }
            }

            try
            {
                if (controlException != null)
                {
                    BuildErrorMessage(controlException);
                }
            }
            catch (Exception ex)
            {
                var errorText = SNSR.GetString(SNSR.Portlets.ContentCollection.ErrorLoadingContentView, HttpUtility.HtmlEncode(ex.Message));

                this.Controls.Clear();
                this.Controls.Add(new LiteralControl(errorText));
            }
        }
Пример #27
0
 internal static void ResourceNotFound(Content content, string propertyName)
 {
     throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.ResourceNotFound_2, content.Path, propertyName), ODataExceptionCode.ResourceNotFound);
 }
Пример #28
0
 protected void ThrowNotFound()
 {
     throw new HttpException(404, SNSR.GetString(SNSR.Exceptions.HttpAction.NotFound_1, TargetNode == null ? string.Empty : TargetNode.Name));
 }
Пример #29
0
        protected override void CreateChildControls()
        {
            if (Cacheable && CanCache && IsInCache)
            {
                return;
            }

            if (ShowExecutionTime)
            {
                Timer.Start();
            }

            Content   rootContent      = null;
            Exception controlException = null;

            try
            {
                rootContent = GetModel() as Content;
                if (rootContent != null)
                {
                    rootContent.ChildrenDefinition.AllChildren = AllChildren;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                controlException = ex;
            }

            var model = new ContentCollectionViewModel {
                State = this.State
            };

            try
            {
                var childCount = 0;
                if (rootContent != null)
                {
                    try
                    {
                        childCount = rootContent.Children.Count();
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteException(ex);
                        if (controlException == null)
                        {
                            controlException = ex;
                        }
                    }
                }

                try
                {
                    model.Pager = GetPagerModel(childCount, State, string.Empty);
                }
                catch (Exception ex)
                {
                    Logger.WriteException(ex);
                    if (controlException == null)
                    {
                        controlException = ex;
                    }

                    //in case of error, set dummy pager model
                    model.Pager = new PagerModel(0, State, string.Empty);
                }

                model.ReferenceAxisName = CollectionAxis == CollectionAxisMode.ReferenceProperty ? ReferenceAxisName : null;
                model.Content           = rootContent;

                if (RenderingMode == RenderMode.Xslt)
                {
                    XmlModelData = model.ToXPathNavigator();
                }
                else if (RenderingMode == RenderMode.Ascx || RenderingMode == RenderMode.Native)
                {
                    var viewPath = RenderingMode == RenderMode.Native
                                       ? "/root/Global/Renderers/ContentCollectionView.ascx"
                                       : Renderer;

                    Control presenter = null;

                    try
                    {
                        var viewHead = NodeHead.Get(viewPath);
                        if (viewHead != null && SecurityHandler.HasPermission(viewHead, PermissionType.RunApplication))
                        {
                            presenter = Page.LoadControl(viewPath);
                        }

                        // we may display a message if the user does not have enough permissions for the view
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteException(ex);
                        if (controlException == null)
                        {
                            controlException = ex;
                        }
                    }

                    if (presenter != null)
                    {
                        var ccView = presenter as ContentCollectionView;
                        if (ccView != null)
                        {
                            ccView.Model = model;
                        }

                        if (rootContent != null)
                        {
                            var itemlist = presenter.FindControl(ContentListID);
                            if (itemlist != null)
                            {
                                try
                                {
                                    ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemlist,
                                                                                                        rootContent.Children);
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteException(ex);
                                    if (controlException == null)
                                    {
                                        controlException = ex;
                                    }
                                }
                            }
                        }

                        var itemPager = presenter.FindControl("ContentListPager");
                        if (itemPager != null)
                        {
                            try
                            {
                                ContentQueryPresenterPortlet.DataBindingHelper.SetDataSourceAndBind(itemPager,
                                                                                                    model.Pager.PagerActions);
                            }
                            catch (Exception ex)
                            {
                                Logger.WriteException(ex);
                                if (controlException == null)
                                {
                                    controlException = ex;
                                }
                            }
                        }

                        Controls.Clear();
                        Controls.Add(presenter);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                if (controlException == null)
                {
                    controlException = ex;
                }
            }

            try
            {
                if (controlException != null)
                {
                    BuildErrorMessage(controlException);
                }
            }
            catch (Exception ex)
            {
                var errorText = SNSR.GetString(SNSR.Portlets.ContentCollection.ErrorLoadingContentView, HttpUtility.HtmlEncode(ex.Message));

                this.Controls.Clear();
                this.Controls.Add(new LiteralControl(errorText));
            }

            ChildControlsCreated = true;

            if (ShowExecutionTime)
            {
                Timer.Stop();
            }
        }
Пример #30
0
        public PostInfo(JournalItem journalItem, string lastPath)
        {
            IsJournal    = true;
            LastPath     = lastPath;
            CreationDate = journalItem.When;
            var backspIndex = journalItem.Who.IndexOf('\\');

            if (backspIndex != -1)
            {
                var domain = journalItem.Who.Substring(0, backspIndex);
                var name   = journalItem.Who.Substring(backspIndex + 1);
                CreatedBy = User.Load(domain, name);
            }

            //var contentName = string.Empty;
            //if (journalItem.Wherewith.StartsWith(contextPath))
            //{
            //    contentName = journalItem.Wherewith.Substring(contextPath.Length).TrimStart('/');
            //    // if workspace relative path is empty, the context path is the workspace itself
            //    if (string.IsNullOrEmpty(contentName))
            //        contentName = RepositoryPath.GetFileName(contextPath);
            //}
            //else
            //{
            //    contentName = RepositoryPath.GetFileName(journalItem.Wherewith);
            //}

            var what    = journalItem.What.ToLower();
            var typeStr = string.Empty;

            // type & type string
            if (what == "created")
            {
                Type    = PostType.JournalCreated;
                typeStr = SNSR.GetString(SNSR.Wall.What_Created);
            }
            else if (what == "modified")
            {
                Type    = PostType.JournalModified;
                typeStr = SNSR.GetString(SNSR.Wall.What_Modified);
            }
            else if (what == "deleted" || what == "deletedphysically")
            {
                Type    = PostType.JournalDeletedPhysically;
                typeStr = SNSR.GetString(SNSR.Wall.What_Deleted);
            }
            else if (what == "moved")
            {
                Type    = PostType.JournalMoved;
                typeStr = SNSR.GetString(SNSR.Wall.What_Moved);
            }
            else if (what == "copied")
            {
                Type    = PostType.JournalCopied;
                typeStr = SNSR.GetString(SNSR.Wall.What_Copied);
            }
            else
            {
                throw new NotImplementedException(String.Format("Processing '{0}' journal type is not implemented", what));
            }

            var displyaName       = ResourceManager.Current.GetString(journalItem.DisplayName);
            var targetDisplayName = ResourceManager.Current.GetString(journalItem.TargetDisplayName);

            Text = Type == PostType.JournalCopied || Type == PostType.JournalMoved ?
                   string.Format("{0} <a href='{1}'>{2}</a> {5} <a href='{3}'>{4}</a>", typeStr, "{{path}}", displyaName, journalItem.TargetPath, targetDisplayName, SNSR.GetString(SNSR.Wall.What_To)) :
                   string.Format("{0} <a href='{1}'>{2}</a>", typeStr, "{{path}}", displyaName);

            JournalId = journalItem.Id; // journal's id to leave out item from wall if post already exists
            Id        = journalItem.Id;
            ClientId  = "J" + Id.ToString();
            Path      = lastPath;

            // details
            switch (Type)
            {
            case PostType.JournalModified:
                Details = journalItem.Details;
                break;

            case PostType.JournalMoved:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.SourcePath), journalItem.TargetPath, SNSR.GetString(SNSR.Wall.Source), SNSR.GetString(SNSR.Wall.Target));
                break;

            case PostType.JournalCopied:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.Wherewith), journalItem.TargetPath, SNSR.GetString(SNSR.Wall.Source), SNSR.GetString(SNSR.Wall.Target));
                break;

            default:
                break;
            }

            //SharedContent = Node.LoadNode(journalItem.Wherewith);
        }