Пример #1
0
        public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
            {
                return(new HttpUnauthorizedResult());
            }

            var activity = _activitiesManager.GetActivityByName(name);

            if (activity == null)
            {
                return(HttpNotFound());
            }

            // validating form values
            _formManager.Validate(new ValidatingContext {
                FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider
            });

            // stay on the page if there are validation errors
            if (!ModelState.IsValid)
            {
                // build the form, and let external components alter it
                var form = activity.Form == null ? null : _formManager.Build(activity.Form);

                // bind form with existing values.
                _formManager.Bind(form, ValueProvider);

                var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form);

                return(View(viewModel));
            }

            var model = new UpdatedActivityModel {
                ClientId = clientId,
                Data     = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues))
            };

            TempData["UpdatedViewModel"] = model;

            return(RedirectToAction("Edit", new {
                id,
                localId
            }));
        }
Пример #2
0
        public ActionResult GetUserList()
        {
            var users = _userService.GetUsers();

            dynamic jObj = new JObject();

            jObj.Users = new JArray(users.Select(x =>
            {
                dynamic user = new JObject();
                user.id      = x.Id;
                user.Name    = x.UserName;

                return(user);
            }));


            return(Json(FormParametersHelper.ToJsonString(jObj), JsonRequestBehavior.AllowGet));
        }
Пример #3
0
        public ActionResult CreatePost(LayoutEditViewModel model, FormCollection formCollection)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageQueries, T("Not authorized to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            // validating form values
            model.Layout = _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == model.Category && x.Type == model.Type);

            _formManager.Validate(new ValidatingContext {
                FormName = model.Layout.Form, ModelState = ModelState, ValueProvider = ValueProvider
            });

            var form = _formManager.Build(model.Layout.Form) ?? Services.New.EmptyForm();

            _formManager.Bind(form, formCollection);

            model.Form = form;

            if (ModelState.IsValid)
            {
                var layoutRecord = new LayoutRecord {
                    Category = model.Category, Type = model.Type
                };
                var query = _queryService.GetQuery(model.QueryId);
                query.Layouts.Add(layoutRecord);

                var dictionary = formCollection.AllKeys.ToDictionary(key => key, formCollection.Get);

                // save form parameters
                layoutRecord.State       = FormParametersHelper.ToString(dictionary);
                layoutRecord.Description = model.Description;
                layoutRecord.Display     = model.Display;
                layoutRecord.DisplayType = model.DisplayType;

                Services.Notifier.Information(T("Layout Created"));

                _repository.Create(layoutRecord);
                return(RedirectToAction("Edit", new { id = layoutRecord.Id }));
            }

            return(View(model));
        }
Пример #4
0
        public ActionResult AddAssignment(int taskId)
        {
            TaskAssignment _taskAssignment = new TaskAssignment();
            var            users           = _userService.GetUsers();

            _taskAssignment.Users = users;
            dynamic jObj = new JObject();

            jObj.Users = new JArray(users.Select(x =>
            {
                dynamic user = new JObject();
                user.id      = x.Id;
                user.Name    = x.UserName;

                return(user);
            }));
            _taskAssignment.jsonData = FormParametersHelper.ToJsonString(jObj);
            return(View("AddAssignment", _taskAssignment));
        }
Пример #5
0
        public ActionResult EditPost(int id, string category, string type, [DefaultValue(-1)] int eventId, FormCollection formCollection)
        {
            var rule = _rulesServices.GetRule(id);

            var eventRecord = rule.Events.Where(a => a.Id == eventId).FirstOrDefault();

            // add new event record if it's a newly created event
            if (eventRecord == null)
            {
                eventRecord = new EventRecord {
                    Category = category, Type = type
                };
                rule.Events.Add(eventRecord);
            }

            var e = _rulesManager.DescribeEvents().SelectMany(x => x.Descriptors).Where(x => x.Category == category && x.Type == type).FirstOrDefault();

            // validating form values
            _formManager.Validate(new ValidatingContext {
                FormName = e.Form, ModelState = ModelState, ValueProvider = ValueProvider
            });

            if (ModelState.IsValid)
            {
                var dictionary = formCollection.AllKeys.ToDictionary(key => key, formCollection.Get);

                // save form parameters
                eventRecord.Parameters = FormParametersHelper.ToString(dictionary);

                return(RedirectToAction("Edit", "Admin", new { id }));
            }

            // model is invalid, display it again
            var form = _formManager.Build(e.Form);

            AddSubmitButton(form);
            _formManager.Bind(form, formCollection);
            var viewModel = new EditEventViewModel {
                Id = id, Event = e, Form = form
            };

            return(View(viewModel));
        }
Пример #6
0
        private string ProjectManagementTaskJson <T>(IEnumerable <T> _tasks) where T : TaskMgmtPart
        {
            //IEnumerable<TaskMgmtPartRecord> _tasks = _projTasks.GetTasks();
            // ProjectTaskViewModel _taskPartVM = new ProjectTaskViewModel(_tasks);
            dynamic jsonTask = new JObject();

            jsonTask.tasks = new JArray(_tasks.Select(_task =>
            {
                dynamic task          = new JObject();
                task.id               = _task.Id;
                task.name             = _task.Name;
                task.description      = _task.Description;
                task.status           = _task.Status;
                task.code             = _task.TaskCode;
                task.level            = _task.Level;
                task.duration         = _task.Duration;
                task.startIsMilestone = _task.StartIsMilestone;
                task.endIsMilestone   = _task.EndIsMilestone;
                task.progress         = _task.Progress;
                if (_task.Dependancy != null)
                {
                    task.depends = _task.Dependancy;
                }
                //task.start = DateTime.Now.AddDays(10).Millisecond;
                if (_task.ProjStartDate != null)
                {
                    DateTime start = (DateTime)_task.ProjStartDate;
                    task.start     = (long)(start - new DateTime(1970, 1, 1)).TotalMilliseconds;
                }
                if (_task.ProjEndDate != null)
                {
                    DateTime end = (DateTime)_task.ProjEndDate;
                    task.end     = (long)(end - new DateTime(1970, 1, 1)).TotalMilliseconds;
                }
                return(task);
            }));
            jsonTask.selectedRow      = 0;
            jsonTask.canWrite         = true;
            jsonTask.canWriteOnParent = true;

            return(FormParametersHelper.ToJsonString(jsonTask));
        }
Пример #7
0
        private static string GetLayoutState(int queryId, int columnCount, string desc)
        {
            var datas = new Dictionary <string, string> {
                { "QueryId", queryId.ToString(CultureInfo.InvariantCulture) },
                { "Category", "Html" },
                { "Type", "ngGrid" },
                { "Description", desc },
                { "Display", "1" },
                { "DisplayType", "Summary" },
                { "Alignment", "horizontal" },
                { "Columns", columnCount.ToString(CultureInfo.InvariantCulture) },
                { "GridId", string.Empty },
                { "GridClass", string.Empty },
                { "RowClass", string.Empty }
            };

            var re = FormParametersHelper.ToString(datas);

            return(re);
        }
Пример #8
0
        private string GetResizeUrl(string path, string width)
        {
            var state = new Dictionary <string, string> {
                { "Width", width.ToString(CultureInfo.InvariantCulture) },
                { "Height", "0" }
            };

            var filter = new FilterRecord
            {
                Category = "Transform",
                Type     = "Resize",
                State    = FormParametersHelper.ToString(state)
            };

            var profile = "Transform_Resize"
                          + "_w_" + Convert.ToString(width)
                          + "_h_" + Convert.ToString(0);

            return(_imageProfileManager.Value.GetImageProfileUrl(path, profile, filter));
        }
