Home > .NET, ASP.NET MVC, Developing Using CodeFluent Entities, Entity Framework, Pet Shop Reloaded > [Pet Shop Reloaded] Using the generated code – Part 1

[Pet Shop Reloaded] Using the generated code – Part 1


In this article, we will talk about using the code generated by CodeFluent Entities and Entity Framework. On the first part of this article we will focus on using the code generated by CodeFluent Entities then on an upcoming article we will see how to use the code generated by Entity Framework and the differences between the two approaches.

Use of CodeFluent Entities generated code

In order to use the code generated by CodeFluent Entities do not forget to add a reference to our class library project which contains the generated files as well as a reference to the “CodeFluent.Runtime” and the “CodeFluent.Runtime.Web”. Those DLL can be found in the installation directory of CodeFluent Entities, by default in “C:Program Files (x86)SoftFluentCodeFluentx64”.

First of all, we need to modify the “Web.config” file according to the screenshot below to add our connection string, add the generated blob handler in the “HttpHandler” section and register membership and role providers generated by CodeFluent Entities which are based on the AspNet membership and role providers.

9

In order for our blob handler to work we need to add a new route to be ignored in our “RouteConfig.cs” file as it is showed in the code below.

 routes.IgnoreRoute("{handler}.ashx");

Once our “Web.config” file is set up, our web application is able to reach our database, display images stored in, and use generated providers.

We are now able to create a controller and a view associated to this controller to show how it works.

Therefore, I will create a “CategoryController” containing an “Index” ActionResult method which will use our custom method to load products by their category name.

Once our “Web.config” file is set up, our web application is able to reach our database, display images stored in, and use generated providers.

We are now able to create a controller and a view associated to this controller to show how it works.

Therefore, I will create a “CategoryController” containing an “Index” ActionResult method which will use our custom method to load products by their category name.

[HttpGet]
public ActionResult Index(string name)
{

ProductCollection products = ProductCollection.LoadByCategoryName(name);

if (products != null && products.Count != 0){

ViewBag.CategoryName = name;

return View(products);

}

else if (products != null && products.Count == 0){

ViewBag.CategoryName = "No such category";

return View(products);

}

else

return RedirectToAction("Index", "Home");

}

As you can see in the code above, we are getting all the matching products from our database and we returning this ProductCollection to our view.

Before going further, we will take a look to what was generated inside this “ProductCollection” class focusing on the “LoadByCategoryName” method.

[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]

public static PetShopReloaded.ProductCollection LoadByCategoryName(string category)

{

PetShopReloaded.ProductCollection ret = PetShopReloaded.ProductCollection.PageLoadByCategoryName(int.MinValue, int.MaxValue, null, category);

return ret;

}

public static System.Data.IDataReader PageDataLoadByCategoryName(CodeFluent.Runtime.PageOptions pageOptions, string category)

{

if ((category == default(string)))

{

throw new System.ArgumentNullException("category");

}

CodeFluent.Runtime.CodeFluentPersistence persistence = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName).Persistence;

persistence.CreateStoredProcedureCommand(null, "Product", "LoadByCategoryName");

persistence.AddParameter("@category", category);

if ((pageOptions != null))

{

System.Collections.IEnumerator enumerator = pageOptions.OrderByArguments.GetEnumerator();

bool b;

int index = 0;

for (b = enumerator.MoveNext(); b; b = enumerator.MoveNext())

{

CodeFluent.Runtime.OrderByArgument argument = ((CodeFluent.Runtime.OrderByArgument)(enumerator.Current));

persistence.AddParameter(string.Format("@_orderBy{0}", index), argument.Name);

persistence.AddParameter(string.Format("@_orderByDirection{0}", index), ((int)(argument.Direction)));

index = (index + 1);

}

}

System.Data.IDataReader reader = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName).Persistence.ExecuteReader();

return reader;

}

