how to access database in orchard?

Topics: Writing modules
Mar 9, 2011 at 3:08 PM
Edited Mar 9, 2011 at 3:10 PM

Hello. I don't need to add fields to database, or make custom types.

I need to make custom sitemap export to xml only read some data.

What would be easiest way to get IEnumerable<MenuItem> object with menu items in it?

AdminController methods now look like this

   public ActionResult Index()        {            return View();        }  

     [AcceptVerbs(HttpVerbs.Post)]      

 public ActionResult Index(string FILENAME, SiteMapType SiteMapType)        

{            

Repository<MenuItem> menu;    // In this line I would love to read data

Response.Clear();      

FILENAME = string.IsNullOrWhiteSpace(FILENAME) ? DateTime.Now.ToString("yyyy-MM-dd") + " - Sitemap.xml" : FILENAME + ".xml";    

Response.ContentType = "text/xml";        

Response.AddHeader("Content-Disposition", "attachment; filename=" + FILENAME);    

if (SiteMapType == SiteMapType.ASP)          

 {    Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");  Response.Write("<siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" >");    }    

else       {            

   Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");        

   Response.Write("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");    

   Response.Write(" xmlns:image=\"http://www.sitemaps.org/schemas/sitemap-image/1.1\"");    

   Response.Write(" xmlns:video=\"http://www.sitemaps.org/schemas/sitemap-video/1.1\">");            }

            foreach (var menuitem in menu.Table)          

 {                WriteXml(menuitem, SiteMapType);            }  

if (SiteMapType == SiteMapType.ASP){                Response.Write("</siteMap>");            }        

else            {                Response.Write("</urlset>");            }      

Response.End();        

return View();    

 }        

 public enum SiteMapType    {        Google = 1,        ASP = 2    }

Coordinator
Mar 9, 2011 at 5:23 PM

Did you try getting a dependency on IMenuService and calling Get on that?

Mar 10, 2011 at 9:08 AM
Edited Mar 10, 2011 at 9:09 AM

Hello again, 

I have added 

        private readonly IMenuService _menuService;      

         AdminController( IMenuService menuService)        { _menuService = menuService;  }

but its not packed with menu items,  I get IEnumerable<MenuPart>  instead and they dont have url, nor tree structure like MenuItems do.

 

I found article http://www.java2s.com/Open-Source/CSharp/Web-Frameworks/Orchard/Orchard/Core/Navigation/Controllers/AdminController.cs.htm

but then i try to convert 

MenuPart to MenuItem 

 if(menuitem.Is<MenuItem>())        

       WriteXml(menuitem.As<MenuItem>(), SiteMapType);

i get error 

"Error 13 The type 'Orchard.UI.Navigation.MenuItem' cannot be used as type parameter 'T' in the generic type or method 'Orchard.ContentManagement.ContentExtensions.As<T>(Orchard.ContentManagement.IContent)'. There is no implicit reference conversion from 'Orchard.UI.Navigation.MenuItem' to 'Orchard.ContentManagement.IContent'. C:\inetpub\wwwroot\inspra\src\Orchard.Web\Modules\SiteMapXmlExport\Controllers\AdminController.cs 72 26 SiteMapXmlExport"

So again is there a way to get  MenuItem collection?

I will add WriteXml method, explains why I need tree structure

public void WriteXml(MenuItem parent, SiteMapType SiteMapType)        

