How to retrieve common part info .

Topics: General, Writing modules
Sep 8, 2013 at 10:01 AM
I have a model
namespace Ective.NGame.Models
{
    public class NGroupPartRecord : ContentPartRecord
    {
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }
 
    }
}
 public class NGroupPart : ContentPart<NGroupPartRecord>
    {
        [Required]
        public string Name
        {
            get { return Record.Name; }
            set { Record.Name = value; }
        }

        public string Description
        {
            get { return Record.Description; }
            set { Record.Description = value; }
        }

        
Handle

namespace Ective.NGame.Handlers
{
    public class NGroupPartHandler:ContentHandler
    {
        public NGroupPartHandler(IRepository<NGroupPartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));
            Filters.Add(new ActivatingFilter<NGroupPart>("NGroup"));
           
        }
    }
}
Driver
namespace Ective.NGame.Drivers
{
    public class NGroupPartDriver : ContentPartDriver<NGroupPart>
    {
        protected override string Prefix
        {
            get { return "NGroup"; }
        }

        protected override DriverResult Display(
            NGroupPart part, string displayType, dynamic shapeHelper)
        {

            return ContentShape("Parts_NGroup", () => shapeHelper.Parts_NGroup(
                Name: part.Name,
                Description: part.Description));
        }

       
        //GET
        protected override DriverResult Editor(
            NGroupPart part, dynamic shapeHelper)
        {

            return ContentShape("Parts_NGroup_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/NGroup",
                    Model: part,
                    Prefix: Prefix));
        }
        //POST
        protected override DriverResult Editor(
            NGroupPart part, IUpdateModel updater, dynamic shapeHelper)
        {

            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }
    }
}
migration
public int Create() {
            // Creating table NGroupPartRecord
            SchemaBuilder.CreateTable("NGroupPartRecord", table => table
                .ContentPartRecord()
                .Column("Name", DbType.String)
                .Column("Description", DbType.String)
            );

             ContentDefinitionManager.AlterPartDefinition(
                typeof(NGroupPart).Name, cfg => cfg.Attachable());


            return 1;
        }

public int UpdateFrom1()
        {
            ContentDefinitionManager.AlterTypeDefinition("NGroupPart",
                cfg => cfg
                    .WithPart("CommonPart")
                    );

            return3;
        }
my controller
namespace Ective.NGame.Controllers
{
      [Admin]
    public class NGroupAdminController :Controller,IUpdateModel
    {
        private dynamic Shape { get; set; }
        public Localizer T { get; set; }
        public IOrchardServices Services { get; set; }
        private readonly INGroupService _nGroupService;
        private readonly ISiteService _siteService;
        private readonly IContentManager _contentManager;
        private readonly INotifier _notifier;
        private readonly IRepository<NGroupPart> _repository;

        public NGroupAdminController(
            IOrchardServices services,
            INGroupService nGroupService, 
            IShapeFactory shapeFactory, 
            ISiteService siteService, 
            IContentManager contentManager, 
            INotifier notifier)
        {
            Services = services; 
            Shape = shapeFactory;
            T = NullLocalizer.Instance;
            _nGroupService = nGroupService;
            _siteService = siteService;
            _contentManager = contentManager;
            _notifier = notifier;
         
        }
       
        public ActionResult Index(PagerParameters pagerParameters, NGroupsSearchVM search)
        {

            // Create a basic query that selects all customer content items, joined with the UserPartRecord table
            var nGroupQuery = _nGroupService.GetNGroup().List();

            // If the user specified a search expression, update the query with a filter
            if (!string.IsNullOrWhiteSpace(search.Expression))
            {

                var expression = search.Expression.Trim();

                nGroupQuery = from ngroup in nGroupQuery 
                                where
                                    ngroup.Name.Contains(expression, StringComparison.InvariantCultureIgnoreCase) ||
                                    ngroup.Description.Contains(expression, StringComparison.InvariantCultureIgnoreCase) 
                                    
                                select ngroup;
            }

            // Project the query into a list of customer shapes
            var nGroupProjection = from ngroup in nGroupQuery
                                      select Shape.Customer
                                      (
                                        Id: ngroup.Id,
                                        Name: ngroup.Name,
                                        Description: ngroup.Description );

            // The pager is used to apply paging on the query and to create a PagerShape
            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters.Page, pagerParameters.PageSize);

