Browsed by
Month: November 2015

AngularJS Directive with Chart.js

AngularJS Directive with Chart.js

As part of a project I’m working on with my good friend Ryan we found a need to be able to easily create some charts to display some metrics to our users. As we’re using AngularJS on our site, the logical step was to create a reusable directive that would allow us to easily hook up charts wherever we needed them – and this is what I’m going to walk through in this post.

I’ll assume you know the basics of setting up an Angular app so I won’t cover that here, and I’ve gone with the very unique name ‘app’ for mine. Download Chart.js and add a reference on your site – or reference the hosted script like I’ve done for this demo (though I’d never recommend this approach for anything that actually goes live!).
So the first step is to create your controller as this is where we’ll be setting the values and options your chart uses, as well as the specified chart type. For the purpose of this demo I’ve borrowed the line chart data and options from the documentation section of the Chart.js website.
I’ve added variables for ChartType, ChartData and ChartOptions on to the controller and initialised with the borrowed values, so my controller looks like this:

Now we have a controller where we can dictate the type of chart we want to load, along with the data and options to be used. Obviously in this sample I’ve hard coded the values which isn’t very useful – ideally (and this is what I’ve done for our project) these values would be retrieved from an Angular service.

The next thing we need to do is to create a directive that makes use of these values. The main things we need here are the template that will be used, the link function for the code to generate the chart, and the scope so we can isolate the values required for the charts.
Given how simple it is to create a chart using Chart.js – it’s just a canvas element – I didn’t see the need to separate this out into a separate HTML file to be used, which would be my usual approach for anything more complex.
The link function needs to find the chart on the page, and determine what chart to create based on the ChartType variable I set on the controller. Using this it then creates the specified chart on the canvas.
Following this, I know have the following directive:

As you can see I’ve used a switch statement on the ChartType in order to call the appropriate method for creating a chart. This is the part of the sample I’m not overly happy with, but I can’t find a better way. Ideally, it would be a single method call to Chart.js that takes in the chart type as a parameter, but instead there are separate methods for each different type – hence the switch statement.

That’s all that’s required! The directive can now be used to create a chart on your page easily, just modify the controller to set the scope variables and your chart will be created as you specify.

My index.html page to use the directive looks like this:

As always, happy to take input and learn if there’s a way I can improve any of this!
And if you’re interested in taking a look at my full code, it can be found on GitHub here.

Basic Form Validation with AngularJS and Bootstrap

Basic Form Validation with AngularJS and Bootstrap

Following on from my previous post, I’m going to cover adding some basic client side validation to the form we created.
We’ll start with the fullName input, so add the required tag to the input element like this:

We’ve now stated that this input needs to have a value in order for our form to be valid. However, if you run the form you can leave the input blank and click submit, and the form will still close as though the data is fine, so we’ll stop that happening.
Go to the ‘formController.js’ and to our submitForm function. In here, we just want to return without closing the form if the form is invalid, like so:

Now if you run the form, leave the input blank, and click the submit button, you’ll see that the form no longer closes.
However, this isn’t much use to the user as they get no information as to why nothing is happening, so let’s add that validation to the fullName input.
Back on ‘formTemplate.html’ we want to modify the div around the fullName input to show something is wrong, we can do this using the bootstrap ‘has-error’ class, and the ng-class directive to determine whether this class is applied or not.
We want this class to be active when the input is invalid, so now the div looks like this:

This gives us a nice red border around the input to highlight there’s an error when nothing has been entered in the input. However, this shows as an error when the user first enters the form which might confuse some people.
So we only want the error formatting to be applied once the user has modified the control, we can do that using the $touched:

Now when you run the form, the error formatting will only be applied when you enter text in the input and then delete it, or if you enter the input and then move to another element without entering text.

The error is now highlighted, but it still isn’t clear to the user what the issue is, so let’s add a message to the form that informs the user of what the problem is. To do this, we want to add a span underneath our input with the message, like so:

