MarkAFarrugia

Freelance Web Development in Malta

By

Showshappening Revamp

Hi all,

I’m sorry I’m not updating my posts lately but I am really busy developing two websites which one of them is Showshappening. Once I have some free time I will be uploading some new MVC posts and also some new features which I have learned whilst embarking on these 2 projects.

In the meantime you can give me your feedback on Showshappening :) .

CU….

By

Debugging .NET and Paypal IPN on your local machine

So basically it’s been a long time since I have written a blog post since I was very busy developing www.showshappening.com which will soon be official and which will hopefully be a successful website where users will buy tickets online. Whilst I was developing this website I realized that once I thought about writing a blog post which can be very useful to developers who are developing websites which will allow users to send money through PayPal. This blog post concerns mainly the ability to debug your own code when serving PayPal IPN responses.

As a summary the outcomes of this blog post are to

  1. Understand how to debug .NET code when using PayPal IPN using normal breakpoints, which you are familiar with, using Visual Studio on your local machine.

To follow this blog post you should have these prerequisites

  1. WebMatrix (a free Microoft tool which can host websites) which will act as our IIS. This can be downloaded from here.
  2. Have access to your internal router to route port 80 traffic to your development machine
  3. Ideally have a dyndns or no-ip account
  4. Switch off Windows Firewall to ensure that traffic is not blocked to your development machine (Do not forget to turn this on again after your fix your code issues :) )

So  let me start by giving you a basic understanding of what PayPal Instant Payment Notification(IPN) is. In essense PayPal IPN is one the techniques adopted by PayPal to notify your website that a specific PayPal payment has in actual fact been effected. This can be used for several scenarios such as the one explained underneath

  1. A business has created its own website whereby users can buy products from his/her website
  2. Users buy products from this website
  3. The business has decided to use PayPal to accept payments for products bought
  4. Money is transferred from the buyer PayPal account to the business owner PayPal account when a user checks out items in his shopping cart
  5. When a user confirms a payment through PayPal after checking out items the business owner is notified and the products are then delivered to the buyer

To meet the above requirements the developer needs to create some code which will serve PayPal reponses to ensure that a payment has been affected and thus finalizing an order. This is one of the most important parts of any application since you do not wish to end up of having a user sending payments from his PayPal account, and then not receiving his orders. Thus, as a developer your need to ensure that this code works well. That is why debugging is very important to ensure that you are performing correct operations when serving PayPal IPN responses.

When using PayPal IPN it is unfortunately a nightmare when it comes to debugging your own .NET code. This is due to the fact that PayPal IPN does not send responses to your own local machine but rather to well known URLs. So let’s see how you can actually debug your code using your Visual Studio and placing normal breakpoints on your local machine to ensure that everything works as expected before publishing your own website.

The first step you should take is to host your own website using WebMatrix. Open WebMatrix, click on Open Site and then select Open Folder As Site and choose the folder where your website files are located. A new window like the one shown in Figure 1 will be shown.

Figure 1 - WebMatrix

Figure 1 – WebMatrix

You should now click on Settings so to specifiy an address for your website which can be accessed from outside. You can also type in your external IP which your ISP providers. You can get your external IP from here. In my case I am using an internal port number of 9999 to serve incoming requests (Figure 2). Whenever you change the address of your website you should restart your site using the small icon in WebMatrix.

Figure 2 - Changing URL in WebMatrix

Figure 2 – Changing URL in WebMatrix

Now open your Router administration console so that we can forward incoming traffic to your development machine. At this point you should know your internal IP of your own development machine. In Figure 3 you can see my Router configuration window. Open the Forwarding window of your Router administration console. Unfortunately all routers have their own specific window so I cannot tell you which link you should click on in your Router configuration window to open this window. However if you take a look at Figure 3 you will note that my internal development machine IP is 192.168.2.102. I am forwarding all requests coming from port 80 (HTTP port) to port number 9999 on my development machine, which is my local website. Thus in Figure 3

  1. The Service Port are the Incoming requests coming from Port 80
  2. The Internal Port is the port which I have used in WebMatrix to serve incoming requests
  3. The IP Address is the local IP of my development machine