            // Apply paging
            var ngroups = nGroupProjection.Skip(pager.GetStartIndex()).Take(pager.PageSize);

            // Construct a Pager shape
            var pagerShape = Shape.Pager(pager).TotalItemCount(nGroupQuery.Count());

            // Create the viewmodel
            var model = new NGroupsIndexVM(ngroups, search, pagerShape);

            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var group = _nGroupService.GetNGroup(id);
            
           var model  = new NGroupViewModel { Name =group.Name,Description = group.Description} ;
           TryUpdateModel(model);
           if (!ModelState.IsValid)
               return RedirectToAction("Index");

           return View(model);


        
        }
               
        [HttpPost, ActionName("Edit")]
        public ActionResult EditPOST(int id)
        {
           
            var ngroup = _contentManager.Get<NGroupPart>(id, VersionOptions.DraftRequired);
        
            if (TryUpdateModel(ngroup))
            {
                if (!_nGroupService.VerifyNGroupUnicity(id, ngroup.Name))
                {
                    ModelState.AddModelError("Name", ("Duplicated name insert not allowed"));
                }
                
            }
        
            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

               

                return View () ;
            }

            _notifier.Add(NotifyType.Information, T("Your customer has been saved"));
            return RedirectToAction("Edit", new { id });
        }

        public ActionResult Create()
        {
            var model = new NGroupViewModel();
            return View(model);
        }

        [HttpPost, ActionName("Create")]
        public ActionResult CreatePOST()
        {
            var viewModel = new NGroupViewModel();
            TryUpdateModel(viewModel);

            if (String.IsNullOrEmpty(viewModel.Name))
            {
               ModelState.AddModelError("Name", ("Group name can't be empty"));
              
            }


            var group = _nGroupService.GetNGroupByName(viewModel.Name);
            if (group != null)
            {
                ModelState.AddModelError("Name", ("Group with same name already exists"));
            }

            if (!ModelState.IsValid)
            {
              
                return View(viewModel);
            }

            _nGroupService.CreateNGroup(viewModel.Name, viewModel.Description); 

         
            return RedirectToAction("Index");
        }

        
        public ActionResult Delete(int id)
        {
            var group = _nGroupService.GetNGroup(id);

            if (group != null)
            {
                _contentManager.Remove(group.ContentItem);
                _notifier.Add(NotifyType.Information, T("Group {0} deleted", group.Name));
            }

            return RedirectToAction("Index");
        }

          bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) {
            return TryUpdateModel(model, prefix, includeProperties, excludeProperties);
        }
 
        void IUpdateModel.AddModelError(string key, LocalizedString errorMessage) {
            ModelState.AddModelError(key, errorMessage.Text);
        } 
    } 
    
}
Just want to know , how can i retrieve the common part info , so that i can diplay the created date , last update date , and updated users?
Sep 8, 2013 at 11:51 AM
You can use As<CommonPart>() method on the part object.


Sep 8, 2013 at 3:24 PM
Sorry i don't quit get it .
I have refer some of the forum ref , i change my Service as join

NGroupService
   public IContentQuery<NGroupPart> GetNGroup()
        {
            return _orchardServices.ContentManager.Query<NGroupPart, NGroupPartRecord>()
                .Join<CommonPartRecord>()
                .OrderByDescending(x => x.CreatedUtc);

        }
AS the controller will call for this GetNGroup
amespace Ective.NGame.Controllers
{
      [Admin]
    public class NGroupAdminController :Controller,IUpdateModel
    {
        private dynamic Shape { get; set; }
        public Localizer T { get; set; }
        public IOrchardServices Services { get; set; }
        private readonly INGroupService _nGroupService;
        private readonly ISiteService _siteService;
        private readonly IContentManager _contentManager;
        private readonly INotifier _notifier;
        private readonly IRepository<NGroupPart> _repository;

        public NGroupAdminController(
            IOrchardServices services,
            INGroupService nGroupService, 
            IShapeFactory shapeFactory, 
            ISiteService siteService, 
            IContentManager contentManager, 
            INotifier notifier)
        {
            Services = services; 
            Shape = shapeFactory;
            T = NullLocalizer.Instance;
            _nGroupService = nGroupService;
            _siteService = siteService;
            _contentManager = contentManager;
            _notifier = notifier;
         
        }
       
        public ActionResult Index(PagerParameters pagerParameters, NGroupsSearchVM search)
        {

            // Create a basic query that selects all customer content items, joined with the UserPartRecord table
            var nGroupQuery = _nGroupService.GetNGroup().List();

            // If the user specified a search expression, update the query with a filter
            if (!string.IsNullOrWhiteSpace(search.Expression))
            {

                var expression = search.Expression.Trim();

                nGroupQuery = from ngroup in nGroupQuery 
                                where
                                    ngroup.Name.Contains(expression, StringComparison.InvariantCultureIgnoreCase) ||
                                    ngroup.Description.Contains(expression, StringComparison.InvariantCultureIgnoreCase) 
                                    
                                select ngroup;
            }

            // Project the query into a list of customer shapes
            var nGroupProjection = from ngroup in nGroupQuery
                                      select Shape.Customer
                                      (
                                        Id: ngroup.Id,
                                        Name: ngroup.Name,
                                        Description: ngroup.Description );

            // The pager is used to apply paging on the query and to create a PagerShape
            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters.Page, pagerParameters.PageSize);

            // Apply paging
            var ngroups = nGroupProjection.Skip(pager.GetStartIndex()).Take(pager.PageSize);

            // Construct a Pager shape
            var pagerShape = Shape.Pager(pager).TotalItemCount(nGroupQuery.Count());

            // Create the viewmodel
            var model = new NGroupsIndexVM(ngroups, search, pagerShape);

            return View(model);
        }
From this var nGroupQuery = _nGroupService.GetNGroup().List() , i can't assign As<CommonPart>().
Where should i put this As<CommonPart>() ?

thanks
Sep 8, 2013 at 3:25 PM
any good references example for using this common part ? i searching for so long , still can't get what i need. hope some one can give me a hand.
thanks
Sep 8, 2013 at 4:11 PM
You can call this method on a content part or content item, on an IContent to be exact. So the usage would be something like this:

select Shape.Customer
(
Id: ngroup.Id,
Name: ngroup.Name,
Description: ngroup.Description,
Something: ngroup.As<CommonPart>().Owner.UserName;
);

With the Join calls in content manager queries, you just include the joined part's properties in the SQL query, to prevent an extra roundtrip. Just for performance. DB tables are joined on content ID, which is a shared key among content part records of the same content item.

As<Type>() is an extension method implemented in Orchard.ContentManagement.ContentExtensions.cs file. If you search for references in the orchard code you can find many examples. For examples of using this with CommonPart, you can use search in Visual Studio for .As<CommonPart>()



Sep 8, 2013 at 4:45 PM
kassobasi , Thanks for your help. Now i get what i needed.
I still very new in orchard cms ,but i feel this is very good cms and easy to extend.

For others who need the same assist. if you add below code

select Shape.Customer
(
Id: ngroup.Id,
Name: ngroup.Name,
Description: ngroup.Description,
Something: ngroup.As<CommonPart>().Owner.UserName;
);

and facing object not initial error in VS . you can add ActivatingFilter in your handle

namespace Ective.NGame.Handlers
{
public class NGroupPartHandler:ContentHandler
{
    public NGroupPartHandler(IRepository<NGroupPartRecord> repository)
    {
        Filters.Add(StorageFilter.For(repository));
        Filters.Add(new ActivatingFilter<NGroupPart>("NGroup"));
        ___Filters.Add(new ActivatingFilter<Orchard.Core.Common.Models.CommonPart>("NGroup"));___
    }
}
}
Sep 9, 2013 at 3:47 AM
You are welcome. Also, if your migration method were like:

public int UpdateFrom1()
{
ContentDefinitionManager.AlterTypeDefinition("NGroup",
cfg => cfg
.WithPart("CommonPart")
.WithPart("NGroupPart")
);

return 2;
}

You wouldn't need that activating filters.


Sep 9, 2013 at 7:47 AM
Thanks . yes i try it. it work.
One more question is , how to i get the last modified record user ?
I Only can find As<CommonPart>().Owner.UserName , i assume this is the record creator user .
Coordinator
Sep 9, 2013 at 7:50 AM
You can't. You need an additional module that creates audit traces. I think this is doing that: http://gallery.orchardproject.net/List/Modules/Orchard.Module.Downplay.Audit