Archive

Posts Tagged ‘asp.net mvc’

Orchard Alpha released

August 3rd, 2010 Patrick No comments

As promised, Project Orchard reached with Alpha milestone just now with the downloads available at http://orchard.codeplex.com

Among the features included in this release

  • The core module API is mostly baked
  • Data migrations for updating database schema on module activation and upgrade between versions of modules
  • Basic command-line scaffolding of modules and data migrations
  • Dynamic compilation of module source, for notepad-style development
    • Defining custom content types, parts, and fields
    • Define new content types (admin panel or code)
    • Add fields to content types (admin panel or code)
    • Associate content parts to types (admin panel or code)
    • Add fields or parts to existing content types (admin panel or code)
  • Packaging and installing modules (as zip files) – can include source, binaries, or both
  • Sharing modules via an ATOM feed (to be exposed on OrchardProject.net), and installing from the feed using a new “Gallery” module
  • Enabling, disabling, and upgrading module features and their dependencies (admin panel or command-line)
  • Search
  • Localization support for both the Orchard application and database-driven content items
  • Azure support
  • Multi-tenancy support
  • Interactive command-line support for many administrative tasks
  • Some basic reporting/logging functionality
  • Everything from previous Mix release: pages, blogs, comments, tags, users/roles, media, menu navigation, and basic theme support
Categories: Uncategorized Tags: ,

A 7 part tutorial on project Orchard based on the latest change set

July 26th, 2010 Patrick No comments

 

Over the weekend I created a tutorial to create a module inside project Orchard. I referred to the original walkthrough found inside project Orchard’s website. The original walkthrough was created for the March 2010 release of project orchard and I have modified the codes and steps so that it will work with the latest change set.

Below is the Table of Content

What is project Orchard and a Hello World sample

Hooking into Admin panel

Working with Data

Orchard Content Type

Attaching a part to content type

Composing view using different content parts

Finishing touch on the front end listing and shopping cart

For the complete project source code, download from my Windows Live SkyDrive here.

 

 

It is best if you check out the Mar 2010 build and the original tutorial as well for more info on Orchard.

 

Cheers.

Categories: Uncategorized Tags: ,

Hello Orchard Final Part–Building the module front end

July 26th, 2010 Patrick 5 comments

With the backend Product administration page done, now we can build the front end to list the products and a simple shopping cart

Following are copy-pastes from the walkthrough at orchardproject.net with my modifications

1. Let’s first update our HomeController query the ContentManager for the list of products, passing the model to the View:

using Orchard.Commerce.Models;using Orchard.ContentManagement;

[Themed]    public class HomeController : Controller    {

        private readonly IContentManager _contentManager;

        public HomeController(IContentManager contentManager)        {            _contentManager = contentManager;        }

        public ActionResult Index()        {            return View(_contentManager.Query<Product>().List());        }    }

2. Now let’s update the Home/Index.ascx view page to render the list of products. To make this easier, delete the existing Index.ascx page and right-click the Index() action to “Add > View” in Visual Studio. This time, we’ll add a strongly-typed view that takes the Product type, and choose “List” for the View content type:

image

3. In Index.ascx, add this at the top of the file:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Orchard.Commerce.Models.Product>>" %><div class="page-title"><%=Html.TitleForPage("Product list")%></div>    <table>

4. Type Ctrl-F5 to build and run the site. Click the “Shop” menu item on the front-end to reveal your list of products.

image

5. Let’s now create a “Details” view so we can verify we can see tags and add comments (recall the UI composition section above). In the HomeController, add this:

using Orchard.Mvc.Results;

public ActionResult Details(int id)        {            var product = _contentManager.Get<Product>(id);            if (product == null)                return new NotFoundResult();

            var viewModel = _contentManager.BuildDisplayModel<Product>(product,            "Details");

            return View(viewModel);        }

6. Let’s then create the “Details.ascx” view under Views > Home:

image

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Orchard.Mvc.ViewModels.ContentItemViewModel<Orchard.Commerce.Models.Product>>" %><div class="page-title">    <%=Html.TitleForPage("Product details")%></div><%= Html.DisplayForItem(Model) %><div>    <%=Html.ActionLink("Back to List", "Index") %></div>



Note the “Details” string. It a convention for the type of display (other include summary, list, etc.). Let’s update the ProductDriver to handle the composition:

protected override DriverResult Display(Product product, string displayType){   return ContentPartTemplate(product, "Product.Fields").Location("primary", "1");}

This is very similar to the “Editor” method. Product.Fields is the template used to render the fields. Let’s create Product.Fields.ascx in the “DisplayTemplates” folder.

image

7. Add Product.Fields.ascx under the “Views > DisplayTemplates” folder:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Orchard.Commerce.Models.Product>" %><fieldset>    <legend>        <%= Html.Encode(Model.Sku)%></legend>    <p>    </p>    <h3>        <%= Html.Encode(Model.Description)%></h3>    <p>        Price:        <%= Html.Encode(String.Format("{0:F}", Model.Price))%></p></fieldset>

8. And finally update the Index view to link the “sku” field to the product details page:

Replace this:

<td>   <%: item.Sku %></td>

With this:

<td>  <%= Html.ActionLink(item.Sku ?? "sku", "Details", new { id = item.Id })%></td>

9. Type Ctrl-F5 to build and run the site. Now, when clicking on a “sku” in the index view, we get to the product details page (with comments and tags).

