Esempio n. 1
0
        public void Execute(FeedContext context)
        {
            var projectionId = context.ValueProvider.GetValue("projection");

            if (projectionId == null)
            {
                return;
            }

            var limitValue = context.ValueProvider.GetValue("limit");
            var limit      = 20;

            if (limitValue != null)
            {
                limit = (int)limitValue.ConvertTo(typeof(int));
            }

            var containerId = (int)projectionId.ConvertTo(typeof(int));
            var container   = _contentManager.Get <ProjectionPart>(containerId);

            if (container == null)
            {
                return;
            }

            var inspector = new ItemInspector(container, _contentManager.GetItemMetadata(container), _htmlFilters);

            if (context.Format == "rss")
            {
                var link = new XElement("link");
                context.Response.Element.SetElementValue("title", inspector.Title);
                context.Response.Element.Add(link);
                context.Response.Element.SetElementValue("description", inspector.Description);

                context.Response.Contextualize(requestContext => {
                    var urlHelper  = new UrlHelper(requestContext);
                    var uriBuilder = new UriBuilder(urlHelper.RequestContext.HttpContext.Request.ToRootUrlString())
                    {
                        Path = urlHelper.RouteUrl(inspector.Link)
                    };
                    link.Add(uriBuilder.Uri.OriginalString);
                });
            }
            else
            {
                context.Builder.AddProperty(context, null, "title", inspector.Title);
                context.Builder.AddProperty(context, null, "description", inspector.Description);
                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    context.Builder.AddProperty(context, null, "link", urlHelper.RouteUrl(inspector.Link));
                });
            }

            var items = _projectionManager.GetContentItems(container.Record.QueryPartRecord.Id, 0, limit).ToList();

            foreach (var item in items)
            {
                context.Builder.AddItem(context, item);
            }
        }
