Ejemplo n.º 1
0
        private static string ReplaceResources(string markupStr)
        {
            if (string.IsNullOrEmpty(markupStr))
            {
                return(markupStr);
            }

            var p = 0;

            while (true)
            {
                p = markupStr.IndexOf("{{$", p);
                if (p < 0)
                {
                    break;
                }
                var q = markupStr.IndexOf("}}", p + 2);
                if (q < 0)
                {
                    break;
                }
                var resKey = markupStr.Substring(p + 2, q - p - 2);

                markupStr = markupStr.Remove(p, q - p + 2);
                markupStr = markupStr.Insert(p, SNSR.GetString(resKey));
            }
            return(markupStr);
        }
Ejemplo n.º 2
0
 private void SetContentViewFieldError()
 {
     if (this.ContentException == null)
     {
         this.ContentException = new InvalidOperationException(SNSR.GetString(SNSR.Exceptions.ContentView.InvalidDataHead));
     }
 }
Ejemplo n.º 3
0
        internal async Task WriteErrorResponseAsync(HttpContext httpContext, ODataException oe)
        {
            var error = new Error
            {
                Code          = string.IsNullOrEmpty(oe.ErrorCode) ? Enum.GetName(typeof(ODataExceptionCode), oe.ODataExceptionCode) : oe.ErrorCode,
                ExceptionType = oe.InnerException?.GetType().Name ?? oe.GetType().Name,
                Message       = new ErrorMessage
                {
                    Lang  = System.Globalization.CultureInfo.CurrentUICulture.Name.ToLower(),
                    Value = SNSR.GetString(oe.Message).Replace(Environment.NewLine, "\\n").Replace('"', ' ').Replace('\'', ' ').Replace(" \\ ", " ")
                },
                InnerError =
#if DEBUG
                    new StackInfo
                {
                    Trace = Utility.CollectExceptionMessages(oe)
                }
#else
                    null
#endif
            };

            httpContext.Response.ContentType = "application/json";
            httpContext.Response.StatusCode  = oe.HttpStatusCode;
            await WriteErrorAsync(httpContext, error).ConfigureAwait(false);
        }
Ejemplo n.º 4
0
        internal void WriteErrorResponse(HttpContext context, ODataException oe)
        {
            var error = new Error
            {
                Code          = string.IsNullOrEmpty(oe.ErrorCode) ? Enum.GetName(typeof(ODataExceptionCode), oe.ODataExceptionCode) : oe.ErrorCode,
                ExceptionType = oe.InnerException == null?oe.GetType().Name : oe.InnerException.GetType().Name,
                Message       = new ErrorMessage
                {
                    Lang  = System.Globalization.CultureInfo.CurrentUICulture.Name.ToLower(),
                    Value = SNSR.GetString(oe.Message).Replace(Environment.NewLine, "\\n").Replace('"', ' ').Replace('\'', ' ').Replace(" \\ ", " ")
                },
                InnerError =
#if DEBUG
                    new StackInfo
                {
                    Trace = Utility.CollectExceptionMessages(oe)
                }
#else
                    HttpContext.Current != null && HttpContext.Current.IsDebuggingEnabled
                    ? new StackInfo {
                    Trace = Utility.CollectExceptionMessages(oe)
                }
                : null
#endif
            };

            context.Response.ContentType = "application/json";
            WriteError(context, error);
            context.Response.StatusCode             = oe.HttpStatusCode;
            context.Response.TrySkipIisCustomErrors = true;
        }