Figure 3 - Port Forwarding in Router

Figure 3 – Port Forwarding in Router

Once you did all the above settings you should now open your website using the URL specified in WebMatrix. In my case I can type http://myurl.com or else you can type your external IP which your ISP allocated to your machine. Your website should now open. If this did not happen ensure that

  1. You do not have Windows firewall turned on
  2. You have correctly set WebMatrix and correctly inputted the correct address inside the settings window
  3. You have correctly set up port forwarding on your router

Once your website is correctly shown from outside then we can move to the next step. Make sure you have a developer account set up in PayPal. You can create one here. Log in to PayPal sandbox environment and open up the PayPal IPN simulator from here.

Now open Visual Studio. Run your application and set a breakpoint on the code which is handling PayPal IPN, as shown in Figure 4. In Visual Studio click on Debug and then click on Attach to Process. You should find a process called IISExpress.exe. Double click on it so you attach the debugger to IIS Express.

Figure 4 - IPN Breakpoint

Figure 4 – IPN Breakpoint

Now open the PayPal IPN window and type the address of your local development machine which serves the PayPal IPN. For example in my case in Figure 5 I’m typing http://myurl.com/PayPal/PayPalIPN and type in any data your ASP.NET application is reading from PayPal IPN. Basically in this PayPal IPN window you can type the Gross amount (mc_gross field in IPN) which represents the total amount the user has paid, and the InvoiceId (invoice field in IPN) which represents the Invoice the user is paying.

Figure 5 - IPN Simulator

Figure 5 – IPN Simulator

Finally click on Send IPN in PayPal IPN simulator and you should see that the Visual Studio stops on your breakpoint and you can trace all your code using Visual Studio and hopefully ensure that everything works well in your PayPal IPN .NET code.

I hope that you found this blog post interesting…… :)

By

MVC 4 and Javascript/StyleSheets bundling

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :)

In this blog post I will cover one of the new constructs which have been introduced in MVC 4 which is bundling. Basically MVC provides a way to bundle a set of Javascript or CSS files into one single bundle.

The outcomes of this blog are

  1. Understand how ASP.NET MVC Bundles work

The prerequisities of this blog are

  1. Have some understanding of what is JQuery
  2. Have some knowledge on ASP.NET MVC

So let me start this blog. One of the main reasons why I have moved from the traditional ASP.NET to ASP.NET MVC is its tight integration with JQuery. When an ASP.NET MVC solution is created JQuery files are automatically added with the solution. You will note that the JQuery files, whenever a new solution is created, are placed in the Scripts folder. Whilst I am writing this blog the JQuery version which Visual Studio automatically adds is JQuery.1.7.1, as shown in Figure 1. You can overwrite the JQuery version by downloading the latest JQuery library from here.

Figure 1 - JQuery files in Solution

Figure 1 – JQuery files in Solution

One of the most important issues you will encounter whilst developing with JQuery is that you would have to make use of multiple JQuery libraries to meet certain objectives. Rather than adding the libraries one by one ASP.NET MVC uses what so called bundles to bundle all the similar JQuery libraries.

To show how these bundles work open the Layout.cshtml which acts as the MasterPage and which ASP.NET MVC creates in its template project, or open a MasterPage for an existing project which you have created. Scroll down to the end of the page and you should find the two lines of code shown underneath.

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

Let me first explain the first line of code shown in the above snippet. This line of code is ensuring that all the JQuery files which are contained in the JQuery bundle are rendered in HTML. Now how does Visual Studio know what is included in the JQuery bundle? You can find this information in the BundleConfig.cs which is found under the App_Start folder.

The underneath code is a code snippet of the BundleConfig file.

public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
 "~/Scripts/jquery-{version}.js"));
}