I’ve added the ‘help-block’ class to the span which gives us the font colouring and some padding all courteously from Bootstrap, but the problem we have is that it’s currently always shown, so we want to modify the span so it’s only visible when the error formatting on the input is being shown. We can achieve this using ng-show and the same condition that’s on the input, so the div will now look like this:

Now the message is displayed along with the formatting, but only when appropriate!

A problem we still have with the form is that if the user tries to submit the form before touching the input, it’s still not clear to the user what the problem is. We can fix this by using $submitted on the class of the div and the show of the span, like this:

Now when you try and submit the form without entering data the validation is applied and the user can see the errors, whilst the existing validation still works. This is only one input, but the principle is the same for others so you can expand and change the validation principles as you see fit.

You can now be sure that the data from your form is populated as you see fit, but there’s still a chance that something could go wrong with the submission of data regardless, for example on a log in form where the password is wrong. We’ll need a way of displaying this to the user, so we’ll hook up the submit form functionality to a fake function which you would replace with a call to your api.
So in ‘formController’ add another function, I’ve called it fakeApiCall. Have it accept a ‘name’ parameter, and return true when it’s a specified hard coded value, or false otherwise. My function looks like this:

We’ll also need a variable on the scope adding, this will be used to bind to our error notifications visibility, which I called ‘submitError’.
Now we just need to call this in our submitForm function, and when it returns true we close the form, otherwise we set ‘submitError’ to true, so the ‘submitForm’ function now looks like this:

Now we need to add the notification to the form so it can be displayed. This is provided by Bootstrap making it easy to implement, so add it to the top of your form:

If you run this now you’ll see the form looks as normal, however if you submit the data with something other than your hardcoded value (in my case ‘Rufio’) then you’ll see a red notification box displayed at the top of your form. The last thing I did here was to make this notification dismissable. Again, this is personal preference, but it’s easy enough to implement.
Again, functionality is provided by Bootstrap, so you just need to add a button in the notifications div, and modify the class to mark it as a dismissable alert, so you end up with this:

However, if you run this you’ll see that the dismiss button actually has no effect. This is because the functionality is provided by the bootstrap.js script which we haven’t included in this project, so we need to add this in our ‘index.html’ file. You’ll also need to include jQuery as the bootstrap.js script depends on it. So add those two scripts, with jQuery being the first of the two to prevent errors, and your index.html head section will now look like this:

And that’s the basics of client side form validation with AngularJS and Bootstrap! Just expand these principles to cover the rest of your form how you see fit, and replace the fake function and ones similar to actual calls to your API and you’re good to go.

Modal Dialogs with AngularJS and Bootstrap

Modal Dialogs with AngularJS and Bootstrap

A modal dialog is a good way of displaying basic forms to the user, such as a login form, contact form etc. In this post I’m going to cover the basics of using a modal dialog with AngularJS, AngularUI and Bootstrap, giving us a simple modal form with some basic formatting that can be used for a number of scenarios.
First thing to note is that I created this using Visual Studio, so some steps might be different for you, however this is basic enough that it shouldn’t be an issue.
So the first thing is to create a new blank ASP.NET project, and then use Nuget Package Manager to add what we need – in this case that’s AngularJS, AngularJS UI Bootstrap, and Bootstrap.
We’re then going to need a webpage to land on, so create a new index.html file in your project.
In this file add references to the three packages, along with angular-route, in the like so:

The next step is to set up our angular app, so create a folder called ‘app’ in the project. First we want to create a new JavaScript file called ‘ModalDialogsApp.js’.
We don’t want to do too much with the app just now, so just initialise the app and inject ng-route and ui.bootstrap.
We’ll be using ng-route to handling routing in the application later on, and ui.bootstrap is used to make a modal dialog.
The entire file will then look like this:

Now we need our view to display to the user, so under the app folder create a ‘Home.html’ file and a ‘HomeController.js’ file.
Navigate to the newly created ‘HomeController.js’ file and initialise the controller, injecting $scope and $modal, and create an empty function called showModalForm – this will be used later to display the form.
Once done, the controller will now look like this:

