Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

December 17, 2014

Reusing Validation Messages in AngularJS

Filed under: AngularJS @ 1:03 pm
Tags: ,

One of the many new features in AngularJS 1.3 is the ability to reuse validation messages.

When displaying validation messages, you may find that you often reuse very similar messages:

“Class name must be entered.”  “Start date must be entered.”  “End date must be entered.”

Wouldn’t it be nice if you could reuse error messages instead of repeating them throughout the application? Angular 1.3 provides an ngMessagesInclude directive as part of the new Angular ngMessages module that allows you to share error messages throughout an application.

This post shows you how to use this new feature.

For more information about the new features in AngularJS 1.3, check out my latest Pluralsight course, authored with Joe Eames:

What’s New in Angular 1.3

screenshot

Reusing validation messages in Angular requires the following steps:

  1. Create an HTML file for the common messages.
  2. Include the HTML file in the same element as ngMessages.
  3. Override any messages as required.

Let’s take it one step at a time.

NOTE: If you are new to using ngMessages, check out the Angular 1.3 course.

Create the Messages File

The first step is to create the HTML template file for the common message text. In this file, add HTML with an ng-message attribute for each message. The value of the ng-message attribute must be a valid $error object key. That key is often the name of the validation type, for example: required, minlength, or maxlength.

The message text itself should be generic, meaning it should not refer to specific field names or field requirements.

The resulting HTML file could look something like this:

<span ng-message=”required”>
This item cannot be blank.</span>
<span ng-message=”minlength”>
You have not met this item’s minimum length.</span>
<span ng-message=”maxlength”>
You have exceeded this item’s maximum length.</span>

Include the HTML File

The next step is to include the messages HTML file for each input element that wants to reuse the messages using ng-messages-include. Insert this directive in the same element containing the ng-messages directive.

The following shows an Email field with a label, textbox, and validation. The entire form-group is shown below to provide context for the validation messages.

<div class=”form-group”
     ng-class=”{‘has-error':classForm.inputInstructorEmail.$invalid &&
                            classForm.inputInstructorEmail.$touched}”>
    <label class=”col-md-2 control-label”
           for=”inputInstructorEmail”>Instructor’s Email</label>

    <div class=”col-md-4″>
        <input class=”form-control”
               type=”email”
               id=”inputInstructorEmail”
               name=”inputInstructorEmail”
               placeholder=”instructor’s email”
               ng-model=”vm.class.instructorEmail”
               required
               minlength=”6″ />
    </div>
    <span class=”help-block has-error”
          ng-if=”classForm.inputInstructorEmail.$touched”
          ng-messages=”classForm.inputInstructorEmail.$error”
          ng-messages-include=”app/errorMessages.html” >
        <span ng-message=”email”>
            Instructor’s email must be a valid email address.
        </span>
    </span>
</div>

Notice that the only ng-message directive included in the code above is for an invalid email address. This one is required here because it was not included in the messages html file.

Override Messages as Required

There may be times when you want a customized message. In those cases, you can easily override a message by simply adding a child element with an ng-message directive. The child element ng-message will always override any message defined for the same key in the included messages file.

    <span class=”help-block has-error”
          ng-if=”classForm.inputInstructorEmail.$touched”
          ng-messages=”classForm.inputInstructorEmail.$error”
          ng-messages-include=”app/errorMessages.html” >
        <span ng-message=”email”>
            Instructor’s email must be a valid email address.
        </span>
        <span ng-message=”minlength”>
            Instructor’s email must be at least 6 characters in length.
        </span>

    </span>

Use this technique any time you want to reuse messages throughout your application.

Enjoy!

November 25, 2014

Exception Handling in an AngularJS Application

Filed under: AngularJS @ 9:25 am

Wouldn’t it be great if everything always just worked? That we never had a runtime error… That the server-side Web services were always available and worked? But we know that is not the case. Things go wrong.