Esempio n. 2
0
        public ActionResult QueryResults(int queryId, int skip = 0, int count = 12)
        {
            if (!_services.Authorizer.Authorize(Orchard.Projections.Permissions.ManageQueries, T("Not allowed to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var query = _contentManager.Get(queryId).As <QueryPart>();

            if (query == null)
            {
                return(HttpNotFound(T("Query not found.").Text));
            }
            var contentItems  = _projectionManager.GetContentItems(queryId, skip, count);
            var totalCount    = _projectionManager.GetCount(queryId);
            var contentShapes = contentItems.Select(item =>
                                                    _contentManager.BuildDisplay(item, "SummaryAdmin"));

            var list = Shape.List();

            list.AddRange(contentShapes);
            list.Attributes.Add("data-total-count", totalCount.ToString(CultureInfo.InvariantCulture));

            return(new ShapePartialResult(this, list));
        }
Esempio n. 3
0
        private IEnumerable <SelectListItem> GetOptions(Query element, string displayType, int?queryId, IDictionary <string, object> tokenData)
        {
            var optionLabel   = element.OptionLabel;
            var runtimeValues = GetRuntimeValues(element);

            if (!String.IsNullOrWhiteSpace(optionLabel))
            {
                yield return(new SelectListItem {
                    Text = displayType != "Design" ? _tokenizer.Replace(optionLabel, tokenData) : optionLabel
                });
            }

            if (queryId == null)
            {
                yield break;
            }

            var contentItems    = _projectionManager.GetContentItems(queryId.Value).ToArray();
            var valueExpression = !String.IsNullOrWhiteSpace(element.ValueExpression) ? element.ValueExpression : "{Content.Id}";
            var textExpression  = !String.IsNullOrWhiteSpace(element.TextExpression) ? element.TextExpression : "{Content.DisplayText}";

            foreach (var contentItem in contentItems)
            {
                var data  = new { Content = contentItem };
                var value = _tokenizer.Replace(valueExpression, data);
                var text  = _tokenizer.Replace(textExpression, data);

                yield return(new SelectListItem {
                    Text = text,
                    Value = value,
                    Selected = runtimeValues.Contains(value, StringComparer.OrdinalIgnoreCase)
                });
            }
        }
Esempio n. 4
0
        public IEnumerable <JObject> Get(string id, string fieldName)
        {
            var partDefinition = _contentDefinitionManager.GetPartDefinition(id);

            if (partDefinition == null)
            {
                return(null);
            }
            var fieldDefinition = partDefinition.Fields.FirstOrDefault(x => x.Name == fieldName);

            if (fieldDefinition == null)
            {
                return(null);
            }
            var queryId      = int.Parse(fieldDefinition.Settings["ReferenceFieldSettings.QueryId"]);
            var items        = new List <JObject>();
            var contentItems = _projectionManager.GetContentItems(queryId);

            foreach (var contentItem in contentItems)
            {
                var item = new JObject();
                item["DisplayText"] = _contentManager.GetItemMetadata(contentItem).DisplayText;
                item["Id"]          = contentItem.Id;
                items.Add(item);
            }
            return(items);
        }
        protected override DriverResult Display(HighlightsGroupPart part, string displayType, dynamic shapeHelper)
        {
            ViewsInfos viewsInfos = _HighlightsService.ChooseView(part);
            var        group      = new HighlightsGroupViewModel {
                Id              = part.Id,
                DisplayPlugin   = part.DisplayPlugin,
                DisplayTemplate = part.DisplayTemplate,
                ItemsSourceType = part.ItemsSourceType,
            };

            IEnumerable <dynamic> items          = null;
            IList <dynamic>       fromQueryItems = new List <dynamic>();

            if (part.ItemsSourceType == Enums.ItemsSourceTypes.ByHand)
            {
                items = _HighlightsService.GetHighlightsItemsContentByGroupId(part.Id, part.DisplayTemplate, part.DisplayPlugin, viewsInfos.SuffixShapeName.Replace("_", ""));
            }
            else if (part.ItemsSourceType == Enums.ItemsSourceTypes.FromQuery)
            {
                var queryItems = _projectionManager.GetContentItems(part.Query_Id, 0, 10);
                fromQueryItems = _HighlightsService.MapContentToHighlightsItemsViewModel(queryItems, part.DisplayTemplate, part.DisplayPlugin, viewsInfos);
            }
            var dict = new Dictionary <string, object> {
                { "HighlightsGroup", group },
                { "HighlightsItems", part.ItemsSourceType == Enums.ItemsSourceTypes.FromQuery?fromQueryItems:items }
            };
            var args = Arguments.From(dict.Values, dict.Keys);

            return(ContentShape(viewsInfos.ResultShapeName,
                                () => _shapeFactory.Create(viewsInfos.ResultShapeName, args)));
            //return null;
        }
Esempio n. 6
0
        private IEnumerable <SelectListItem> GetOptions(Query element, int?queryId)
        {
            var optionLabel = element.OptionLabel;

            if (!String.IsNullOrWhiteSpace(optionLabel))
            {
                yield return(new SelectListItem {
                    Text = optionLabel
                });
            }

            if (queryId == null)
            {
                yield break;
            }


            var contentItems    = _projectionManager.GetContentItems(queryId.Value).ToArray();
            var valueExpression = !String.IsNullOrWhiteSpace(element.ValueExpression) ? element.ValueExpression : "{Content.Id}";
            var textExpression  = !String.IsNullOrWhiteSpace(element.TextExpression) ? element.TextExpression : "{Content.DisplayText}";

            foreach (var contentItem in contentItems)
            {
                var data  = new { Content = contentItem };
                var value = _tokenizer.Replace(valueExpression, data);
                var text  = _tokenizer.Replace(textExpression, data);

                yield return(new SelectListItem {
                    Text = text,
                    Value = value
                });
            }
        }
Esempio n. 7
0
        public List <QueryPart> GetCalendarQueries()
        {
            IEnumerable <QueryPart> queryParts = _orchardServices.ContentManager.Query <QueryPart, QueryPartRecord>("Query").List();

            List <QueryPart> calendarQueries = new List <QueryPart>();

            foreach (QueryPart part in queryParts)
            {
                ContentItem contentItem = _projectionManager.GetContentItems(part.Id).FirstOrDefault();

                int countTitleParts    = contentItem.TypeDefinition.Parts.Where(r => r.PartDefinition.Name == "TitlePart").Count();
                int countTimeSpanParts = contentItem.TypeDefinition.Parts.Where(r => r.PartDefinition.Name == "TimeSpanPart").Count();

                if ((countTitleParts > 0) && (countTimeSpanParts > 0))
                {
                    calendarQueries.Add(part);
                }
            }

            return(calendarQueries);
        }
        public JObject GetJson(IContent content, int page = 1, int pageSize = 10, string filter = "")
        {
            JObject json;

            // BuildDisplay populates the TagCache properly with the Id of the content
            // It impacts performances but we have to choose if to call the BuildDisplay or to manually populate the Tag cache with the content Id
            _orchardServices.ContentManager.BuildDisplay(content);
            var filteredContent = content;

            _filter = filter.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.EndsWith(".") ? x : x + ".").ToArray();

            json = new JObject(SerializeObject(filteredContent, 0, 0));
            dynamic part;

            #region [Projections]
            // Projection
            try {
                part = ((dynamic)filteredContent).ProjectionPart;
            }
            catch {
                part = null;
            }
            if (part != null)
            {
                var queryId     = part.Record.QueryPartRecord.Id;
                var queryItems  = _projectionManager.GetContentItems(queryId, (page - 1) * pageSize, pageSize);
                var resultArray = new JArray();
                foreach (var resulted in queryItems)
                {
                    // BuildDisplay populates the TagCache properly with the Id of the content
                    // It impacts performances but we have to choose if to call the BuildDisplay or to manually populate the Tag cache with the content Id
                    _orchardServices.ContentManager.BuildDisplay((ContentItem)resulted);
                    resultArray.Add(new JObject(SerializeObject((ContentItem)resulted, 1, part.Id)));
                }
                if ((json.Root.HasValues) && (json.Root.First.HasValues) && (json.Root.First.First.HasValues))
                {
                    JProperty array = new JProperty("ProjectionPageResults", resultArray);
                    json.Root.First.First.Last.AddAfterSelf(array);
                }
                else
                {
                    json.Add("ProjectionPageResults", resultArray);
                }
            }
            #endregion

            //NormalizeSingleProperty(json);

            return(json);
        }
Esempio n. 9
0
        public ActionResult Preview(int id)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageQueries, T("Not authorized to manage queries")))
            {
                return(new HttpUnauthorizedResult());
            }

            var contentItems  = _projectionManager.GetContentItems(id, 0, 20);
            var contentShapes = contentItems.Select(item => _services.ContentManager.BuildDisplay(item, "Summary"));

            var list = Shape.List();

            list.AddRange(contentShapes);

            return(View((object)list));
        }
