Exemple #1
0
        /// <summary>
        /// Populates a Content List (of Teasers) by executing the query it specifies.
        /// </summary>
        /// <param name="contentList">The Content List which specifies the query and is to be populated.</param>
        /// <param name="localization">The context Localization.</param>
        public virtual void PopulateDynamicList <T>(ContentList <T> contentList, Localization localization) where T : EntityModel
        {
            using (new Tracer(contentList, localization))
            {
                BrokerQuery query = new BrokerQuery
                {
                    Start         = contentList.Start,
                    PublicationId = Int32.Parse(localization.LocalizationId),
                    PageSize      = contentList.PageSize,
                    SchemaId      = MapSchema(contentList.ContentType.Key, localization),
                    Sort          = contentList.Sort.Key
                };

                // TODO: For now BrokerQuery always returns Teasers
                IEnumerable <Teaser> queryResults = query.ExecuteQuery();

                ILinkResolver linkResolver = SiteConfiguration.LinkResolver;
                foreach (Teaser item in queryResults)
                {
                    item.Link.Url = linkResolver.ResolveLink(item.Link.Url);
                }

                contentList.ItemListElements = queryResults.Cast <T>().ToList();
                contentList.HasMore          = query.HasMore;
            }
        }
Exemple #2
0
        RichViewEntity GenerateEntity(Entity entity)
        {
            RichViewEntity richEntity = new RichViewEntity();

            richEntity.Url  = entity.Url;
            richEntity.Type = entity.Type;

            switch (entity.Type)
            {
            case EntityType.String:
            {
                FillEntityData(richEntity, entity);
                richEntity.Text = entity.Data as string;
            }
            break;

            case EntityType.Image:
            {
                richEntity.Text  = entity.Data as string;
                richEntity.Image = _imageNotLoaded;

                LinkResolvedDelegate onLinkResolved = (string result) =>
                {
                    Uri  uriResult;
                    bool isUrl = Uri.TryCreate(result, UriKind.Absolute, out uriResult) && (uriResult.Scheme == "http" || uriResult.Scheme == "https");

                    if (isUrl)
                    {
                        richEntity.Image = RemoteImageCache.Instance.RegisterClient(uriResult, this);
                    }
                    else
                    {
                        richEntity.Image = ContentLoader.Current.Load <Texture2D>(richEntity.Text);
                        _shouldUpdate    = true;
                    }
                };

                _linkResolver.ResolveLink(richEntity.Text, onLinkResolved);
            }
            break;

            case EntityType.ListNumber:
            {
                richEntity.Type = EntityType.String;
                FillEntityData(richEntity, entity);
                richEntity.Text = string.Format("{0}. ", entity.Data);
            }
            break;

            case EntityType.ListBullet:
            {
                richEntity.Type = EntityType.String;
                FillEntityData(richEntity, entity);
                richEntity.Text = _bulletText;
            }
            break;
            }

            return(richEntity);
        }
Exemple #3
0
        private HttpRequestMessage CreateBatchRequest(
            IEnumerable <IApiRequest> requests,
            IDictionary <string, string> parameters,
            IDictionary <string, IEnumerable <string> > headers)
        {
            var batchRequestContent = new MultipartContent("mixed", $"batch_{Guid.NewGuid()}");

            foreach (var request in requests)
            {
                var contentType  = "application/hal+json";
                var innerRequest = new HttpRequestMessage(request.Method, request.Uri);

                var innerRequestHeaders = request.Headers ?? new Dictionary <string, IEnumerable <string> >();
                foreach (var header in innerRequestHeaders)
                {
                    if (header.Key == "Content-Type")
                    {
                        contentType = header.Value.FirstOrDefault();
                        continue;
                    }

                    innerRequest.Headers.Add(header.Key, header.Value);
                }

                innerRequest.Content = GetRequestContent(request.Method, request.Body, contentType);

                batchRequestContent.Add(new BatchRequestContent(innerRequest));
            }

            var batchLink = new Link
            {
                HRef = new Uri(_configuration.RootEndpoint, $"{_configuration.RootEndpoint}/batch").AbsoluteUri
            };
            var batchEndpointUri = _linkResolver.ResolveLink(batchLink, parameters);
            var batchRequest     = new HttpRequestMessage(HttpMethod.Post, batchEndpointUri)
            {
                Content = batchRequestContent
            };

            headers = headers ?? new Dictionary <string, IEnumerable <string> >();
            foreach (var header in headers)
            {
                if (header.Key == "Content-Type")
                {
                    continue;
                }

                batchRequest.Headers.Add(header.Key, header.Value);
            }

            return(batchRequest);
        }
Exemple #4
0
        public async Task <IApiResponse> PingAsync(int webhookId)
        {
            var pingLink = await _linkFactory.CreateLinkAsync($"webhooks/{webhookId}/ping").ConfigureAwait(_halClient);

            var pingUrl  = _linkResolver.ResolveLink(pingLink, new Dictionary <string, string>());
            var response = await _halClient.HttpConnection.SendRequestAsync <string>(
                pingUrl,
                HttpMethod.Post,
                null,
                new Dictionary <string, IEnumerable <string> >(),
                CancellationToken.None);

            return(response);
        }
Exemple #5
0
        public Uri GetAuthorizationUrl(Uri redirectUri, IEnumerable <string> scopes, string state)
        {
            Requires.ArgumentNotNull(redirectUri, nameof(redirectUri));
            Requires.ArgumentNotNull(scopes, nameof(scopes));

            return(_linkResolver.ResolveLink(
                       new Link {
                HRef = _configuration.ViagogoAuthorizationEndpoint.OriginalString
            },
                       new Dictionary <string, string>()
            {
                ["client_id"] = _configuration.ClientId,
                ["response_type"] = "code",
                ["redirect_uri"] = redirectUri.OriginalString,
                ["scope"] = string.Join(" ", scopes),
                ["state"] = state
            }));
        }
Exemple #6
0
        private async Task <IApiResponse <T> > SendRequestAsync <T>(
            Link link,
            HttpMethod method,
            object body,
            IDictionary <string, string> parameters,
            IDictionary <string, IEnumerable <string> > headers,
            CancellationToken cancellationToken)
        {
            Requires.ArgumentNotNull(link, nameof(link));
            Requires.ArgumentNotNull(method, nameof(method));

            headers = headers ?? new Dictionary <string, IEnumerable <string> >();
            if (!headers.ContainsKey("Accept"))
            {
                headers.Add("Accept", new[] { HalJsonMediaType });
            }

            return(await HttpConnection.SendRequestAsync <T>(
                       _linkResolver.ResolveLink(link, parameters),
                       method,
                       body,
                       headers,
                       cancellationToken).ConfigureAwait(Configuration));
        }
Exemple #7
0
        private RichText ResolveRichText(XmlDocument doc, Localization localization)
        {
            const string xlinkNamespaceUri = "http://www.w3.org/1999/xlink";

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
            nsmgr.AddNamespace("xlink", xlinkNamespaceUri);

            // Process/resolve hyperlinks with XLink attributes
            ILinkResolver linkResolver = SiteConfiguration.LinkResolver;

            foreach (XmlElement linkElement in doc.SelectNodes("//a[@xlink:href]", nsmgr))
            {
                // DD4T BinaryPublisher may have resolved a href attribute already (for links to MM Components)
                string linkUrl = linkElement.GetAttribute("href");
                if (string.IsNullOrEmpty(linkUrl))
                {
                    // No href attribute found. Apparently the XLink refers to a regular Component; we resolve it to a URL here.
                    string tcmUri = linkElement.GetAttribute("href", xlinkNamespaceUri);
                    if (!string.IsNullOrEmpty(tcmUri))
                    {
                        // Try to resolve directly to Binary content of MM Component.
                        linkUrl = linkResolver.ResolveLink(tcmUri, resolveToBinary: true);
                    }
                }
                if (!string.IsNullOrEmpty(linkUrl))
                {
                    // The link was resolved; set HTML href attribute
                    linkElement.SetAttribute("href", linkUrl);
                    ApplyHashIfApplicable(linkElement, localization);

                    // Remove all XLink and data- attributes
                    IEnumerable <XmlAttribute> attributesToRemove = linkElement.Attributes.Cast <XmlAttribute>()
                                                                    .Where(a => a.NamespaceURI == xlinkNamespaceUri || a.LocalName == "xlink" || a.LocalName.StartsWith("data-")).ToArray();
                    foreach (XmlAttribute attr in attributesToRemove)
                    {
                        linkElement.Attributes.Remove(attr);
                    }
                }
                else
                {
                    // The link was not resolved; remove the hyperlink.
                    XmlNode parentNode = linkElement.ParentNode;
                    foreach (XmlNode childNode in linkElement.ChildNodes)
                    {
                        parentNode.InsertBefore(childNode, linkElement);
                    }
                    parentNode.RemoveChild(linkElement);
                }
            }

            // Resolve embedded media items
            List <EntityModel> embeddedEntities = new List <EntityModel>();

            foreach (XmlElement imgElement in doc.SelectNodes("//img[@data-schemaUri]", nsmgr))
            {
                string[]       schemaTcmUriParts = imgElement.GetAttribute("data-schemaUri").Split('-');
                SemanticSchema semanticSchema    = SemanticMapping.GetSchema(schemaTcmUriParts[1], localization);

                // The semantic mapping may resolve to a more specific model type than specified here (e.g. YouTubeVideo instead of just MediaItem)
                Type      modelType = semanticSchema.GetModelTypeFromSemanticMapping(typeof(MediaItem));
                MediaItem mediaItem = (MediaItem)modelType.CreateInstance();
                mediaItem.ReadFromXhtmlElement(imgElement);
                if (mediaItem.MvcData == null)
                {
                    // In DXA 1.1 MediaItem.ReadFromXhtmlElement was expected to set MvcData.
                    // In DXA 1.2 this should be done in a GetDefaultView override (which is also used for other embedded Entities)
                    mediaItem.MvcData = mediaItem.GetDefaultView(localization);
                }
                embeddedEntities.Add(mediaItem);

                // Replace img element with marker XML processing instruction
                imgElement.ParentNode.ReplaceChild(
                    doc.CreateProcessingInstruction(EmbeddedEntityProcessingInstructionName, String.Empty),
                    imgElement
                    );
            }

            // Split the XHTML into fragments based on marker XML processing instructions.
            string xhtml = doc.DocumentElement.InnerXml;
            IList <IRichTextFragment> richTextFragments = new List <IRichTextFragment>();
            int lastFragmentIndex = 0;
            int i = 0;

            foreach (Match embeddedEntityMatch in EmbeddedEntityProcessingInstructionRegex.Matches(xhtml))
            {
                int embeddedEntityIndex = embeddedEntityMatch.Index;
                if (embeddedEntityIndex > lastFragmentIndex)
                {
                    richTextFragments.Add(new RichTextFragment(xhtml.Substring(lastFragmentIndex, embeddedEntityIndex - lastFragmentIndex)));
                }
                richTextFragments.Add(embeddedEntities[i++]);
                lastFragmentIndex = embeddedEntityIndex + embeddedEntityMatch.Length;
            }
            if (lastFragmentIndex < xhtml.Length)
            {
                // Final text fragment
                richTextFragments.Add(new RichTextFragment(xhtml.Substring(lastFragmentIndex)));
            }

            return(new RichText(richTextFragments));
        }