The most common ways to handle exceptions in an Angular application are:

  • With a JavaScript try/catch block
    • You can add a try/catch block around code that could fail
    • That allows you to catch specific errors and handle them appropriately.
  • You can use the Angular global exception handler
    • Angular has a built-in service, called $exceptionHandler, that catches exceptions
    • By decorating this service, you can tailor it to the needs of your application.
  • When working with promises, you can also add failure or catch functions

This post covers the second option, using the Angular global exception handler.

If you are interested in more information, I cover exception handling in detail in my Pluralsight course: “AngularJS Line of Business Applications“.

image

Decorating $exceptionHandler

Angular provides a built-in global exception handling service called $exceptionHandler. Any uncaught exception is delegated to this service. This service only catches exceptions, not communication errors (such as 404 not found) or syntax errors.

The default implementation of $exceptionHandler logs any exceptions to the browser console. You can change this functionality by decorating the $exceptionHandler service.

Say we wanted to change the default global exception handler to display a message to the user. We could accomplish this by decorating the $exceptionHandler service as shown in the code below:

image

  • Line 14:
    • The above code configures the application with a decorator.
    • The code needs the Angular built-in $provide service, so it is passed as a parameter to the configuration function.
  • Line 15:
    • The $provide service is used internally as part of Angular’s component registration process.
    • The decorator method of this service can intercept requests and provide different or additional functionality.
    • The decorator method takes two parameters:
      • The first parameter is the string name of the service being decorated. In this case, it is the $exceptionHandler service.
      • The second parameter is a min-safe array containing the name of each decorator function parameter and then the decorator function itself.
  • Line 16:
    • The decorator function has a dependency on $delegate. So $delegate is listed in the min-safe array.
    • $delegate provides the original service to the method. This allows you to call the base implementation of that service.
  • Line 17:
    • $delegate is passed as a parameter to the decorator function.
  • Line 18:
    • This method returns a decorated $exceptionHandler service object.
    • The returned function has two parameters: the exception and the cause.
  • Line 19+20:
    • In this example, the code in the returned function replaces the exception message with a custom message.
  • Line 21:
    • Then it uses $delegate to call the base implementation of the service.
    • The base implementation simply logs the error to the console.
  • Line 22
    • Lastly, this code adds an alert to notify the user of the issue.

Now, any time that an unhandled exception occurs, the message is logged to the console (the default behavior) *and* the user is notified with an alert.

You can add anything you need to this function. For example, you may want to add more extensive logging or a more detailed message.

Enjoy!

November 24, 2014

Creating Pretty Tabs with HTML and CSS

Filed under: AngularJS @ 4:31 pm
Tags: , ,

If you are building data entry forms with HTML (using AngularJS or ASP.NET or other technologies), you may find that you need more space than can fit onto one page. In that case, you may want to implement tabs.

In my AngularJS course entitled “AngularJS Line of Business Applications“, I demonstrate how to build data entry forms using tabs. The result looked like this:

image

I also showed a version with styled tabs like this:

image

This blog post details how to change the rectangular tabs from the first image to the more stylized tabs in the second image.

To keep the example simple, we’ll work with just the tabs:

image

The code for the page shown above with the rectangular tabs is as follows:

<!DOCTYPE html>
<html>
<head lang=”en”>
    <meta charset=”UTF-8″>
    <title>Acme Product Management</title>

    <!– Style sheets –>
    <link href=”css/bootstrap.css” rel=”stylesheet”/>
    <link href=”css/app.css” rel=”stylesheet”/>
</head>

<body>
  <div class=”panel panel-primary”>
    <div class=”panel-heading” style=”font-size:large”>
        Acme Product Management
    </div>

    <div class=”panel-body”>
        <div class=”wizard”>
            <a>
                Basic Information
            </a>
            <a>
                Price Details
            </a>
            <a>
                Search Tags
            </a>
        </div>
   </div>

  </div>