Esempio n. 10
0
        public IEnumerable <FormattedEvent> GetFormattedCalendarEvents(CalendarPart part)
        {
            var contentItems = _projectionManager.GetContentItems(part.QueryId);

            var provider = _calendarProviders.SingleOrDefault(p => p.Name == part.Plugin);

            if (provider == null)
            {
                // fallback to default
                provider = _calendarProviders.Single(p => p.Name == "Default");
            }

            var models = provider.FormatCalendarEvents(contentItems);

            return(models);
        }
Esempio n. 11
0
        public ActionResult Preview(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(TestPermission))
            {
                return(new HttpUnauthorizedResult());
            }

            var contentItems  = _projectionManager.GetContentItems(id, 0, 20);
            var contentShapes = contentItems.Select(item => _orchardServices.ContentManager.BuildDisplay(item, "Summary"));

            var list = Shape.List();

            list.AddRange(contentShapes);

            return(View(list));
        }
        public IEnumerable <MenuItem> Filter(IEnumerable <MenuItem> items)
        {
            foreach (var item in items)
            {
                if (item.Content != null && item.Content.ContentItem.ContentType == "NavigationQueryMenuItem")
                {
                    // expand query
                    var navigationQuery = item.Content.As <NavigationQueryPart>();
                    var contentItems    = _projectionManager.GetContentItems(navigationQuery.QueryPartRecord.Id, navigationQuery.Skip, navigationQuery.Items).ToList();

                    var menuPosition = item.Position;
                    int index        = 0;
                    foreach (var contentItem in contentItems)
                    {
                        if (contentItem != null)
                        {
                            var part = contentItem;

                            var menuText = _contentManager.GetItemMetadata(part).DisplayText;
                            var routes   = _contentManager.GetItemMetadata(part).DisplayRouteValues;

                            var inserted = new MenuItem {
                                Text             = new LocalizedString(menuText),
                                IdHint           = item.IdHint,
                                Classes          = item.Classes,
                                Url              = item.Url,
                                Href             = item.Href,
                                LinkToFirstChild = false,
                                RouteValues      = routes,
                                LocalNav         = item.LocalNav,
                                Items            = new MenuItem[0],
                                Position         = menuPosition + ":" + index++,
                                Permissions      = item.Permissions,
                                Content          = part
                            };

                            yield return(inserted);
                        }
                    }
                }
                else
                {
                    yield return(item);
                }
            }
        }
Esempio n. 13
0
        public void DumpList(DumperServiceContext context)
        {
            if (_projectionManager != null)
            {
                var part = context.Content
                           .ContentItem
                           .As <ProjectionPart>();

                if (part != null)
                {
                    var mainSb = new StringBuilder();

                    mainSb.Append("{");
                    mainSb.AppendFormat("\"n\": \"{0}\"", "ProjectionList");
                    mainSb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                    mainSb.Append(", \"m\": [");

                    var queryId    = part.Record.QueryPartRecord.Id;
                    var queryItems = _projectionManager
                                     .GetContentItems(queryId, (context.Page - 1) * context.PageSize, context.PageSize);

                    if (queryItems.Any())
                    {
                        mainSb.Append(
                            string.Join(",", queryItems
                                        .Select((ci, index) => {
                            var sb = new StringBuilder();
                            sb.Append("{");
                            var dump = context.GetDumper()
                                       .Dump(ci, 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());
                }
            }
        }
Esempio n. 14
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);
        }
Esempio n. 15
0
        protected override DriverResult Editor(ContentPart part, ReferenceField field, dynamic shapeHelper)
        {
            var settings = field.PartFieldDefinition.Settings.GetModel <ReferenceFieldSettings>();

            var contentItems = _projectionManager.GetContentItems(settings.QueryId)
                               .Select(c => new SelectListItem {
                Text     = Services.ContentManager.GetItemMetadata(c).DisplayText,
                Value    = c.Id.ToString(CultureInfo.InvariantCulture),
                Selected = field.Value == c.Id
            }).ToList();

            var model = new ReferenceFieldViewModel {
                ContentId = field.Value,
                Field     = field,
                ItemList  = new SelectList(contentItems, "Value", "Text", field.Value)
            };

            return(ContentShape("Fields_Reference_Edit", GetDifferentiator(field, part),
                                () => shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: model, Prefix: GetPrefix(field, part))));
        }
        public JObject GetJson(IContent content, int page = 1, int pageSize = 10)
        {
            JObject json;
            dynamic shape           = _orchardServices.ContentManager.BuildDisplay(content); // Forse non serve nemmeno
            var     filteredContent = shape.ContentItem;

            json = new JObject(SerializeObject(filteredContent, 0));
            dynamic part;

            #region [Projections]
            // Projection
            try {
                part = ((dynamic)filteredContent).ProjectionPart;
            } catch {
                part = null;
            }
            if (part != null)
            {
                var queryId     = part.Record.QueryPartRecord.Id;
                var queryItems  = _projectionManager.GetContentItems(queryId, (page - 1) * pageSize, pageSize);
                var resultArray = new JArray();
                foreach (var resulted in queryItems)
                {
                    resultArray.Add(new JObject(SerializeContentItem((ContentItem)resulted, 0)));
                }
                if ((json.Root.HasValues) && (json.Root.First.HasValues) && (json.Root.First.First.HasValues))
                {
                    JProperty array = new JProperty("ProjectionPageResults", resultArray);
                    json.Root.First.First.Last.AddAfterSelf(array);
                }
                else
                {
                    json.Add("ProjectionPageResults", resultArray);
                }
            }
            #endregion

            //NormalizeSingleProperty(json);

            return(json);
        }
Esempio n. 17
0
        // TODO: use something else than query because Queries do not take permissions in account
        public List <QueryPart> GetEventDefinitionQueries()
        {
            var queryParts             = _orchardServices.ContentManager.Query <QueryPart, QueryPartRecord>("Query").List();
            var eventDefinitionQueries = new List <QueryPart>();

            foreach (var part in queryParts)
            {
                var contentItem = _projectionManager.GetContentItems(part.Id).FirstOrDefault();
                if (contentItem == null)
                {
                    return(new List <QueryPart>());
                }

                // Check if has Event Definition part
                if (contentItem.TypeDefinition.Parts.Any(p => p.PartDefinition.Name == typeof(SchedulingPart).Name))
                {
                    eventDefinitionQueries.Add(part);
                }
            }

            return(eventDefinitionQueries);
        }
        public ActionResult GetObjectByAlias(string displayAlias, SourceTypes sourceType = SourceTypes.ContentItem, ResultTarget resultTarget = ResultTarget.Contents, string mfilter = "", int page = 1, int pageSize = 1000, bool tinyResponse = true, int deeplevel = 10, decimal version = 0)
        {
            try {
                if (page < 1)
                {
                    page = 1;
                }
                if (pageSize < 1)
                {
                    pageSize = 1000;
                }
                var autoroutePart = _orchardServices.ContentManager.Query <AutoroutePart, AutoroutePartRecord>()
                                    .ForVersion(VersionOptions.Published)
                                    .Where(w => w.DisplayAlias == displayAlias).List().SingleOrDefault();
                IContent item = null;
                if (autoroutePart != null && autoroutePart.ContentItem != null)
                {
                    item = autoroutePart.ContentItem;
                }
                else
                {
                    Response rsp = _utilsServices.GetResponse(ResponseType.None, "Pagina non trovata");

                    XmlSerializer serializer = new XmlSerializer(typeof(Response));
                    XmlDocument   doc        = new XmlDocument();
                    StringWriter  sww        = new StringWriter();
                    XmlWriter     writer     = XmlWriter.Create(sww);
                    serializer.Serialize(writer, rsp);
                    var xml = sww.ToString();
                    return(this.Content(xml, "text/xml"));
                    // return new HttpNotFoundResult();
                }

                List <dynamic> ListShape = new List <dynamic>();
                string         CiType    = "";
                if (item.ContentItem.ContentType == "ProjectionPage")
                {
                    #region Projection

                    var part = ((dynamic)item.ContentItem).ProjectionPart;
                    if (part != null)
                    {
                        var queryId = part.Record.QueryPartRecord.Id;

                        var queryItems = _projectionManager.GetContentItems(queryId, (page - 1) * pageSize, pageSize);

                        //   int i = 0;
                        if (queryItems.Count == 0)
                        {
                            return(null);
                        }
                        foreach (var projitem in queryItems)
                        {
                            // autoroutePart = projitem.AutoroutePart;
                            CiType = projitem.ContentType;
                            List <dynamic> list2 = ItemsMultiLanguage(projitem.AutoroutePart);
                            //  var merged = new List<dynamic>(ListShape);
                            ListShape.AddRange(list2.Where(p2 =>
                                                           ListShape.All(p1 => p1.ContentItem.Id != p2.ContentItem.Id)));
                            // ListShape = merged;
                        }

                        #endregion Projection
                    }
                }
                else
                {
                    //  string tipoCI = item.ContentItem.ContentType;
                    //   string CiType = ((ContentItem)autoroutePart.ContentItem).ContentType;
                    //  int id = ((ContentItem)autoroutePart.ContentItem).Id;

                    ListShape = ItemsMultiLanguage(autoroutePart);
                    CiType    = ((ContentItem)autoroutePart.ContentItem).ContentType;
                }

                //int masterid = 0;
                //int teoric_masterid = 0;
                //try {
                //    teoric_masterid = ((ContentItem)autoroutePart.ContentItem).As<LocalizationPart>().MasterContentItem.Id;
                //    masterid = teoric_masterid;
                //}
                //catch {
                //    masterid = id;
                //}
                //var contentsLocalized = _orchardServices.ContentManager.Query(CiType).Where<LocalizationPartRecord>(l => l.MasterContentItemId == masterid || l.Id == masterid).List();
                //List<dynamic> ListShape = new List<dynamic>();
                //foreach (ContentItem singleCi in contentsLocalized) {
                //    ListShape.Add(_orchardServices.ContentManager.BuildDisplay(singleCi));
                //}

                var namespaces = this.GetType().FullName.Split('.').AsEnumerable();
                namespaces = namespaces.Except(new string[] { this.GetType().Name });
                namespaces = namespaces.Except(new string[] { namespaces.Last() });
                var area = string.Join(".", namespaces);
                if (version > 0)
                {
                    CiType += version.ToString();
                }
                string myview = "~/" + @"App_Data/Sites/" + _shellSetting.Name + "/WebServices/" + CiType + ".cshtml";
                string myfile = HostingEnvironment.MapPath("~/") + @"App_Data\Sites\" + _shellSetting.Name + @"\WebServices\" + CiType + ".cshtml";
                if (System.IO.File.Exists(myfile))
                {
                    return(View(myview, (object)ListShape));
                }
                else
                {
                    Response rsp = _utilsServices.GetResponse(ResponseType.None, "Contenuto non disponibile");
                    //  rsp.Message =;
                    XmlSerializer serializer = new XmlSerializer(typeof(Response));
                    XmlDocument   doc        = new XmlDocument();
                    StringWriter  sww        = new StringWriter();
                    XmlWriter     writer     = XmlWriter.Create(sww);
                    serializer.Serialize(writer, rsp);
                    var xml = sww.ToString();
                    return(this.Content(xml, "text/xml"));
                }
            } catch (Exception ex) {
                Response rsp = _utilsServices.GetResponse(ResponseType.None, ex.Message);
                //   rsp.Message=;
                XmlSerializer serializer = new XmlSerializer(typeof(Response));
                XmlDocument   doc        = new XmlDocument();
                StringWriter  sww        = new StringWriter();
                XmlWriter     writer     = XmlWriter.Create(sww);
                serializer.Serialize(writer, rsp);
                var xml = sww.ToString();
                return(this.Content(xml, "text/xml"));
            }
        }
Esempio n. 19
0
        public List <EventViewModel> GetEvents(int queryId, DateTime intervalStart, DateTime intervalEnd, CalendarPart part = null, bool addDayForThreshold = false)
        {
            List <EventViewModel> list = new List <EventViewModel>();

            //Recupero tutti gli eventi dalla query associata al calendario
            //var eventArray = _projectionManager.GetContentItems(queryId, 0, 0, part == null ? null : new Dictionary<string, object> { { "Content", part } }).ToList();
            var eventArray = _projectionManager.GetContentItems(queryId, 0, 0); //TODO: issue when we want to do tokenized queries from widgets

            //Recupero gli eventi senza ripetizione e li aggiungo al calendario
            var listNoRepeat = new List <EventViewModel>();

            listNoRepeat = eventArray
                           .Where(w => ((dynamic)w).ActivityPart.Repeat == false)
                           .Select(s =>
                                   new EventViewModel {
                content = ((dynamic)s),
                start   = ((dynamic)s).ActivityPart.AllDay ? ((dynamic)s).ActivityPart.DateTimeStart.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : ((dynamic)s).ActivityPart.DateTimeStart.ToString("yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture),
                end     = ((dynamic)s).ActivityPart.AllDay ?
                          (addDayForThreshold ?
                           ((dynamic)s).ActivityPart.DateTimeEnd.AddDays(1).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
                                    : ((dynamic)s).ActivityPart.DateTimeEnd.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
                          )
                                : ((dynamic)s).ActivityPart.DateTimeEnd.ToString("yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture)
            }
                                   )
                           .ToList();
            list.AddRange(listNoRepeat);

            //Recupero gli eventi con ripetizione giornaliera ed elaboro la loro aggiunta al calendario
            var listDayRepeat = new List <ContentItem>();

            listDayRepeat = eventArray
                            .Where(w => ((dynamic)w).ActivityPart.Repeat == true && ((dynamic)w).ActivityPart.RepeatType == "D")
                            .ToList();

            foreach (var item in listDayRepeat)
            {
                bool allday = ((dynamic)item).ActivityPart.AllDay;

                DateTime eventStartDate = ((dynamic)item).ActivityPart.DateTimeStart;
                DateTime eventEndDate   = ((dynamic)item).ActivityPart.DateTimeEnd;

                int eventDuration = (eventEndDate.Date - eventStartDate.Date).Days;

                //Uniformo la rappresentazione delle date, poiché in fullcalendar se allDay vale true il giorno finale è incluso e se vale false invece è escluso
                if (allday && addDayForThreshold)
                {
                    eventDuration += 1;
                }

                DateTime startDate = new DateTime(Math.Max(intervalStart.AddDays(-eventDuration).Ticks, eventStartDate.Ticks));

                DateTime endDate;
                if (((dynamic)item).ActivityPart.RepeatEnd)
                {
                    endDate = new DateTime(Math.Min(intervalEnd.Ticks, (((dynamic)item).ActivityPart.RepeatEndDate).Ticks));
                }
                else
                {
                    endDate = intervalEnd;
                }

                string startTimePart = "";
                string endTimePart   = "";

                if (!allday)
                {
                    startTimePart = "T" + eventStartDate.ToString("HH:mm", CultureInfo.InvariantCulture);

                    if (!eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture).Equals("00:00"))
                    {
                        endTimePart = "T" + eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        endTimePart = "T23:59";
                    }
                }

                DateTime loopDate = startDate;
                while (DateTime.Compare(loopDate.Date, endDate.Date) <= 0)
                {
                    list.Add(new EventViewModel {
                        content = ((dynamic)item),
                        start   = loopDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + startTimePart,
                        end     = loopDate.AddDays(eventDuration).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + endTimePart
                    });

                    loopDate = loopDate.AddDays(((dynamic)item).ActivityPart.RepeatValue);
                }
            }

            //Recupero gli eventi con ripetizione settimanale ed elaboro la loro aggiunta al calendario
            var listWeekRepeat = new List <ContentItem>();

            listWeekRepeat = eventArray
                             .Where(w => ((dynamic)w).ActivityPart.Repeat == true && ((dynamic)w).ActivityPart.RepeatType == "W")
                             .ToList();

            foreach (var item in listWeekRepeat)
            {
                bool allday = ((dynamic)item).ActivityPart.AllDay;

                DateTime eventStartDate = ((dynamic)item).ActivityPart.DateTimeStart;
                DateTime eventEndDate   = ((dynamic)item).ActivityPart.DateTimeEnd;

                int eventDuration = (eventEndDate.Date - eventStartDate.Date).Days;

                //Uniformo la rappresentazione delle date, poiché in fullcalendar se allDay vale true il giorno finale è incluso e se vale false invece è escluso
                if (allday && addDayForThreshold)
                {
                    eventDuration += 1;
                }

                string startTimePart = "";
                string endTimePart   = "";

                if (!allday)
                {
                    startTimePart = "T" + eventStartDate.ToString("HH:mm", CultureInfo.InvariantCulture);

                    if (!eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture).Equals("00:00"))
                    {
                        endTimePart = "T" + eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        endTimePart = "T23:59";
                    }
                }

                string repeatDetails = ((dynamic)item).ActivityPart.RepeatDetails;

                DateTime loopDate = intervalStart.AddDays(-eventDuration);
                while (DateTime.Compare(loopDate.Date, intervalEnd.Date) <= 0)
                {
                    bool repeat = ((dynamic)item).ActivityPart.RepeatEnd ? DateTime.Compare(loopDate.Date, ((dynamic)item).ActivityPart.RepeatEndDate.Date) <= 0 : true;

                    int weeksPassed = (loopDate.Date - eventStartDate.Date).Days / 7;

                    if (repeatDetails.Contains(loopDate.DayOfWeek.ToString()) &&
                        DateTime.Compare(loopDate.Date, eventStartDate.Date) >= 0 &&
                        (weeksPassed % ((dynamic)item).ActivityPart.RepeatValue) == 0 &&
                        repeat)
                    {
                        list.Add(new EventViewModel {
                            content = ((dynamic)item),
                            start   = loopDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + startTimePart,
                            end     = loopDate.AddDays(eventDuration).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + endTimePart
                        });
                    }

                    loopDate = loopDate.AddDays(1);
                }
            }

            //Recupero gli eventi con ripetizione mensile ed elaboro la loro aggiunta al calendario
            var listMonthRepeat = new List <ContentItem>();

            listMonthRepeat = eventArray
                              .Where(w => ((dynamic)w).ActivityPart.Repeat == true && ((dynamic)w).ActivityPart.RepeatType == "M")
                              .ToList();

            foreach (var item in listMonthRepeat)
            {
                bool allday = ((dynamic)item).ActivityPart.AllDay;

                DateTime eventStartDate = ((dynamic)item).ActivityPart.DateTimeStart;
                DateTime eventEndDate   = ((dynamic)item).ActivityPart.DateTimeEnd;

                int eventDuration = (eventEndDate.Date - eventStartDate.Date).Days;

                //Uniformo la rappresentazione delle date, poiché in fullcalendar se allDay vale true il giorno finale è incluso e se vale false invece è escluso
                if (allday && addDayForThreshold)
                {
                    eventDuration += 1;
                }

                string startTimePart = "";
                string endTimePart   = "";

                if (!allday)
                {
                    startTimePart = "T" + eventStartDate.ToString("HH:mm", CultureInfo.InvariantCulture);

                    if (!eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture).Equals("00:00"))
                    {
                        endTimePart = "T" + eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        endTimePart = "T23:59";
                    }
                }

                DateTime loopEnd;
                if (((dynamic)item).ActivityPart.RepeatEnd)
                {
                    loopEnd = new DateTime(Math.Min(intervalEnd.Ticks, (((dynamic)item).ActivityPart.RepeatEndDate).Ticks));
                }
                else
                {
                    loopEnd = intervalEnd;
                }

                DateTime loopDate = eventStartDate;

                //Ripetizione per numero di mese
                if (((dynamic)item).ActivityPart.RepeatDetails.Contains("DayNum"))
                {
                    int monthDifference = 0;
                    while (DateTime.Compare(loopDate.Date, loopEnd.Date) <= 0)
                    {
                        if (DateTime.Compare(loopDate.Date, intervalStart.Date) >= 0 ||
                            (DateTime.Compare(loopDate.Date, intervalStart.Date) < 0 && DateTime.Compare(loopDate.AddDays(eventDuration).Date, intervalStart.Date) >= 0))
                        {
                            list.Add(new EventViewModel {
                                content = ((dynamic)item),
                                start   = loopDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + startTimePart,
                                end     = loopDate.AddDays(eventDuration).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + endTimePart
                            });
                        }

                        //Calcolo la differenza in mesi a partire dalla data iniziale ed effettuo l'aggiunta di mesi a partire da essa
                        //Se non facessi così, ad esempio un loop sul 30 del mese verrebbe spostato al 28/29 dopo Febbraio
                        monthDifference = (loopDate.Year - eventStartDate.Year) * 12 + loopDate.Month - eventStartDate.Month;
                        loopDate        = eventStartDate.AddMonths(monthDifference + ((dynamic)item).ActivityPart.RepeatValue);
                    }
                }
                else if (((dynamic)item).ActivityPart.RepeatDetails.Contains("DayWeek"))
                {
                    int nthInMonth = (int)Math.Ceiling(Decimal.Divide(eventStartDate.Day, 7));

                    while (DateTime.Compare(loopDate.Date, loopEnd.Date) <= 0)
                    {
                        DateTime eventDate;
                        if (DateTime.Compare(loopDate.Date, eventStartDate.Date) == 0)
                        {
                            eventDate = eventStartDate;
                        }
                        else
                        {
                            eventDate = getNthDayOfMonth(eventStartDate.DayOfWeek, nthInMonth, loopDate.Month, loopDate.Year);
                        }

                        if (DateTime.Compare(eventDate.Date, intervalStart.Date) >= 0 ||
                            (DateTime.Compare(eventDate.Date, intervalStart.Date) < 0 && DateTime.Compare(eventDate.AddDays(eventDuration).Date, intervalStart.Date) >= 0))
                        {
                            list.Add(new EventViewModel {
                                content = ((dynamic)item),
                                start   = eventDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + startTimePart,
                                end     = eventDate.AddDays(eventDuration).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + endTimePart
                            });
                        }

                        loopDate = loopDate.AddMonths(((dynamic)item).ActivityPart.RepeatValue);
                    }
                }
            }

            //Recupero gli eventi con ripetizione annuale ed elaboro la loro aggiunta al calendario
            var listYearRepeat = new List <ContentItem>();

            listYearRepeat = eventArray
                             .Where(w => ((dynamic)w).ActivityPart.Repeat == true && ((dynamic)w).ActivityPart.RepeatType == "Y")
                             .ToList();

            foreach (var item in listYearRepeat)
            {
                bool allday = ((dynamic)item).ActivityPart.AllDay;

                DateTime eventStartDate = ((dynamic)item).ActivityPart.DateTimeStart;
                DateTime eventEndDate   = ((dynamic)item).ActivityPart.DateTimeEnd;

                int eventDuration = (eventEndDate.Date - eventStartDate.Date).Days;

                //Uniformo la rappresentazione delle date, poiché in fullcalendar se allDay vale true il giorno finale è incluso e se vale false invece è escluso
                if (allday && addDayForThreshold)
                {
                    eventDuration += 1;
                }

                string endTimePart = "";
                if (!allday)
                {
                    if (!eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture).Equals("00:00"))
                    {
                        endTimePart = "T" + eventEndDate.ToString("HH:mm", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        endTimePart = "T23:59";
                    }
                }

                DateTime loopDate;
                int      loopEnd = ((dynamic)item).ActivityPart.RepeatEnd ? Math.Min(intervalEnd.Year, (((dynamic)item).ActivityPart.RepeatEndDate).Year) : intervalEnd.Year;

                for (int year = eventStartDate.Year; year <= loopEnd; year = year + ((dynamic)item).ActivityPart.RepeatValue)
                {
                    loopDate = new DateTime(year, eventStartDate.Month, eventStartDate.Day, eventStartDate.Hour, eventStartDate.Minute, eventStartDate.Second);

                    bool repeat = ((dynamic)item).ActivityPart.RepeatEnd ? DateTime.Compare(loopDate.Date, ((dynamic)item).ActivityPart.RepeatEndDate.Date) <= 0 : true;

                    if (DateTime.Compare(loopDate.Date, intervalEnd.Date) <= 0 &&
                        (DateTime.Compare(loopDate.Date, intervalStart.Date) >= 0 || (DateTime.Compare(loopDate.Date, intervalStart.Date) < 0 && DateTime.Compare(loopDate.AddDays(eventDuration).Date, intervalStart.Date) >= 0)) &&
                        repeat)
                    {
                        list.Add(new EventViewModel {
                            content = ((dynamic)item),
                            start   = allday ? loopDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : loopDate.ToString("yyyy-MM-ddTHH:mm", CultureInfo.InvariantCulture),
                            end     = loopDate.AddDays(eventDuration).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + endTimePart
                        });
                    }
                }
            }

            return(list);
        }