{            if (SiteMapType == SiteMapType.ASP)            

{                Response.Write("<siteMapNode url=\"" + parent.Url + "\" title=\"" + parent.Text + "\" description=\"" + parent.Text + "\">");            }            

else            {                Response.Write("<url>");                Response.Write("<loc>" + parent.Url + "</loc> ");                             }

if (parent.Items.Any())                

foreach (MenuItem child in parent.Items)                    

WriteXml(child, SiteMapType);            

else            {

                if (SiteMapType == SiteMapType.ASP)                

{                    Response.Write("</siteMapNode>");                }                

else                {                    Response.Write("</url>");                }            

}

Mar 10, 2011 at 9:30 AM
Edited Mar 10, 2011 at 9:37 AM

Also if i try

public class AdminController : Controller ,IUpdateModel    

{        

private readonly IMenuService _menuService;        

private readonly IRepository<MenuItem> _repository;        

    public AdminController(              IRepository<MenuItem> repository,        IMenuService menuService                      )  

     {            _repository = repository;            _menuService = menuService;           }      

}

 

  [AcceptVerbs(HttpVerbs.Post)]        

public ActionResult Index(string FILENAME, SiteMapType SiteMapType)      

 {         
            var menu = _repository.Table; 

menu is empty collection

and if i call

var singlemenuitem = _repository.Get(15);

I get error

No persister for: Orchard.UI.Navigation.MenuItem

the record is there 

Navigation_MenuItemPartRecord:

Id Url

15 spec-nav

what am I doing wrong?

Mar 10, 2011 at 2:43 PM
Edited Mar 11, 2011 at 6:51 AM

all done

probably not the 'right way'

heres the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Core.Navigation.Services;
using Orchard.Core.Navigation.Models;
using Orchard.Data;
using Orchard.UI.Navigation;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement;
using Orchard.Localization;

namespace SiteMapXmlExport.Controllers
{
    public class SitemapXmlInput
    {
        public string Filename { get; set; }
        public SiteMapType SiteMapType { get; set; }
        public bool AddSite { get; set; }
    }
    public class AdminController : Controller
    {
        private readonly IMenuService _menuService;
        private List<MenuPart> menuitems;
        public AdminController(IMenuService menuService)
        {
            _menuService = menuService;
        }
        public ActionResult Index()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(SitemapXmlInput Input)
        {
            menuitems = _menuService.Get().ToList();
            Response.Clear();
            Input.Filename = string.IsNullOrWhiteSpace(Input.Filename) ? DateTime.Now.ToString("yyyy-MM-dd") + " - Sitemap.xml" : Input.Filename + ".xml";
            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Input.Filename);
            if (Input.SiteMapType == SiteMapType.ASP)
            {
                Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                Response.Write("<siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" >");
            }
            else
            {
                Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
                Response.Write("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");
                Response.Write(" xmlns:image=\"http://www.sitemaps.org/schemas/sitemap-image/1.1\"");
                Response.Write(" xmlns:video=\"http://www.sitemaps.org/schemas/sitemap-video/1.1\">");
            }
            foreach (var menuitem in menuitems.Where(o => !o.MenuPosition.Contains(".")))
                if (menuitem.Is<MenuItemPart>())
                    WriteXml(menuitem, Input);

            if (Input.SiteMapType == SiteMapType.ASP)
            {
                Response.Write("</siteMap>");
            }
            else
            {
                Response.Write("</urlset>");
            }
            Response.End();
            return View();
        }
        public void WriteXml(MenuPart parent, SitemapXmlInput Input)
        {
            string url = Input.AddSite ? Request.Url.OriginalString.Substring(0, Request.Url.OriginalString.IndexOf("Admin")) + parent.As<MenuItemPart>().Url : parent.As<MenuItemPart>().Url;
            if (Input.SiteMapType == SiteMapType.ASP)
            {
                Response.Write("<siteMapNode url=\"" + url + "\" title=\"" + parent.MenuText + "\" description=\"" + parent.MenuText + "\">");
            }
            else
            {
                Response.Write("<url>");
                Response.Write("<loc>" + url + "</loc> ");
                // TODO: uncommnet then MenuItem will have Image property or Element
                // Response.Write("<image:image>");
                // Response.Write("<image:loc>"+parent.Image.Url+"</image:loc>");
                // Response.Write("</image:image>");
                // TODO: uncomment then MenuItem will have Video property or Element
                // Response.Write("<video:video>");
                // Response.Write("<video:content_loc>"+parent.Video.Url+"</video:content_loc>");
                // Response.Write("<video:player_loc allow_embed="yes" autoplay="ap=1">"+parent.Video.PlayerUrl+"</video:player_loc>");
                // Response.Write("<video:thumbnail_loc>"+parent.Video.Thumbnail+"</video:thumbnail_loc>");
                // Response.Write("<video:title>"+parent.Video.Text+"</video:title>  ");
                // Response.Write("<video:description>"+parent.Video.Description+"</video:description>");
                // Response.Write("</video:video>");     
            }
            if (menuitems.Where(o => o.MenuPosition.StartsWith(parent.MenuPosition + ".")).Any())
            {
                int dotcount = parent.MenuPosition.Count(o => o == '.');
                foreach (MenuPart child in menuitems.Where(o => o.MenuPosition.StartsWith(parent.MenuPosition + ".") && o.MenuPosition.Count(oo => oo == '.') == parent.MenuPosition.Count(ooo => ooo == '.') + 1))
                    if (child.Is<MenuItemPart>())
                        WriteXml(child, Input);
            }

            if (Input.SiteMapType == SiteMapType.ASP)
            {
                Response.Write("</siteMapNode>");
            }
            else
            {
                Response.Write("</url>");
            }
        }
    }
    public enum SiteMapType
    {
        Google = 1,
        ASP = 2
    }
    public class SiteMapXmlExportService
    {
        private readonly IRepository<MenuItem> _repository;
        public SiteMapXmlExportService(
    IRepository<MenuItem> repository
  )
        {
            _repository = repository;
        }
    }
    public class AdminMenu : INavigationProvider
    {
        private readonly IContentDefinitionManager _contentDefinitionManager;
        private readonly IContentManager _contentManager;

        public AdminMenu(IContentDefinitionManager contentDefinitionManager, IContentManager contentManager)
        {
            _contentDefinitionManager = contentDefinitionManager;
            _contentManager = contentManager;
        }

        public Localizer T { get; set; }
        public string MenuName { get { return "admin"; } }

        public void GetNavigation(NavigationBuilder builder)
        {
            var contentTypeDefinitions = _contentDefinitionManager.ListTypeDefinitions().OrderBy(d => d.Name);
            builder.Add(T("SiteMapXmlExport"), "5",
             menu =>
                 menu.Add(T("SiteMapXmlExport"), "5", item => item.Action("Index", "Admin", new { area = "SiteMapXmlExport", id = "" }))
            );
        }
    }
}

Coordinator
Mar 10, 2011 at 7:50 PM

When you want to paste code into these forums, you can use the last icon on the toolbar: that will properly conserve the formatting of the code and even color it.

It seems like you are trying to build a sitemap from the menu data. Did you look at the existing site map module?

http://orchardproject.net/gallery/List/Modules/Orchard.Module.Orchard.SiteMap (this is currently giving a 404 but is being looked into)

Mar 11, 2011 at 7:00 AM

Sorry for the mess, I needed sitemap XML export. Already done.