If you examine the above code you will note that the bundle is called “~/bundles/jquery” and this matches the first line of code (@Scripts.Render(“~/bundles/jquery”)) shown in the previous code snippet. This bundle includes one single JQuery file which is located under the Scripts folder as shown in line 3 and 4 in the above code snippet. Now run your project and at the end of your HomePage you should find the HTML shown in Figure 2.

Figure 2 - JQuery HTML in MasterPage

Figure 2 – JQuery HTML in MasterPage

So basically the @Scripts.Render(“~/bundles/jquery”) found in the Layout.cshtml just renders all the JQuery files found in the JQuery bundle specified in the BundleConfig.cs.

You should have noted in the above explanation that we have used the ScriptBundle class in the BundleConfig.cs to bundle Javascript files. MVC also gives you the opportunity to bundle StyleSheets and this is already done by the MVC Template project in the BundleConfig.cs. Noe that instead of the ScriptBundle the StyleBundle class is used.

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

To render the stylesheets in your page then you should use the underneath code. The above code works exactly as the @Scripts.Render. However rather then rendering JavaScript files which are located in a Javascript bundle, CSS files are rendered.

@Styles.Render("~/Content/css")

So basically in the above code snippet you are requesting .NET to render all CSS files found under the ~/Content/css bundle.

Finally let me explain what the code at line 2 in the underneath code snippet does. This code snippet was shown in a previous code snippet but I only gave an explanation for what code at line 1 does.

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

The above code snippet is found in the Layout.cshtml which acts as your MasterPage. Basically this line of code is rendering any Scripts section found in a child page which is making use of the MasterPage. For example, let’s assume that in your child page you want to use another JQuery library apart from the main JQuery library, which will be responsible for validating data. The underneath code will basically add the validation Javascript libraries found in the jqueryval bundle

@section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
}

If you run your solution and open the child page which has the above code snippet, and then open the HTML which is rendered for this page you will find the HTML shown in Figure 3. You will note that first the main JQuery library is rendered, and then there are the scripts found in the JQueryval bundle.

Figure 3 - JQuery Validation Bundle

Figure 3 – JQuery Validation Bundle

I hope you found this blog post useful and till next time take care of yourselves :) .

By

Uploading Images in ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover how we can upload an image back to our server
  2. Understand when and how we can use IF conditions using Razor syntax
  3. Display a Product Image back in our View
  4. Understand how we can use the RedirectToAction and passing data back to out controller

The prerequisites of this blog are

  1. You should have a Products table which has a specific field of type Varchar which will store the image path
  2. You should have some understanding of LINQ To Entities
  3. You should have SQL Server Express installed. You can download it from here.
  4. You should have an Images and then Products subfolder in your project where we will be saving the uploaded image

In this blog I will be writing on how you can upload an Image back to a server using ASP.NET MVC. For those of you who are familiar with ASP.NET will find that the way this is done using ASP.NET MVC is somewhat different. In ASP.NET you would use the FileUpload control which takes care of most of the functionality.

So first things first. Let’s start by modifying our Edit Product View we have created in this blog. We will be adding an HTML form tag which basically is a form which posts back to a Controller action method which saves the image back to the server, and updates the relevant product with the image path. The Controller action method’s name is UploadProductImage and will accept a ProductId parameter. The underneath code snippet is the actual code which should be placed in our ASP.NET MVC View.

<form id="productimageuploadform" action="/Products/UploadProductImage" method="post" name="productimageuploadform" enctype="multipart/form-data">
  <input id="ProductId" type="hidden" name="ProductId" value="@Model.ProductId" />
 <input id="imguploadproductimage" title="Upload a product image" type="file" name="imguploadproductimage" />
 <input title="Upload image" type="submit" value="Upload" /></form>

Let me explain the above code. In the first line I am creating a form which posts back to the Products/UploadProductImage controller method. Note that a form which will upload an image should have the attribute enctype set to multipart/form-data. If this is not set the image will not be uploaded.

