Generate Better Code, Faster!

Code Generation Are you or your developers writing stored procedures by hand? Are they creating duplicate CRUD (Create Read Update Delete) logic in multiple places? If so, you should consider a code generator.

Advantages of using a Code Generator

The benefits of using a code generator, such as the PDSA Haystack Code Generator to generate your data access logic are huge! If you are not using one, you need to ask yourself why? If the answer is because you think no one else can write code the way you can, that is not a good enough reason. When you consider how long it takes you to create, test and debug data access code, and how much time you put in when the schema of a table changes, you will soon find out that you are wasting a lot of time. The major reasons for using code generation are as follows:

  • Generation of INSERT, UPDATE and DELETE statements
  • Generation of stored procedures to do INSERT, UPDATE and DELETE
  • Bullet proof code for doing the Create, Read, Update, Delete (CRUD) logic
  • Ability to regenerate CRUD classes if schema changes
  • Consistency of code from one application to another
  • Moves SQL out of the UI tier and into a middle tier where it belongs
  • Moves the dependence on a particular database provider out of the UI
  • Reduces code complexity in the UI layer
  • Ability to map columns to properties in a class
  • Provide IntelliSense of tables, stored procedures, views and columns
  • Provides strong-typing of data in one location
  • Ability to customize templates to fit "your" style
  • Abstracts and encapsulates all data access code
  • Ability to separate programmers working on UI and data access

How to Pick a Code Generator

Before you start using a code generator you need to find one that allows you to do all of the things listed above. Be sure you can quickly and easily modify the code that is generated. In addition looks for one that supports generating multiple UI layers such as WPF, Angular, MVC, etc. The ability to generate a SOA layer such as Web API calls or WCF is an added bonus. 

Summary

How you create your CRUD logic needs to be thought out just as much as how you design the rest of your application architecture. Making many small classes/methods and then combining those together produces much more robust and maintainable code. Sure you end up with more classes, but these can be move to other assemblies so you don’t have to see all those files. You will definitely benefit in the long run. Using a code generator can really help speed up the development and ensure quality when developing the CRUD logic for your database application.

There are several code generators available for you to use. PDSA has the Haystack Code Generator (www.pdsa.com/haystack). The Haystack Code Generator does support all of the items listed above including the ones listed in how to pick a code generator.

Visit www.pdsa.com/haystack to learn more about Haystack and to download a free trial version.

Click here to read a special report on what code generation can do for you.

The Journey from MVC to Angular

MVC to Angular Paul Sheriff has just released an exciting new course called The Journey from MVC to Angular. Check it out at http://bit.ly/2a3wVNU

Do you want to learn how to move from MVC step-by-step to AngularJS? This course will show you how to do just that. Learn to slowly replace your Razor code with client-side code that is much more efficient. Moving to client-side can give you incredible performance gains on your web pages. If you have ever wanted to learn this exciting technology, now is the time with this new course.

Head on over to Pluralsight, sign up, and start watching the course today!

Shift Your KPI's to a Mobile Platform

Mobile Web Apps Is your boss asking you to make sure all your web applications look good on a mobile device? Is he looking for all his Key Performance Indicators (KPI) for his business to be displayed on his phone? If so, then you are ready to step up to HTML5, Angular, and Bootstrap. These technologies make it easy to create the responsive web application your boss wants. No need to create a native mobile app for applications like these. A mobile web application works just fine.

Like most technologies, there is a little bit of a learning curve, but that is where PDSA can help you. We have already built a ton of mobile web applications, so we can get your jumpstarted right away. Let us help you get started and you can work with us side-by-side so you learn the correct way to build responsive web applications.

Contact PDSA Today

For a complimentary assessment of your particular needs, call PDSA at (714) 734-9792 and ask for David Lefort or Michael Krasowski. We are happy to be of assistance.

Application Performance Affects your Business

Performance If your application runs slow then your users and/or customers are unhappy. This will directly affect your bottom line. There are many reasons for performance bottlenecks. We have time-tested procedures to help you find these bottlenecks and resolve them.

Do you know the 59 areas that most affect your applications performance?

PDSA has a checklist of over 59 of the most common performance-robbing code in applications. We help you find these areas and give you recommendations for fixing each and every one. After our performance review we present back to you:

Findings: The bottlenecks found in your application.

Reasons: The reason why an item steals performance from your application.

Recommendations: Our recommendations describing steps needed to improve or correct your application.

Remediation: For an additional fee, PDSA can help you implement the recommendations.

Here is a very small sample of our checklist:

  • Use Angular instead of Razor
  • Inefficient SQL Queries
  • Inappropriate use of Entity Framework
  • Incorrect usage of ADO.NET
  • Garbage collection usage
  • Incorrect use of variables
  • Method refactoring

SQL Usage

We identify and find areas in your application where SQL may have been used inappropriately, or should have been used instead of code.

ADO.NET / Web API / Entity Framework

There are many ways to use ADO.NET, WCF Services, Web API, Entity Framework and other data access technologies. Choosing the most efficient method can greatly speed up your application. Our experts point out where improvement is needed in those areas.

Streamlining Method Calls

The correct use of methods in classes is vital for performance in your applications. Sometimes, just a little re-factoring of code can create a well-performing application.

Get a PDSA Performance Audit Today!

PDSA can give your application a professional performance audit and teach your programmers where to find performance bottlenecks. Contact us today for a free consultation. Or call us at (714) 734-9792 and talk to David Lefort (ext. 222) or Michael Krasowski (ext. 223).


Offshore is not the Bargain You May Think It Is

Offshore Where are my Savings? Most people think you can save over 75% by developing applications offshore. The reality, as many studies have shown, is almost no savings at all. The savings of that low hourly rate are quickly eaten up in bad coding, not getting what you want, and your time managing those offshore people. This article explores the pitfalls of offshoring software development.

Be Careful What You Send Off Shore Almost every article you read about companies sending projects offshore hoping to save money end up with higher costs than anticipated, missed milestones and inadequate quality. Add it all up and you are much better off doing your project here.

Read our special report entitled Offshore is not the Bargain You May Think

Complimentary Webcast: Replace MVC Table with Angular

On June 30, 2016 at 10:00am PST watch as Paul D. Sheriff presents a step by step introduction to adding Angular to an MVC application. You will learn how to replace server-side razor code that builds an HTML table, with the Web API and Angular to build the same HTML table. You will seen how Angular can help speed up your web applications and how easy it is to use this popular client-side framework.


There is no experience with Angular needed to attend. To sign up, please contact David Lefort at Davidl@pdsa.com or call him at (714) 734-9792 x222.

Best Ways to Reduce Software Bugs

Reduce Bugs

Recently I had a mentoring client of mine ask me, what he thought was a simple question. “How do I make sure I don’t have bugs in my code?” That seems like such a simple question, but as we all know, there is no single answer to this question, if any answer at all. After all, we are all human, and we make mistakes. However, I did try to give him a little bit of advice from things that I have learned over the years. In this special report, I exam some of the ways to avoid bugs in our applications.

Read our special report entitled Best Ways to Reduce Software Bugs.

Things You Need to Know to Survive any Project

AngularWe have been involved in project management related activities for over 30 years. Our special report is a collection of things you need to know to help you survive any project. This list is not exhaustive, but has many important recommendations that you can begin using today.

We have divided the discussion into 5 key areas: customer, people, process, technology and communication. All of these areas are closely integrated in any project, and the glue that holds them all together is you.

Read our special report entitled Project Manager's Survival Guide or Deliver On-Time and On-Budget.

Call the Web API from Angular

This is the 3rd blog post in our series on Angular. The first part entitled Get Started with Angular shows you how to add Angular to a project. The second part, Build Lists of Data Using Angular, showed you how to build lists of data using hard-coded arrays of object literals. You should read those two blog entries first if you are not familiar with adding Angular to a project, don’t know what a module or a controller is, or want to understand basic data binding.

In this blog post, you will take the product page with the HTML table and call a Web API to retrieve product data. The data returned from the Web API builds the HTML table of products using the ng-repeat directive.

To prepare for calling a Web API from your Angular controller, you need to do a little setup. For purposes of this blog post, you will be doing the following things.

  1. Build Product classes to hold product data
  2. Add a Web API Controller to your Project
  3. Ensure you have configured ASP.NET to use the Web API
  4. Call the Web API from Angular

Build Product Classes

Instead of using JavaScript object literals to populate an HTML table, you want to retrieve a set of objects from some data store on a server. Web API will take one of your classes and serialize it into a JSON object. To start, create a class named TrainingProduct that contains all of the properties to represent a product object. Create the class shown below in your web project.

public class TrainingProduct
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public DateTime IntroductionDate { get; set; }
  public string Url { get; set; }
  public decimal Price { get; set; }
  public int CategoryId { get; set; }
}

Next, build a class named TrainingProductManager that is responsible for building a collection of TrainingProduct objects. You could use the Entity Framework, Haystack or any other data layer you want to retrieve data from a Product table in a database. To keep things simple in this post, I am just going to create some mock data as shown in the code below.

public class TrainingProductManager
{
  public List<TrainingProduct> Get()
  {   
    List<TrainingProduct> ret = new List<TrainingProduct>();
    // TODO: Add your own data access method here
    ret = CreateMockData();
      
    return ret;
  }
  protected List<TrainingProduct> CreateMockData()
  {
    List<TrainingProduct> ret = new List<TrainingProduct>();
    ret.Add(new TrainingProduct()
    {
      ProductId = 1,
      ProductName = "Extending Bootstrap with CSS, 
                    JavaScript and jQuery",
      IntroductionDate = Convert.ToDateTime("6/11/2015"),
      Url = "http://bit.ly/1SNzc0i",
      Price = Convert.ToDecimal(29.00),
      CategoryId = 1
    });
    ret.Add(new TrainingProduct()
    {
      ProductId = 2,
      ProductName = "Build your own Bootstrap Business
                     Application Template in MVC",
      IntroductionDate = Convert.ToDateTime("1/29/2015"),
      Url = "http://bit.ly/1I8ZqZg",
      Price = Convert.ToDecimal(29.00),
      CategoryId = 1
    });
    // MORE ENTRIES HERE
}

Once you have a generic List of TrainingProduct objects, it is this data that is returned from the Web API. As I stated previously, Web API will automatically serialize this generic List into an array of JSON objects and return that to your Angular controller.

Add Web API to your Project

Depending on how you built your project you may or may not have the appropriate DLLs and other necessary artifacts to support an ASP.NET Web API controller class. I am going to assume that you have not used a Web API in your project and show you how to add them to your project.

Add a new folder \Controllers-Api. While it is not necessary to add a new folder to contain your Web API controller classes, I like keeping them separate from my MVC controllers.

Right mouse click on your Visual Studio project and select Add | New Folder from the content-sensitive menu. Set the name to Controllers-Api and press the enter key.

Add a new controller by right-mouse clicking on the new folder you just added and select Add | Web API Controller Class (v2.1). NOTE: If this option does not show up on your Add menu, select New Item…, drill into the Web | Web API folder on the dialog and select Web API Controller Class (v2.1). Set the name to ProductController and click the OK or the Add button.

Within the ProductController class locate the following method stub created for you by Visual Studio.

// GET api/<controller>
public IEnumerable<string> Get() {
  return new string[] { "value1", "value2" };
}

Replace this method with the following code. NOTE: You may need to include the Namespace in which you created the TrainingProduct and TrainingProductManager classes.

[HttpGet()]
public IHttpActionResult Get() {
  IHttpActionResult ret = null;
  TrainingProductManager mgr =
    new TrainingProductManager();
  List<TrainingProduct> list;
  // Get all Products
  list = mgr.Get();
  if (list.Count > 0) {
    ret = Ok(list);
  }
  else {
    ret = NotFound();
  }
  return ret;
}

In the code above you create an instance of the TrainingProductManager class as you use that to get a collection of TrainingProduct objects. The return value from your Web API should always be an instance of an IHttpActionResult. This message includes an HTTP status code such as 200 or 404 plus any data you wish to send. In this case you use the Ok() method that is part of the ApiController class. This method accepts any data you wish to send, in this case the list of products, and sets a 200 status code. This is where the Web API framework automatically serializes your data into JSON. If there are no products to return use the NotFound() method to return a 404 status code to inform the front end that no data was found.

Configure Web API Routes

If you did not have any Web API features in your project before, you may need to register your intent to use the Web API with ASP.NET. This means that you have to configure the route that MVC should follow to locate any Web API controller so MVC knows they are different from a page controller. To do this, create a different prefix for calling your API controllers such as “api”. The easiest method to accomplish this registration is to create a class called WebApiConfig. Add this class to the \App_Start folder in your project. Type the following code into this new class. NOTE: Check to make sure this class does not already exist in your \App_Start folder.

using System.Web.Http;
public static void Register(
       HttpConfiguration config)
{
  // Web API routes
  config.MapHttpAttributeRoutes();
  // Add route for our API calls
  config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id =
                  RouteParameter.Optional }
  );
}

The above code first configures the ASP.NET runtime to allow for Web API calls by calling the MapHttpAttributeRoutes method. Next, it adds a new HttpRoute and sets up a new template with the “api” prefix. When you make a call to your Web API controllers you always prefix them with “api” to distinguish them from a normal MVC page controller. You can use any prefix you desire, but “api” is an industry convention.

Now that you have this class and method defined you need to call it from the Application_Start method in the Global.asax. Open the Global.asax file and add two new using statements. The first will be to the System.Web.HTTP namespace. This is needed to access the GlobalConfiguration class that is responsible for configuring the ASP.NET runtime with your new Web API template. The second namespace will the name of your project, followed by App_Start which is the folder name used when you create a class within that folder.

using System.Web.HTTP;
using [YOUR PROJECT NAME].App_Start;

Locate the Application_Start() method and add the line of code GlobalConfiguration.Configure() above the RouteConfig.RegisterRoutes() method call as shown in the code below.

protected void Application_Start() {
  AreaRegistration.RegisterAllAreas();
  FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  GlobalConfiguration.Configure(WebApiConfig.Register);
  RouteConfig.RegisterRoutes(RouteTable.Routes);
  BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Call Web API from your Controller

Now that you have all the classes in place for a Web API call, you are now ready to call it from your Angular code. Open up the productController.js file and modify the beginning of the function PTCController. Add one more core service that Angular provides, namely the data service that communicates with remote HTTP servers via a browser’s built-in mechanism such as XMLHttpRequest or JSONP. The name of this core Angular service is passed to your controller as $http. Just like you did with your $scope variable, let’s assign this to your own variable. Use the name dataService in this sample.

function PTCController($scope, $http) {
  var vm = $scope;
  var dataService = $http;

Locate where you declared the vm.products variable in the previous blog post and modify the variable to be an empty array instead of hard-coded object literals as shown in the code below.

// Expose a 'products' collection
vm.products = [];

In future posts I will cover how to deal with exceptions that come back from Web API calls, but for now, let’s just create a function to handle any exceptions by grabbing the data.ExceptionMessage property that comes back from the Web API calls.

function handleException(error) {
  alert(error.data.ExceptionMessage);
}

Write a function called productList() to make the Web API call using the data service passed into our controller. The data service provided by Angular exposes several shortcut methods corresponding to the appropriate HTTP verbs, namely; get, post, put, delete and a few others. Since we are performing a GET to retrieve our product data from our Web API, call the get() method on the data service.

function productList() {
  dataService.get("/api/Product")
    .then(function (result) {
      vm.products = result.data;
    }, function (error) {
      handleException(error);
    });
}

Let’s break down the various components of the get() method. Here is an overview of this function.

$http.get("URL TO WEB API")
     .then(success function (result){}, 
           error   function (error) {});

The parameter you pass to the get() method is the URL to your Web API controller. This method returns a “promise” which is nothing more than an object that takes care of making an asynchronous call for you. The chained method then() is used to inform the promise of what function to call if the Web API is successful and which function to call if an error is returned. In each case an object is passed back to you with some properties that you can query to see what happened. The objects are the same for both success and failure and contain the following properties:

data = Either a string or object containing data from your Web API call
status = An HTTP status code number such as 200 or 404
headers = A function to allow you to get the headers from the call
config = A configuration object that was used for sending the request
statusText = An HTTP status text returned from the call

Look at the productList() function you wrote and see that in the success function, you take the data property from the result parameter and assign that to your array named vm.products. By doing this, you allow the data binding of Angular to take over and update any bound items on the page. In this case the ng-repeat attached to the <tr> on your HTML table causes a redrawing of your HTML table based on the new data in the array.

Now that you have the function productList() written, you need to call it when you enter your controller. Immediately after declaring all your variables on your scope, call the productList() function. Below is what the complete productController.js file should now look like.

(function () {
  'use strict';
  angular.module('ptcApp')
    .controller('PTCController', PTCController);
  function PTCController($scope, $http) {
    var vm = $scope;
    var dataService = $http;
    // Expose a 'product' object
    vm.product = {
      ProductName: 'Pluralsight Subscription'
    };
    // Create a list of categories
    vm.categories = [
      { CategoryName: 'Videos' },
      { CategoryName: 'Books' },
      { CategoryName: 'Articles' }
    ];
    vm.products = [];
    productList();
    function handleException(error) {
      alert(error.data.ExceptionMessage);
    }
    function productList() {
      dataService.get("/api/Product")
        .then(function (result) {
          vm.products = result.data;
        }, function (error) {
          handleException(error);
        });
    }
  }
})();

The last thing you need to do is to modify the building of the product table data. Let’s add a couple more columns to our HTML table using the following code:

<tr ng-repeat="product in products">
  <td>{{product.ProductName}}</td>
  <td>{{product.IntroductionDate | date: mm/dd/yyyy }}</td>
  <td>{{product.Url}}</td>
  <td class="text-right">{{product.Price | currency: $ }}</td>
</tr>

In this new ng-repeat you are adding the IntroductionDate and Url to the table. Notice the use of the “date” filter that assists you in formatting the IntroductionDate data.  Figure 1 shows you what the final HTML product table looks like after running this sample.


Figure 1: A list of products retrieved via the Web API.

Summary

The $http data service is built-in to Angular. All you need to do is to add an additional parameter in your controller function. It is recommended you assign the $http variable to your own variable name for flexibility. Also in this post you learned to configure your web project to make calls to a Web API.

More Angular Blog Posts

PDSA has www.pluralsight.com courses on Angular. Check out The Journey from MVC to Angular.

Sample Code

You can download the code for this sample at www.pdsa.com/downloads. Choose the category “PDSA Blog”, then locate the sample PDSA Blog Sample: Call the Web API from Angular.

Build Lists of Data with Angular

AngularThis is the 2nd blog post in our series on Angular. The first part entitled Get Started with Angular shows you how to add Angular to a project. You should read that blog first if you are not familiar with adding Angular to a project, don’t know what a module or a controller is, or want to understand basic data binding.

In this blog post you will build a couple of different types of lists of data using the ng-repeat directive. Building unordered lists and HTML tables is very straight-forward in Angular. As with anything in Angular, you need to have a variable defined on the $scope variable that contains the data you wish to display. Use the ng-repeat directive and data binding to iterate over the data and create bulleted list items or <tr> and <td> elements.

Create an Unordered List

Start with the project from the first blog post entitled Get Started with Angular. Open the project, then locate and open the \Scripts\productController.js file. Add a new variable to the $scope variable in the controller function as shown in the code highlighted in bold below.

function PTCController($scope) {
  var vm = $scope;
  // Create a list of categories
  vm.categories = [
    { CategoryName: 'Videos' }, 
    { CategoryName: 'Books' }, 
    { CategoryName: 'Articles' }
  ];
}

This code creates an array of object literals. Each object is a category object with a single property called CategoryName. This CategoryName property is set to a string such as ‘Videos’, ‘Books’, or ‘Articles. These string values are to be displayed in an unordered list on our HTML page.

Locate the AngularSample01.html page in the root of the project. Copy and paste this HTML page back into the root of the project. Rename this newly copied file to AngularSample02.html. Replace everything within the <div class=”container”> with the following HTML.

<h3>Categories</h3>
<div class="row">
  <div class="col-xs-12">
    <ul>
      <li ng-repeat="category in categories">
        {{category.CategoryName}}
      </li>
    </ul>
  </div>
</div>

The ng-repeat (also written as ngRepeat) directive contains two variable names and the word ‘in’. The first variable name ‘category’ is a name that you are using for a local variable within this loop. Think of this like the variable name you create in a foreach statement in C#. The second variable name, ‘categories’ refers to the categories variable you created in the controller on the $scope variable. The ‘in’ word simply separates the local variable from the variable on the $scope. Again, this is just like a foreach statement in C#.

The ng-repeat directive instructs Angular to iterate over the collection of objects in the categories variable and place each object into the variable named category. You are also instructing Angular to create a new <li> for each object in the collection. Angular then looks for any data binding tokens between the <li> and the </li> tags. If it finds one, it evaluates the expression. In this case the expression says to look for a property name called CategoryName on the object just retrieved from the categories collection. If it can get the value from the CategoryName property it displays that value between the <li> and the </li> elements.

At this point you should be able to run the page. Go ahead and run the page, and if you did everything correctly, you should see a page that looks similar to Figure 1.


Figure 1: An unordered list of categories

Create an HTML Table

Let’s now use the ng-repeat directive to build an HTML table of products. Create an object literal array of product objects to build that table. Add a new variable named ‘products’ to your $scope variable in your controller function, as shown in the sample below.

function PTCController($scope) {
  var vm = $scope;
  vm.products = [
    { ProductName: 'Video 1', Price: 10 },
    { ProductName: 'Video 2', Price: 10 },
    { ProductName: 'Book 1', Price: 20 },
    { ProductName: 'Article 1', Price: 5 },
    { ProductName: 'Article 2', Price: 6 },
  ];
}

The above code creates an array of object literals where each one is a product object. These product objects contain two properties: ProductName and Price. Some default data has been filled in to give us something to display as shown in Figure 2.

Locate the AngularSample02.html page in the root of the project. Copy and paste this HTML page back into the root of the project. Rename this newly copied file to AngularSample03.html. Replace everything within the <div class=”container”> with the following HTML.

<h3>Products</h3>
<table class="table table-bordered table-striped
              table-condensed">
  <thead>
    <tr>
      <th>Product Name</th>
      <th class="text-right">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="product in products">
      <td>{{product.ProductName}}</td>
      <td class="text-right">
         {{product.Price | currency: $ }}
      </td>
    </tr>
  </tbody>
</table>

In the code above you use the ng-repeat directive to build a list of <tr> elements for each product object in the products collection. For each product object build two <td> elements. The first <td> element contains the ProductName value. The second <td> element displays the price; however, there is something a little extra in the data binding token.

This something extra is called a ‘filter’ and is used to format the data coming from the data binding expression. You place a vertical pipe after the property being bound, then add the filter named ‘currency’, followed by a colon and a US dollar sign symbol ($). This instructs Angular that it should take the price value, treat it as a decimal value, and format it according to United States currency formatting rules. There are other filters you can use in data binding: filter, number, date, json, lowercase, uppercase, limitTo, orderBy. You can learn more about these filters at https://docs.angularjs.org/api/ng/filter.


Figure 2: A table created from Angular data binding

Summary

In this blog post you learned to use the ng-repeat directive to create a list of items. You first learned to build an unordered list using an array of category objects. Next, you built an HTML table of product objects and even saw how to format a currency value using a filter.

More Angular Blog Posts

PDSA has www.pluralsight.com courses on Angular. Check out The Journey from MVC to Angular.

Sample Code

You can download the code for this sample at www.pdsa.com/downloads. Choose the category “PDSA Blog”, then locate the sample PDSA Blog Sample: Build Lists of Data with Angular.