Esempio n. 1
0
        public void OD_MBO_BuiltIn_TakeLockOver()
        {
            IsolatedODataTest(() =>
            {
                var user = CreateUser("*****@*****.**");
                SecurityHandler.CreateAclEditor()
                .Allow(2, user.Id, false, PermissionType.PermissionTypes)
                .Apply();

                File file;
                using (new CurrentUserBlock(user))
                {
                    file = new File(CreateTestRoot("TestFiles"))
                    {
                        Name = "File-1"
                    };
                    file.Save();
                    file.CheckOut();
                }

                Assert.AreEqual(user.Id, file.LockedById);

                var url      = ODataTools.GetODataUrl(Content.Create(file));
                var response = ODataPostAsync($"{url}/TakeLockOver", "",
                                              "models=[{'user':'******'}]")
                               .ConfigureAwait(false).GetAwaiter().GetResult();

                Assert.AreEqual(200, response.StatusCode);
                Assert.AreEqual("Ok", response.Result);
                file = Node.Load <File>(file.Id);
                Assert.AreEqual(Identifiers.AdministratorUserId, file.LockedById);
            });
        }
Esempio n. 2
0
        public void OD_MBO_BuiltIn_TakeOwnership()
        {
            IsolatedODataTest(() =>
            {
                File file;
                using (new CurrentUserBlock(User.Administrator))
                {
                    file = new File(CreateTestRoot("TestFiles"))
                    {
                        Name = "File-1"
                    };
                    file.Save();
                    Assert.AreEqual(Identifiers.AdministratorUserId, file.OwnerId);
                }

                var user = CreateUser("*****@*****.**");

                var url      = ODataTools.GetODataUrl(Content.Create(file));
                var response = ODataPostAsync($"{url}/TakeOwnership", "",
                                              $"models=[{{'userOrGroup':'{user.Path}'}}]")
                               .ConfigureAwait(false).GetAwaiter().GetResult();

                Assert.AreEqual(204, response.StatusCode);
                file = Node.Load <File>(file.Id);
                Assert.AreEqual(user.Id, file.OwnerId);
            });
        }
Esempio n. 3
0
 protected override string GetCallBackScript()
 {
     return(GetServiceCallBackScript(
                url: ODataTools.GetODataOperationUrl(Content, "CopyTo", true),
                scriptBeforeServiceCall: "var path = '" + Content.Path + "'",
                postData: "JSON.stringify({ targetPath: targetPath })",
                inprogressTitle: ResourceManager.Current.GetString("Action", "CopyInProgressDialogTitle"),
                successContent: ResourceManager.Current.GetString("Action", "CopyDialogContent"),
                successTitle: ResourceManager.Current.GetString("Action", "CopyDialogTitle"),
                successCallback: @"SN.Util.RefreshExploreTree([targetPath]);",
                errorCallback: @"SN.Util.RefreshExploreTree([targetPath]);",
                successCallbackAfterDialog: "location = location;",
                errorCallbackAfterDialog: "location = location;"
                ));
 }
Esempio n. 4
0
        protected override string GetCallBackScript()
        {
            return(GetServiceCallBackScript(
                       url: ODataTools.GetODataOperationUrl(Content, "MoveBatch", true),
                       scriptBeforeServiceCall: "var paths = " + GetPathListMethod(),
                       postData: "JSON.stringify({ targetPath: targetPath, paths: paths })",
                       inprogressTitle: SenseNetResourceManager.Current.GetString("Action", "MoveInProgressDialogTitle"),
                       successContent: SenseNetResourceManager.Current.GetString("Action", "MoveDialogContent"),
                       successTitle: SenseNetResourceManager.Current.GetString("Action", "MoveDialogTitle"),
                       successCallback: @"
var pathToRefresh = SN.Util.GetParentPath(paths[0]);
SN.Util.RefreshExploreTree([pathToRefresh, targetPath]);",
                       errorCallback: @"
var pathToRefresh = SN.Util.GetParentPath(paths[0]);
SN.Util.RefreshExploreTree([pathToRefresh, targetPath]);",
                       successCallbackAfterDialog: "location=location;",
                       errorCallbackAfterDialog: "location=location;"
                       ));
        }