The next step is to go to the ‘Home.html’ file and delete all the generated content, and simply replace it with a button that calls the showModalForm function you just created:

Now that the skeleton is set up, we need a way to get to this view, so go back to ‘ModalDialogsApp.js’ and set up the routing to load the view with it’s controller when the user hits ‘/home’ and to redirect there if another address is entered.
So under your app initialisation you’ll have:

In order for the routing to work and the view to be displayed, the app needs to be defined on our main page, and we need to add the references to our JavaScript files. In ‘index.html’ add the references to ‘ModalDialogsApp.js’ and ‘HomeController.js’, and declare the app on the html tag, and the view in the body.
Your ‘index.html’ file should now look like this:

You can now run the app and see the view is being displayed, and that trying to move to another page on the site redirects you back to ‘/home’!
However, nothing is actually happening, so we need to create the form and hook it up to our button.
We need somewhere to keep our form, so create a new folder under the ‘app’ folder called ‘ModalForm’. In this folder create two more files, ‘formTemplate.html’ and ‘formController.js’.
Go to the newly created ‘formController.js’ and initialise the controller, injecting $scope and $modalInstance. Then we want to add a function called submitForm, but leave it blank for now – we’ll use this later to close our dialog.
We also need an object creating for our form to bind to, so create an object called accountDetails. Your controller should now look like this:

Now we need to set up our form to be displayed, so go to the ‘formTemplate.html’ file you created. Remove all generated code as we don’t need it, and add two divs, one for the header and one for the body.
Set the class for the header div to ‘modal-header’ and the class for the body div to ‘modal-body’, these will give us some formatting on the form.
Inside the body, create the form. I added the form-horizontal class to mine, but that’s really just personal preference for the layout.
In the form add two fieldsets, in the first one add a couple of fields for the user to interact with – I added name and email fields to match the object we created in the controller earlier.
In the second fieldset add a submit button that calls the submitForm function, we’ll use this to close the form later.
Your ‘formTemplate.html’ should now look something like this:

In order to make use of this controller, we need to add a reference to the controller we created in our ‘index.html’ file, and finally we need to add the functionality to open the dialog in ‘HomeController.js’ on our showModalForm function, so the controller will now look like this:

Running the app now you can click the button and a modal dialog will be displayed!
Clicking outside of the form will close the dialog, but clicking our submit button currently does nothing. You’ll also notice that the formatting on the form looks pretty terrible.
So lets add another fieldset, improve the formatting, and set up binding on the form.
To improve the formatting we can simply make use of the Bootstrap grid system – this lets you layout components over 12 columns, giving us a nice and easy, and responsive, way of displaying our controls.
I opted to split the grid with 3 columns for the label, and 9 for the inputs. This is done by adding the ‘col-sm-3’ class to the label, and wrapping the input in a div that has the ‘col-sm-9’ class.
So the first form group will now look like this:

The inputs on the form need binding to an object on the controller so that user input can be used. This is done using ng-model, and binding each input to the accountDetails object we created on the controller earlier.
A form with one legend and one set of input looks a bit barren, so I added another fieldset with two more inputs in the same pattern as before. With the new inputs, we also need to remember to add values to the object on the controller so we have something to bind to.
So the full ‘formTemplate.html’ file looks something like this:

The final thing we need to do is to close the dialog when submit is clicked. To do so go to the ‘formController.js’ file and modify the submitForm function to call close on the $modalInstance we injected earlier:

I also created a variable and set it to the accountDetails object, this allows you to break in the function and see that the binded values have been updated with whatever was input on the form.
And that’s it, a simple modal form that can be used in a number of scenarios.
In my next post I’ll show how I added some basic client side validation to the form so that the user can only submit valid data.

Progress Bars and the BackgroundWorker – C# & WPF

Progress Bars and the BackgroundWorker – C# & WPF

This is just a quick introduction on my implementation of using a progress bar in WPF and C#.
The first step is to create the progress bar itself, which is a built in WPF control. So create a dialog and place a progress bar control as so:

