Music Store¶
This tutorial builds an online shop that sells records of different formats. Users browse the records, look at the details of one, and add it to a cart that becomes an order. Staff manage the catalogue and the orders. It uses the Web Application template, so sign-in and user management already exist.
It is longer than Hello World and My Store, and it shows the parts those do not: inheritance from a built-in class, a many-to-many association, enumerations, operations in the business objects, and a form that carries logic. It assumes you have done Hello World and have seen the steps in My Store, which this page does not repeat.
In this tutorial you will:
- Create the application
- Model the products and the orders, with two operations
- Define roles and permissions
- Create the administrative forms
- Build the product details form, with the cart logic
- Build the home page, the cart in the master page, and the order list
Create the application¶
Open the Control Panel, choose Create, and fill in the window:
- Application name: MusicStore
- Domain: Music
- Implementation strategy: .NET Core - Angular
- Template: Web Application
The window is described in New Project.
Theme and default page¶
In the Project Explorer open Configuration and then app. On the General page, open Default Theme and choose LightTheme. Save.
On the Default Pages page, check the DefaultPage row. In this template it already points to HomePage and its Render action, which is where the shop will go. There is nothing to change.
Business objects¶
The products¶
Add a business object named ProductsBO (right-click Domain, then Add, then Empty Business Object). Add these classes with the steps from Hello World, part two:
| Class | Attributes |
|---|---|
| Category | Name (string) |
| Subcategory | Name (string) |
| Performer | Name (string) |
| Product | Name (string), Description (string), Price (decimal), Year (DateTime), Image (Collection[byte]) |
Pick Collection[byte] for Image: it is the second entry when you search the type list for byte, and it holds the picture as binary data.
Then add two enumerations with +, New Enumeration. Type the name, then each value, pressing Enter after each:
- Format: Default, CD, DVD, Vinyl, Cassette
- Release: Default, BestSeller, New, Future, WebOffer
Draw the associations, as in My Store:
- Category and Subcategory. A category has many subcategories, and a subcategory has one category. Deleting a category deletes its subcategories (CascadeDelete). Rename the attribute to Subcategories and make the Subcategory side navigable.
- Subcategory and Product. The same pattern: a subcategory has many products, a product has at most one subcategory, and deleting a subcategory deletes its products. Name the collection Products.
- Product and Performer. A product can have many performers, and a performer can appear in many products. Choose Many for both indicators. Make both sides navigable and name the attributes Performers and Products.
- Product and the enumerations. Draw a line from Product to Format, and another to Release. An enumeration has no multiplicity or delete rules: the line only adds an attribute to Product. Studio names the attributes Attribute and Attribute_1. Select each one and, in Properties, rename them to Format and Release.
The finished model:
Save.
The orders¶
Add a second business object, OrdersBO. The story is: a registered user puts products in a cart and sets quantities, submits the cart, and an employee moves the order through its statuses.
User. Studio's template already has a class for users, ApplicationUser, with everything needed for signing in. Add a class named User and, in Properties, open Base Class and choose ApplicationUser.
The new class inherits all the attributes of ApplicationUser, and its identity becomes UserName. Buyers and employees will both be *User*s. Collapse the class with the arrow at its title to keep the diagram readable.
Status. Add an enumeration Status with the values Initial, Submitted, InProgress, Billed, Sent and Paid.
Order and OrderedProduct. Add the class Order with the attributes Timestamp (DateTime) and Status (Status; type Status in the list, and pick it above WorkflowStatus). Add OrderedProduct with Quantity (int). Give Quantity an Initial Value of 1, and make it required, in the attribute's Properties.
Product, as a shadow class. Product lives in ProductsBO, so bring it in with +, New Shadow Class, and select Product.
Draw three associations:
| Association | Rules |
|---|---|
| User and Order | A user has many orders (name the attribute Orders), and an order has one user. Deleting a user deletes the orders (CascadeDelete). |
| Order and OrderedProduct | An order has many ordered products (name the attribute Products), and each belongs to one order. Deleting an order deletes its lines. |
| OrderedProduct and Product | An ordered product has one product, and a product can be in many ordered products. A product that is in an order cannot be deleted (Restricted). |
Use Auto Layout to arrange the diagram, then save.
Two operations¶
Some rules do not fit in a diagram. Add them as operations. Select a class, open the Operations tab at the bottom, click + and choose New Operation. The editor opens with a stub. Replace it with the code below and save. See Operations.
A product can be deleted only if no unpaid order contains it. On the Product class:
function bool CanBeDeleted()
{
bool hasOrders =
(Domain.OrderedProduct.GetAll().First(x => x.Order.Status != Domain.Status.Paid && x.Product.Id == this.Id) != null);
return !hasOrders;
}
Finding the cart. The cart is the signed-in user's order with the status Initial. A static operation on the Order class returns it, and creates it when asked to:
static function Domain.Order GetOngoingOrder(bool createIfNotExists)
{
Domain.Order ongoingOrder =
Domain.Order.GetAll().First(x => x.Status == Domain.Status.Initial && x.User.Email == AppLib.Session.GetCurrentUser().Email);
if (createIfNotExists && ongoingOrder == null)
{
ongoingOrder = Domain.Order.Create();
ongoingOrder.Status = Domain.Status.Initial;
var email = AppLib.Session.GetCurrentUser().Email;
var user = Domain.User.Find(x => x.Email == email).First();
if (user == null)
{
throw BusinessException.Create("User [" + email + "] not found! Cannot instantiate a new Order.");
}
ongoingOrder.User = user;
}
return ongoingOrder;
}
The operation's name in the list is updated after you save.
Roles and permissions¶
Open Configuration, app, Security. As in My Store, part two, add the permissions and the roles, and give the roles their permissions.
| Permission | Description |
|---|---|
| ManageData | Can manage categories, subcategories, products and performers |
| CreateOrder | Can create a new order |
| EditOrder | Can edit an existing order |
| DeleteOrder | Can delete an order |
| AddProductToOrder | Can add products to an order |
| EditProductInOrder | Can edit the products in an order |
| DeleteProductFromOrder | Can remove products from an order |
| Role | Permissions |
|---|---|
| Administrator | All of them, together with the ones it already has |
| Clerk (works in the store, can handle orders) | EditOrder, DeleteOrder, AddProductToOrder, EditProductInOrder, DeleteProductFromOrder |
| Customer (a registered user who buys) | CreateOrder, EditOrder, AddProductToOrder, EditProductInOrder, DeleteProductFromOrder |
Once an order is submitted, a customer should no longer change it. That rule is code in the controllers and the validations, not a permission.
The administrative forms¶
For each of Category, Subcategory, Performer and Product, right-click the Forms folder, choose Add, Form, Data Entry and List Form, and select the class. Leave the names and the menu item as they are, as for the Product wizard below. Each class gets a form and a list.
For each list and form, open the Controller, select each action, uncheck Available To All Authenticated, and choose the permission ManageData. See Controller. Only people with that permission can now open the forms, so only administrators do.
What Studio generates for the product¶
Open ProductForm. The wizard has already done much of the work.
In the DataSets panel it created three datasets: FormatDataset and ReleaseDataset, one for each enumeration, and SubcategoryDataSource, which fetches the subcategories.
In the form, Format and Release are already dropdowns bound to Product.Format and Product.Release. The subcategory is shown through a Select Subcategory button that opens a list, and the performers are an editable table.
Refine it:
- Required and formats. Check Required on Name and Price, and give Price a value format with two decimals. See Hello World, part three and My Store.
- A dropdown for the subcategory. Delete the subcategory panel. Drag SubcategoryDataSource from the DataSets panel onto the form and choose Drop Down. In Display & Value Options set Display Member to Name, and set the Model Binding to Product.Subcategory.
- An image. Add an Image control with Type set to Bound, Binding Type to DataBaseBinary, and Model Binding to Product.Image.
- Performers from a list. Instead of typing a name each time, add a dataset from an operation on Performer, drop it onto the Performers panel as a Data Picklist with Allow multiple selection, bound to Product.Performers, and switch off adding and deleting rows in the table.
- A warning with no performer, and a Delete button that follows the rules. Add a Data Validation of type Warning with
return Model.Product.Performers.Length == 0;. Add a CanBeDeleted property of type bool to the form's model, set it in the entry actions (AddProduct and EditProduct) withModel.CanBeDeleted = Model.Product.CanBeDeleted();, and add a Conditional Formatting with the conditionreturn !Model.CanBeDeleted;that disables the Delete button. See Logic.
The user form¶
The template's ManageUser form manages ApplicationUser. To manage your own User class, open it, change the type of the ApplicationUser property in its model to User, and change the line in the NewUser action that creates the user to Model.ApplicationUser = Domain.User.Create();.
The product details form¶
This form shows one product, tells a customer whether it is already in the cart, and adds it. It is opened from the home page.
Add an Empty Form named ProductDetails. In the Master page list, choose MasterPage. The template offers only MasterPage and MasterPageSignIn.
The model¶
In the Model panel add three items:
- Product, with +, New Domain Property, and the class Product
- Quantity, with +, New Interface Property, of type int
- Added, with +, New Interface Property, of type bool
The controller¶
An empty form has one action, Index, which is its entry point. Change its signature so that the id of a product can be passed in, and fill in the model:
function void Index(int id)
{
Model.Title = LocalResources.RES_PAGETITLE_Index;
//Find the Product we are showing and use it to fill the Model
Model.Product = Domain.Product.GetByKey(id);
//Correct the Quantities, if needed
Controller.CorrectQuantity.Execute();
//Check whether an Order has already been created for this User
Domain.Order ongoingOrder = Domain.Order.GetOngoingOrder(false);
if (ongoingOrder != null)
{
//Check whether the Order contains the Product we are showing
Domain.OrderedProduct orderedProduct = ongoingOrder.Products.First(x => x.Product.Id == Model.Product.Id);
if (orderedProduct != null)
{
Model.Added = true;
Model.Quantity = orderedProduct.Quantity;
}
}
}
Add three more actions. Select the + in the list of actions and click New Controller Action, then change its Name in Properties to match the function you paste in. Studio shows the name of the action, not the name in the code, so the two must agree.
CorrectQuantity keeps the quantity at 1 or more. Leave its properties as they are:
function void CorrectQuantity()
{
if (Model.Quantity == null || Model.Quantity < 1)
{
Model.Quantity = 1;
}
}
AssignQuantity changes the quantity by an amount. Uncheck Available To All Anonymous and Available To All Authenticated, and choose the permission AddProductToOrder:
function void AssignQuantity(int quantity)
{
Model.Quantity = Model.Quantity + quantity;
Controller.CorrectQuantity.Execute();
}
AddToCart does the real work. Uncheck both availability boxes, and choose CreateOrder and AddProductToOrder:
function void AddToCart()
{
//Either fetch the "ongoing" Order of this User, or create a new one
Domain.Order ongoingOrder = Domain.Order.GetOngoingOrder(true);
//Either fetch the ordered Product, or create a new one
Domain.OrderedProduct orderedProduct = ongoingOrder.Products.First(x => x.Product.Id == Model.Product.Id);
if (orderedProduct == null)
{
orderedProduct = Domain.OrderedProduct.Create();
}
//Assign the Product to this Order and set its Quantity
orderedProduct.Product = Model.Product;
orderedProduct.Quantity = Model.Quantity;
//Add the Product to the Order
ongoingOrder.Products.Add(orderedProduct);
//Save everything
ongoingOrder.Save();
//Mark the Product as Added, for UI reasons
Model.Added = true;
}
After you save, validate the form. The Validation panel at the bottom should report no errors, as above. If it says that the controller does not contain a definition for CorrectQuantity, an action still has its default name.
The view¶
Build the view from the model, as in Hello World, part three. Drag the attributes of Product onto the form and change them with Change To:
- Image: an image control, Type Bound, Binding Type DataBaseBinary, read only, height 250
- Name: a label
- Year: a label named YearLabel, filled by a calculated expression
- Price: a label with the value format $1,000.23
- Description: a label
- Quantity: a text box with Update binding while typing, mask integer, maximum length 5, and CorrectQuantity as its On Change action
- two icons, minus and plus, with AssignQuantity as their On Click action and the action parameters -1 and 1
- a button, with AddToCart as its On Click action, and a label inside it named AddToCartLabel
Then add the logic, as in Logic:
- A Conditional Formatting with the condition
return Model.Added;. Its Then part disables the quantity text box and the button, and hides the two icons. Create the reverse action. - A Calculated Expression applied to AddToCartLabel:
if (Model.Added) { return "Added!"; } else { return "Add to Cart"; } - A Calculated Expression applied to YearLabel:
return "(" + Model.Product.Year.Year() + ")";
The home page¶
The template's HomePage, in the APP_Default Pages folder, shows welcome text and a Learn more button.
Delete its content and build the store in it.
Model. A collection of Product named Products, plus four filter items: FilterByRelease (Release), FilterByFormat (Format), FilterByName (string) and FilterByPerformer (string). Create FormatDataSet and ReleaseDataSet from the enumerations, as the wizard did for ProductForm.
Controller. In Render, load the products:
Add Filter:
Model.Products = Domain.Product.GetAll();
if (!string.IsNullOrWhiteSpace(Model.FilterByName))
{
Model.Products = Model.Products.Where(x => x.Name.Contains(Model.FilterByName, true));
}
if (!string.IsNullOrWhiteSpace(Model.FilterByPerformer))
{
Model.Products = Model.Products.Where(x => x.Performers.Any(y => y.Name.Contains(Model.FilterByPerformer, true)));
}
if (Model.FilterByRelease != Domain.Release.Default)
{
Model.Products = Model.Products.Where(x => x.Release == Model.FilterByRelease);
}
if (Model.FilterByFormat != Domain.Format.Default)
{
Model.Products = Model.Products.Where(x => x.Format == Model.FilterByFormat);
}
and ClearFilters:
Model.Products = Domain.Product.GetAll();
Model.FilterByFormat = Domain.Format.Default;
Model.FilterByRelease = Domain.Release.Default;
Model.FilterByName = "";
Model.FilterByPerformer = "";
View. Use a layout with two columns, a narrow one for the filters and a wide one for the products. In the wide column, bind a table to Products with a single cell that holds the name, the image, the price and a More button. Set the button's On Click (and the cell's) to open ProductDetails, action Index, with the action parameter Table_CurrentItem.Id, rendered in a Modal Dialog. In the narrow column, drop FilterByName and FilterByPerformer, the two datasets as dropdowns bound to FilterByFormat and FilterByRelease, and the buttons Search (Filter) and Clear (ClearFilters).
The cart in the master page¶
Open MasterPage in the APP_Master Pages folder.
Model. TotalItems (int) and TotalAmount (decimal).
View. In the header, add a small table with two labels bound to TotalItems and TotalAmount, and a shopping-cart icon.
Controller. Add RefreshCart, available only to the permissions CreateOrder, EditOrder and EditProductInOrder:
try
{
Domain.Order ongoingOrder = Domain.Order.GetOngoingOrder(false);
if (ongoingOrder != null)
{
Model.TotalItems = ongoingOrder.Products.Sum(x => x.Quantity);
Model.TotalAmount = ongoingOrder.Products.Sum(x => x.Product.Price * x.Quantity);
}
}
catch Exception x
{
DebugLib.Logger.WriteErrorLine(x.Message);
DebugLib.Logger.WriteErrorLine(x.StackTrace);
}
and call Controller.RefreshCart.Execute(); from the master page's entry action, so the cart is refreshed on every page. A Conditional Formatting with the condition return Model.TotalItems != null && Model.TotalItems > 0; shows the cart table, with a reverse action that hides it. Style the table in the LightTheme with a custom CSS class, as described in Theme Editor.
The orders¶
Create the Data Entry and List Form for Order, as for the other classes. In OrderList, show orders only to signed-in users: keep Available To All Authenticated on its entry action. Then restrict what a customer sees, in the dataset's Filtering code:
//Find the logged in user, based on his/her e-mail
Domain.User currentUser = Domain.User.GetAll().First(x => x.Email == AppLib.Session.GetCurrentUser().Email);
//See whether he/she is a Customer
bool isCustomer = currentUser.Roles.First(x => string.Compare(x.Name, "Customer") == 0) != null;
//If yes (Customer) show only this User's Orders
if (isCustomer)
{
return DataItem.User.Id == currentUser.Id;
}
//In all other (Authenticated) cases, show all records
return true;
You can copy controls and actions from one form to another. Take what you need from ProductDetails for the order form.
Build and run¶
Save, validate and build. Create the administrator as described in Create an Administrator Account, sign in, and fill the catalogue through the administrative forms. Then create a customer, give it the Customer role, and try the shop.
