Пример #9
0
        private FilterRecord Filter(
            int Width,
            int Height,
            string Mode,
            string Alignment,
            string PadColor)
        {
            var state = new Dictionary <string, string> {
                { "Width", Width.ToString(CultureInfo.InvariantCulture) },
                { "Height", Height.ToString(CultureInfo.InvariantCulture) },
                { "Mode", Mode },
                { "Alignment", Alignment },
                { "PadColor", PadColor },
            };

            return(new FilterRecord {
                Category = "Transform",
                Type = "Resize",
                State = FormParametersHelper.ToString(state)
            });
        }
Пример #10
0
        public ActionResult Edit(int id)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit media profiles")))
            {
                return(new HttpUnauthorizedResult());
            }

            var profile   = _profileService.GetImageProfile(id);
            var viewModel = new AdminEditViewModel {
                Id   = profile.Id,
                Name = profile.Name
            };

            var filterEntries = new List <FilterEntry>();
            var allFilters    = _imageProcessingManager.DescribeFilters().SelectMany(x => x.Descriptors).ToList();

            foreach (var filter in profile.Filters.OrderBy(f => f.Position))
            {
                var category = filter.Category;
                var type     = filter.Type;

                var f = allFilters.FirstOrDefault(x => category == x.Category && type == x.Type);
                if (f != null)
                {
                    filterEntries.Add(
                        new FilterEntry {
                        Category       = f.Category,
                        Type           = f.Type,
                        FilterRecordId = filter.Id,
                        DisplayText    = String.IsNullOrWhiteSpace(filter.Description) ? f.Display(new FilterContext {
                            State = FormParametersHelper.ToDynamic(filter.State)
                        }).Text : filter.Description
                    });
                }
            }

            viewModel.Filters = filterEntries;

            return(View(viewModel));
        }
Пример #11
0
        private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord)
        {
            if (workflowDefinitionRecord == null)
            {
                throw new ArgumentNullException("workflowDefinitionRecord");
            }

            var workflowDefinitionModel = new WorkflowDefinitionViewModel {
                Id   = workflowDefinitionRecord.Id,
                Name = workflowDefinitionRecord.Name
            };

            dynamic workflow = new JObject();

            workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => {
                dynamic activity  = new JObject();
                activity.Name     = x.Name;
                activity.Id       = x.Id;
                activity.ClientId = x.Name + "_" + x.Id;
                activity.Left     = x.X;
                activity.Top      = x.Y;
                activity.Start    = x.Start;
                activity.State    = FormParametersHelper.FromJsonString(x.State);

                return(activity);
            }));

            workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => {
                dynamic connection        = new JObject();
                connection.Id             = x.Id;
                connection.SourceId       = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id;
                connection.TargetId       = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id;
                connection.SourceEndpoint = x.SourceEndpoint;
                return(connection);
            }));

            workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow);

            return(workflowDefinitionModel);
        }
Пример #12
0
 private void InvokeOtherProvider(
     SortCriterionContext context, SortCriterionConfiguration criterion)
 {
     if (allSortProviders.Any())
     {
         // pretend we are the ProjectionManager here
         // look for the specific filter component
         var descriptor = AllDescriptors()
                          .FirstOrDefault(x =>
                                          x.Category == criterion.SortCriterionProviderCategory &&
                                          x.Type == criterion.SortCriterionProviderType);
         if (descriptor == null)
         {
             Logger.Error(
                 T("It was impossible to find a descriptor for sort provider with category {0} and type {1}.",
                   criterion.SortCriterionProviderCategory, criterion.SortCriterionProviderType).Text);
         }
         else
         {
             var criterionState = FormParametersHelper.ToDynamic(criterion.SortCriterionProviderState ?? "");
             criterionState.Sort = criterion.Ascending;
             var sortCriterionContext = new SortCriterionContext {
                 Query           = context.Query,
                 State           = criterionState,
                 QueryPartRecord = context.QueryPartRecord,
                 Tokens          = context.Tokens
             };
             descriptor.Sort(sortCriterionContext);
             context.Query = sortCriterionContext.Query;
         }
     }
     if (criterion.Children.Any())
     {
         foreach (var childCriterion in criterion.Children)
         {
             CriterionApplication(context, childCriterion);
         }
     }
 }
Пример #13
0
        public ActionResult Edit(int id, string category, string type, int filterId = -1)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageQueries, T("Not authorized to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var filter = _projectionManager.DescribeFilters().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == category && x.Type == type);

            if (filter == null)
            {
                return(HttpNotFound());
            }

            // build the form, and let external components alter it
            var form = filter.Form == null ? null : _formManager.Build(filter.Form);

            string description = "";

            // bind form with existing values).
            if (filterId != -1)
            {
                var group        = _groupRepository.Get(id);
                var filterRecord = group.Filters.FirstOrDefault(f => f.Id == filterId);
                if (filterRecord != null)
                {
                    description = filterRecord.Description;
                    var parameters = FormParametersHelper.FromString(filterRecord.State);
                    _formManager.Bind(form, new DictionaryValueProvider <string>(parameters, CultureInfo.InvariantCulture));
                }
            }

            var viewModel = new FilterEditViewModel {
                Id = id, Description = description, Filter = filter, Form = form
            };

            return(View(viewModel));
        }
Пример #14
0
        private static void SortStaffProfileQuery(QueryPart staffProfileQuery)
        {
            var sortDictionary = new Dictionary <string, string>();

            sortDictionary.Add("Description", "Staff Group");
            sortDictionary.Add("Sort", "false");

            //sort by name
            var profileNameCriteria = staffProfileQuery.SortCriteria.FirstOrDefault();

            if (profileNameCriteria == null)
            {
                profileNameCriteria = new SortCriterionRecord
                {
                    Category    = "TitlePartRecord",
                    Type        = "Title",
                    Description = "Profile Name",
                    Position    = 1
                };
            }
            profileNameCriteria.State = FormParametersHelper.ToString(sortDictionary);
            staffProfileQuery.SortCriteria.Add(profileNameCriteria);
        }
Пример #15
0
        public void Sweep()
        {
            var awaiting = _awaitingActivityRepository.Table.Where(x => x.ActivityRecord.Name == OrchardCollaborationTimerActivity.ActionName).ToList();


            foreach (var action in awaiting)
            {
                try
                {
                    var contentItem = _contentManager.Get(action.WorkflowRecord.ContentItemRecord.Id, VersionOptions.Latest);
                    var tokens      = new Dictionary <string, object> {
                        { "Content", contentItem }
                    };
                    var workflowState = FormParametersHelper.FromJsonString(action.WorkflowRecord.State);
                    workflowState.TimerActivity_StartedUtc = null;
                    action.WorkflowRecord.State            = FormParametersHelper.ToJsonString(workflowState);
                    _workflowManager.TriggerEvent(OrchardCollaborationTimerActivity.ActionName, contentItem, () => tokens);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "OrchardCollaborationTimerBackgroundTask: Error while processing background task \"{0}\" on tenant \"{1}\".", action.ActivityRecord.Name, _shellName);
                }
            }
        }