Ejemplo n.º 5
0
        public static Task Restore(Content content, string destination = null, bool?newname = null)
        {
            if (!(content?.ContentHandler is TrashBag tb))
            {
                throw new InvalidContentActionException("The resource content must be a TrashBag.");
            }

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

            // remember the id to load the content later
            var originalId = tb.DeletedContent.Id;

            try
            {
                if (newname.HasValue)
                {
                    TrashBin.Restore(tb, destination, newname.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(Content.LoadAsync(originalId, CancellationToken.None));
        }
Ejemplo n.º 6
0
        protected override IMetaNode VisitClass(Class @class)
        {
            var visitedProperties = ((IEnumerable <Property>)Visit(@class.Properties)).ToArray();
            var propertyLines     = new List <string>();

            foreach (var property in visitedProperties)
            {
                var fieldDescription = SNSR.GetString(property.FieldSetting.Description);
                if (!string.IsNullOrWhiteSpace(fieldDescription))
                {
                    propertyLines.Add($" /* {fieldDescription} */");
                }
                var isRequired = RequiredFields.Contains(property.Name) ? "!" : "?";
                propertyLines.Add($"public {property.Name}{isRequired}: {GetPropertyTypeName(property)}");
            }

            var type       = @class.Name;
            var parentName = @class.BaseClassName;

            WriteLine($"/**");
            var description = SNSR.GetString(@class.ContentType.Description);

            if (!string.IsNullOrWhiteSpace(description))
            {
                WriteLine($" * {description}");
            }
            WriteLine($" */");
            if (!string.IsNullOrWhiteSpace(parentName))
            {
                WriteLine($"export class {type} extends {parentName} {{");
            }
            else
            {
                WriteLine($"export class {type} {{");
            }

            _indentCount++;
            foreach (var propertyLine in propertyLines)
            {
                WriteLine(propertyLine);
            }
            WriteLine();
            if (string.IsNullOrWhiteSpace(parentName))
            {
                WriteLine("public Actions?: ContentListReferenceField<ActionModel>");
                WriteLine("public Type!: string");
            }
            _indentCount--;
            WriteLine("}");

            if (@class.Properties == visitedProperties)
            {
                return(@class);
            }
            return(@class.Rewrite(visitedProperties));
        }
Ejemplo n.º 7
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var nodeType = value as NodeType;

            if (nodeType == null)
            {
                throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.CannotConvertToJSON_2, typeof(NodeType).FullName, value.GetType().FullName), ODataExceptionCode.CannotConvertToJSON);
            }
            writer.WriteValue(nodeType.Name);
        }
Ejemplo n.º 8
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var versionData = value as VersionNumber;

            if (versionData == null)
            {
                throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.CannotConvertToJSON_2, typeof(VersionNumber).FullName, value.GetType().FullName), ODataExceptionCode.CannotConvertToJSON);
            }
            writer.WriteValue(versionData.ToString());
        }
Ejemplo n.º 9
0
        public static object Restore(Content content, string destination = null, bool?newname = null)
        {
            if (!(content?.ContentHandler is TrashBag tb))
            {
                throw new InvalidContentActionException("The resource content must be a TrashBag.");
            }

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

            try
            {
                if (newname.HasValue)
                {
                    TrashBin.Restore(tb, destination, newname.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);
        }
Ejemplo n.º 10
0
        protected virtual string GetFriendlyErrorMessage(Exception ex)
        {
            if (ex is InvalidContentQueryException)
            {
                return(SNSR.GetString(SNSR.Portlets.ContentCollection.ErrorInvalidContentQuery));
            }

            var text = SNSR.GetString(SNSR.Portlets.ContentCollection.ErrorLoadingContentView);

            return(string.Format(text, ex != null ? HttpUtility.HtmlEncode(ex.Message) : string.Empty));
        }
Ejemplo n.º 11
0
        //----------------------------------------------------------------------------------------------------------------------------------- operations

        /// <summary>
        /// Handles GET operations. Parameters come from the URL or the request stream.
        /// </summary>
        /// <param name="portalContext"></param>
        /// <param name="odataReq"></param>
        internal void WriteOperationResult(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);
            }

            if (!action.IsODataOperation)
            {
                throw new ODataException("Not an OData operation.", ODataExceptionCode.IllegalInvoke);
            }
            if (action.CausesStateChange)
            {
                throw new ODataException("OData action cannot be invoked with HTTP GET.", ODataExceptionCode.IllegalInvoke);
            }

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

            var parameters = GetOperationParameters(action, portalContext.OwnerHttpContext.Request);

            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);
            //Write(response, portalContext);
            WriteOperationResult(response, portalContext, odataReq, count);
        }
Ejemplo n.º 12
0
        // --------------------------------------------------------------------------------------------------------------- operations

        /// <summary>
        /// Handles GET operations. Parameters come from the URL or the request stream.
        /// </summary>
        internal async Task WriteGetOperationResultAsync(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);

                SnTrace.System.WriteError($"OData: {odataReq.PropertyName} operation not found " +
                                          $"for content {content.Path} and user {User.Current.Username}.");

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

            if (!action.IsODataOperation)
            {
                throw new ODataException("Not an OData operation.", ODataExceptionCode.IllegalInvoke);
            }
            if (action.CausesStateChange)
            {
                throw new ODataException("OData action cannot be invoked with HTTP GET.", ODataExceptionCode.IllegalInvoke);
            }

            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, GetOperationParameters(action, httpContext.Request));

            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);
        }