In the second line I am creating a hidden HTML field which stores the ProductId so that this will be passed back to our controller method. You will note that the Controller method has a single parameter also called ProductId. MVC will then map this hidden field value to the ProductId parameter inside the Edit Product controller method, since they have the same name. Recall that in this blog we created a Controller method which returns a single Product back to our Edit View. Thus I am using Razor syntax @Model.ProductId which basically returns the ProductId which is returned from our HttpGet Edit Product controller method.

In line 3 and 4 I am just creating an HTML input file control which basically will allow the user to select an image and a submit button which actually submits back to our Controller method.

Run your application and you should have a View as shown in Figure 1. Please note that this View is a continuation of the Product View we have created in this blog.

Product Upload Image View

Figure 1 – ASP.NET MVC which lets you upload a product image.

Let’s now create code for our UploadProductImage controller method, which the HTML form we have created posts to. This code is shown underneath. Basically in this code we are saving the image back to our server and then updating the existing Product with the image path on our server.

[HttpPost]
 public ActionResult UploadProductImage(Guid ProductId)
 {
 if (Request.Files.Count > 0)
 {
 try
 {
 if (Request.Files[0].ContentLength > 0)
 {
 HttpPostedFileBase postedFile = Request.Files[0];
 string filename = System.IO.Path.GetFileName(Request.Files[0].FileName);
 string strLocation = HttpContext.Server.MapPath("~/images/products");
 Request.Files[0].SaveAs(strLocation + @"\" + filename.Replace('+', '_'));
 Models.DBProducts products = new Models.DBProducts();
 Models.Product Product = products.GetProduct(ProductId);
 Product.ProductImagePath = @"\images\products\" + filename;
 products.EditProduct(Product);
 return RedirectToAction("Edit", new { id = ProductId });
 }
 }
 catch (FormatException ex)
 {
 return Content(ex.Message);
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 return RedirectToAction("Edit", new { id = ProductId });
 }

So let me explain the code above. First of all note the method definition. The method accepts a parameter called ProductId which has the same name as our hidden field inside our HTMLform. You will be able to access the file uploaded using the Request.Files property.

On line 4 I am ensuring that there is at least one file and on line 8 I am ensuring that the file uploaded is not empty.

On line 10 I am getting the actual file uploaded as an HttpPostedFileBase class. I am then getting the filename of the file uploaded.

On line 12 I am getting the actual path where the image will be saved on the server. For those of you who do not know the Server.MapPath() basically returns the physical location on the server for a specific path. So for example, in our case we are getting the server physical path of the images/products folder. Remember that we need to transfer the file from the client pc to the server, and therefore we need to find the server physical location where the image will be saved. On line 13 we are then saving the image from the client to the server physical path using the SaveAs method. I am replacing the + sign with an _ since the + sign is not valid in a URL.

Then from line 15 to 17 I am saving the relative image path back to the database. So for example we might be saving /images/products/Image1.jpg back to our database.

On line 18 and on line 30 I am redirecting the user back to the Edit View and redisplaying the Edit Product MVC View. Note that I am passing the id parameter back to the controller. The Product should then be shown together with its new product image.

Finally let me give you part of the code to display an image on an ASP.NET MVC View. This code should be included in the ASP.NET MVC View which displays the product. I am not going to show you all the code which displays all the other Products fields, since this was covered in this blog. Rather I will only be showing the code which displays the image on our ASP.NET MVC View.

@if (!string.IsNullOrEmpty(Model.ProductImagePath))
 {
 <img src="@Model.ProductImagePath" alt="@Model.ProductDescription" title="@Model.ProductDescription" />
 }

In the above code there are some new things which I will explain. Note the IF statement using Razor syntax. Basically what I am doing is that if the Product has no image associated I am not displaying the img tag. Secondly, I am specifying the src of the Image as being the one which the ProductImagePath inside the Products table points to. Note that in these cases we append Razor code using the @ sign.

Run the application and you should end up with the an ASP.NET MVC View which resembles the one in Figure 2.

Figure 2 - Image uploaded and shown in ASP.NET MVC View

Figure 2 -Image uploaded and shown in ASP.NET MVC View

So I hope you found this blog post useful easy to follow. Till next time take care :) .

By

ASP.NET MVC 4 ViewBag and Dropdownlists

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta,a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover what is the ViewBag and how this can be used to return data back to a View
  2. Use a DropdownList to display data for a foreign key column

The prerequisites to follow this blog are

  1. You should have SQL Server Express installed. You can install it from here
  2. You should have two tables Products and Categories inside your database
  3. You should have some understanding of LINQ To Entities

This blog will explain how you can give the opportunity to a user to select a Product Category from a dropdown list, for a specific Product. In the previous blog we saw how the user had to input the CategoryId manually. This, of course, is not the ideal situation since the user would have to remember all the ids for all the Product Categories manually.

So basically, the first thing we should be doing is to create a method which returns all Product Categories from our database. This method should be included in our business class which is included in our Models folder. This code is shown underneath.

/// <summary>
 /// Gets all product categories
 /// </summary>
 /// <returns>All product categories.</returns>
 public IQueryable<Category> GetCategories()
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 return entities.Categories;
 }

Once we are finished from our business method we need to call this method from our controller method. Basically, this information should be displayed in our ASP.NET MVC View, using a DropdownList. To display this information we need to make use of the SelectListItem which represents one single dropdown option made up of the Text and the Value. The Text property is the text which the user sees in the dropdown whilst the Value is the value stored for the option selected.

Let’s assume we wish to include our DropdownList inside the Create controller method, which basically serves as the controller which adds a new product.  The underneath code is the code snippet inside our controller method which basically creates a List of SelectListItems. For each SelectListItem we are setting its Value to the CategoryId, whilst we are setting its Text to the CategoryName. This would mean that we will be storing the CategoryId inside the ProductCategory foreign key whilst displaying the CategoryName.

[HttpGet]
public ActionResult Create()
{
 List<SelectListItem> Categories = (from p in
 new Models.DBProducts().GetCategories().ToList()
 select new SelectListItem()
 {
 Value = p.CategoryId.ToString(),
 Text = p.CategoryName
 }).ToList();
ViewBag.ProductCategory = Categories;
 return View();
 }

On line 11 I will then make use of the ViewBag which is a special object to pass the List of all SelectListItems back to the respective View. The ViewBag is no more than a container of objects which can then be accessed from the ASP.NET MVC View. You can place any object in the ViewBag and then access it using from the MVC View. We are naming the ViewBag variable ProductCategory so that it would have the same name as our ProductCategory field which can be found in the Products table. Recall that in our previous blog we ensured that the fields, found inside our ASP.NET MVC view, had the same names as the table’s fields found in our database. This will enable ASP.NET MVC to map the field values to their relevant database column fields.

Now let’s concentrate on how we will display the DropdownList in our ASP.NET MVC View. This can be done by using the DropDownList helper as shown in the underneath code. You should ensure that the name given is the same as the name given in the ViewBag found in our controller method.

@Html.DropDownList("ProductCategory")

If you run your ASP.NET MVC application and navigate to the Create Product controller method you should end up with a page like the one shown in Figure 1.

Figure 1 - Dropdownlist in View

Figure 1 – How the DropDownList will be shown in your ASP.NET MVC View

The actual HTML which is created is then shown underneath.

<select id="ProductCategory" name="ProductCategory"><option value="1">Motherboards</option>
<option value="2">CPU</option>
</select>

Note that each Category SelectListItem we have created in our Controller is represented by an HTML Option. We are storing the CategoryId as the Value whilst we are showing the CategoryName back to the user.

I hope that you found this blog interesting and that you have learned how to use DropdownLists in ASP.NET MVC.

By

Adding, Editing and Deleting data using ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :) .

In the previous blog I have gone into the detail of how an ASP.NET MVC View can be used to display data. We also went into the details of how some of the ASP.NET MVC helper controls work and how they can be used.

At the end of this blog you should have an understanding of how to

  1. Create an MVC view to ADD a product
  2. Create an MVC view to EDIT a product
  3. Create an MVC view to DELETE a product

The prerequisites for this blog are

  1. Follow the previous blog where I explained how to create a View which lists all products and where for each products the user would have the possiblity to add/edit and delete products.
  2. Ensure you have a Products table inside an SQL Express table and that you have defined your LINQ To Entities model. You can follow this blog if you still haven’t done so.

So let’s start by creating the View which will add a new product. We will be creating two controller methods called Create which one will be decorated with an HttpGet used to display the View, while the other one will be decorated with an HttpPost which will be used to post the products information and adds the product to the database.

The HttpGet CreateNew method is shown underneath. You will note that this method only returns the respective View related to this controller.

[HttpGet]
public ActionResult Create()
        {
            return View();
        }

Now click the right mouse button inside the Create method and click on Add View. You should ensure that you create a strongly typed view of type Product. The ScaffoldTemplate should be Create since this View will be used to create a new product. This is also shown in Figure 1.

CreateNew Add View Template

Figure 1 – The CreateNew template which ASP.NET MVC makes available to create an ASP.NET MVC view which creates new records.