CodeFluent Entities automatically generates “LoadBy” methods in collection classes for each entity relationship. For example, in the “ProductCollection” class we have a “LoadByCategory” method, as a Product has a relation with Category. We have also defined a “LoadByCategoryName” method to meet our specific needs. This method was generated using CFQL which is a platform independent language (https://blog.codefluententities.com/?s=cfql).

image

You can see that the code generated by CodeFluent Entities is clear and intelligible. Plus, if your business needs requires something really specific you can still extend what was generated by CodeFluent Entities since all the classes generated are partial classes. Therefore, you can focus on what matter for you and your application and not on the plumbing code.

CodeFluent Entities also generates methods to create, modify and delete data. Regarding creation or modification, a “Save” method is provided. This method will either save modifications made to an object or create this one if it doesn’t exist and it can be used as shown in the code sample below.

//Creation sample
Product product = new Product() { Name = "Demo" };
product.Save();

//Update sample
Product product = Product.Load(MyProductId);
product.Save();

For deletion, a “Delete” method is provided by CodeFluent Entities, a sample is shown below.

//Delete sample
Product product = Product.Load(MyProductId);
product.Delete();

CRUD methods are generated by default by CodeFluent Entities for all entities.

Taking for example the view where we show our items, we just want to display the content of the “ProductCollection” we passed from our controller. Therefore, we are creating a view which have a model type of “ProductCollection”. This view also uses the layout of the web application. Since we have passed a collection we need an enumerator, in this case we are using a “foreach”, to display its content. We are also adding some style to make it look nicer.

@model PetShopReloaded.ProductCollection

@{

Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2 style="color: #444444;">@ViewBag.CategoryName</h2>

@foreach (var item in Model) {

<a href="@Url.Action("Index", "Product", new { item.Category.EntityDisplayName, item.Name })">

<p>@item.Name</p>

<img id="@item.Id" src='@(Request.ApplicationPath + CodeFluent.Runtime.Web.UI.BinaryLargeObjectHttpHandler.BuildUrl(null, CodeFluent.Runtime.Web.UI.WebControls.BinaryLargeObjectUrlType.Image, "PetShopReloaded.Product", "Product_Image", null, null, null, null, null, -1, -1, 0, new object[] { item.Id }))' style="width: 100%; height: 200px; margin:0; padding:0;"/>

<p style="text-align:justify; width: 278px; padding: 6px; height:35px; margin: 0; font-size: 9pt;">@item.Description</p>

</a>

}

As you can see, the “src” property of the “img” tag isn’t a simple variable. Since our images are stored in the database as BLOB’s as we said earlier we need an http handler. This BLOB handler was also generated by CodeFluent Entities.

public partial class HttpHandler : CodeFluent.Runtime.Web.UI.BinaryLargeObjectHttpHandler

{

private CodeFluent.Runtime.CodeFluentContext _context;

public override CodeFluent.Runtime.CodeFluentContext CodeFluentContext

{

get

{

if ((this._context == null))

{

if ((this.EntityClrFullTypeName == "PetShopReloaded.Item"))

{

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

return this._context;

}

if ((this.EntityClrFullTypeName == "PetShopReloaded.Product"))

{

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

return this._context;

}

this._context = CodeFluentContext.Get(PetShopReloaded.Constants.PetShopReloadedStoreName);

}

return this._context;

}

}

public override CodeFluent.Runtime.BinaryServices.BinaryLargeObject LoadBinaryLargeObject(System.Web.HttpContext context, string propertyName, object[] identifiersValues)

{

if ((this.EntityClrFullTypeName == "PetShopReloaded.Item"))

{

PetShopReloaded.Item Item = PetShopReloaded.Item.Load(((int)(ConvertUtilities.ChangeType(identifiersValues[0], typeof(int), -1))));

if ((Item == null))

{

return null;

}

if ((propertyName == "Item_Image"))

{

return Item.Image;

}

}

if ((this.EntityClrFullTypeName == "PetShopReloaded.Product"))

{

PetShopReloaded.Product Product = PetShopReloaded.Product.Load(((int)(ConvertUtilities.ChangeType(identifiersValues[0], typeof(int), -1))));

if ((Product == null))

{

return null;

}

if ((propertyName == "Product_Image"))

{

return Product.Image;

}

}

return null;

}

}

Remembering the model of our application you will notice that this generated BLOB handler will be able to handle image from “Product” and “Item” tables, which also are the only entities where we defined properties of type “image”. Also you can check-out the Blob http Handler article for more information.

To conclude, we can say that CodeFluent Entities provides ready-to-use code for you developers allowing you to focus on the application you are working on.

NB. For our application Pet Shop Reloaded we have used the generated BOM classes in a Web context (ASP .NET MVC), but know that you can also use it in other contexts like a WPF or a Windows Forms application.

Cheers,

The SoftFluent Team.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s