</body>

</html>

Notice that the tabs are defined with anchor (<a>) tags. Notice also that this HTML links to two css files:

body {
    background-color: #C6D9F1;
}

.wizard a {
    background: #efefef;
    display: inline-block;
    margin-right: 5px;
    min-width: 150px;
    outline: none;
    padding: 10px 40px 10px;
    position: relative;
    text-decoration: none;
}
.wizard .active {
    background: #007ACC;
    color: #fff;
}

We’ll need to add some additional styles to the app.css file in order to implement the arrow-style tabs as shown below:

image

First, we’ll add a before selector for the anchor tag:

.wizard a:before {
        width: 0;
        height: 0;
        border-top: 20px inset transparent;
        border-bottom: 20px inset transparent;
        border-left: 20px solid #fff;
        position: absolute;
        content: “”;
        top: 0;
        left: 0;
    }

This creates the “cut out” on the left side of the tabs.

Then we’ll add the triangle shaped arrow on the right side of the tabs using an after selector for the anchor tag:

.wizard a:after {
        width: 0;
        height: 0;
        border-top: 20px inset transparent;
        border-bottom: 20px inset transparent;
        border-left: 21px solid #efefef;
        position: absolute;
        content: “”;
        top: 0;
        right: -20px;
        z-index: 2;
    }

Lastly, we want to ignore the “cut out” border on the left side of the first tab and the arrow on the right side of the last tab. This gives us a clean look for the far left and far right of the tab bar:

.wizard a:first-child:before,
.wizard a:last-child:after {
        border: none;
    }

And if you want to round the corners at the far left and far right of the tab bar, you can round them with this:

.wizard a:first-child {
        -webkit-border-radius: 8px 0 0 0px;
        -moz-border-radius: 8px 0 0 0px;
        border-radius: 8px 0 0 0px;
    }

.wizard a:last-child {
        -webkit-border-radius: 0 8px 0px 0;
        -moz-border-radius: 0 8px 0px 0;
        border-radius: 0 8px 0px 0;
    }

Try building this simple page and then adding each css class and running the application to see its effect on the tabs before adding the next css class.

Enjoy!

November 7, 2014

"Getting to Great With C#": A Learning Path

Filed under: C# @ 9:31 am
Tags: , , ,

As developers, we are always looking for ways to hone our skills. If you are a C# developer, there are many paths to take. That is where a learning path can help.

A learning path provides a specific set of recommendations for enhancing your C# development skills. The “Getting to Great with C#” learning path shows you how to use the C# language to build well-crafted applications. It focuses less on language features and more on good programming practices and techniques. So if you are already familiar with C# and are looking to elevate your skills, check out this learning path.

image

These map to the following Pluralsight courses:

Course Duration
Object-Oriented Programming Fundamentals in C# 4h 22m
Defensive Coding in C# 4h 32m
Clean Code: Writing Code for Humans 3h 10m
C# Interfaces 2h 52m
Abstract Art: Getting Things “Just Right” 2h 08m
Dependency Injection On-Ramp 2h 38m
SOLID Principles of Object Oriented Design 4h 08m
Design Patterns On-Ramp 3h 31m
Design Patterns Library 15h 01m

See this blog post for more information on this learning path.

Enjoy!

October 2, 2014

AngularJS: Visualizing Data with Charts

Filed under: AngularJS @ 5:20 pm

Data visualization can help users see patterns in an often overwhelming amount of data. One key technique for visualizing data is to display that data in a set of charts.

image

Because charting is a common requirement, there are JavaScript libraries available for building charts. D3.js is one such library. D3.js is a JavaScript library for manipulating documents based on data. It provides powerful data visualization components. With all of its power and flexibility comes a steep learning curve.

Luckily, you won’t have to learn d3 to build charts with Angular. Angular-charts is a wrapper around basic d3 features for use in Angular. You can use Angular-charts to build pie, bar, line, point, and area charts.