You will note that the new View which is created contains all the fields which a single Product entity has and this is shown underneath.

@model MVCForBlog.Models.Product
@{
    ViewBag.Title = "CreateNew";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CreateNew</h2>
@using (Html.BeginForm())
 {
    @Html.ValidationSummary(true)
<fieldset><legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductName)
 @Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductCategory)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductCategory)
 @Html.ValidationMessageFor(model => model.ProductCategory)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductDescription)
 @Html.ValidationMessageFor(model => model.ProductDescription)
</div>
 <input type="submit" value="Create" />
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Let me explain some new constructs which are included in this form. On the first line you have the following code @model MVCForBlog.Models.Product. This means that this View accepts a single Product instance.

On line 7 there is a tag which is Html.BeginForm. This is basically a construct which will then be rendered as a form tag which will post to the Create controller method which will then be used to add a new product and which we will be creating shortly. The HTML tag which is rendered when your MVC application runs is shown underneath

<form action="/products/Create" method="post">

On line 32 then there is an HTML submit button which will be used to submit the information on the form back to our Create controller method.

Before creating the Controller method which will be used to add a new Product we need to add the method in our business class which is located inside our Models folder. This method will actually add our product back to the database. This will be done using LINQ To Entities. This code is shown underneath and as you can see there is nothing complex which is being done. I am just actually adding a new Product instance back to the database.

/// <summary>
 /// Adds a new product back to the database.
 /// </summary>
 /// <param name="NewProduct">New product to be added.</param>
 public void AddProduct(Product NewProduct)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 entities.Products.AddObject(NewProduct);
 entities.SaveChanges();
 }

Now let’s go back to our Create (HttpPost) controller method and let’s call this newly created method as shown in the underneath code.

[HttpPost]
 public ActionResult Create(Models.Product NewProduct)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.AddProduct(NewProduct);
 return RedirectToAction("Index");
 }

Now let me explain how the above code works. As you will note the method Create accepts a Product instance parameter. This Product instance parameter will be filled from the Create View in our ASP.NET MVC project. Basically what MVC does is that it maps the Html fields to our Product entity model. So for example, if one of the Product’s field name is ProductName, and you have a textbox in your html with its Name set to ProductName, its value will be mapped to the Product’s ProductName field.

This way you can pass a whole object in the Controller method and be sure that all fields will be filled automatically. Recall that when we created the Create View we used some special ASP.NET MVC constructs such as  @Html.EditorFor(model => model.ProductName) which actually maps to our Product table.

So basically once the user clicks on Create button, in the Create view, the Product instance is passed back to our Create (HttpPost) controller method and the Product is added back to our database. The code at line 6 then basically redirects us to the Products Index controller method which actually lists all products.

Now that we have created the Controller method which creates a new product, let’s create the one which edits an existing product. Before we can create this controller, we have to create a method which returns one single Product according to a ProductId which is passed. This method should be created inside the Models folder inside our business class as shown underneath.