Пример #16
0
        public ActionResult Edit(int id)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit rules")))
            {
                return(new HttpUnauthorizedResult());
            }

            var rule      = _rulesServices.GetRule(id);
            var viewModel = new EditRuleViewModel {
                Id      = rule.Id,
                Enabled = rule.Enabled,
                Name    = rule.Name
            };

            #region Load events
            var eventEntries = new List <EventEntry>();
            var allEvents    = _rulesManager.DescribeEvents().SelectMany(x => x.Descriptors);

            foreach (var eventRecord in rule.Events)
            {
                var category = eventRecord.Category;
                var type     = eventRecord.Type;

                var ev = allEvents.Where(x => category == x.Category && type == x.Type).FirstOrDefault();
                if (ev != null)
                {
                    var eventParameters = FormParametersHelper.FromString(eventRecord.Parameters);
                    eventEntries.Add(
                        new EventEntry {
                        Category      = ev.Category,
                        Type          = ev.Type,
                        EventRecordId = eventRecord.Id,
                        DisplayText   = ev.Display(new EventContext {
                            Properties = eventParameters
                        })
                    });
                }
            }

            viewModel.Events = eventEntries;

            #endregion

            #region Load actions
            var actionEntries = new List <ActionEntry>();
            var allActions    = _rulesManager.DescribeActions().SelectMany(x => x.Descriptors);

            foreach (var actionRecord in rule.Actions.OrderBy(x => x.Position))
            {
                var category = actionRecord.Category;
                var type     = actionRecord.Type;

                var action = allActions.Where(x => category == x.Category && type == x.Type).FirstOrDefault();
                if (action != null)
                {
                    var actionParameters = FormParametersHelper.FromString(actionRecord.Parameters);
                    actionEntries.Add(
                        new ActionEntry {
                        Category       = action.Category,
                        Type           = action.Type,
                        ActionRecordId = actionRecord.Id,
                        DisplayText    = action.Display(new ActionContext {
                            Properties = actionParameters
                        })
                    });
                }
            }

            viewModel.Actions = actionEntries;
            #endregion

            return(View(viewModel));
        }
Пример #17
0
        public ActionResult EditPost(int id, string localId, string data, bool clearWorkflows)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows")))
            {
                return(new HttpUnauthorizedResult());
            }

            var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id);

            if (workflowDefinitionRecord == null)
            {
                return(HttpNotFound());
            }

            workflowDefinitionRecord.Enabled = true;

            var state           = FormParametersHelper.FromJsonString(data);
            var activitiesIndex = new Dictionary <string, ActivityRecord>();

            workflowDefinitionRecord.ActivityRecords.Clear();

            foreach (var activity in state.Activities)
            {
                ActivityRecord activityRecord;

                workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord {
                    Name  = activity.Name,
                    X     = activity.Left,
                    Y     = activity.Top,
                    Start = activity.Start,
                    State = FormParametersHelper.ToJsonString(activity.State),
                    WorkflowDefinitionRecord = workflowDefinitionRecord
                });

                activitiesIndex.Add((string)activity.ClientId, activityRecord);
            }

            workflowDefinitionRecord.TransitionRecords.Clear();

            foreach (var connection in state.Connections)
            {
                workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord {
                    SourceActivityRecord      = activitiesIndex[(string)connection.SourceId],
                    DestinationActivityRecord = activitiesIndex[(string)connection.TargetId],
                    SourceEndpoint            = connection.SourceEndpoint,
                    WorkflowDefinitionRecord  = workflowDefinitionRecord
                });
            }

            if (clearWorkflows)
            {
                workflowDefinitionRecord.WorkflowRecords.Clear();
            }
            else
            {
                var removeWorkflows = new List <WorkflowRecord>();
                foreach (var workflowRecord in workflowDefinitionRecord.WorkflowRecords)
                {
                    var removeAwaitingActivites = new List <AwaitingActivityRecord>();
                    // Update any awaiting activity records with the new activity record.
                    foreach (var awaitingActivityRecord in workflowRecord.AwaitingActivities)
                    {
                        var clientId = awaitingActivityRecord.ActivityRecord.GetClientId();
                        if (activitiesIndex.ContainsKey(clientId))
                        {
                            awaitingActivityRecord.ActivityRecord = activitiesIndex[clientId];
                        }
                        else
                        {
                            removeAwaitingActivites.Add(awaitingActivityRecord);
                        }
                    }

                    foreach (var item in removeAwaitingActivites)
                    {
                        workflowRecord.AwaitingActivities.Remove(item);
                    }

                    // Remove any workflows with no awaiting activities.
                    if (!workflowRecord.AwaitingActivities.Any())
                    {
                        removeWorkflows.Add(workflowRecord);
                    }
                }

                foreach (var item in removeWorkflows)
                {
                    workflowDefinitionRecord.WorkflowRecords.Remove(item);
                }
            }

            Services.Notifier.Success(T("Workflow saved successfully"));

            // Don't pass the localId to force the activites to refresh and use the deterministic clientId.
            return(RedirectToAction("Edit", new { id }));
        }
Пример #18
0
        public ActionResult Edit(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageQueries, T("Not authorized to edit queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var query     = _queryService.GetQuery(id);
            var viewModel = new AdminEditViewModel {
                Id   = query.Id,
                Name = query.Name
            };

            #region Load Filters
            var filterGroupEntries = new List <FilterGroupEntry>();
            var allFilters         = _projectionManager.DescribeFilters().SelectMany(x => x.Descriptors).ToList();

            foreach (var group in query.FilterGroups)
            {
                var filterEntries = new List <FilterEntry>();

                foreach (var filter in group.Filters)
                {
                    var category = filter.Category;
                    var type     = filter.Type;

                    var f = allFilters.FirstOrDefault(x => category == x.Category && type == x.Type);
                    if (f != null)
                    {
                        filterEntries.Add(
                            new FilterEntry {
                            Category       = f.Category,
                            Type           = f.Type,
                            FilterRecordId = filter.Id,
                            DisplayText    = String.IsNullOrWhiteSpace(filter.Description) ? f.Display(new FilterContext {
                                State = FormParametersHelper.ToDynamic(filter.State)
                            }).Text : filter.Description
                        });
                    }
                }

                filterGroupEntries.Add(new FilterGroupEntry {
                    Id = group.Id, Filters = filterEntries
                });
            }

            viewModel.FilterGroups = filterGroupEntries;

            #endregion

            #region Load Sort criterias
            var sortCriterionEntries = new List <SortCriterionEntry>();
            var allSortCriteria      = _projectionManager.DescribeSortCriteria().SelectMany(x => x.Descriptors).ToList();

            foreach (var sortCriterion in query.SortCriteria.OrderBy(s => s.Position))
            {
                var category = sortCriterion.Category;
                var type     = sortCriterion.Type;

                var f = allSortCriteria.FirstOrDefault(x => category == x.Category && type == x.Type);
                if (f != null)
                {
                    sortCriterionEntries.Add(
                        new SortCriterionEntry {
                        Category = f.Category,
                        Type     = f.Type,
                        SortCriterionRecordId = sortCriterion.Id,
                        DisplayText           = String.IsNullOrWhiteSpace(sortCriterion.Description) ? f.Display(new SortCriterionContext {
                            State = FormParametersHelper.ToDynamic(sortCriterion.State)
                        }).Text : sortCriterion.Description
                    });
                }
            }

            viewModel.SortCriteria = sortCriterionEntries;

            #endregion

            #region Load Layouts
            var layoutEntries = new List <LayoutEntry>();
            var allLayouts    = _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).ToList();

            foreach (var layout in query.Layouts)
            {
                var category = layout.Category;
                var type     = layout.Type;

                var f = allLayouts.FirstOrDefault(x => category == x.Category && type == x.Type);
                if (f != null)
                {
                    layoutEntries.Add(
                        new LayoutEntry {
                        Category       = f.Category,
                        Type           = f.Type,
                        LayoutRecordId = layout.Id,
                        DisplayText    = String.IsNullOrWhiteSpace(layout.Description) ? f.Display(new LayoutContext {
                            State = FormParametersHelper.ToDynamic(layout.State)
                        }).Text : layout.Description
                    });
                }
            }

            viewModel.Layouts = layoutEntries;

            #endregion

            return(View(viewModel));
        }