One thing to note here is that, in my opinion, for the tasks this implementation was originally designed for, an indeterminate progress bar would have been best. However I was tasked with implementing a progress bar which updated towards 100% so that users were aware of (roughly) how long was remaining on the process.
First, I modified the constructor of the dialog to accept two strings as a parameter, this sets the title on the dialog of the progress bar, and also sets a message on the dialog to inform the user of what’s happening (we’ll add a way to update this later). A private integer is added that will be used to update the progress bar incrementally if desired, and this value is just set to 5 by default.

Now in the .cs file for the progress bar we’ll need some methods to update the progress bar when necessary. For my project, I added three methods here.
One to update the progress which takes in a string and an integer as parameters. The string updates a label I placed above the progress bar to inform the user of what’s currently happening, while the integer sets the new value which moves the progress bar along:

The next method was to increment progress. This was added to provide a simpler way to update the progress bar at specified points in the process, giving a smoother motion to the updating of the progress bar:

And finally I added a method simply to set the increment amount so that it wouldn’t continuously need to be passed as a parameter throughout the process:

On these methods I’ve made the updates to the dialog through the use of a dispatcher. Because the methods that will be updating the progress bar are called from a BackgroundWorker, this is required to stop exceptions being raised by attempting to modify the dialog off of the main UI thread.
The next thing needed is to add a class for handling the BackgroundWorker so that methods can be run whilst updating the progress bar.
To start with I created the constructor and some private variables:

The main thing to note here is the Action that is passed in as a parameter. This is done so that you can have a single entry point that allows you to open and run the progress dialog, regardless of what method you’re wanting to use – provided they take the Progress Dialog as a parameter.
This constructor registers the created BackgroundWorker to the DoWork and RunWorkerCompleted events, initializes the progress dialog, starts the worker running asynchronously, and then displays the progress dialog to the user.
The RunWorkerCompleted event handler has been kept simple, here I just use the event to close the progress dialog as it’s no longer required, however you can add whatever you see fit in here:

And finally we create the DoWork event handler:

This event handler simply calls the Action that was passed in to the constructor earlier, passing in the progress dialog instance so that the method can update the progress. The Action is called inside a try-catch block as errors that are thrown on the BackgroundWorker may not be handled appropriately by exception handling elsewhere, so it would be wise to do so here.
And that’s it really!
An example of opening the dialog and running a method is like so:

Where MyDoWorkMethod is any method that accepts a ProgressDialog as a parameter.
As mentioned earlier, some parts of this implementation are less than ideal – primarily around the way the progress bar is updated for me. This could be avoided by using an indeterminate progress bar, as this isn’t being used for something we can accurately timebox such as a download or a loop performing a specific number of actions.
Another way would be not to pass the Action as a parameter and call logic directly in the DoWork event handler, this way you can simply use the BackgroundWorkers ReportProgress method to update the dialog.
Any suggestions or criticisms, feel free to comment or contact me directly! Always keen to learn and improve 🙂

Resizing Bitmap Images in C# and WPF

Resizing Bitmap Images in C# and WPF

I found myself needing to resize a bitmap image I have in the resources of my project, and apply the resized image to a button. A quick Google found some suggestions, but no clear way of doing so – as such, I thought I’d show my solution here.

The first step is to get the BitmapSource from the Bitmap image you have in the resources file:

Using this BitmapSource we can then use TransformedBitmap to get a new scaled Bitmap, like so:

scaleX and scaleY should be the scale by which you want to resize the image. In my case, I was shrinking an image from 32×32 to 16×16, so both variables were set to 0.5d

To set a new image for a button it needs to be done as the Background, which requires it to be an Image Brush. So now we need to create a new ImageBrush and set the ImageSource to our resized image:

Another thing to note is that when creating a new Brush, the Stretch property will default to Fill. This may be ok, but if like me you wanted the image to stay centred and small, simply set the property to None:

Then simply set the Background property of your button (or other control) to this new brush:

And that’s it, the image is resized in the code and applied to the button!