/// <summary>
 /// Gets one single product according to an id which is passed.
 /// </summary>
 /// <returns>One single product according to product id which is passed.</returns>
 public Product GetProduct(Guid ProductId)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 return entities.Products.SingleOrDefault(p=>p.ProductId == ProductId);
 }

Now let’s create a Controller method called Edit as shown in the underneath code which calls the method which we have created. Note that whilst in the Create controller method we are not returning any object back to the view, in this case we are returning one single product back to the View. The View then displays this product.

[HttpGet]
 public ActionResult Edit()
 {</pre>
Models.DBProducts db = new Models.DBProducts();
return View(db.GetProduct(id));
}
<pre>

Let’s create a View which our ScaffoldTemplate is Edit as shown in Figure 2.

Edit Product View

Figure 2 – ASP.NET MVC View which edits an existing product.

The Edit View MVC code is shown underneath. As you will note the code resembles the Create ASP.NET MVC View. In fact we can say that it is practically the same view with the different that this View will be used to edit a specific product rather than adding a new product.

@model MVCForBlog.Models.Product
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Product</legend>

        @Html.HiddenFor(model => model.ProductId)

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductCategory)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductCategory)
            @Html.ValidationMessageFor(model => model.ProductCategory)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductDescription)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductDescription)
            @Html.ValidationMessageFor(model => model.ProductDescription)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Test it out. Run your application, list all the products and click on Edit. You should get a window with the details of the Product you have clicked on. Our next step is to make our Edit work.

Before we create our Controller method which edits our product, we need to create the Edit method inside our business class which edits a Product instance. This code is shown underneath and this code might seem complicated for some of you. What I am doing is that I am getting the current Product from our database (line 8), attaching the existing product to our Entities instance (line 9) and then applying the new values on the existing Product (line 10). Finally I am saving the modified Product back to the database.

/// <summary>
 /// Edits a current product by getting the existing product and then applying the new values on the existing product.
 /// </summary>
 /// <param name="EditedProduct">Edited product.</param>
 public void EditProduct(Product EditedProduct)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 Product ExistingProuct = entities.Products.SingleOrDefault(p => p.ProductId == EditedProduct.ProductId);
 entities.Products.Attach(ExistingProuct);
 entities.Products.ApplyCurrentValues(EditedProduct);
 entities.SaveChanges();
}

Let’s create the Edit controller which will act as our HttpPost method. This method will accept a Product instance and than call the Edit method inside our business class to edit the Product. Finally we redirect to our Product Index to list all the existing products. The product you have edited should now have the new values. This code is shown underneath.

[HttpPost]
 public ActionResult Edit(Models.Product EditedProduct)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.EditProduct(EditedProduct);
 return RedirectToAction("Index");
}

So now what’s remaining is the Delete controller method which actually is the easiest one we will be having since we do not need to create a View for this. Let’s start by creating the method in our business class which actually deletes the product.

 /// <summary>
 /// Deletes an existing product.
 /// </summary>
 /// <param name="ProductId">Product id to be deleted.</param>
 public void DeleteProduct(Guid ProductId)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
Product ProductToDelete = this.GetProduct(ProductId);
 entities.Products.DeleteObject(ProductToDelete);
 entities.SaveChanges();
 }

In the above code I am first getting the existing product to be deleted (line 8) and then deleting the actual object from our database (line 9).

Now let’s create our Delete controller method which will accept an Id parameter which actually calls the newly created method. Basically this controller method is shown underneath. Make sure to call the parameter id because if not it will not work. In some future blog post I will also cover why this happens.

 public ActionResult Delete(Guid id)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.DeleteProduct(id);
 return RedirectToAction("Index");
}

So that’s all for this blog. You should now have a View which actually lists all the products and then the user is able to Add/Edit and Deletes an existing product.
I hope you found this blog interesting and useful… CYA soon.

By

Trial version available of Stock control available