Пример #19
0
        public IEnumerable <ContentItem> GetContentItems(int queryId, ContentPart part, int skip = 0, int count = 0)
        {
            var availableSortCriteria = DescribeSortCriteria().ToList();

            var queryRecord = _queryRepository.Get(queryId);

            if (queryRecord == null)
            {
                throw new ArgumentException("queryId");
            }

            var contentItems = new List <ContentItem>();

            // prepares tokens
            Dictionary <string, object> tokens = new Dictionary <string, object>();

            if (part != null)
            {
                tokens.Add("Content", part.ContentItem);
            }

            // aggregate the result for each group query
            foreach (var contentQuery in GetContentQueries(queryRecord, queryRecord.SortCriteria.OrderBy(sc => sc.Position), tokens))
            {
                contentItems.AddRange(contentQuery.Slice(skip, count));
            }

            if (queryRecord.FilterGroups.Count <= 1)
            {
                return(contentItems);
            }

            // re-executing the sorting with the cumulated groups
            var ids = contentItems.Select(c => c.Id).ToArray();

            if (ids.Length == 0)
            {
                return(Enumerable.Empty <ContentItem>());
            }

            var groupQuery = _contentManager.HqlQuery().Where(alias => alias.Named("ci"), x => x.InG("Id", ids));

            // iterate over each sort criteria to apply the alterations to the query object
            foreach (var sortCriterion in queryRecord.SortCriteria.OrderBy(s => s.Position))
            {
                var sortCriterionContext = new SortCriterionContext {
                    Query = groupQuery,
                    State = FormParametersHelper.ToDynamic(sortCriterion.State)
                };

                string category = sortCriterion.Category;
                string type     = sortCriterion.Type;

                // look for the specific filter component
                var descriptor = availableSortCriteria.SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == category && x.Type == type);

                // ignore unfound descriptors
                if (descriptor == null)
                {
                    continue;
                }

                // apply alteration
                descriptor.Sort(sortCriterionContext);

                groupQuery = sortCriterionContext.Query;
            }

            return(groupQuery.Slice(skip, count));
        }
        protected override DriverResult Display(ProjectionPart part, string displayType, dynamic shapeHelper)
        {
            var query = part.Record.QueryPartRecord;

            // retrieving paging parameters
            var queryString = Services.WorkContext.HttpContext.Request.QueryString;

            var pageKey = String.IsNullOrWhiteSpace(part.Record.PagerSuffix) ? "page" : "page-" + part.Record.PagerSuffix;
            var page    = 0;

            if (queryString.AllKeys.Contains(pageKey))
            {
                Int32.TryParse(queryString[pageKey], out page);
            }

            // default page size
            int pageSize = part.Record.Items;

            // if 0, then assume "All"
            if (pageSize == 0)
            {
                pageSize = Int32.MaxValue;
            }

            // if pageSize is provided on the query string, ensure it is compatible with allowed limits
            var pageSizeKey = "pageSize" + part.Record.PagerSuffix;

            if (queryString.AllKeys.Contains(pageSizeKey))
            {
                int qsPageSize;

                if (Int32.TryParse(queryString[pageSizeKey], out qsPageSize))
                {
                    if (part.Record.MaxItems == 0 || qsPageSize <= part.Record.MaxItems)
                    {
                        pageSize = qsPageSize;
                    }
                }
            }

            var pager = new Pager(Services.WorkContext.CurrentSite, page, pageSize);

            var pagerShape = shapeHelper.Pager(pager)
                             .ContentPart(part)
                             .PagerId(pageKey);

            return(Combined(
                       ContentShape("Parts_ProjectionPart_Pager", shape => {
                if (!part.Record.DisplayPager)
                {
                    return null;
                }

                return pagerShape;
            }),
                       ContentShape("Parts_ProjectionPart_List", shape => {
                // generates a link to the RSS feed for this term
                var metaData = Services.ContentManager.GetItemMetadata(part.ContentItem);
                _feedManager.Register(metaData.DisplayText, "rss", new RouteValueDictionary {
                    { "projection", part.Id }
                });

                // execute the query
                var contentItems = _projectionManager.GetContentItems(query.Id, pager.GetStartIndex() + part.Record.Skip, pager.PageSize).ToList();

                // sanity check so that content items with ProjectionPart can't be added here, or it will result in an infinite loop
                contentItems = contentItems.Where(x => !x.Has <ProjectionPart>()).ToList();

                // applying layout
                var layout = part.Record.LayoutRecord;

                LayoutDescriptor layoutDescriptor = layout == null ? null : _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == layout.Category && x.Type == layout.Type);

                // create pager shape
                if (part.Record.DisplayPager)
                {
                    var contentItemsCount = _projectionManager.GetCount(query.Id);
                    pagerShape.TotalItemCount(contentItemsCount);
                }

                // renders in a standard List shape if no specific layout could be found
                if (layoutDescriptor == null)
                {
                    var list = Services.New.List();
                    var contentShapes = contentItems.Select(item => Services.ContentManager.BuildDisplay(item, "Summary"));
                    list.AddRange(contentShapes);

                    return list;
                }

                var tokens = new Dictionary <string, object> {
                    { "Content", part.ContentItem }
                };
                var allFielDescriptors = _projectionManager.DescribeProperties().ToList();
                var fieldDescriptors = layout.Properties.OrderBy(p => p.Position).Select(p => allFielDescriptors.SelectMany(x => x.Descriptors).Select(d => new { Descriptor = d, Property = p }).FirstOrDefault(x => x.Descriptor.Category == p.Category && x.Descriptor.Type == p.Type)).ToList();
                var tokenizedDescriptors = fieldDescriptors.Select(fd => new { fd.Descriptor, fd.Property, State = FormParametersHelper.ToDynamic(_tokenizer.Replace(fd.Property.State, tokens)) }).ToList();

                var layoutComponents = contentItems.Select(
                    contentItem => {
                    var contentItemMetadata = Services.ContentManager.GetItemMetadata(contentItem);

                    var propertyDescriptors = tokenizedDescriptors.Select(
                        d => {
                        var fieldContext = new PropertyContext {
                            State = d.State,
                            Tokens = tokens
                        };

                        return new { d.Property, Shape = d.Descriptor.Property(fieldContext, contentItem) };
                    });

                    // apply all settings to the field content, wrapping it in a FieldWrapper shape
                    var properties = Services.New.Properties(
                        Items: propertyDescriptors.Select(
                            pd => Services.New.PropertyWrapper(
                                Item: pd.Shape,
                                Property: pd.Property,
                                ContentItem: contentItem,
                                ContentItemMetadata: contentItemMetadata
                                )
                            )
                        );

                    return new LayoutComponentResult {
                        ContentItem = contentItem,
                        ContentItemMetadata = contentItemMetadata,
                        Properties = properties
                    };
                }).ToList();

                var tokenizedState = _tokenizer.Replace(layout.State, new Dictionary <string, object> {
                    { "Content", part.ContentItem }
                });

                var renderLayoutContext = new LayoutContext {
                    State = FormParametersHelper.ToDynamic(tokenizedState),
                    LayoutRecord = layout,
                };

                if (layout.GroupProperty != null)
                {
                    var groupPropertyId = layout.GroupProperty.Id;
                    var display = _displayHelperFactory.CreateHelper(new ViewContext {
                        HttpContext = _workContextAccessor.GetContext().HttpContext
                    }, new ViewDataContainer());

                    // index by PropertyWrapper shape
                    var groups = layoutComponents.GroupBy(
                        x => {
                        var propertyShape = ((IEnumerable <dynamic>)x.Properties.Items).First(p => ((PropertyRecord)p.Property).Id == groupPropertyId);

                        // clear the wrappers, as they shouldn't be needed to generate the grouping key itself
                        // otherwise the DisplayContext.View is null, and throws an exception if a wrapper is rendered (#18558)
                        ((IShape)propertyShape).Metadata.Wrappers.Clear();

                        string key = Convert.ToString(display(propertyShape));
                        return key;
                    }).Select(x => new { Key = x.Key, Components = x });

                    var list = Services.New.List();
                    foreach (var group in groups)
                    {
                        var localResult = layoutDescriptor.Render(renderLayoutContext, group.Components);
                        // add the Context to the shape
                        localResult.Context(renderLayoutContext);

                        list.Add(Services.New.LayoutGroup(Key: new MvcHtmlString(group.Key), List: localResult));
                    }

                    return list;
                }


                var layoutResult = layoutDescriptor.Render(renderLayoutContext, layoutComponents);

                // add the Context to the shape
                layoutResult.Context(renderLayoutContext);

                return layoutResult;
            })));
        }
        public string GetImageProfileUrl(string path, string profileName, ContentItem contentItem, params FilterRecord[] customFilters)
        {
            // path is the publicUrl of the media, so it might contain url-encoded chars

            // try to load the processed filename from cache
            var  filePath = _fileNameProvider.GetFileName(profileName, System.Web.HttpUtility.UrlDecode(path));
            bool process  = false;

            //after reboot the app cache is empty so we reload the image in the cache if it exists in the _Profiles folder
            if (string.IsNullOrEmpty(filePath))
            {
                var profileFilePath = _storageProvider.Combine("_Profiles", FormatProfilePath(profileName, System.Web.HttpUtility.UrlDecode(path)));

                if (_storageProvider.FileExists(profileFilePath))
                {
                    _fileNameProvider.UpdateFileName(profileName, System.Web.HttpUtility.UrlDecode(path), profileFilePath);
                    filePath = profileFilePath;
                }
            }

            // if the filename is not cached, process it
            if (string.IsNullOrEmpty(filePath))
            {
                Logger.Debug("FilePath is null, processing required, profile {0} for image {1}", profileName, path);

                process = true;
            }

            // the processd file doesn't exist anymore, process it
            else if (!_storageProvider.FileExists(filePath))
            {
                Logger.Debug("Processed file no longer exists, processing required, profile {0} for image {1}", profileName, path);

                process = true;
            }

            // if the original file is more recent, process it
            else
            {
                DateTime pathLastUpdated;
                if (TryGetImageLastUpdated(path, out pathLastUpdated))
                {
                    var filePathLastUpdated = _storageProvider.GetFile(filePath).GetLastUpdated();

                    if (pathLastUpdated > filePathLastUpdated)
                    {
                        Logger.Debug("Original file more recent, processing required, profile {0} for image {1}", profileName, path);

                        process = true;
                    }
                }
            }

            // todo: regenerate the file if the profile is newer, by deleting the associated filename cache entries.
            if (process)
            {
                Logger.Debug("Processing profile {0} for image {1}", profileName, path);

                ImageProfilePart profilePart;

                if (customFilters == null || !customFilters.Any(c => c != null))
                {
                    profilePart = _profileService.GetImageProfileByName(profileName);
                    if (profilePart == null)
                    {
                        return(String.Empty);
                    }
                }
                else
                {
                    profilePart      = _services.ContentManager.New <ImageProfilePart>("ImageProfile");
                    profilePart.Name = profileName;
                    foreach (var customFilter in customFilters)
                    {
                        profilePart.Filters.Add(customFilter);
                    }
                }

                // prevent two requests from processing the same file at the same time
                // this is only thread safe at the machine level, so there is a try/catch later
                // to handle cross machines concurrency
                lock (String.Intern(path)) {
                    using (var image = GetImage(path)) {
                        if (image == null)
                        {
                            return(null);
                        }

                        var filterContext = new FilterContext {
                            Media = image, FilePath = _storageProvider.Combine("_Profiles", FormatProfilePath(profileName, System.Web.HttpUtility.UrlDecode(path)))
                        };

                        var tokens = new Dictionary <string, object>();
                        // if a content item is provided, use it while tokenizing
                        if (contentItem != null)
                        {
                            tokens.Add("Content", contentItem);
                        }

                        foreach (var filter in profilePart.Filters.OrderBy(f => f.Position))
                        {
                            var descriptor = _processingManager.DescribeFilters().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == filter.Category && x.Type == filter.Type);
                            if (descriptor == null)
                            {
                                continue;
                            }

                            var tokenized = _tokenizer.Replace(filter.State, tokens);
                            filterContext.State = FormParametersHelper.ToDynamic(tokenized);
                            descriptor.Filter(filterContext);
                        }

                        _fileNameProvider.UpdateFileName(profileName, System.Web.HttpUtility.UrlDecode(path), filterContext.FilePath);

                        if (!filterContext.Saved)
                        {
                            try {
                                var newFile = _storageProvider.OpenOrCreate(filterContext.FilePath);
                                using (var imageStream = newFile.OpenWrite()) {
                                    using (var sw = new BinaryWriter(imageStream)) {
                                        if (filterContext.Media.CanSeek)
                                        {
                                            filterContext.Media.Seek(0, SeekOrigin.Begin);
                                        }
                                        using (var sr = new BinaryReader(filterContext.Media)) {
                                            int count;
                                            var buffer = new byte[8192];
                                            while ((count = sr.Read(buffer, 0, buffer.Length)) != 0)
                                            {
                                                sw.Write(buffer, 0, count);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e) {
                                Logger.Error(e, "A profile could not be processed: " + path);
                            }
                        }

                        filterContext.Media.Dispose();
                        filePath = filterContext.FilePath;
                    }
                }
            }

            // generate a timestamped url to force client caches to update if the file has changed
            var publicUrl = _storageProvider.GetPublicUrl(filePath);
            var timestamp = _storageProvider.GetFile(filePath).GetLastUpdated().Ticks;

            return(publicUrl + "?v=" + timestamp.ToString(CultureInfo.InvariantCulture));
        }
Пример #22
0
        protected override void OnDisplaying(Projection element, ElementDisplayingContext context)
        {
            var queryId  = element.QueryId;
            var layoutId = element.LayoutId;
            var query    = queryId != null?_contentManager.Get <QueryPart>(queryId.Value) : default(QueryPart);

            var emptyContentItemsList = Enumerable.Empty <ContentManagement.ContentItem>();

            context.ElementShape.ContentItems = emptyContentItemsList;
            context.ElementShape.BuildShapes  = (Func <string, IEnumerable <dynamic> >)(displayType => emptyContentItemsList.Select(x => _contentManager.BuildDisplay(x, displayType)));

            if (query == null || layoutId == null)
            {
                return;
            }

            // Retrieving paging parameters.
            var queryString = _services.WorkContext.HttpContext.Request.QueryString;
            var pageKey     = String.IsNullOrWhiteSpace(element.PagerSuffix) ? "page" : "page-" + element.PagerSuffix;
            var page        = 0;

            // Default page size.
            var pageSize = element.ItemsToDisplay;

            // Don't try to page if not necessary.
            if (element.DisplayPager && queryString.AllKeys.Contains(pageKey))
            {
                Int32.TryParse(queryString[pageKey], out page);
            }

            // If 0, then assume "All", limit to 128 by default.
            if (pageSize == 128)
            {
                pageSize = Int32.MaxValue;
            }

            // If pageSize is provided on the query string, ensure it is compatible within allowed limits.
            var pageSizeKey = "pageSize" + element.PagerSuffix;

            if (queryString.AllKeys.Contains(pageSizeKey))
            {
                int qsPageSize;

                if (Int32.TryParse(queryString[pageSizeKey], out qsPageSize))
                {
                    if (element.MaxItems == 0 || qsPageSize <= element.MaxItems)
                    {
                        pageSize = qsPageSize;
                    }
                }
            }

            var pager = new Pager(_services.WorkContext.CurrentSite, page, pageSize);

            // TODO: Investigate this further and see if it makes sense to implement for a Projection Element.
            //// Generates a link to the RSS feed for this term.
            //var metaData = _services.ContentManager.GetItemMetadata(part.ContentItem);
            //_feedManager.Register(metaData.DisplayText, "rss", new RouteValueDictionary { { "projection", part.Id } });

            // Execute the query.
            var contentItems = _projectionManager.GetContentItems(query.Id, pager.GetStartIndex() + element.Skip, pager.PageSize).ToList();

            context.ElementShape.ContentItems = contentItems;
            context.ElementShape.BuildShapes  = (Func <string, IEnumerable <dynamic> >)(displayType => contentItems.Select(x => _contentManager.BuildDisplay(x, displayType)));

            // TODO: Figure out if we need this for a Projection Element, and if so, how.
            //// Sanity check so that content items with ProjectionPart can't be added here, or it will result in an infinite loop.
            //contentItems = contentItems.Where(x => !x.Has<ProjectionPart>()).ToList();

            // Applying layout.
            var layout = layoutId != null?_layoutRepository.Get(layoutId.Value) : default(LayoutRecord);

            var layoutDescriptor = layout == null ? null : _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == layout.Category && x.Type == layout.Type);

            // Create pager shape.
            if (element.DisplayPager)
            {
                var contentItemsCount = Math.Max(0, _projectionManager.GetCount(query.Id) - element.Skip);
                var pagerShape        = _services.New.Pager(pager)
                                        .Element(element)
                                        .PagerId(pageKey)
                                        .TotalItemCount(contentItemsCount);

                context.ElementShape.Pager = pagerShape;
            }

            // Renders in a standard List shape if no specific layout could be found.
            if (layoutDescriptor == null)
            {
                var contentShapes = contentItems.Select(item => _contentManager.BuildDisplay(item, "Summary"));

                var list = context.ElementShape.List = _services.New.List();
                list.AddRange(contentShapes);

                return;
            }

            var allFielDescriptors = _projectionManager.DescribeProperties().ToList();
            var fieldDescriptors   = layout.Properties.OrderBy(p => p.Position).Select(p => allFielDescriptors.SelectMany(x => x.Descriptors).Select(d => new { Descriptor = d, Property = p }).FirstOrDefault(x => x.Descriptor.Category == p.Category && x.Descriptor.Type == p.Type)).ToList();

            var layoutComponents = contentItems.Select(contentItem => {
                var contentItemMetadata = _contentManager.GetItemMetadata(contentItem);
                var propertyDescriptors = fieldDescriptors.Select(d => {
                    var fieldContext = new PropertyContext {
                        State  = FormParametersHelper.ToDynamic(d.Property.State),
                        Tokens = new Dictionary <string, object> {
                            { "Content", contentItem }
                        }
                    };

                    return(new { d.Property, Shape = d.Descriptor.Property(fieldContext, contentItem) });
                });

                // Apply all settings to the field content, wrapping it in a FieldWrapper shape.
                var properties = _services.New.Properties(
                    Items: propertyDescriptors.Select(
                        pd => _services.New.PropertyWrapper(
                            Item: pd.Shape,
                            Property: pd.Property,
                            ContentItem: contentItem,
                            ContentItemMetadata: contentItemMetadata
                            )
                        )
                    );

                return(new LayoutComponentResult {
                    ContentItem = contentItem,
                    ContentItemMetadata = contentItemMetadata,
                    Properties = properties
                });
            }).ToList();

            var tokenizedState = _tokenizer.Replace(layout.State, new Dictionary <string, object> {
                { "Content", context.Content.ContentItem }
            });

            var renderLayoutContext = new LayoutContext {
                State        = FormParametersHelper.ToDynamic(tokenizedState),
                LayoutRecord = layout,
            };

            if (layout.GroupProperty != null)
            {
                var groupPropertyId = layout.GroupProperty.Id;
                var display         = _displayHelperFactory.CreateHelper(new ViewContext {
                    HttpContext = _services.WorkContext.HttpContext
                }, new ViewDataContainer());

                // Index by PropertyWrapper shape.
                var groups = layoutComponents.GroupBy(x => {
                    var propertyShape = ((IEnumerable <dynamic>)x.Properties.Items).First(p => ((PropertyRecord)p.Property).Id == groupPropertyId);

                    // clear the wrappers, as they shouldn't be needed to generate the grouping key itself
                    // otherwise the DisplayContext.View is null, and throws an exception if a wrapper is rendered (#18558)
                    ((IShape)propertyShape).Metadata.Wrappers.Clear();

                    string key = Convert.ToString(display(propertyShape));
                    return(key);
                }).Select(x => new { Key = x.Key, Components = x });

                var list = context.ElementShape.List = _services.New.List();
                foreach (var group in groups)
                {
                    var localResult = layoutDescriptor.Render(renderLayoutContext, group.Components);

                    // Add the Context to the shape.
                    localResult.Context(renderLayoutContext);
                    list.Add(_services.New.LayoutGroup(Key: new MvcHtmlString(group.Key), List: localResult));
                }
                return;
            }

            var layoutResult = layoutDescriptor.Render(renderLayoutContext, layoutComponents);

            // Add the Context to the shape.
            layoutResult.Context(renderLayoutContext);

            // Set the List shape to be the layout result.
            context.ElementShape.List = layoutResult;
        }
        public void ApplyFilter(FilterContext context)
        {
            var queryId = (string)context.State.QueryId;
            int id      = 0;

            if (!string.IsNullOrWhiteSpace(queryId) &&
                int.TryParse(queryId, out id))
            {
                var queryPart = _contentManager.Get <QueryPart>(id);
                if (queryPart != null && allFilterProviders.Any())
                {
                    var recursionGuardString = (string)context.State.OtherQueriesFilterRecursionGuard ?? "";
                    var recursionGuard       = recursionGuardString
                                               .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                               .Select(int.Parse)
                                               .ToList();
                    // prevent processing an "inner" query if it's the same as the "outer" query
                    recursionGuard.Add(context.QueryPartRecord.Id);
                    if (!recursionGuard.Contains(queryPart.Id))
                    {
                        // we haven't processed this filter before in this query
                        // prevent processing the same filter recursively several times
                        recursionGuard.Add(queryPart.Id);
                        recursionGuardString = string.Join(",", recursionGuard.Select(i => i.ToString()));
                        var queryRecord = queryPart.Record;
                        // pretend we are a ProjectionManager
                        var tokens = context.Tokens;
                        foreach (var group in queryRecord.FilterGroups)
                        {
                            var contentQuery = context.Query;
                            foreach (var filter in group.Filters)
                            {
                                var tokenizedState = _tokenizer.Replace(filter.State, tokens);
                                var dynState       = FormParametersHelper.ToDynamic(tokenizedState);
                                dynState.OtherQueriesFilterRecursionGuard = recursionGuardString;
                                var innerContext = new FilterContext {
                                    Query           = contentQuery,
                                    State           = dynState,
                                    QueryPartRecord = queryRecord,
                                    Tokens          = tokens
                                };

                                string category = filter.Category;
                                string type     = filter.Type;

                                var descriptor = AllDescriptors()
                                                 .FirstOrDefault(d => d.Category == category && d.Type == type);
                                if (descriptor == null)
                                {
                                    continue;
                                }
                                // Apply filters
                                descriptor.Filter(innerContext);
                                contentQuery = innerContext.Query;
                            }
                            context.Query = contentQuery;
                        }
                    }
                    else
                    {
                        Logger.Warning(T("Prevent recursive execution of filter with Id {0}.", queryPart.Id).Text);
                    }
                }
            }
        }
Пример #24
0
        public ActionResult Edit(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageQueries, T("Not authorized to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var layoutRecord = _repository.Get(id);

            if (layoutRecord == null)
            {
                return(HttpNotFound());
            }

            var layoutDescriptor = _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == layoutRecord.Category && x.Type == layoutRecord.Type);

            // Build the form, and let external components alter it.
            var form = _formManager.Build(layoutDescriptor.Form) ?? Services.New.EmptyForm();

            var viewModel = new LayoutEditViewModel {
                Id              = id,
                QueryId         = layoutRecord.QueryPartRecord.Id,
                Category        = layoutDescriptor.Category,
                Type            = layoutDescriptor.Type,
                Description     = layoutRecord.Description,
                Display         = layoutRecord.Display,
                DisplayType     = String.IsNullOrWhiteSpace(layoutRecord.DisplayType) ? "Summary" : layoutRecord.DisplayType,
                Layout          = layoutDescriptor,
                Form            = form,
                GroupPropertyId = layoutRecord.GroupProperty == null ? 0 : layoutRecord.GroupProperty.Id
            };

            // Bind form with existing values.
            var parameters = FormParametersHelper.FromString(layoutRecord.State);

            _formManager.Bind(form, new DictionaryValueProvider <string>(parameters, CultureInfo.InvariantCulture));

            #region Load Fields

            var fieldEntries = new List <PropertyEntry>();
            var allFields    = _projectionManager.DescribeProperties().SelectMany(x => x.Descriptors);

            foreach (var field in layoutRecord.Properties)
            {
                var fieldCategory = field.Category;
                var fieldType     = field.Type;

                var f = allFields.FirstOrDefault(x => fieldCategory == x.Category && fieldType == x.Type);
                if (f != null)
                {
                    fieldEntries.Add(
                        new PropertyEntry {
                        Category         = f.Category,
                        Type             = f.Type,
                        PropertyRecordId = field.Id,
                        DisplayText      = String.IsNullOrWhiteSpace(field.Description) ? f.Display(new PropertyContext {
                            State = FormParametersHelper.ToDynamic(field.State)
                        }).Text : field.Description,
                        Position = field.Position
                    });
                }
            }

            viewModel.Properties = fieldEntries.OrderBy(f => f.Position);

            #endregion

            return(View(viewModel));
        }
Пример #25
0
        public IEnumerable <IHqlQuery> GetContentQueries(QueryPartRecord queryRecord, IEnumerable <SortCriterionRecord> sortCriteria, Dictionary <string, object> tokens)
        {
            var availableFilters      = DescribeFilters().ToList();
            var availableSortCriteria = DescribeSortCriteria().ToList();

            if (tokens == null)
            {
                tokens = new Dictionary <string, object>();
            }

            // pre-executing all groups
            foreach (var group in queryRecord.FilterGroups)
            {
                var contentQuery = _contentManager.HqlQuery().ForVersion(VersionOptions.Published);

                // iterate over each filter to apply the alterations to the query object
                foreach (var filter in group.Filters)
                {
                    var tokenizedState = _tokenizer.Replace(filter.State, tokens);
                    var filterContext  = new FilterContext {
                        Query = contentQuery,
                        State = FormParametersHelper.ToDynamic(tokenizedState)
                    };

                    string category = filter.Category;
                    string type     = filter.Type;

                    // look for the specific filter component
                    var descriptor = availableFilters
                                     .SelectMany(x => x.Descriptors)
                                     .FirstOrDefault(x => x.Category == category && x.Type == type);

                    // ignore unfound descriptors
                    if (descriptor == null)
                    {
                        continue;
                    }

                    // apply alteration
                    descriptor.Filter(filterContext);

                    contentQuery = filterContext.Query;
                }

                // iterate over each sort criteria to apply the alterations to the query object
                foreach (var sortCriterion in sortCriteria.OrderBy(s => s.Position))
                {
                    var sortCriterionContext = new SortCriterionContext {
                        Query = contentQuery,
                        State = FormParametersHelper.ToDynamic(sortCriterion.State)
                    };

                    string category = sortCriterion.Category;
                    string type     = sortCriterion.Type;

                    // look for the specific filter component
                    var descriptor = availableSortCriteria
                                     .SelectMany(x => x.Descriptors)
                                     .FirstOrDefault(x => x.Category == category && x.Type == type);

                    // ignore unfound descriptors
                    if (descriptor == null)
                    {
                        continue;
                    }

                    // apply alteration
                    descriptor.Sort(sortCriterionContext);

                    contentQuery = sortCriterionContext.Query;
                }


                yield return(contentQuery);
            }
        }
Пример #26
0
        private IList <FilterRecord> CreateFilters(string entityName, ListQueryModel model, out string filterDescription)
        {
            IList <FilterRecord> filterRecords;

            filterDescription = string.Empty;
            if (model.FilterGroupId == 0)
            {
                var filterDescriptors = _projectionManager.DescribeFilters()
                                        .Where(x => x.Category == entityName + "ContentFields")
                                        .SelectMany(x => x.Descriptors).ToList();
                filterRecords = new List <FilterRecord>();
                if (model.IsRelationList)
                {
                    if (model.RelationType == "OneToMany")
                    {
                        var settings = new Dictionary <string, string> {
                            { "Operator", "MatchesAny" },
                            { "Value", model.CurrentItem.ToString("D") }
                        };
                        var relationFilter = new FilterRecord {
                            Category    = entityName + "ContentFields",
                            Type        = entityName + "." + model.RelationId + ".",
                            State       = FormParametersHelper.ToString(settings),
                            Description = "Only show entries related to current item."
                        };
                        filterRecords.Add(relationFilter);
                        var descriptor = filterDescriptors.First(x => x.Type == relationFilter.Type);
                        filterDescription += descriptor.Display(new FilterContext {
                            State = FormParametersHelper.ToDynamic(relationFilter.State)
                        }).Text;
                    }
                }

                foreach (var filter in model.Filters)
                {
                    if (filter.FormData.Length == 0)
                    {
                        continue;
                    }
                    var record = new FilterRecord {
                        Category = entityName + "ContentFields",
                        Type     = filter.Type,
                    };
                    var dictionary = new Dictionary <string, string>();
                    foreach (var data in filter.FormData)
                    {
                        if (dictionary.ContainsKey(data.Name))
                        {
                            dictionary[data.Name] += "&" + data.Value;
                        }
                        else
                        {
                            dictionary.Add(data.Name, data.Value);
                        }
                    }
                    record.State = FormParametersHelper.ToString(dictionary);
                    filterRecords.Add(record);
                    var descriptor = filterDescriptors.First(x => x.Type == filter.Type);
                    filterDescription += descriptor.Display(new FilterContext {
                        State = FormParametersHelper.ToDynamic(record.State)
                    }).Text;
                }
            }
            else
            {
                filterRecords = _filterGroupRepository.Get(model.FilterGroupId).Filters;
            }
            return(filterRecords);
        }
Пример #27
0
        private IEnumerable <JObject> GetLayoutComponents(ProjectionPart part, int skipCount, int pageCount)
        {
            // query
            var query = part.Record.QueryPartRecord;

            // applying layout
            var layout = part.Record.LayoutRecord;
            var tokens = new Dictionary <string, object> {
                { "Content", part.ContentItem }
            };
            var allFielDescriptors = _projectionManager.DescribeProperties().ToList();
            var fieldDescriptors   = layout.Properties.OrderBy(p => p.Position).Select(p => allFielDescriptors.SelectMany(x => x.Descriptors).Select(d => new { Descriptor = d, Property = p }).FirstOrDefault(x => x.Descriptor.Category == p.Category && x.Descriptor.Type == p.Type)).ToList();

            fieldDescriptors = fieldDescriptors.Where(c => c != null).ToList();
            var tokenizedDescriptors = fieldDescriptors.Select(fd => new { fd.Descriptor, fd.Property, State = FormParametersHelper.ToDynamic(_tokenizer.Replace(fd.Property.State, tokens)) }).ToList();

            // execute the query
            var contentItems = _projectionManager.GetContentItems(query.Id, skipCount, pageCount).ToList();

            // sanity check so that content items with ProjectionPart can't be added here, or it will result in an infinite loop
            contentItems = contentItems.Where(x => !x.Has <ProjectionPart>()).ToList();

            var layoutComponents = contentItems.Select(
                contentItem => {
                var result          = new JObject();
                result["ContentId"] = contentItem.Id;
                tokenizedDescriptors.ForEach(
                    d => {
                    var fieldContext = new PropertyContext {
                        State  = d.State,
                        Tokens = tokens
                    };
                    var shape         = d.Descriptor.Property(fieldContext, contentItem);
                    string text       = (shape == null) ? string.Empty : shape.ToString();
                    var filedName     = d.Property.GetFiledName();
                    result[filedName] = text;
                });
                return(result);
            }).ToList();

            return(layoutComponents);
        }
Пример #28
0
        public ActionResult Edit(int id, string category, string type, int propertyId = -1)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var property = _projectionManager.DescribeProperties().SelectMany(x => x.Descriptors).Where(x => x.Category == category && x.Type == type).FirstOrDefault();

            if (property == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new PropertyEditViewModel {
                Id          = id,
                Description = String.Empty,
                Property    = property
            };

            dynamic form = null;

            // build the form, and let external components alter it
            if (property.Form != null)
            {
                form           = _formManager.Build(property.Form);
                viewModel.Form = form;
            }

            // bind form with existing values.
            if (propertyId != -1)
            {
                var propertyRecord = _repository.Get(propertyId);
                if (propertyRecord != null)
                {
                    viewModel.Description = propertyRecord.Description;
                    if (property.Form != null)
                    {
                        var parameters = FormParametersHelper.FromString(propertyRecord.State);
                        _formManager.Bind(form, new DictionaryValueProvider <string>(parameters, CultureInfo.InvariantCulture));
                    }

                    viewModel.CreateLabel        = propertyRecord.CreateLabel;
                    viewModel.ExcludeFromDisplay = propertyRecord.ExcludeFromDisplay;
                    viewModel.Label         = propertyRecord.Label;
                    viewModel.LinkToContent = propertyRecord.LinkToContent;

                    viewModel.CustomizeLabelHtml    = propertyRecord.CustomizeLabelHtml;
                    viewModel.CustomizePropertyHtml = propertyRecord.CustomizePropertyHtml;
                    viewModel.CustomizeWrapperHtml  = propertyRecord.CustomizeWrapperHtml;
                    viewModel.CustomLabelCss        = propertyRecord.CustomLabelCss;
                    viewModel.CustomLabelTag        = propertyRecord.CustomLabelTag;
                    viewModel.CustomPropertyCss     = propertyRecord.CustomPropertyCss;
                    viewModel.CustomPropertyTag     = propertyRecord.CustomPropertyTag;
                    viewModel.CustomWrapperCss      = propertyRecord.CustomWrapperCss;
                    viewModel.CustomWrapperTag      = propertyRecord.CustomWrapperTag;

                    viewModel.NoResultText = propertyRecord.NoResultText;
                    viewModel.ZeroIsEmpty  = propertyRecord.ZeroIsEmpty;
                    viewModel.HideEmpty    = propertyRecord.HideEmpty;

                    viewModel.RewriteOutput      = propertyRecord.RewriteOutput;
                    viewModel.RewriteText        = propertyRecord.RewriteText;
                    viewModel.StripHtmlTags      = propertyRecord.StripHtmlTags;
                    viewModel.TrimLength         = propertyRecord.TrimLength;
                    viewModel.AddEllipsis        = propertyRecord.AddEllipsis;
                    viewModel.MaxLength          = propertyRecord.MaxLength;
                    viewModel.TrimOnWordBoundary = propertyRecord.TrimOnWordBoundary;
                    viewModel.PreserveLines      = propertyRecord.PreserveLines;
                    viewModel.TrimWhiteSpace     = propertyRecord.TrimWhiteSpace;
                }
            }

            return(View(viewModel));
        }
Пример #29
0
        public ActionResult EditPost(LayoutEditViewModel model, FormCollection formCollection)
        {
            // Validating form values.
            var layout = _projectionManager.DescribeLayouts().SelectMany(x => x.Descriptors).FirstOrDefault(x => x.Category == model.Category && x.Type == model.Type);

            _formManager.Validate(new ValidatingContext {
                FormName = layout.Form, ModelState = ModelState, ValueProvider = ValueProvider
            });

            var form = _formManager.Build(layout.Form) ?? Services.New.EmptyForm();

            _formManager.Bind(form, formCollection);

            model.Layout = layout;
            model.Form   = form;
            var layoutRecord = _repository.Get(model.Id);

            if (ModelState.IsValid)
            {
                var dictionary = formCollection.AllKeys.ToDictionary(key => key, formCollection.Get);

                // Save form parameters.
                layoutRecord.State         = FormParametersHelper.ToString(dictionary);
                layoutRecord.Description   = model.Description;
                layoutRecord.Display       = model.Display;
                layoutRecord.DisplayType   = model.DisplayType;
                layoutRecord.GroupProperty = layoutRecord.Properties.FirstOrDefault(x => x.Id == model.GroupPropertyId);

                Services.Notifier.Success(T("Layout Saved"));

                return(RedirectToAction("Edit", new { id = layoutRecord.Id }));
            }

            #region Load Fields

            var fieldEntries = new List <PropertyEntry>();
            var allFields    = _projectionManager.DescribeProperties().SelectMany(x => x.Descriptors);

            foreach (var field in layoutRecord.Properties)
            {
                var fieldCategory = field.Category;
                var fieldType     = field.Type;

                var f = allFields.FirstOrDefault(x => fieldCategory == x.Category && fieldType == x.Type);
                if (f != null)
                {
                    fieldEntries.Add(
                        new PropertyEntry {
                        Category         = f.Category,
                        Type             = f.Type,
                        PropertyRecordId = field.Id,
                        DisplayText      = String.IsNullOrWhiteSpace(field.Description) ? f.Display(new PropertyContext {
                            State = FormParametersHelper.ToDynamic(field.State)
                        }).Text : field.Description,
                        Position = field.Position
                    });
                }
            }

            model.Properties = fieldEntries.OrderBy(f => f.Position);
            #endregion

            return(View(model));
        }
Пример #30
0
 private void SerializeState()
 {
     Record.State = FormParametersHelper.ToJsonString(State);
 }