If you want to create charts in your Angular application, try out the charting example on the Angular-charts page.

Or check out the “Visualizing Data with Charts” module in my “AngularJS Line of Business Applications” course.

Enjoy!

October 1, 2014

Angular Talk at Visual Studio Live! in Washington DC on October 7th, 2014

Filed under: AngularJS,Visual Studio @ 5:25 pm

I am very excited to talk about AngularJS at the upcoming Visual Studio Live! conference in Washington DC!

The session is entitled “Build an Angular and Bootstrap Web Application in Visual Studio from the Ground Up“. It is aimed at intermediate level developers that are new to or just getting started with AngularJS. Because this *is* a Visual Studio conference, the sample application is built using a Visual Studio Web Site for the Angular application and ASP.NET Web API for the back-end Web service. (Though the talk only walks through the Angular code, not the Web API code … we only have 75 minutes!)

If you are looking for the code for this session, you can find it on github here.

If you are not familiar with github, just click the Download ZIP button in the bottom right to download a zip file containing the code.

image

If you are interested in more information about Angular, check out my latest Pluralsight course: “AngularJS Line of Business Applications”. The sample application for the course is built from scratch using WebStorm, but could be created using Visual Studio.

Enjoy!

September 19, 2014

Object-Oriented Programming (OOP) Terms

Filed under: C#,OOP @ 10:22 am

I recently completed a course for Pluralsight entitled “Object-Oriented Programming Fundamentals in C#.” In that course, I cover OOP concepts and definitions of common OOP terms. In the discussion board for that course, someone suggested a “cheat sheet” that summarized the definitions. So here it is:

Basics

Object-Oriented Programming (OOP): An approach to designing and building applications that are flexible, natural, well-crafted, and testable by focusing on objects that interact cleanly with one another.

Class: The code describing a particular entity in the application, such as Customer, Order, or Address. The class contains the code defining the properties and methods (see below).

Property: The code defining the data managed by the class, such as CustomerName, OrderNumber, or EmailAddress.

Method: The code defining the actions or behaviors of the class, such as Validate or CalculateTotal. Methods are defined in the code with C# functions.

Members: Refers to the properties and methods for a class.

Object: An instance of a class that is created at runtime. In C#, an instance is created with the new keyword.

Object Variable: The variable used when creating an object. For example, var myCustomer = new Customer(); In this example, myCustomer is the object variable. Use the object variable to set the properties and call the methods. The object variable retains the state of the object.

Method signature: The code defining the method function including the function name and the set of parameters. The signature does not include the return type. Every function signature within a class must be unique. The signature is used to “match up” calls to the function.

Overloading: Methods that have the same name but different parameters. Example: public bool Retrieve() and public bool Retrieve(int id). The Retrieve method in this example is said to have “two overloads”.

Contract: The set of public properties and methods in a class define the classes contract. The class makes a promise that it will provide the defined properties and methods to any other code that needs them. This is also known as the “class interface“.

Constructor: Code that is executed each time an instance of the class is created.

Default Constructor: A constructor with no parameters.

Overriding: When using inheritance (see below), a child class can override a member of the parent class to provide its own implementation.

Interface: An explicit interface is a separate type (INotifyPropertyChanged for example) that defines a set of properties and methods with no implementation. Any class can then implement an interface to use the set of properties and methods provided in the interface. Think of an interface as a role that an object can play. For example, an ILoggable interface defines a logging role. An IEmail interface defines an emailing role. An Order class may implement both the ILoggable and IEmail interface to take on both roles. An Address class may implement only the ILoggable interface.

Four Pillars of Object-Oriented Programming

The pillars of OOP define the key characteristics of object-oriented programming and are:

Abstraction: The process of defining classes by simplifying reality, ignoring extraneous details, and focusing on what is important for a purpose. For example, a customer may have a name, title, address, marital status, pets, children, credit card information, vehicles, etc. But if the purpose of the application is to process orders, the application may only care about the customer’s name, address, and credit card information.

Encapsulation: A way to hide (or encapsulate) the data and implementation details within a class, thus hiding complexity. In C#, data elements are defined with private backing fields and exposed through property getters and setters. So the data is encapsulated.

Inheritance: A relationship between classes whereby child (or derived) classes inherit all of the members of the parent (or base) class. For example, an application may define a “business object base” class that all business objects inherit from. This base class can contain members common to all child classes, such as entity state information.

Polymorphism: Basically “many forms”. The concept that a single method can behave differently depending on the type of object that calls it. For example, the Validate method in Customer class performs differently from the Validate method in the Order class.

Inheritance-Based Polymorphism: Polymorphism in the case where the method is defined in a base class and behaves differently for each child class.

Interface-Based Polymorphism: Polymorphism in the case where the method is defined in an interface and behaves differently in each class that implements the interface.

Class Relationships

Collaboration: “Uses a” relationship. Objects can collaborate with other objects. For example: Customer Repository “uses a” Customer object to populate on a retrieve and serialize on a save.

Composition: “Has a” relationship. Objects can be composed of other objects. For example, Order “has a” Customer and Order “has a” shipping address.

Inheritance: “Is a” relationship. Objects can be subtyped. For example, a Business Type Customer “is a” Customer and a Residential Type Customer “is a” Customer.

C# OOP Terms

Auto-implemented properties: Properties that create and manage the encapsulated backing field automatically.

Static method: Adding the static modifier on a member of the class (property or method) defines that the member belongs to the class itself, not an instance of the class.

Sealed class: Class that cannot be used as a base class for an inheritance relationship.

Abstract class: Class that cannot be instantiated, so no objects can be created from the class. Nor can it be accessed by its class name. The class can only be used as a base class for other classes.

Concrete class: Class that can be instantiated. Basically, the opposite of an abstract class.

Static class: Class that cannot be instantiated, so no objects can be created from the class. The class members are instead accessed using the class name. A static class provides a shortcut to the members of the class when instancing is unwarranted. For example, the .NET Framework Console class is a static class. To call the WriteLine method you use Console.WriteLine. You don’t have to create a new instance of Console.

Abstract method: Method with no implementation (basically no code). The method must be overridden by a child class.

Virtual method: Method with an implementation that can be overridden by a child class.

For More Information

For more information and detailed coding examples for these concepts/terms, check out the course.

Enjoy!

September 5, 2014

Abstract Class vs Interface

Filed under: C#,OOP @ 5:10 pm

Since publishing my course on Object-Oriented Programming Fundamentals in C# for Pluralsight, I often receive questions from viewers. One of the common questions is on the difference between an Abstract Class and an Interface.

Abstract Class

An abstract class is a class that cannot be instantiated, meaning you can’t use the new keyword to create one. Some key qualities of an abstract class:

  • It is intended to be used as a base class for other classes that inherit from it.
  • It can provide implementation, meaning that it can contain the code for an operation.

For example, you could define an abstract product base class:

public abstract class ProductBase

{

   public bool Save {

       // Code here to save the product

   }

}

The Save method here would contain the code to save a product.

You could then create specialized product classes: BookProduct, GroceryProduct, and OfficeProduct. Each of these specialized classes inherit from the ProductBase class. The specialized product classes then don’t need to contain the logic for the save, because it is provided in the base class.

Say you then define another abstract class for logging.

public abstract class Logging

{

   public void Log{

       // Code here to log information

   }

}

You need the logging functionality in the BookProduct class. Since C# does not allow multiple inheritance, the BookProduct class cannot inherit from *both* the ProductBase class and the Logging class. You instead have to create a hierarchy:

BookProduct class inherits from ProductBase class which inherits from the Logging class.