Ejemplo n.º 13
0
        private void CreateSelectNewControlsIfNeed()
        {
            if (this._displayMode != SelectNewContentTypeMode)
            {
                return;
            }

            if (this._container == null)
            {
                CreateContainer();
            }

            _contentTypeNames    = new DropDownList();
            _contentTypeNames.ID = "ContentTypeNames";

            var result = DropDownPartField.GetWebContentTypeList();

            if (result.Count > 0)
            {
                IEnumerable <Node> nodes = result.Nodes;
                var gc = PortalContext.Current.ContextNode as GenericContent;
                foreach (var ctContent in nodes.Select(Content.Create))
                {
                    if (!gc.IsAllowedChildType(ctContent.Name))
                    {
                        continue;
                    }

                    _contentTypeNames.Items.Add(new ListItem(ctContent.DisplayName, ctContent.Name));
                }
            }

            if (_contentTypeNames.Items.Count > 0)
            {
                _newContentButton = new Button
                {
                    ID   = "NewContentButton",
                    Text = HttpContext.GetGlobalResourceObject("SingleContentPortlet", "CreateNewContent") as string
                };
                ;
                _newContentButton.Click += _newContentButton_Click;

                _container.Controls.Clear();
                _container.Controls.Add(_contentTypeNames);
                _container.Controls.Add(_newContentButton);
            }
            else
            {
                _container.Controls.Clear();
                _container.Controls.Add(new LiteralControl(SNSR.GetString("SingleContentPortlet", "NoAllowedChildTypes")));
            }
        }
Ejemplo n.º 14
0
 internal static IEnumerable <ODataActionItem> GetHtmlActionItems(Content content, ODataRequest request)
 {
     return(GetActions(content, request).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
     }));
 }
Ejemplo n.º 15
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var imgData = value as ImageField.ImageFieldData;

            if (imgData == null)
            {
                throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.CannotConvertToJSON_2, typeof(ImageField.ImageFieldData).FullName, value.GetType().FullName), ODataExceptionCode.CannotConvertToJSON);
            }
            writer.WriteStartObject();
            var url = imgData.Field == null ? "#" : ((ImageField)imgData.Field).ImageUrl;

            writer.WritePropertyName("_deferred");
            writer.WriteValue(url);
            writer.WriteEnd();
        }
Ejemplo n.º 16
0
        protected override object GetModel()
        {
            var sf = SmartFolder.GetRuntimeQueryFolder();

            var model = Content.Create(sf);

            if (!this.AllowEmptySearch && SearchTextIsTooGeneric(this.QueryString))
            {
                if (HttpContext.Current.Request.Params.AllKeys.Contains(QueryParameterName))
                {
                    this.ErrorMessage = SNSR.GetString(ContextSearchClass, "Error_GenericSearchExpression");
                }
                return(model);
            }

            sf.Query = ReplaceTemplates(this.QueryString);

            var baseModel = base.GetModel() as Content;

            if (baseModel != null)
            {
                model.ChildrenDefinition           = baseModel.ChildrenDefinition;
                model.ChildrenDefinition.PathUsage = PathUsageMode.NotUsed;
                if (FilterByContext)
                {
                    var ctx = GetContextNode();
                    if (ctx != null)
                    {
                        //add filter: we search only under the current context
                        var escapedPath = ctx.Path.Replace("(", "\\(").Replace(")", "\\)");
                        model.ChildrenDefinition.ContentQuery =
                            ContentQuery.AddClause(model.ChildrenDefinition.ContentQuery,
                                                   ContentQuery.AddClause(sf.Query, string.Format("InTree:\"{0}\"", escapedPath), ChainOperator.And), ChainOperator.And);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(sf.Query))
                    {
                        model.ChildrenDefinition.ContentQuery = ContentQuery.AddClause(model.ChildrenDefinition.ContentQuery, sf.Query, ChainOperator.And);
                    }
                }
            }

            ResultModel = model;

            return(model);
        }
Ejemplo n.º 17
0
        public override object Execute(Content content, params object[] parameters)
        {
            var paths     = (string[])parameters[0];
            var permanent = parameters.Length > 1 && parameters[1] != null && (bool)parameters[1];

            var exceptions = new List <Exception>();

            foreach (var path in paths)
            {
                try
                {
                    var node = Node.LoadNode(path);
                    if (node == null)
                    {
                        throw new InvalidOperationException(string.Format(SNSR.GetString(SNSR.Exceptions.Operations.ContentDoesNotExistWithPath_1), path));
                    }

                    var gc = node as GenericContent;
                    if (gc != null)
                    {
                        gc.Delete(permanent);
                    }
                    else
                    {
                        var ct = node as ContentType;
                        if (ct != null)
                        {
                            ct.Delete();
                        }
                    }
                }
                catch (Exception e)
                {
                    exceptions.Add(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.
                    Logger.WriteException(e);
                }
            }
            if (exceptions.Count > 0)
            {
                throw new Exception(String.Join(Environment.NewLine, exceptions.Select(e => e.Message)));
            }

            return(null);
        }
Ejemplo n.º 18
0
 private ODataOperation CreateOdataOperation(ActionBase a, string selfUrl)
 {
     return(new ODataOperation
     {
         Title = SNSR.GetString(a.Text),
         Name = a.Name,
         Target = string.Concat(selfUrl, "/", a.Name),
         Forbidden = a.Forbidden,
         Parameters = a.ActionParameters.Select(p => new ODataOperationParameter
         {
             Name = p.Name,
             Type = ResolveODataParameterType(p.Type),
             Required = p.Required
         }).ToArray()
     });
 }
Ejemplo n.º 19
0
 internal static IEnumerable <ODataActionItem> GetActionItems(Content content, ODataRequest request)
 {
     return(GetActionsWithScenario(content, request).Select(a => new ODataActionItem
     {
         Name = a.Action.Name,
         DisplayName = SNSR.GetString(a.Action.Text),
         Icon = a.Action.Icon,
         Index = a.Action.Index,
         Url = a.Action.Uri,
         IncludeBackUrl = a.Action.GetApplication() == null ? 0 : (int)a.Action.GetApplication().IncludeBackUrl,
         ClientAction = !string.IsNullOrEmpty((a.Action as ClientAction)?.Callback),
         Forbidden = a.Action.Forbidden,
         IsODataAction = a.Action.IsODataOperation,
         ActionParameters = a.Action.ActionParameters.Select(p => p.Name).ToArray(),
         Scenario = a.Scenario
     }));
 }
Ejemplo n.º 20
0
        protected ODataActionItem[] GetActions(Content content)
        {
            var snActions = GetSnActions(content);

            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
            });

            return(actions.ToArray());
        }
Ejemplo n.º 21
0
        protected void BuildMainScreen()
        {
            ClearControls();

            var c = Page.LoadControl(ViewPath);

            if (c == null)
            {
                return;
            }

            this.Controls.Add(c);

            var trashBag = GetContextNode() as TrashBag;

            if (trashBag == null)
            {
                return;
            }

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

            if (this.DestinationTextBox != null)
            {
                this.DestinationTextBox.Text = trashBag.OriginalPath;

                if (this.DestinationButton != null)
                {
                    this.DestinationButton.OnClientClick = GetOpenContentPickerScript(this.DestinationTextBox);
                }
            }

            if (this.ContentLabel != null)
            {
                var lc = trashBag.DeletedContent;
                if (lc != null)
                {
                    this.ContentLabel.Text = HttpUtility.HtmlEncode(SNSR.GetString(lc.DisplayName));
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Constructor of taglist.
        /// </summary>
        public TagList()
        {
            InnerControlID = "InnerTagListBox";

            _adminMode = User.Current.IsInGroup(Group.Administrators);

            _tbTagList = new TextBox {
                ID = InnerControlID
            };
            _errorLabel = new Label {
                ID = "InnerErrorLabel"
            };
            _btnAddTag = new Button {
                ID = "btnAddTag", Text = SNSR.GetString(SR.FieldControls.TagList_AddTag), OnClientClick = "return false;"
            };
            _taglist          = new TagCollection();
            _searchPath       = "";
            _searchFilterName = "TagFilter";
        }
Ejemplo n.º 23
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var urls = value as Dictionary <string, string>;

            if (urls == null)
            {
                throw new ODataException(SNSR.GetString(SNSR.Exceptions.OData.CannotConvertToJSON_2, "Dictionary<string, string>", value.GetType().FullName), ODataExceptionCode.CannotConvertToJSON);
            }

            writer.WriteStartArray();
            foreach (var item in urls)
            {
                writer.WriteStartObject();
                writer.WritePropertyName(item.Key);
                writer.WriteValue(item.Value);
                writer.WriteEndObject();
            }
            writer.WriteEndArray();
        }
Ejemplo n.º 24
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() }
            });
        }
Ejemplo n.º 25
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));
        }
Ejemplo n.º 26
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";
        }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
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 }
            });
        }
Ejemplo n.º 29
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));
        }
Ejemplo n.º 30
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());
        }