Today I have created a trial version of my Stock control application. Please follow this link so that you would be able to view all the available features which this application makes available. I’m sure you will find loads of features which can help you out in the day to day running of your business.

Please contact me if you are interested in this application.

By

Examining the MVC View which displays data

In the previous blog post we saw how we can list data inside our views. However we did not dwell into the HTML markup which ASP.NET MVC creates when a list of items is displayed.

At the end of this blog you should have an understanding of

  1. How an ASP.NET MVC View to display data can look like
  2. Understand the HTML markup which is available to display records on an MVC View
The prerequisites for this blog are
  1. You should follow this blog to create a View which lists data back from a database

If you open the View which ASP.NET MVC created, which in our case is called Index and is located under the Views/Products folder you will find the underneath HTML markup.

@model IEnumerable

@{
 ViewBag.Title = "Index";
 Layout = "~/Views/Shared/_Layout.cshtml";
}</pre>
<h2>Index</h2>
<pre>
 @Html.ActionLink("Create New", "Create")</pre>
@foreach (var item in Model) {}
<table>
<tbody>
<tr>
<th>@Html.DisplayNameFor(model => model.ProductName)</th>
<th>@Html.DisplayNameFor(model => model.ProductCategory)</th>
<th>@Html.DisplayNameFor(model => model.ProductDescription)</th>
<th></th>
</tr>
<tr>
<td>@Html.DisplayFor(modelItem => item.ProductName)</td>
<td>@Html.DisplayFor(modelItem => item.ProductCategory)</td>
<td>@Html.DisplayFor(modelItem => item.ProductDescription)</td>
<td>@Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
 @Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
 @Html.ActionLink("Delete", "Delete", new { id=item.ProductId })</td>
</tr>
</tbody>
</table>
<pre>

From the above code you will soon realize that ASP.NET MVC is basically rendering all products as a table. Now let me explain some important constructs which are written in the above code.

From line number 1 you will deduce that this View accepts a list of Products. This would have been returned from the actual controller.

@model IEnumerable

In line number 11 you will find a special ASP.NET MVC construct which is @Html.ActionLink(“Create New”, “Create”). This basically creates a link which will take you to the Create Product’s controller method. The text displayed for the hyperlink will be Create New. This will basically take you to a page where you can create a new product.

   @Html.ActionLink("Create New", "Create")

At line number 16 you have another special MVC construct which is @Html.DisplayNameFor(model => model.ProductName) which basically displays a label for the ProductName field which belongs to the Products table.

    @Html.DisplayNameFor(model => model.ProductName)

At line number 30 a special construct @Html.DisplayFor(modelItem => item.ProductName) to display a specific input element related to the table’s field is shown. For example, if you have a String field then this construct will render as an HTML textbox, whilst if the field is a boolean then this will get rendered an HTML checkbox.

     @Html.DisplayFor(modelItem => item.ProductName)

At line number 39,40 and 41 you have 3 constructs which are very similar which will basically render as a hyperlink and will take you to the Edit, Details and Delete Product’s controller methods respectively. These controller methods will give the user the opportunity to Edit, View product details and Delete a specific product respectively.

       @Html.ActionLink("Edit", "Edit", new { id=item.ProductId }) |
       @Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
       @Html.ActionLink("Delete", "Delete", new { id=item.ProductId })

So in this blog post I explained some special ASP.NET MVC helpers and how they can help you display data. I hope you found this blog post useful. In the next blog post we will be creating the controller method which will let us Edit, Create, View Details and Delete a specific product.

By

ShowsHappening.com launched

So today I have launched a free event ticketing website on www.showshappening.com which lets you create and manage your own events. In particular this system lets you

  1. Create events
  2. Create event plans and associate them with any event
  3. Lets you create different ticket types
  4. Associate ticket type with any event plan section
  5. Specify different prices on different ticket types
  6. Different reports to see the amount of tickets which have been sold for your event
  7. Printing tickets for your event
  8. Scanning tickets at venue using any Android phone