GroceryProduct class also inherits from ProductBase class which now inherits from the Logging class. So even if the GroceryProduct class does not want or need logging, it still has all of the logging features because Logging is part of its class hierarchy.

This can lead to deep inheritance chains that make the code more complex and difficult to maintain/extend.

Interface

An interface is a set of properties and methods. You can think of an interface as a contract whereby if a class implements the interface, it promises to implement *all* of the properties and methods in the interface. Some key qualities of an interface:

  • It is intended to be implemented by other classes. Each class that implements the interface promises to provide code for each property and method in the interface.
  • An interface cannot contain any implementation, meaning that it does not contain any code, just declarations.

Using the same example as above, you could define IProduct:

   public interface IProduct{

       bool Save();

   }

This interface cannot contain any code for the save. So each product class (BookProduct, GroceryProduct, and OfficeProduct) would need to implement this interface and provide its own code for the save feature.

Say you then define an interface for logging.

   public interface ILoggable{

       void Log();

   }

Any of the product classes that need logging can implement this interface. You can think of an interface as defining a role that a class can take on. For example, the BookProduct class could take on a logging role, email role, and printing role by implementing a logging interface, email interface, and printing interface.

By using an interface:

  • Only the specialized product classes that need logging can implement the ILoggable interface.
  • Each product class that does implement the ILoggable interface needs to provide its own implementation.
  • Other classes (completely unrelated to products) can use the ILoggable interface. The class does not need to be defined within the same hierarchy.

Summary

You can think of an abstract class as a bucket of functionality shared by all of your relatives. And an interface as a role that anyone in the community can take on.

Use an abstract class if:

  • You are building a base class.
  • You want to provide code that the specialized child classes could use (or override)
  • You don’t need the functionality in the abstract class for any classes other than those within the class hierarchy.

Use an interface if:

  • You are defining a “role” that a class could take on.
  • You may want to use the interface on unrelated classes.
  • Each class implementing the interface will provide an implementation.

Thoughts? Questions? Please use the space below to submit your comments.

Enjoy!

PS circle

Check out my Pluralsight courses!

August 1, 2014

Boldly Code With Us: Preview of Visual Studio Live! Washington, D.C.

Filed under: AngularJS,General,Visual Studio @ 4:09 pm

Earlier this week I presented a preview of my two sessions for the Visual Studio Live! conference coming up in Washington DC on October 6-9, 2014. My two sessions at the conference are:

  • New IDE and Editor Features in Visual Studio 2013
  • Build an Angular and Bootstrap Web Application in Visual Studio from the Ground Up

In the preview, I outlined some of the new IDE and Editor features and then selected one to demonstrate.

I then provided an introduction to AngularJS, specifically what it is and why you may want to use it for development of client-side Web applications.

If you are interested, the recording of this preview presentation is posted here.

Enjoy!

PS circleCheck out my Pluralsight courses!
July 30, 2014

Learn AngularJS at VSLive in Washington DC

Filed under: AngularJS,General @ 5:24 pm

If you’ve ever been to Washington DC you know that it is filled with pomp and circumstance. It seems every activity is wrapped in ceremony.

That may be fun when touring history … but no so much when you are writing a Web application. When building an application you want to get work done, not spend lots of time on ritual and setup and ceremony.

AngularJS is all about simplification … getting rid of ritual and ceremony. With AngularJS …

  • You don’t have to write code to navigate the document object model (DOM) as you do with JQuery. No need to id everything and find the Ids on the page.
  • You don’t have to write any code that maps properties from your model to the UI and back again … AngularJS provides automatic two-way data binding.
  • You can easily call a Web service such as Web API.
  • You can write clean Web code!

Join me in Washington DC October 6-9 and learn how to use Angular to build your next Web application.

Use this promo code: DCSPK13 or click on the image below for more information or to register. You’ll save $400!

DCSPK13

Enjoy!

Next Page »

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs