Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sitemap #1040

Open
ejazmusavi opened this issue Oct 12, 2022 · 3 comments
Open

Sitemap #1040

ejazmusavi opened this issue Oct 12, 2022 · 3 comments

Comments

@ejazmusavi
Copy link

is there any existing module to get sietmap?

@fetullahyldz
Copy link

I can help you with this. There is a sitemap I wrote.

@fetullahyldz
Copy link

[Area("Settings")]
[ApiExplorerSettings(IgnoreApi = true)]
public class CatalogSiteMapController : Controller
{

    private readonly ISitemapGenerator _sitemapGenerator;
    private readonly ISitemapImageGenerator _sitemapImageGenerator;
    public CatalogSiteMapController(ISitemapGenerator sitemapGenerator, ISitemapImageGenerator sitemapImageGenerator)
    {

        _sitemapGenerator = sitemapGenerator;
        _sitemapImageGenerator = sitemapImageGenerator;
    }

    [HttpGet("SiteMap.xml")]
    public virtual IActionResult SiteMap()
    {
        var siteMap = _sitemapGenerator.Generate();
        return Content(siteMap, "text/xml");
    }

    [HttpGet("imageSiteMap.xml")]
    public virtual IActionResult ImageSiteMap()
    {
        var siteMap = _sitemapImageGenerator.Generate();
        return Content(siteMap, "text/xml");
    }
}

@fetullahyldz
Copy link

public class SitemapGenerator : ISitemapGenerator
{

    private readonly IUrlHelperFactory _urlHelperFactory;
    private readonly IRepository<Product> _productRepository;
    private readonly IRepository<Brand> _brandRepository;
    private readonly IRepository<Page> _PageRepository;
    private readonly IRepository<Category> _categoryRepository;
    private readonly IRepository<NewsItem> _newsRepository;
    private readonly IRepository<NewsCategory> _newsCategoryRepository;
    private readonly IMediaService _mediaService;
    private IServiceProvider _serviceProvider;
    private readonly IContentLocalizationService _contentLocalizationService;
    public SitemapGenerator(IUrlHelperFactory urlHelperFactory, IRepository<Product> productRepository,
      IRepository<Brand> brandRepository,
      IRepository<Category> categoryRepository, IRepository<NewsItem> newsRepository, IRepository<NewsCategory> newsCategoryRepository,
      IMediaService mediaService, IServiceProvider serviceProvider, IContentLocalizationService contentLocalizationService, IRepository<Page> PageRepository)
    {
        _urlHelperFactory = urlHelperFactory;
        _productRepository = productRepository;
        _brandRepository = brandRepository;
        _categoryRepository = categoryRepository;
        _newsRepository = newsRepository;
        _newsCategoryRepository = newsCategoryRepository;
        _mediaService = mediaService;
        _serviceProvider = serviceProvider;
        _contentLocalizationService = contentLocalizationService;
        _PageRepository = PageRepository;

    }
    public bool ForceSslForAllPages { get; set; }
    protected virtual IList<SitemapUrl> GenerateUrls()
    {
        var sitemapUrls = new List<SitemapUrl>();
        var actionContext =new HttpContextAccessor();
        var urlHelper = actionContext.HttpContext.Request.Scheme.ToLower() + "://" + actionContext.HttpContext.Request.Host.Value;

        var CultureCategory = _contentLocalizationService.GetLocalizationFunction<Category>();
        //Category
        foreach (var category in _categoryRepository.Query().Where(x => x.IsPublished && !x.IsDeleted))
        {
            var categoryUrl = urlHelper + "/" + CultureCategory(category.Id, nameof(category.Slug), category.Slug);
            sitemapUrls.Add(new SitemapUrl(categoryUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }

        var CultureProduct = _contentLocalizationService.GetLocalizationFunction<Product>();
        //products
        foreach (var products in _productRepository.Query().Where(x => x.IsPublished && x.IsVisibleIndividually && !x.IsDeleted))
        {
            var productsUrl = urlHelper + "/" + CultureProduct(products.Id, nameof(products.Slug), products.Slug);
            sitemapUrls.Add(new SitemapUrl(productsUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }

        //Barand marka
        foreach (var brand in _brandRepository.Query().Where(x => x.IsPublished && !x.IsDeleted))
        {
            var brandsUrl = urlHelper + "/" + brand.Slug;
            sitemapUrls.Add(new SitemapUrl(brandsUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }

        var CulturePage = _contentLocalizationService.GetLocalizationFunction<Page>();
        //Sayfalar 
        foreach (var page in _PageRepository.Query().Where(x => x.IsPublished && !x.IsDeleted))
        {
            var pagedsUrl = urlHelper + "/" + CulturePage(page.Id, nameof(page.Slug), page.Slug);
            sitemapUrls.Add(new SitemapUrl(pagedsUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }

        var CultureNewsCat = _contentLocalizationService.GetLocalizationFunction<NewsCategory>();
        //haber kategori
        foreach (var newscat in _newsCategoryRepository.Query().Where(x => x.IsPublished && !x.IsDeleted))
        {
            var newscatsUrl = urlHelper + "/" + CultureNewsCat(newscat.Id, nameof(newscat.Slug), newscat.Slug);
            sitemapUrls.Add(new SitemapUrl(newscatsUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }

        var CultureNewsItem = _contentLocalizationService.GetLocalizationFunction<NewsItem>();
        //haberler
        foreach (var news in _newsRepository.Query().Where(x => x.IsPublished && !x.IsDeleted))
        {
            var newsUrl = urlHelper + "/" + CultureNewsItem(news.Id, nameof(news.Slug), news.Slug);
            sitemapUrls.Add(new SitemapUrl(newsUrl, UpdateFrequency.Daily, DateTime.UtcNow));
        }
        //custom URLs         

        return sitemapUrls;
    }
    public List<string> SitemapCustomUrls { get; set; }



    public virtual string Generate()
    {
        using (var stream = new MemoryStream())
        {
            Generate(stream);
            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }


    public virtual void Generate(Stream stream)
    {
        //generate all URLs for the sitemap
        var sitemapUrls = GenerateUrls();

        //split URLs into separate lists based on the max size 
        var sitemaps = sitemapUrls.Select((url, index) => new { Index = index, Value = url })
            .GroupBy(group => group.Index / BestSeoDefaults.SitemapMaxUrlNumber)
                .Select(group => group.Select(url => url.Value).ToList()).ToList();

        if (!sitemaps.Any())
            return;

        //URLs more than the maximum allowable, so generate a sitemap index file
        if (sitemapUrls.Count >= BestSeoDefaults.SitemapMaxUrlNumber)
        {
            //write a sitemap index file into the stream
            WriteSitemapIndex(stream, sitemaps.Count);
        }
        else
        {
            //otherwise generate a standard sitemap
            WriteSitemap(stream, sitemaps.First());
        }

    }

    protected virtual void WriteSitemapIndex(Stream stream, int sitemapNumber)
    {
        var urlHelper = GetUrlHelper();
        using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("sitemapindex");
            writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
            writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

            //write URLs of all available sitemaps
            for (var id = 1; id <= sitemapNumber; id++)
            {
                var url = urlHelper.RouteUrl("sitemap-indexed.xml", new { Id = id }, GetHttpProtocol());
                var location = XmlHelper.XmlEncode(url);

                writer.WriteStartElement("sitemap");
                writer.WriteElementString("loc", location);
                writer.WriteElementString("lastmod", DateTime.UtcNow.ToString(BestSeoDefaults.SitemapDateFormat));
                writer.WriteElementString("changefreq", "daily");
                writer.WriteElementString("priority", "1");
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
    }
    protected virtual void WriteSitemap(Stream stream, IList<SitemapUrl> sitemapUrls)
    {
        using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument();
            writer.WriteStartElement("urlset");
            writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
            writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

            //write URLs from list to the sitemap
            foreach (var url in sitemapUrls)
            {
                writer.WriteStartElement("url");
                var location = XmlHelper.XmlEncode(url.Location);

                writer.WriteElementString("loc", location);
                writer.WriteElementString("lastmod", url.UpdatedOn.ToString(BestSeoDefaults.SitemapDateFormat, CultureInfo.InvariantCulture));
                writer.WriteElementString("changefreq", url.UpdateFrequency.ToString().ToLowerInvariant());
                writer.WriteElementString("priority", "1");
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
    }

    protected virtual string GetHttpProtocol()
    {
        return ForceSslForAllPages ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
    }
    protected virtual IUrlHelper GetUrlHelper()
    {
        var actionContext = GetActionContext();
        return _urlHelperFactory.GetUrlHelper(actionContext);
    }
    #region Nested class

    /// <summary>
    /// Represents sitemap URL entry
    /// </summary>
    protected class SitemapUrl
    {
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="location">URL of the page</param>
        /// <param name="frequency">Update frequency</param>
        /// <param name="updatedOn">Updated on</param>
        public SitemapUrl(string location, UpdateFrequency frequency, DateTime updatedOn)
        {
            Location = location;
            UpdateFrequency = frequency;
            UpdatedOn = updatedOn;
        }

        /// <summary>
        /// Gets or sets URL of the page
        /// </summary>
        public string Location { get; set; }

        /// <summary>
        /// Gets or sets a value indicating how frequently the page is likely to change
        /// </summary>
        public UpdateFrequency UpdateFrequency { get; set; }

        /// <summary>
        /// Gets or sets the date of last modification of the file
        /// </summary>
        public DateTime UpdatedOn { get; set; }
    }

    #endregion

    private ActionContext GetActionContext()
    {
        var httpContext = new DefaultHttpContext
        {
            RequestServices = _serviceProvider
        };

        return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants