protected override DriverResult Display(WidgetsContainerPart part, string displayType, dynamic shapeHelper) {
            // TODO: make DisplayType configurable
            if (displayType != "Detail")
                return null;

            var settings = part.Settings.GetModel<WidgetsContainerSettings>();

            var widgetParts = _widgetManager.GetWidgets(part.Id, part.ContentItem.IsPublished());

            if (!settings.UseHierarchicalAssociation) {
                if (!string.IsNullOrWhiteSpace(settings.AllowedWidgets))
                    widgetParts = widgetParts.Where(x => settings.AllowedWidgets.Split(',').Contains(x.TypeDefinition.Name));
                if (!string.IsNullOrWhiteSpace(settings.AllowedZones))
                    widgetParts = widgetParts.Where(x => settings.AllowedZones.Split(',').Contains(x.Zone));
            } else if (settings.HierarchicalAssociation != null && settings.HierarchicalAssociation.Count() > 0) {
                widgetParts = widgetParts.Where(wp => settings.HierarchicalAssociation.Any(z => z.ZoneName.Equals(wp.Zone) && z.Widgets.Any(w => w.WidgetType == wp.TypeDefinition.Name || w.WidgetType == "All")));
            }
            // Build and add shape to zone.
            var workContext = _wca.GetContext();
            var zones = workContext.Layout.Zones;
            foreach (var widgetPart in widgetParts) {
                var widgetShape = _contentManager.BuildDisplay(widgetPart);
                zones[widgetPart.Zone].Add(widgetShape, widgetPart.Position);
            }

            return null;
        }
Exemplo n.º 2
0
        public ActionResult AddWidget(int hostId, string widgetType, string zone, string returnUrl)
        {
            if (!IsAuthorizedToManageWidgets())
            {
                return(new HttpUnauthorizedResult());
            }

            var widgetPart = _services.ContentManager.New <WidgetPart>(widgetType);

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

            try {
                var widgetPosition = _widgetManager.GetWidgets(hostId).Count(widget => widget.Zone == widgetPart.Zone) + 1;
                widgetPart.Position        = widgetPosition.ToString(CultureInfo.InvariantCulture);
                widgetPart.Zone            = zone;
                widgetPart.AvailableLayers = _widgetsService.GetLayers().ToList();
                widgetPart.LayerPart       = _widgetManager.GetContentLayer();

                var model = _services.ContentManager.BuildEditor(widgetPart).HostId(hostId);
                return(View(model));
            }
            catch (Exception exception) {
                Logger.Error(T("Creating widget failed: {0}", exception.Message).Text);
                _services.Notifier.Error(T("Creating widget failed: {0}", exception.Message));
                return(this.RedirectLocal(returnUrl, () => RedirectToAction("Edit", "Admin", new { area = "Contents" })));
            }
        }
        public WidgetsContainerPartHandler(
            IContentManager contentManager,
            IWidgetManager widgetManager,
            ILocalizationService localizationService,
            ShellSettings shellSettings,
            ITaxonomyService taxonomyService)
        {
            _contentManager      = contentManager;
            _widgetManager       = widgetManager;
            _localizationService = localizationService;
            _shellSettings       = shellSettings;
            _taxonomyService     = taxonomyService;
            if (!string.IsNullOrEmpty(_shellSettings.RequestUrlPrefix))
            {
                _urlPrefix = new UrlPrefix(_shellSettings.RequestUrlPrefix);
            }
            T = NullLocalizer.Instance;

            OnRemoved <WidgetsContainerPart>((context, part) => {
                DeleteWidgets(part);
            });
            OnUpdateEditorShape <WidgetsContainerPart>((context, part) => {
                var lPart = part.ContentItem.As <LocalizationPart>();
                if (lPart != null)
                {
                    var settings = part.Settings.GetModel <WidgetsContainerSettings>();
                    if (settings.TryToLocalizeItems)
                    {
                        var culture = lPart.Culture;
                        var widgets = _widgetManager.GetWidgets(part.ContentItem.Id, part.ContentItem.IsPublished())
                                      .Where(p => p.ContentItem.Has <LocalizationPart>() &&
                                             p.ContentItem.Get <LocalizationPart>().Culture == null);
                        foreach (var widget in widgets)
                        {
                            var ci = widget.ContentItem;
                            _localizationService.SetContentCulture(ci, culture.Culture);
                            // manage taxonomy field out of the normal flow:
                            // gets translations of selected terms in taxonomy fields before BuildEditor()
                            var translatedTaxo = TranslateTaxonomies(ci, culture, _localizationService);

                            // simulates a user that opens in edit model the widget and saves it
                            // to trigger all handlers and drivers
                            var shapeWidget = _contentManager.BuildEditor(ci);
                            var shapeUpdate = _contentManager.UpdateEditor(ci, new CustomUpdater(shapeWidget, culture.Culture, Logger));

                            // sets translated terms in taxonomy fields after UpdateEditor()
                            ApplyTranslatedTaxonomies(ci, translatedTaxo, _taxonomyService);

                            ci.VersionRecord.Published = false;
                            _contentManager.Publish(ci);
                        }
                    }
                }
            });
        }
        private void DeleteWidgets(WidgetsContainerPart part)
        {
            var contentItem = part.ContentItem;

            var widgets = _widgetManager.GetWidgets(contentItem.Id, false);

            foreach (var w in widgets)
            {
                _contentManager.Remove(w.ContentItem);
            }
        }
        protected override DriverResult Display(WidgetsContainerPart part, string displayType, dynamic shapeHelper)
        {
            // TODO: make DisplayType configurable
            if (displayType != "Detail")
            {
                return(null);
            }

            var widgetParts = _widgetManager.GetWidgets(part.Id);

            // Build and add shape to zone.
            var workContext = _wca.GetContext();
            var zones       = workContext.Layout.Zones;

            foreach (var widgetPart in widgetParts)
            {
                var widgetShape = _contentManager.BuildDisplay(widgetPart);
                zones[widgetPart.Zone].Add(widgetShape, widgetPart.Position);
            }

            return(null);
        }
        public void DumpList(DumperServiceContext context)
        {
            var part = context.Content
                       .ContentItem
                       .Parts
                       .FirstOrDefault(pa => pa.PartDefinition.Name == "WidgetsContainerPart");

            if (part != null)
            {
                var mainSb = new StringBuilder();
                mainSb.Append("{");
                mainSb.AppendFormat("\"n\": \"{0}\"", "WidgetList");
                mainSb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                mainSb.Append(", \"m\": [");

                var queryItems = _widgetManager.GetWidgets(part.Id);
                if (queryItems.Any())
                {
                    mainSb.Append(
                        string.Join(",", queryItems
                                    .Select((wep, index) => {
                        var sb = new StringBuilder();
                        sb.Append("{");
                        var dump = context.GetDumper()
                                   .Dump(wep, string.Format("[{0}]", index));
                        context.ConvertToJson(dump, sb);
                        sb.Append("}");
                        return(sb.ToString());
                    }))
                        );
                }

                mainSb.Append("]");
                mainSb.Append("}");

                // Add the serialization to the results
                context.ContentLists.Add(mainSb.ToString());
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Reset the culture of all widgets in the cloned content if this is a translation
        /// </summary>
        /// <param name="context"></param>
        /// <param name="part"></param>
        private void ResetWidgetsLocalization(CloneContentContext context, WidgetsContainerPart part)
        {
            var baseLocPart = part.ContentItem.As <LocalizationPart>();

            if (baseLocPart != null)
            {
                var    routeData = _wca.GetContext().HttpContext.Request.RequestContext.RouteData.Values;
                object action, area;
                if (routeData.TryGetValue("action", out action) &&
                    routeData.TryGetValue("area", out area) &&
                    action.ToString().ToUpperInvariant() == "TRANSLATE" &&
                    area.ToString().ToUpperInvariant() == "ORCHARD.LOCALIZATION")
                {
                    var widgetsLocParts = _widgetManager
                                          .GetWidgets(context.CloneContentItem.Id, context.CloneContentItem.IsPublished())
                                          .Select(wi => wi.ContentItem.As <LocalizationPart>())
                                          .Where(pa => pa != null);
                    foreach (var wLocPart in widgetsLocParts)
                    {
                        wLocPart.Culture = null;
                    }
                }
            }
        }
        private ActionResult GetContent(IContent content, SourceTypes sourceType = SourceTypes.ContentItem, ResultTarget resultTarget = ResultTarget.Contents, string fieldspartsFilter = "", int page = 1, int pageSize = 10, bool tinyResponse = true, bool minified = false, bool realformat = false, int deeplevel = 10, string[] complexBehaviour = null)
        {
            var result = new ContentResult {
                ContentType = "application/json"
            };
            var jsonString = "{}";

            var      _filterContentFieldsParts = fieldspartsFilter.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            XElement dump;
            XElement projectionDump = null;
            // il dump dell'oggetto principale non filtra per field
            ObjectDumper    dumper = new ObjectDumper(deeplevel, null, false, tinyResponse, complexBehaviour);
            dynamic         shape; //, specificShape;
            var             sb          = new StringBuilder();
            List <XElement> listContent = new List <XElement>();

            // verifico se l'oggetto è soggetto all'accettazione delle policies
            var policy = content.As <Policy.Models.PolicyPart>();

            //if (policy != null) {
            //    if ((String.IsNullOrWhiteSpace(_orchardServices.WorkContext.HttpContext.Request.QueryString["v"]))) {// E' soggetto a privacy, quindi faccio sempre il redirect se manca il parametro in querystring v=
            //        if (policy.HasPendingPolicies ?? false) { // se ha delle pending policies deve restituire le policy text, legate al contenuto, qui ndi non deve mai servire cache
            //            var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), Guid.NewGuid());
            //            _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //        } else {// se NON ha delle pending policies deve restituire un url non cacheato (quindi aggiungo v=),
            //            var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), "cached-content");
            //            _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //            //_orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //        }
            //        return null; // in entrambi i casi ritorno null come risultato della current request
            //    }
            //}
            if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo serivre la lista delle pending policies
            //policy.PendingPolicies
            {
                sb.Insert(0, "{");
                sb.AppendFormat("\"n\": \"{0}\"", "Model");
                sb.AppendFormat(", \"v\": \"{0}\"", "VirtualContent");
                sb.Append(", \"m\": [{");
                sb.AppendFormat("\"n\": \"{0}\"", "VirtualId"); // Unused property for mobile mapper needs
                sb.AppendFormat(", \"v\": \"{0}\"", "0");
                sb.Append("}]");

                sb.Append(", \"l\":[");

                int i = 0;
                sb.Append("{");
                sb.AppendFormat("\"n\": \"{0}\"", "PendingPolicies");
                sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                sb.Append(", \"m\": [");

                foreach (var item in _policyServices.PendingPolicies(content.ContentItem))
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append("{");
                    dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                    projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                    JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                    sb.Append("}");
                    i++;
                }
                sb.Append("]");
                sb.Append("}");

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            else     // Se l'oggetto NON ha delle pending policies allora posso servire l'oggetto stesso
            {
                shape = _orchardServices.ContentManager.BuildDisplay(content);
                if (sourceType == SourceTypes.ContentItem)
                {
                    dump = dumper.Dump(content, "Model");
                }
                else
                {
                    dump = dumper.Dump(shape, "Model");
                }
                //dump.XPathSelectElements("");
                //var filteredDump = dump.Descendants();
                //ConvertToJSon(dump, sb);
                JsonConverter.ConvertToJSon(dump, sb, minified, realformat);
                sb.Insert(0, "{");
                sb.Append(", \"l\":[");
                // Dopo avere convertito il contentItem in JSON aggiungo i Json delle eventuali liste
                dynamic part                 = null;
                var     firstList            = true;
                var     listDumpedContentIds = new List <int>();

                #region [ProjectionPart ]

                try {
                    part = shape.ContentItem.ProjectionPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    var queryId    = part.Record.QueryPartRecord.Id;
                    var queryItems = _projectionManager.GetContentItems(queryId, (page - 1) * pageSize, pageSize);
                    int i          = 0;
                    sb.Append("{");
                    sb.AppendFormat("\"n\": \"{0}\"", "ProjectionList");
                    sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                    sb.Append(", \"m\": [");

                    foreach (var item in queryItems)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append("{");
                        dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                        projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                        JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        sb.Append("}");
                        i++;
                    }
                    sb.Append("]");
                    sb.Append("}");
                }
                part = null;

                #endregion [ProjectionPart ]

                #region [CalendarPart ]

                try {
                    part = shape.ContentItem.CalendarPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    if (_orchardServices.WorkContext.TryResolve <IEventsService>(out _eventsService))  // non sempre questo modulo è attivo quindi se non riesce a risolvere il servizio, bypassa la chiamata
                    {
                        var queryItems = _eventsService.GetAggregatedList(part, page, pageSize);
                        int i          = 0;
                        sb.Append("{");
                        sb.AppendFormat("\"n\": \"{0}\"", "EventList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                        sb.Append(", \"m\": [");

                        foreach (var item in queryItems)
                        {
                            if (i > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append("{");
                            dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                            projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb);
                            sb.Append("}");
                            i++;
                        }
                        sb.Append("]");
                        sb.Append("}");
                    }
                }
                part = null;

                #endregion [CalendarPart ]

                #region [ExernalField]

                var ExtertalFields = (dynamic)
                                     (from parte in ((ContentItem)shape.ContentItem).Parts
                                      from field in parte.Fields
                                      where (field.GetType().Name == "FieldExternal" && ((dynamic)field).Setting.GenerateL)
                                      select field).FirstOrDefault();
                if (ExtertalFields != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    //sb.Append("{");
                    //sb.AppendFormat("\"n\": \"{0}\"", "ExternalContent");
                    //sb.AppendFormat(", \"v\": \"{0}\"", "ExternalContent");
                    //sb.Append(", \"m\": [");

                    sb.Append("{");
                    dumper = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                    //nameDynamicJsonArray = "List<generic>";
                    if (ExtertalFields.ContentObject != null)
                    {
                        if (ExtertalFields.ContentObject.GetType() == typeof(ExternalFieldRemoteException))
                        {
                            throw new ExternalFieldRemoteException();
                        }
                        projectionDump = dumper.Dump(cleanobj(ExtertalFields.ContentObject), ExtertalFields.Name, "List<generic>");
                        JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                    }
                    //    sb.Append("}]}");
                    sb.Append("}");
                }

                #endregion [ExernalField]

                #region [ WidgetsContainerPart ]

                try {
                    part = shape.ContentItem.WidgetsContainerPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    //var queryId = part.Record.QueryPartRecord.Id;
                    if (_orchardServices.WorkContext.TryResolve <IWidgetManager>(out _widgetManager))  // non semepre questo modulo è attivo quindi se non riesce a risolvere il servizio, bypassa la chiamata
                    {
                        if (!firstList)
                        {
                            sb.Append(",");
                        }
                        firstList = false;
                        var queryItems = _widgetManager.GetWidgets(part.Id);
                        int i          = 0;
                        sb.Append("{");
                        sb.AppendFormat("\"n\": \"{0}\"", "WidgetList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                        sb.Append(", \"m\": [");

                        foreach (var item in queryItems)
                        {
                            if (i > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append("{");
                            dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                            projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                            sb.Append("}");
                            i++;
                        }
                        sb.Append("]");
                        sb.Append("}");
                    }
                }

                #endregion [ WidgetsContainerPart ]

                #region [ Taxonomy/TermsPart ]

                part = null;
                try {
                    if (shape.ContentItem.ContentType.EndsWith("Term") || !String.IsNullOrWhiteSpace(shape.ContentItem.TypeDefinition.Settings["Taxonomy"]))
                    {
                        part = shape.ContentItem.TermPart;
                    }
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    dynamic termContentItems;
                    if (resultTarget == ResultTarget.Terms)
                    {
                        termContentItems = _taxonomyService.GetChildren(part, true);
                    }
                    else if (resultTarget == ResultTarget.SubTerms)
                    {
                        termContentItems = _taxonomyService.GetChildren(part, false);
                    }
                    else
                    {
                        termContentItems = _taxonomyService.GetContentItems(part, (page - 1) * pageSize, pageSize);
                    }

                    int i = 0;
                    sb.Append("{");
                    if (resultTarget == ResultTarget.Contents)
                    {
                        sb.AppendFormat("\"n\": \"{0}\"", "TaxonomyTermList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                    }
                    else
                    {
                        sb.AppendFormat("\"n\": \"{0}\"", "TermPartList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "TermPart[]");
                    }
                    sb.Append(", \"m\": [");

                    foreach (var item in termContentItems)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append("{");
                        dumper = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                        if (resultTarget == ResultTarget.Contents)
                        {
                            projectionDump = dumper.Dump(item.ContentItem, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        }
                        else
                        {
                            var dumperForPart = new ObjectDumper(deeplevel, _filterContentFieldsParts, true, tinyResponse, complexBehaviour);
                            projectionDump = dumperForPart.Dump(item, "TermPart");
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        }
                        sb.Append("}");
                        i++;
                    }
                    sb.Append("]");
                    sb.Append("}");
                }
                part = null;

                #endregion [ Taxonomy/TermsPart ]

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            jsonString     = sb.ToString().Replace("\t", " ");
            result.Content = jsonString;
            return(result);
        }