clip_image006

Implementing a basic shopping cart

To give another take on UI composition, we are going to implement a simple shopping cart, and we will display it in the “sidebar” zone using the MVC 2 RenderAction method.

1. Let’s first define the data model we are going to use to store the shopping cart data (we are using simple records, not content items for this simple example). Add a ShoppingCartRecord class in the Models folder:

using Orchard.Data.Conventions;using System.Collections.Generic;

namespace Orchard.Commerce.Models{    public class ShoppingCartRecord    {        public ShoppingCartRecord()        {            Entries = new List<ShoppingCartEntryRecord>();        }

        public virtual int Id { get; set; }

        public virtual int UserId { get; set; }

        [CascadeAllDeleteOrphan]        public virtual IList<ShoppingCartEntryRecord> Entries { get; set; }

    }

    public class ShoppingCartEntryRecord    {        public virtual int Id { get; set; }        public virtual ProductRecord Product { get; set; }        public virtual int Quantity { get; set; }    }}

2. Next, let’s update the HomeController class to use more services we are going to need:

using Orchard.Data;using Orchard.UI.Notify;using Orchard.Security;using Orchard.Localization;

[Themed]    public class HomeController : Controller    {        private readonly IContentManager _contentManager;        private readonly IRepository<ShoppingCartRecord> _repository;        private readonly INotifier _notifier;        public virtual IUser CurrentUser { get; set; }        public Localizer T { get; set; }

        public HomeController(IContentManager contentManager, IRepository<ShoppingCartRecord> repository, INotifier notifier)        {            _contentManager = contentManager;            _repository = repository;            _notifier = notifier;        }

Some things to note about this code:

§ “IRespository<ShoppingCartRecord> gives access to the database

§ “CurrentUser” gives access to the logged-in user

§ “T” gives access to the localization service

§ “INotifier” gives access to the notification area of the application

Now, let’s implement the “AddToCart” action…

We’ll create the cart for the user if needed, add 1 product to the list, and display a “Product added” message to the notification area of the site.

Note that in this simple example, we don’t handle anonymous users very well – there is a single shopping cart for the whole site. We also don’t support “merging” the shopping cart content when an anonymous user decides to log in after creating his shopping cart. These are more advanced applications of a shopping cart implementation that we will skip for now.

3. In HomeController, add the AddToCart action method:

public ActionResult AddToCart(int id)        {            // Retrieve shopping cart for current user

            ShoppingCartRecord cart;

            if (CurrentUser == null)            {                cart = _repository.Fetch(c => c.UserId == 0).SingleOrDefault();            }

            else            {                cart = _repository.Fetch(c => c.UserId ==                CurrentUser.Id).SingleOrDefault();            }

            // Create cart if none found

            if (cart == null)            {                cart = new ShoppingCartRecord();                _repository.Create(cart);                cart.UserId = (CurrentUser == null ? 0 : CurrentUser.Id);            }

            // Add product to cart entry            var product = _contentManager.Get<Product>(id).Record;            var entry = cart.Entries.Where(e => e.Product == product).SingleOrDefault();

            if (entry == null)            {                entry = new ShoppingCartEntryRecord                {                    Product = product,                    Quantity = 0                };                cart.Entries.Add(entry);            }

            entry.Quantity++;            _notifier.Add(NotifyType.Information, T("Added {1} to shopping cart",            entry.Quantity, product.Sku));            // Back to product list            return RedirectToAction("Index");        }

4. Finally, update the “Index.ascx” view (under Views > Home) to include a “Add to cart” column:

a. Add a “Buy” column…

<th>Buy</th>

b. And add an “Add To Cart” link…

<td><%= Html.ActionLink("Add to cart", "AddToCart", new { id= item.Id })%></td>

5. Type Ctrl-F5 to build and run the site.

NOTE: Since we created a new record class, there is a need to update the database. Go into the admin page and trigger Database Update under Site Configuration –> Dev Tools menu.

image

We now have a working “Add to cart” link next to each product in the list

We also get notification that a product has been added to the cart

image

Well that’s it! There is another section about rendering the shopping cart content on the sidebar which I will update with another post later due to some issue with the Controller rendering.

If you want to revisit back the previous past, you can go to the TOC page I created here.

Categories: Uncategorized Tags: ,

Hello Orchard 6–Composing view using different content parts

July 26th, 2010 Patrick 1 comment

This is the 6th part of my Orchard introduction. As of today I updated my source code to reflect today’s build and also because I need it for certain bug fixes. For more info about my previous posting, check out

Part 1

Part 2

Part 3

Part 4

Part 5

In part 5, we talk about composing content type with parts to import commonly used properties such as Owner and Published Date. Now we want to reused UI in our view composition. According to the original walkthrough document on how UI composition works:-

image

The idea behind UI composition is that the view of a product (in our example, the editor view in the admin panel) should be assembled from the constituent views from all the attached parts. Each part defines its own view templates that expect a specific view model type to be passed to it. The obtain these view models, the Controller action calls the BuildXxxModel methods on ContentManager. The ContentManager delegates to ContentDriver types (one for each part) to retrieve the appropriate view models for each part. The ContentManager then aggregates those into a single view model that is handed back to the Controller. What is actually passed back from the ContentDriver is a ContentPartTemplate object – the view, the model for that view, and the zone and location/position within the zone to render the part (note that the zone/position information will eventually be driven from metadata/templates instead of code).

Let’s get started

1. First of all, add reference to Orchard.Tags and Orchard.Comments

image

2. Then let’s enable the “Comments” and “Tags” part for our ProductHandler:

using Orchard.Tags.Models;using Orchard.Comments.Models;
public ProductHandler(IRepository<ProductRecord> repository)        {            Filters.Add(new ActivatingFilter<Product>(ProductHandler.ContentType.Name));            Filters.Add(new ActivatingFilter<Orchard.Core.Common.Models.CommonPart>(ProductHandler.ContentType.Name));            Filters.Add(new ActivatingFilter<CommentsPart>(ProductHandler.ContentType.Name));            Filters.Add(new ActivatingFilter<TagsPart>(ProductHandler.ContentType.Name));            Filters.Add(StorageFilter.For(repository));        }

 

For now, the association of content parts is done in code. However, eventually this will move to a metadata system that enables association of parts to items on-the-fly, using the Orchard admin panel instead of writing code to do this. This would enable our Product type to be completely independent, with no compile-time dependency on specific parts.

2. Now let’s update the “Create” method of our AdminController to create the ContentItemViewModel for the product:

public ActionResult Create(){  var product = _contentManager.New<Product>("product");   var model = _contentManager.BuildEditorModel(product);   return View(model);}

3. We also need to update the “Create.ascx” view to use the “ContentItemViewModel” and dispatch the form composition to the Orchard HtmlHelper.

<%@ Control Language="C#" Inherits="Orchard.Mvc.ViewUserControl<Orchard.Mvc.ViewModels.ContentItemViewModel<Orchard.Commerce.Models.Product>>" %><h1>    <%=Html.TitleForPage(T("Create Product").ToString()) %></h1><% using (Html.BeginFormAntiForgeryPost())   { %><%=Html.ValidationSummary() %><%=Html.EditorForModel(Model)%><fieldset>    <input type="submit" value="Create" /></fieldset><% } %><div>    <p>        <%=Html.ActionLink("Back to List", "Index") %></p></div>

4. Next, we will define a driver and template for the Product type that participates in this UI composition process.

Create a new Drivers folder and then add a new ProductDriver class (that derives from ContentItemDriver). This class is responsible for returning the appropriate view model, template, and location for the various views of a Product (in our example, the editor view):

using System;using System.Collections.Generic;using System.Linq;using System.Web;using Orchard.ContentManagement.Drivers;using Orchard.Commerce.Models;using Orchard.ContentManagement;

namespace Orchard.Commerce.Drivers{    public class ProductDriver : ContentItemDriver<Product>    {

        protected override bool UseDefaultTemplate { get { return true; } }

        protected override DriverResult Display(Product product, string displayType)        {            return ContentPartTemplate(product, "Product.Fields").Location("primary", "1");        }

        //GET        protected override DriverResult Editor(Product product)        {            return ContentPartTemplate(product, "Product.Fields").Location("primary", "3");        }

        //POST        protected override DriverResult Editor(Product part, IUpdateModel updater)        {            updater.TryUpdateModel(part, Prefix, null, null);            return Editor(part);        }    }}

This code says that the template to use for displaying the product is “Product.Fields”. Notice how we pass the “products” instance as the view model for that template. We also mention it’s going to be displayed in the “primary” zone, at the top of the zone (position=”1”).

5. Let’s now create “Product.Fields.ascx” under the Commerce > Views > EditorTemplates folder. This is essentially the same as our former “Create” view, which displayed the editors for properties for the Product type.

clip_image002

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Orchard.Commerce.Models.Product>" %><fieldset>    <legend>Fields</legend>    <%=Html.HiddenFor(model=>model.Id) %>    <div class="editor-label">        <%= Html.LabelFor(model => model.Sku) %>    </div>    <div class="editor-field">        <%= Html.TextBoxFor(model => model.Sku)%>        <%= Html.ValidationMessageFor(model => model.Sku)%>    </div>    <div class="editor-label">        <%= Html.LabelFor(model => model.Description)%>    </div>    <div class="editor-field">        <%= Html.TextBoxFor(model => model.Description)%>        <%= Html.ValidationMessageFor(model => model.Description)%>    </div>    <div class="editor-label">        <%= Html.LabelFor(model => model.Price) %>    </div>    <div class="editor-field">        <%= Html.TextBoxFor(model => model.Price) %>        <%= Html.ValidationMessageFor(model => model.Price) %>    </div></fieldset>

6. Type Ctrl-F5 to build and run the site.

Now when we click on “Create new Product” link, we see a form which contains the fields of the products, but also tags, comments and owner fields.

clip_image004

7. The last thing we need to do is re-implement the “Create” “Post” action in AdminController.cs:

[HttpPost]        public ActionResult Create(FormCollection input)        {            var product = _contentManager.New<Product>("product");            var model = _contentManager.UpdateEditorModel(product, this);

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

            _contentManager.Create(product);            return RedirectToAction("Index");        }

Note the “this” parameter, passed to UpdateEditorModel. To enable validation of the model, we need an interface between the MVC controller and the content drivers. We are going to implement this interface in the “AdminController” itself, by simply delegating the default MVC base class.

using Orchard.Localization;

namespace Orchard.Commerce.Controllers{    [Admin]    [Themed]    public class AdminController : Controller, IUpdateModel    {        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.ToString());        }

The update/validation of the model is going through the ContentManager, to all the content drivers, and then back to our AdminController. The last thing we need to do is implement the model update/validation for the “Product” part. We do that in the ProductDriver:

protected override DriverResult Editor(Product part, IUpdateModel updater){    updater.TryUpdateModel(part, Prefix, null, null);    return Editor(part);}

8. Type Ctrl-F5 to build and run the site.

We can now create a new product, including model validation!

clip_image006

Categories: Uncategorized Tags: ,

Hello Orchard Part 5–Attaching a part to content type

July 26th, 2010 Patrick No comments

One of the coolest feature in Orchard is the ability to compose different content part together to make a complete content type. This promotes composite applications e.g. the comment content part with its logic and UI can be reused in different part of the application.

Part 5 of this tutorial will shows you how to attach a Common part to the Product content type where this Common part contains properties like Published Data and Owner.

1. Add a reference to Orchard.Core

image

2. Go to the ProductRecord.cs file and update it to include these namespaces:

using System.ComponentModel.DataAnnotations;using Orchard.Core.Common.Models;

Now, let’s illustrate the power of the data composition story… We are going to add a “Common” part to the “Product” content type. The “Common” part is an Orchard extension which automatically keeps track of Owner, Container, CreationDate, etc. for content items.

Here is the definition of the ICommonAspect interface (no need to type this – it’s already defined by Orchard in the Orchard.Core.Common.Models namespace). Once we add this part to our Product type, the CommonAspect data will be saved (as a “Content Part”) with each instance of “Product”.

public interface ICommonAspect : IContent {

IUser Owner { get; set; }

IContent Container { get; set; }

DateTime? CreatedUtc { get; set; }

DateTime? PublishedUtc { get; set; }

DateTime? ModifiedUtc { get; set; }

DateTime? VersionCreatedUtc { get; set; }

DateTime? VersionPublishedUtc { get; set; }

DateTime? VersionModifiedUtc { get; set; }

}

3. Change the ProductHandler class to add a “CommonPart” (was called CommonAspect) part to the “Product” content type:

using Orchard.ContentManagement.Handlers;using Orchard.ContentManagement;using Orchard.Commerce.Models;using Orchard.Data;using Orchard.Core.Common.Models;

namespace Orchard.Commerce.Handlers{    public class ProductHandler : ContentHandler    {        public readonly static ContentType ContentType = new ContentType        {            Name = "product",            DisplayName = "Product"        };

        public ProductHandler(IRepository<ProductRecord> repository)        {            Filters.Add(new ActivatingFilter<Product>(ProductHandler.ContentType.Name));            Filters.Add(new ActivatingFilter<Orchard.Core.Common.Models.CommonPart>(ProductHandler.ContentType.Name));            Filters.Add(StorageFilter.For(repository));        }

    }}

That’s it! Now, whenever a “Product” is going to be manipulated by the application, a “CommonAspect” will go with it. Under the hood, the content manager will activate the “CommonAspect” part when “Products” are activated. The “CommonAspect” implementation will keep track of creation date, modification date and publication dates automatically for us.

3. Let’s illustrate that by displaying the “Created”, “Published” date for each product in the Index.ascx view. Add these 2 lines at the beginning of the file:

<%@ Import Namespace="Orchard.Core.Common.Models"%><%@ Import Namespace="Orchard.ContentManagement"%>

a. Add “Created” and “Published” columns:

<th>   Created</th><th>   Published</th>

b. Access to the “Created” and “Published” dates as follows:

<td>   <%= Html.Encode(String.Format("{0}", item.As<CommonPart>().CreatedUtc))%></td><td>   <%= Html.Encode(String.Format("{0}", item.As<CommonPart>().PublishedUtc)) %></td>

4. Type Ctrl-F5 to build and run in Visual Studio.

Note: If you don’t empty the database at this point, the product created until now will have no “Common” data value. Orchard doesn’t have a story for database upgrade for now. To reset the database (destroy all data for the site), delete the App_Data/Sites folder in your project. You may need to “Show All Files” in Visual Studio’s Solution Explorer before you can see this folder. After deleting the database, you’ll need to walk through the Orchard setup screen again.

Previously the tutorial would ask you to empty the database and recreate the website again. But with the latest data migration facility you need not do so. Just go to Site Configuration –> Dev Tools and trigger the Update Database command.

Notice how the table now shows created and published dates (they have been setup automatically by the content manager, stored in a “Common” aspect table).

clip_image002

Let’s look at what happens when a product instance is created. Set a debug breakpoint in “AdminController.Create” action, on the line of code that invokes _contentManager.Create(product). Type F5 in Visual Studio to begin debugging, and then create a new product using the admin panel in order to hit the breakpoint:

clip_image004

The “Product” content item has 2 parts: the Product part and the “CommonPart” part. If we look at the data maintained by the “CommonPart”, we see that everything is taken care of internally. Here is the “Product” instance after the call to “Create” of content manager:

clip_image006

Categories: Uncategorized Tags: ,

Orchard Content Type

July 26th, 2010 Patrick 2 comments

This is part 4 of my walkthrough document for project Orchard based on the document released in March 2010. Check out here for previous posts – Part 1 Hello World, Part 2 Hocking up admin page, Part 3 Working with data

What is Content Type

Orchard Content Type maybe somewhat similar to SharePoint content type conceptually but architecturally its apple and orange. According to the walkthrough document, an Orchard Content Type is:-

Rather than work with database records directly, let’s start using some of the higher-level abstractions that Orchard CMS offers. Fundamental to the Orchard CMS is the idea of multiple content types – the built-in pages and posts types are examples….

Most importantly:

…we will take advantage of it in the next section, when we explore composition of additional “parts” on the content types (the way that comments and tags are parts applied to pages and posts). Assembling the data and UI of the application from multiple types and parts allows the system to remain loosely coupled and allows installed modules to extend each others types in interesting ways.

Objectives:

1. Create a Product content type

2. Add a ProductHandler for Product type

a. Associate repository and ProductRecord type

b. Associate Product type to content type name

Follow These Steps:

1. Go to the ProductRecord.cs file and update it to inherites ContentPartRecord <Note that I removed the ID property because the base class already has one>:

using System.ComponentModel.DataAnnotations;using System.Web.Mvc;using Orchard.Data;using Orchard.ContentManagement;using Orchard.ContentManagement.Records;using Orchard.ContentManagement.Handlers;

namespace Orchard.Commerce.Models{

    public class ProductRecord: ContentPartRecord      {

        [Required]        public virtual string Sku { get; set; }

        [Required]        public virtual string Description { get; set; }

        [Required]        public virtual decimal Price { get; set; }

    }

}

2. Add a Product.cs file in the Model folder.

using System;using System.Collections.Generic;using System.Linq;using System.Web;using Orchard.ContentManagement;using System.ComponentModel.DataAnnotations;

namespace Orchard.Commerce.Models{    public class Product : ContentPart<ProductRecord>    {        public int Id        {            get { return Record.Id; }            set { Record.Id = value; }        }

        [Required]        public string Sku        {            get { return Record.Sku; }            set { Record.Sku = value; }        }

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

        [Required]        public decimal Price        {            get { return Record.Price; }            set { Record.Price = value; }        }    } }

Then create a Handlers folder and add a  ProductHandler class

image

using Orchard.ContentManagement.Handlers;using Orchard.ContentManagement;using Orchard.Commerce.Models;using Orchard.Data;

namespace Orchard.Commerce.Handlers{    public class ProductHandler : ContentHandler    {        public readonly static ContentType ContentType = new ContentType        {            Name = "product",            DisplayName = "Product"        };

        public ProductHandler(IRepository<ProductRecord> repository)        {            Filters.Add(new ActivatingFilter<Product>(ProductHandler.ContentType.Name));            Filters.Add(StorageFilter.For(repository));        }

    }}

The Product type is an Orchard content type, using ProductRecord for storage. For convenience, we’ve wrapped the properties of the record on the Product type, but this is optional, as the Product type also exposes these properties directly from its Record property, for example Product.Record.SKU. The ProductHandler is responsible for registering the content type with the system, ensuring the the Product type is activated whenever a new “Product” content item is created, and associating the IRepository<ProductRecord> for storage.

We also need to update our Commerce admin pages to use the new content type instead of the record. To do this, we will go through the IContentManager interface to query for products instead of talking to the repository directly. The ContentManager is responsible for resolving the requested content type to a handler (in this case, ProductHandler) and instantiating the type for us.

3. In AdminController.cs…

a. Change all references from “ProductRecord” to “Product”…

b. Change all references to “IRepository<ProductRecord>” to “IContentManager”…

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;

using Orchard.Themes;using Orchard.UI.Admin;using Orchard.ContentManagement;using Orchard.Data;using Orchard.Commerce.Models;

namespace Orchard.Commerce.Controllers{    [Admin]    [Themed]    public class AdminController : Controller    {

        private readonly IContentManager _contentManager;

        public AdminController(IContentManager contentManager)        {            _contentManager = contentManager;        }

        public ActionResult Index()        {            return View(_contentManager.Query<Product>().List());        }

        public ActionResult Create()        {            return View(_contentManager.New<Product>("product"));        }

        [HttpPost]        public ActionResult Create(FormCollection input)        {            var product = _contentManager.New<Product>("product");

            if (!TryUpdateModel(product))            {                return View(product);            }

            _contentManager.Create(product);

            return RedirectToAction("Index");        }    }}

4. Change the “Create.ascx” view to use “Product” instead of “ProductRecord” in the first line (the view model):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Orchard.Commerce.Models.Product>" %>

5. Change the “Index.ascx” view to use “Product” instead of “ProductRecord” in the first line (the view model):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Orchard.Commerce.Models.Product>>" %>

6. Type Ctrl-F5 to build and run in Visual Studio. And when you try to add a new product you will be hit by exception. This is because the database table schema has not been updated.

image

7. Orchard introduces a concept of data migration so that whenever an ContentType is created user will be prompted to update the database via the administration page.

Now create a DataMigrations folder and add a ProductDataMigration class

using Orchard.Data.Migration;

namespace Orchard.Commerce.DataMigrations{    public class ProductDataMigration : DataMigrationImpl    {        public int Create()        {            SchemaBuilder.CreateTable("ProductRecord", table => table                .ContentPartRecord()                .Column<string>("Sku")                .Column<string>("Description")                .Column<string>("Price")                );

            return 0010;        }    }

}

8. Hit Ctrl-F5 and go back to the admin page, you will notice a message on top of the dashboard.

image

9. Click on Site Configuration –> Features. Notice that Orchard.Commerce is in red. Click on the Update command

image

10. Surprisingly I am hit with a transaction error.

image

11. So I found a workaround by renaming the table first from Orchard_Commerce_Product to Orchard_Commerce_Product_bck

12. And I went back to click on Upgrade again. The table migrated successful.

image

13. And I can start data entry for Products.

image[8]

Categories: Uncategorized Tags: ,

Hello Orchard, Part 3–Working with Data

July 26th, 2010 Patrick 1 comment

This is the 3rd instalment of my attempts to modify and complete the original walkthrough of Orchard using the latest change set of the Orchard Framework. Check out part 1 and part 2 here.

Working with Data


Let’s now look at how to work with data. The objective for this section is to create a ProductRecord type that is persisted to the database. We’ll then update the Commerce area admin pages to be able to list and create new products.

Objectives:

1. Create a ProductRecord type that is persisted to the database

2. Add admin pages for creating and listing products

Follow These Steps:

1. Create “ProductRecord.cs” in “Models” folder

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc; 

namespace Orchard.Commerce.Models
{
     public class ProductRecord
    {
         public virtual int Id { get; set; }

         [Required]
        public virtual string Sku { get; set; }

         [Required]
        public virtual string Description { get; set; }

         [Required]
        public virtual decimal Price { get; set; }
     }
 }

 

Orchard generally favors convention over configuration, and in the example above, there are a few conventions at work. First, the *Record suffix on the class, coupled with the fact that the class lives under the *.Models namespace, tells Orchard this is a persistent class that should be backed by a database table. Second, the property named “Id” is conventionally used as the primary key for the record.

2. Add the “IRepository<ProductRecord>” to the AdminController. This is another example of using dependency injection to receive access to services (in this case, the database).

using Orchard.Data;

using Orchard.Commerce.Models;
    [Admin]
    [Themed]
    public class AdminController : Controller
    {
        private readonly IRepository<ProductRecord> _repository;

         public AdminController(IRepository<ProductRecord> repository)
        {
            _repository = repository;
        }

         //
        // GET: /Admin/
         public ActionResult Index()
        {
            return View();
        }
     }

3. Create the 2 “Admin/Create” actions (typical MVC pattern for entity creation)

public ActionResult Create()
        {
            return View(new ProductRecord());
        }

         [HttpPost]
        public ActionResult Create(ProductRecord product)
        {
            if (!ModelState.IsValid)
            {
                return View(product);
            }

            _repository.Create(product);
            return RedirectToAction("Index");
        }

Now, we are going to add the corresponding “Create” view…

4. Build the project first, so the ProductRecord type is available in the Add View dialog.

5. Right-click the Create action and choose “Add View…”

6. Select the “Create a partial view (.ascx)” option

7. Select the “Create a strongly-typed view” option and type “Orchard.Web.Areas.Commerce.Models.ProductRecord” for the View data class. Select “Create” as the View content.

image

8. In the view markup/code, change the ID field to be hidden:

<div class="editor-label">
        <%= Html.HiddenFor(model => model.Id) %>
    </div>
    <div class="editor-field">
        <%= Html.HiddenFor(model => model.Id) %>
        <%= Html.ValidationMessageFor(model => model.Id) %>
    </div>

9. Change Html.BeginForm to Html.BeginFormAntiForgeryPost

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Orchard.Commerce.Models.ProductRecord>" %>
<% using (Html.BeginFormAntiForgeryPost())   {%>
<%: Html.ValidationSummary(true) %>

10. In AdminController.cs, update the Index() method to pass the list of Products from the repository:

public ActionResult Index()
{
     return View(_repository.Table);
}

11. Delete “Views\Admin\index.ascx” file (we are going to re-create it as a “List” view).

12. In AdminController.cs, right-click the “Index()” action and chose “Add View…” to recreate the “Index” view.

a. Choose the partial view option

b. Select the strongly-typed view option, typing “Orchard.Web.Areas.Commerce.Models.ProductRecord” for the View data class.

c. Select “List” as the View content.

image

13. Open Index.ascx

d. Update the table class: <table class="items"> (so it looks nice)

14. Type Ctrl-F5 to build and run the site in Visual Studio.

15. Go to the “Manage Products” admin page

NOTE: So far we have been following the steps in the original document, which should be OK. However with Devtools module added in recent change set, the database table for Product records does not get built automatically. In fact you will get an error message if you click on Manage Products.

image

16. Login to admin module. Click on Site Configuration –> Features and enable Orchard.DevTools module

image

17. After the refresh you shall see Developer Tools under the Site Configuration menu, click on it. Then in the Dev Tools page, click on Database Migration

18. Then you are presented with only 1 menu item which is Update Database option. Click on it to start the table creation.

image

19. Once you see the “Database Updated successfully” option, go back to the Admin page.

Then click on Manage Products under the Commerce menu. And Boo Yah! You will see the manage products page rendered nicely.

image

20. You can create a product (with validation)

21. The “Index” view shows the list of product from the db:

clip_image004

22. Enter a few products to use as sample data…

Categories: Uncategorized Tags: ,

Hello Orchard Part 2

July 25th, 2010 Patrick 2 comments

Find out more about Orchard and how to create a simple Hello World module using latest change set from Codeplex from my first post here.

In my 1st port, I build a very simple module that displays “Hello World” on the front-end using the applied Orchard theme. We’ll also wire up the navigation menu to our module’s routes.

Hooking into the Admin Panel

The next thing we want to do is wire up our custom module to the admin panel, so we have a way to perform administration tasks on the back-end.

Objectives:

1. Add an admin panel page for the custom area

2. Add a menu item to the admin panel for the custom area

Follow These Steps:

1. Open up Orchard.Commerce project and right-click the “Controllers” folder and choose “Add > Controller…”

2. Type “AdminController” for the controller name and click [OK].

3. Add the following namespaces and attributes on the controller class:

using Orchard.Themes;
using Orchard.UI.Admin; 

namespace Orchard.Commerce.Controllers{
    [Admin]
    [Themed]
    public class AdminController : Controller

4. Right-click on the “Index()” method name and choose “Add View…”

5. Selected the “Create a partial view” option and click [Add]

6. Add the following HTML to the View page: <p>Commerce Area Admin</p>

7. Type Ctrl-F5 to build and run in VS.

8. Navigate to this URL in the browser: http://localhost:<port>/Admin/Commerce

clip_image002

ð Note that you will need to log in as admin before you can view this page. By convention, controllers named “Admin*” are protected from access by anonymous site visitors.

Hooking into the admin menu…

1. Add a reference to Orchard.Pages project

image

1. Add an AdminMenu.cs file to the root of the “OrchardCommerce” project. For convenience, you may copy this from another module folder (and change the namespace and area name appropriately).

using Orchard.Pages.Services;
using Orchard.UI.Navigation;
using Orchard.Localization; 

namespace Orchard.Web.Areas.Commerce{
    public class AdminMenu : INavigationProvider
    {
         public Localizer T { get; set; }
         private readonly IPageService _pageService;
         public AdminMenu(IPageService pageService)
        {
            _pageService = pageService;
        }

         public string MenuName { get { return "admin"; } }

         public void GetNavigation(NavigationBuilder builder)
        {
            builder.Add(T("Commerce"), "20",
                menu => menu
                        .Add(T("Manage Products"), "1.0",
                            item => item
                                .Action("Index", "Admin", new { area = "Orchard.Commerce" })));
        }
    }
 }

2. Type Ctrl-F5 to build and run in VS.

3. Navigate to this URL in the browser: http://localhost:<port>/Admin

clip_image004

Orchard uses dependency injection to provide services to the application. In the example above, the INavigationProvider interface derives from IDependency. Simply by including a constructor that accepts INavigationProvider as a parameter, an implementation of this interface will be provided by the application framework to this class when it is constructed. We use this interface to define a main menu item for our Commerce > Manage Products screen. In the next section, we will see dependency injection again when we use the IRepository interface to access the database.

Categories: Uncategorized Tags: ,

Hello Orchard - Creating a Orchard module using latest source code

July 25th, 2010 Patrick 5 comments

What is Orchard?

Project Orchard is the latest open source CMS project by folks in Microsoft based on ASP.NET MVC platform. It has some relationship with project Oxite which is another CMS used by the MIX event website. You can read more about Orchard from the official website here. And you can also check out the official download as well as the latest build from Codeplex. It is light weight where you can do copy-paste deployment onto shared webhosting, doesn’t require SQL Server to run yet at the same time you can add functionalities as a Orchard Module.

 

Official Download

The official download dates back to March 2010 at the time of MIX 2010. The feature sets are primitive and less composite than what’s in the roadmap. It has been 4 months since the release and the team will release a official Alpha release by end of July 2010.

Having said that, the March release comes with a walkthrough which you can follow to build a customized module for Orchard. You can check out the walkthrough here.

March 2010 release

Walkthrough Document

Video walkthrough

Latest Build

In the true spirit of open source, the Orchard team chose Mercurial instead of Team Foundation Server to be the source code host of the project. Codeplex supports both source control systems maybe because of some non-.NET or non-Windows hosted there.

In the March 2010 release Modules are actually ASP.NET MVC 2 Area where else in the latest build, they are individual ASP.NET MVC Web App. The new module design makes Orchard more suitable for composition and multi tenancy, in a way like SharePoint features.

Because of this architecture change, the walkthrough mentioned above does not work with the latest build. So in this and subsequent blog post, I will share more about creating a customized module for latest build of Orchard

Downloading latest build

To get the latest build, you either download from the source tree using TortoiseHG which is a Windows based Mercurial client (instructions here) or you can download the latest changeset from the source code page at Codeplex.

image

Whenever you download source code packages as a zip file from the Web, remember to ‘unblock’ it from the file property page else Visual Studio will give you a not trusted source warning message which can be annoying at times.

image

 

Understand the Orchard architecture

I won’t dwell too deep into this as Bertrand Le Roy wrote an extensive document titled How Orchard Works here. Architects should read this document first to understand how things work.

Accessing the latest change set

image

I downloaded the latest change set as of today and from Windows Explorer you will notice there are 2 Visual Studio solution file. Note also that it has been updated to support Visual Studio 2010 solution. You also note that there is a Windows Azure solution file here but let’s check this out in my future post.

The whole Orchard application framework is inside the Orchard folder while Orchard.Web is the ASP.NET project which can be hosted inside IIS. Let’s open up Orcahrd.sln using VS2010.

image[15]

All in all there are more than 30 projects in project Orchard with Orchard.Core, Orchard.Framework and Orchard.Web at the center of this CMS. On top of that there are some core modules which Orchard needs such as the User, Pages, and Setup modules.

Build and setup a sample site

Orchard supports both SQL Server and SQLite database but for sake of debugging and troubleshooting I will choose SQL Server. Let’s create an empty database inside SQL Server called OrchardTutorialDB in the local SQL Express instance.

image

Back to Visual Studio 2010 with the project opened, press Ctrl-F5. IE will be opened and you will see the Orchard setup page

image

At this page, you need to give a name for the website and assign a website admin account. Then click on ‘Use an existing SQL Server database’ to setup SQL Server. Key in the connection string in the following format

Data Source=.\sqlexpress;Initial Catalog=OrchardTutorialDB ;User Id=myUsername;Password=myPassword;

Note: Skip and leave the Database Table Prefix empty at the moment because of a known bug with using the prefix

image

Click ‘Finish Setup’ and a few minutes later you will see the website up and running!

image

I will normally change my theme to a more presentable one.

image

Hello Orchard - Adding a new Module

Note: from this point onwards I will reuse some of the text in the Orchard Walkthrough document.

NOTE: Step 2 to 4 and 15 to 17 are very additional steps to make the walkthrough works in the new change set.

The objective here is to build a very simply Hello World style webpage themed by Orchard with a menu item on top.

Objectives:

1. A simple custom area that renders “Hello World” on the app’s front-end

2. Views in the custom area that take advantage of the currently applied Orchard theme

3. A menu item on the front-end for navigating to the custom area’s view

Follow These Steps:

1. Right-click the Modules node in VS Solution Explorer, and choose “Add > New Project…”

image

2. In the project creation screen, choose “ASP.NET MVC 2.0 Empty Web Application”

<Very Important> On the path text box, it is default to <Orchard location>\src folder. Change it to <Orchard location>\src\Orchard.Web\Modules\ folder (Screenshot below). Else Orchard will not recognize the new module.

Finally Type “Orchard.Commerce” for the area name and click [OK].

image

3. For Orchard to discover this module, you need to add a module.txt file at the project root folder and insert the following content.

name: Commerce
antiforgery: enabled
author: Patrick Yong
website: http://patrickyong.net
version: 0.1
orchardversion: 0.1.2010.0312
description: Commerce
features:    Orchard.Commerce:
Description: Commerce.
Category: Commerce

4. Modify the web.config file accordingly. Basically I added <httphandlers> and <handlers> in <System.WebServer> for MVC routing.

<?xml version="1.0"?>
<!--  For more information on how to configure your ASP.NET application, please visit  http://go.microsoft.com/fwlink/?LinkId=152368  -->
<configuration>
<system.web>
   <!--             Set compilation debug="true" to insert debugging             symbols into the compiled page. Because this             affects performance, set this value to true only             during development.    -->
   <compilation debug="true" targetFramework="4.0">
   <assemblies>
      <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
   </assemblies>
</compilation>
<customErrors>
   <error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>    -->    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<namespaces>
   <add namespace="System.Web.Mvc"/>
   <add namespace="System.Web.Mvc.Ajax"/>
   <add namespace="System.Web.Mvc.Html"/>
   <add namespace="System.Web.Routing"/>
   <add namespace="System.Linq"/>
   <add namespace="System.Collections.Generic"/>
   <add namespace="Orchard.Mvc.Html"/>
   </namespaces>
</pages>
   <httpHandlers>
      <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   </httpHandlers>
</system.web>
<system.web.extensions/>
<!--         The system.webServer section is required for running ASP.NET AJAX under Internet        Information Services 7.0.  It is not necessary for previous version of IIS.  -->
<system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
   <modules runAllManagedModulesForAllRequests="true"></modules>
   <handlers>
      <remove name="MvcHttpHandler"/>
      <remove name="UrlRoutingHandler"/>
      <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   </handlers>
</system.webServer>
<runtime>
   <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
         <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
         <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
   </assemblyBinding>
</runtime>
</configuration>

5. Right-click the newly created “Ocrhard.Commerce > Controllers” folder, and choose “Add > Controller…”

6. Name the Controller “HomeController”

7. Right-click on the “Index()” method name and choose “Add View…”

image

8. Selected the “Create a partial view” option and click [Add]

image

9. Add the following HTML to the View page: <p>Hello World</p>

10. Add Orchard.Framework and Orchard.Themes to the project reference

image

11. Add the following namespace imports to the HelloController.cs file:

using Orchard.Themes;
using Orchard.UI.Navigation;

12. Add an [Themed] attribute to the HelloController class:

[Themed]
public class HomeController : Controller

13. Add another class to create a new Menu item, you can create a new .cs file in the project root folder or add it inside the controller class

public class MainMenu : INavigationProvider
 {
        public Localizer T { get; set; }
         public String MenuName
        {
            get { return "main"; }
        }

         public void GetNavigation(NavigationBuilder builder)
        {
            builder.Add(menu => menu.Add(T("Shop"), "4", item => item.Action("Index", "Home", new { area = "Orchard.Commerce" })));
        }
}

14. Type Ctrl-F5 to build and run in VS.

15. Login as admin (using the admin account you created during setup) and navigate to the admin page

image

16. Scroll down to look for Site Configuration menu and click on Features

image

17. Voila! If you had done everything right, you will see Orchard.Commerce as a module under the Commerce category. Now click on the ‘Enable’ button.

image

18. After a moment, message(s) will appear and to try out the feature, click on Your Site on top.

image

19. Now you notice an additional item on the top menu

image

 

10. Finally click on ‘Shop’ to Navigate to this URL in the browser: http://localhost:<port>/Commerce

image

Categories: Uncategorized Tags: , ,