Esempio n. 5
0
        public static string ActionMenu(string contentPath, string innerContent, string scenario)
        {
            if (string.IsNullOrEmpty(contentPath))
            {
                return(string.Empty);
            }

            var id         = Guid.NewGuid().ToString();
            var serviceUrl = ODataTools.GetODataOperationUrl(contentPath, "SmartAppGetActions");
            var json       = string.Format(CultureInfo.InvariantCulture,
                                           "\"ItemHoverCssClass\":null,\"Mode\":\"default\",\"ServiceUrl\":\"" + serviceUrl + "?scenario={0}&back={1}&parameters=\",\"WrapperCssClass\":\"sn-actionmenu sn-action-default-mode\"",
                                           scenario,
                                           HttpUtility.UrlEncode(PortalContext.Current.RequestedUri.ToString()));
            var script = "$create(SenseNet.Portal.UI.Controls.ActionMenu, { " + json + " }, null, null, $get(\"" + id + "\"));";

            var element = string.Format(CultureInfo.InvariantCulture, @"<span id='{0}' 
                    class='sn-actionmenu sn-actionmenu-default-mode ui-widget'>
                    <span class='sn-actionmenu-inner ui-state-default ui-corner-all'>{1}</span></span>", id, innerContent);

            return(element + "<script>" + script + "</script>");
        }
Esempio n. 6
0
        protected override string GetCallBackScript()
        {
            var callbackScript = GetServiceCallBackScript(
                url: ODataTools.GetODataOperationUrl(Content, "MoveTo", true),
                scriptBeforeServiceCall: "var path = '" + Content.Path + "'",
                postData: "JSON.stringify({ targetPath: targetPath })",
                inprogressTitle: SenseNetResourceManager.Current.GetString("Action", "MoveInProgressDialogTitle"),
                successContent: SenseNetResourceManager.Current.GetString("Action", "MoveDialogContent"),
                successTitle: SenseNetResourceManager.Current.GetString("Action", "MoveDialogTitle"),
                successCallback: @"
var pathToRefresh = SN.Util.GetParentPath(path);
SN.Util.RefreshExploreTree([pathToRefresh, targetPath]);",
                errorCallback: @"
var pathToRefresh = SN.Util.GetParentPath(path);
SN.Util.RefreshExploreTree([pathToRefresh, targetPath]);",
                successCallbackAfterDialog: @"
location=" + (this.RedirectToBackUrl ? string.Concat("\'", HttpUtility.UrlDecode(this.BackUri), "\'") : "SN.Util.GetParentUrlForPath(path)") + ";",
                errorCallbackAfterDialog: "location=location;"
                );

            return(callbackScript);
        }
Esempio n. 7
0
        public void Aspect_OData_LongTextDoesNotContainCdata()
        {
            var fieldValue = "<p>Field value</p>";
            var aspect     = EnsureAspect("LongTextTest");

            aspect.AddFields(new FieldInfo {
                Name = "Field1", Type = "LongText"
            });

            var content = Content.CreateNew("Car", TestRoot, Guid.NewGuid().ToString());

            content.AddAspects(aspect);
            content["LongTextTest.Field1"] = fieldValue;
            content.Save();

            var uri = ODataTools.GetODataUrl(content);

            ODataTests.CreateTestSite();
            ODataTests.Entity entity;
            try
            {
                using (var output = new System.IO.StringWriter())
                {
                    var pc      = ODataTests.CreatePortalContext(uri, "", output);
                    var handler = new ODataHandler();
                    handler.ProcessRequest(pc.OwnerHttpContext, "GET", null);
                    entity = ODataTests.GetEntity(output);
                }
                var value       = entity.AllProperties["LongTextTest.Field1"];
                var jvalue      = value as JValue;
                var stringValue = (string)jvalue.Value;
                Assert.AreEqual(fieldValue, stringValue);
            }
            finally
            {
                ODataTests.CleanupTestSite();
            }
        }
Esempio n. 8
0
        private static ServiceAction GetServiceAction(Content context, Node view, bool addFullPath, string portletId, string selectedView, string backUrl)
        {
            // create app-less action for view selection
            var act = ActionFramework.GetAction("ServiceAction", context, backUrl,
                                                new
            {
                uiContextId = portletId ?? string.Empty,
                view        = addFullPath ? view.Path : view.Name,
            }) as ServiceAction;

            if (act == null)
            {
                return(null);
            }

            var gc          = view as GenericContent;
            var viewContent = Content.Create(view);
            var icon        = gc != null ? gc.Icon : string.Empty;

            if (string.IsNullOrEmpty(icon))
            {
                icon = "views";
            }

            act.Name        = "ServiceAction";
            act.ServiceName = ODataTools.GetODataUrl(context.Path);
            act.MethodName  = "ContentListViewSetView";
            act.Text        = viewContent.DisplayName;
            act.Icon        = icon;

            if (string.Compare(selectedView, view.Name, StringComparison.InvariantCultureIgnoreCase) == 0 ||
                string.Compare(selectedView, view.Path, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                act.CssClass  = (act.CssClass + " sn-actionlink-selectedview").TrimStart(' ');
                act.Forbidden = true;
            }
            return(act);
        }
Esempio n. 9
0
        internal async Task WriteContentPropertyAsync(string path, string propertyName, bool rawValue, HttpContext httpContext, ODataRequest req, IConfiguration appConfig)
        {
            var content = ODataMiddleware.LoadContentByVersionRequest(path, httpContext);

            if (content == null)
            {
                ODataMiddleware.ContentNotFound(httpContext);
                return;
            }

            if (propertyName == ODataMiddleware.ActionsPropertyName)
            {
                var actionItems = ODataTools.GetActionItems(content, req, httpContext).ToArray();
                await WriteActionsAsync(actionItems, httpContext, req);

                return;
            }
            if (propertyName == ODataMiddleware.ChildrenPropertyName)
            {
                await WriteChildrenCollectionAsync(path, httpContext, req)
                .ConfigureAwait(false);
            }

            if (content.Fields.TryGetValue(propertyName, out var field))
            {
                if (field is ReferenceField refField)
                {
                    var refFieldSetting = refField.FieldSetting as ReferenceFieldSetting;
                    var isMultiRef      = true;
                    if (refFieldSetting != null)
                    {
                        isMultiRef = refFieldSetting.AllowMultiple == true;
                    }
                    if (isMultiRef)
                    {
                        await WriteMultiRefContentsAsync(refField.GetData(), httpContext, req)
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await WriteSingleRefContentAsync(refField.GetData(), httpContext)
                        .ConfigureAwait(false);
                    }
                }
                else if (field is AllowedChildTypesField actField)
                {
                    await WriteMultiRefContentsAsync(actField.GetData(), httpContext, req)
                    .ConfigureAwait(false);
                }
                else if (!rawValue)
                {
                    await WriteSingleContentAsync(httpContext, new ODataEntity { { propertyName, field.GetData() } })
                    .ConfigureAwait(false);
                }
                else
                {
                    await WriteRawAsync(field.GetData(), httpContext)
                    .ConfigureAwait(false);
                }
            }
            else
            {
                await WriteGetOperationResultAsync(httpContext, req, appConfig)
                .ConfigureAwait(false);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Sets the callback URL of the ActionMenu. It represents the service url with correct parameters for the actions.
        /// </summary>
        private void SetServiceUrl()
        {
            var scParams = GetReplacedScenarioParameters();
            var context  = UITools.FindContextInfo(this, ContextInfoID);
            var path     = !string.IsNullOrEmpty(ContextInfoID) ? context.Path : NodePath;

            var encodedReturnUrl = Uri.EscapeDataString(PortalContext.Current.RequestedUri.PathAndQuery);
            var encodedParams    = Uri.EscapeDataString(scParams ?? string.Empty);

            if (string.IsNullOrEmpty(path))
            {
                path = ContentView.GetContentPath(this);
            }

            if (string.IsNullOrEmpty(path))
            {
                this.Visible = false;
                return;
            }

            var head = NodeHead.Get(path);

            if (head == null || !SecurityHandler.HasPermission(head, PermissionType.See))
            {
                this.Visible = false;
                return;
            }

            this.Content = Content.Load(path);

            // Pre-check action count. If empty, hide the action menu.
            if (CheckActionCount)
            {
                var actionCount = 0;

                if (!string.IsNullOrEmpty(Scenario))
                {
                    actionCount = ActionFramework.GetActions(this.Content, Scenario, scParams, null).Count();
                }

                if (actionCount < 2 && string.Equals(Scenario, "new", StringComparison.CurrentCultureIgnoreCase))
                {
                    ClickDisabled = true;
                }
                else if (actionCount == 0)
                {
                    this.Visible = false;
                    return;
                }
            }

            // Pre-check required permissions
            var permissions = SenseNet.ContentRepository.Fields.PermissionChoiceField.ConvertToPermissionTypes(RequiredPermissions).ToArray();

            if (permissions.Length > 0 && !SecurityHandler.HasPermission(head, permissions))
            {
                this.Visible = false;
                return;
            }

            ServiceUrl = string.Format(ODataTools.GetODataOperationUrl(path, "SmartAppGetActions") + "?scenario={0}&back={1}&parameters={2}", Scenario, encodedReturnUrl, encodedParams);
        }