Overloading Functions in Javascript

Javascript does not support the kind of function overloading you find in languages such as C#. For example in C# you can define two version of a function:

// Double a value.
int DoubleAValue(int Value)
{
...

and

// Double a value, but let the user choose only to double
// if the value is greater than 10.
int DoubleAValue(int Value, bool IfGreaterThan10)
{

You can’t do this kind of overloading in Javascript, but a similar capability can be implemented by exploiting the fact that Javascript doesn’t force callers to specify values for all arguments to a function.

So to implement a kind of overloading, you could write your function in Javascript as:

function DoubleAValue(Value, IfGreaterThan10)
{
...

and callers could decide to call the function with or without the second argument:

var Result = DoubleAValue(10);

and

var Result = DoubleAValue(x, true);

To support the optional argument though, the coder has to implement the function to allow for the second argument not to be specified. There is no way to give a default value to the second argument so the function has to check if the argument is present when called. To do this the function can check whether the argument is undefined …

function DoubleAValue(Value, IfGreaterThan10)
{
    var LocalIfGreaterThan10 = true;

    if (typeof IfGreaterThan10 != 'undefined') {
        // The argument is present on this call. Take the value from the argument.
        LocalIfGreaterThan10 = IfGreaterThan10;
    }

    if (Value <= 10 || LocalIfGreaterThan10) {
        Value = Value * 2;
    }

    return Value;
}

For more Javascript help and tips, see: http://www.sliqtools.co.uk/blog/javascript/writing-javascript-objects-and-adding-element-event-handlers/

How to Fix a Hacked Website – Hacked by r00t3xpl0i7

Coming back to one of my WordPress blogs at the weekend I had a nasty surprise. The website was showing the page below indicating that the site had been hacked.

hackedwebsite

To try and see how this could have happened, I attempted to log into the wordpress admin account by going to the URL: www dot mydomain dot com/wp-admin/. What was really surprising was that I could not log in as admin even though the correct WordPress login page was still visible in the wp-admin subfolder.

Fortunately, I was able to log in to the cPanel for the site through the hosting company’s main website and using the File Manager in cPanel, I began to look for any suspicious files or changes.  As I was unable to log in to the WordPress site, I knew I also had to check the passwords in the WordPress MySQL database.

To correct the password, I opened up the WordPress MySQL database using PHPMyAdmin and looked at the admin password and email address in the wp_users table. I found that the email address wasn’t mine – it had been changed. I edited the email address back to mine using PHPMyAdmin and cleared the password field:

wordpress-wpusers

I then went back to the WordPress login page on my site (www dot mydomain dot com/wp-admin/) and clicked the Forgot password link and followed the instructions to set a new password. To be on the safe side I set a very strong password. Having done that I could then login OK to the WordPress control panel.

However at this point, the website was still showing the hacked page. Going back to File Manager in cPanel and looking through the PHP files, I found that the index.php of the WordPress theme (in the wp-content/themes/theme name/ folder had a very recent modified date. Opening up the index.php for viewing showed that the file had been overwritten and now contained PHP to show the hacked page. Unhacking the site was then easy – I logged into the WordPress control panel and switched themes – the site was then back fully functioning. To be on the safe side, I deleted the hacked theme in the WordPress control panel. At this point I’m assuming the hack was due to a weakness in the PHP for the WordPress theme as the password was pretty obscure. However, I’ll be monitoring the WordPress blog to see if the site goes down again.

Writing Javascript Objects and Adding Element Event Handlers

Having developed code in C# and C++ for a number of years, I’ve recently begun to write web software using Javascript. Working out how classes and objects work has been a little confusing and it took a few hours for me to work out how to do things correctly.

In C# and C++ classes and objects work in a similar fashion – you define a class that contains member properties and methods and when you instantiate the class to create an object the methods in the class “belong” to the object, i.e. they can call other methods in the class knowing that the called methods will operate on the same instance members as the caller.

In Javascript, classes are achieved by exploiting the fact that everything is an object including functions. Essentially, in Javascript, a class is created by adding properties and methods to a function object. The following sections show examples of how to do things like define a class, construct an object, define properties and methods.

Simple Javascript Class with Constructor and Properties

Here is a simple Javascript class with a couple of property definitions:

function NumericTextBox(element) {
    // Record the allowable min and max.
    //
    this.Min = 0;
    this.Max = 1000000;
}

The above example defines a NumericTextBox class that accepts an element object in its constructor. The class also defines a Min and a Max property and gives them default values. An object can then be instantiated and its properties set as follows:

var MyObj = new NumericTextBox($('#editfield'));
MyObj.Min = 12;
MyObj.Max = 15;

Note the use of the this keyword to define the properties inside the NumericTextBox constructor. The this points to the object being created by running the constructor, so executing this.Min defines a property Min in the object.

Adding methods to the Javascript Class

Adding a method to the class is done using the prototype keyword, e.g. to add a SetMin method to the NumericTextBox class, do:

NumericTextBox.prototype.SetMin = function (NewMin) {
    this.Min = NewMin;
}

Note the use of the keyword this again (this.Min) when setting the value of a property on the object. this needs to be used to reference the object on which the SetMin method has been called. In languages like C# and C++ there would be no need to insert a this. reference but in Javascript there is.

Adding an Event Handler to the Element Passed to the Javascript Constructor

If we want to add an event handler to the element (JQuery object in this example) passed to the constructor of our class, we have to make sure that when the event is called it executes in the context of our object. For example:

function NumericTextBox(element) {
    this.Min = 0;
    this.Max = 1000000;

    var self = this;

    element.on('keyup', function (ev) {
        self.ReFormatText(ev.target);
    })
}

NumericTextBox.prototype.ReFormatText = function (element) {
}

Note that the keyup event handler calls the class member ReFormatText. However, when the event handler runs, it needs to call the ReFormatText method in the context of the correct object. Unfortunately, due to Javascript scoping rules, if we wrote:

this.ReFormatText(ev.target)

the this keyword would call the method in the wrong context. The method would be called in the context of the event handler function, not in the context of our example object. To get the method called in the correct context, we use the self variable instead, having set the value of self to the correct object context before we defined the event handler.

Calling other Methods in the Same Javascript Object

When one class method calls another in the same class, we need to use the this keyword again so that the called method runs in the correct context and references the correct object’s properties:

NumericTextBox.prototype.SetMin = function (NewMin) {
    this.Min = NewMin;
    this.EnsureMaxGreaterThanMin();
}

There are other ways of defining classes in Javascript but the above techniques allowed me to do everything I needed in a simple class I was developing. I was surprised at how different class definitions were in Javascript compared to C++ or C# but having worked out how to make sure the correct object context was being used in methods, I managed to do everything I needed.

Kendo UI Grid: Custom Edit Button for Ajax Grid

While trying to display a list of data in a Kendo UI grid for which the data was loaded via Ajax, I wanted to have a custom command that loaded a new page to edit a row. In the specific case I was looking at, I didn’t want to edit inline or edit the row data in a popup dialog – I wanted to leave the page showing the grid and load a new HTML page to do the edit.

The project I was working on used ASP.NET MVC and the handy Kendo UI MVC wrappers. The key to loading a new page was inserting a clickable link that could call a controller action and pass in the ID of the row to edit. To keep things consistent, I also wanted my link to look like a normal Kendo UI grid edit button.

While I could find examples of how to include custom links when a Kendo Grid was server bound, finding out how to do the same things for an Ajax bound grid was more difficult. In the end I found that specifying a column template like this worked:

columns.Bound(invoice => invoice.ID)
   .ClientTemplate
      (@Html.ActionLink
          ("<span class='k-icon k-edit'></span>Edit",
           "Edit",
           new { ID = "#=ID#" },
           new { @class = "k-button k-button-icontext" }).ToHtmlString());

Note that the first argument to the Html.ActionLink call is usually used to give the text of the link but I also included a span in order to add the correct Kendo CSS classes to make the link look like a button with an edit icon.

The result of the above client template for a column in a Kendo grid is that an edit button like the following is displayed:

kendo-ui-edit-button

and when the button is pressed, the following controller action is called:

/Invoices/Edit/3

assuming that the controller for the grid is the Invoices controller and that the row ID (or primary key of the record for the row) is 3.

Entity Framework Error: OriginalValues cannot be used for entities in the Added state

When saving new entries to a SQL Server database using the Entity Framework, I came across the following exception error:

OriginalValues cannot be used for entities in the Added state

There may be a number of reasons why the exception was raised but I found that in my case I had to check the data I was trying to save to make sure that values were specified for all the fields and that the fields were in the ranges required by the SQL Server database.

Here is a list of the checks I had to implement before writing the data to the database using Entity Framework:-

1. Check that a value required in the SQL database didn’t have a null value, e.g. make sure a string field had an empty value “” rather than null.

2. Check that string values weren’t too long to fit, e.g. check that if the database field had a max length of 40 characters I wasn’t trying to save more characters than would fit.

3. Check that any DateTime fields were not out of range for the SQL DateTime fields. .Net DateTime defaults have the value 1/1/1 but SQL dates have a different range to .Net and cannot accept values of 1/1/1.

For each DateTime field I called this function to check (and force) the fields into a range the SQL database would accept.

public static DateTime Default(DateTime Value)
{
   if (Value == null)
   {
      return DateTime.Today;
   }
   else
   {
      // Check the .Net value is in a valid range for a SQL DateTime.
      if (Value < SqlDateTime.MinValue.Value || Value > SqlDateTime.MaxValue.Value)
      {
         Value = DateTime.Today;
      }
      return Value;
   }
}

Do I need an accountant?

We’re often asked by small businesses if they should employ an accountant. The answer often depends on the type of person you are and the type of business you’re running.

It’s a good idea to employ an accountant if your tax affairs are complex but many sole traders don’t necessarily need to go to the expense of an accountant. You can save yourself several hundred pounds per year if you’re organised and don’t mind doing a bit of research. It’s easier than you may think to get to grips with it using our practical tips.

1. Deciding Your Tax Year

If you are starting up and deciding on your tax year, it’s simpler and will save time filling out the paperwork, if you run your financial year in line with HMRC’s – 6th April to 5th April

2. Tax Return- DIY!

Tax returns can be much less daunting than they look. Particularly if your turnover is less than the £77,000 threshold, you can fill in the shorter version of the tax return.  (see http://www.hmrc.gov.uk/worksheets/sa210.pdf for more information on whether you are eligible for the shorter version)

It’s helpful to take a look at the form first so you know what kind of information you’ll need to supply. The forms can be downloaded at: https://www.gov.uk/self-assessment-forms-and-helpsheets

These guidance notes contain really helpful information for example, how to calculate your income and expenditure figures and what expenses are allowed: http://www.hmrc.gov.uk/worksheets/sa103f-notes.pdf

Make sure you fill in any of the supplementary sheets that apply to you: “self employment” or “partnership” for example.

Even if you decide you want an accountant to submit your tax return, you can save on costs by preparing a draft of the form for them to check over.

3. Keeping Proper Records

Sorting out your expenses receipts

Make sure you keep all expenses receipts. If you’re organised you’ll file them straight away. If you’re like me, you’ll shove them all in a big pot to deal with later.

If your annual turnover is below £77,000 (as at 2013) you do not need to provide HMRC with a break down of the different types of expenses. You can just put a total figure on your tax return. So you can just go through the receipts and add them up. You don’t need to number them or type them up, you can just write down the total figure for the year’s expenditure.

Having said that, it can be handy to keep tabs on what you’re spending in different areas so if you are really pushed for time or if you have a large number of receipts, you could pay a book-keeper or admin assistant to do this for you.

If you use an accountant to do your tax return, you can still save money by providing them with this total figure instead of paying them to deal with your receipts.

Don’t forget to include expenses that you might not have paper receipts for such as direct debits and online purchases.

Keeping track of your sales

You should try to make a note of all your sales and other income as you go along. Invoices that you issue should be numbered.

You should include a note of other types of income and sales that may not be invoiced or go through the till such as: money paid into the business from personal funds or goods or services taken for you or your family or to pay someone in kind.

Know Where Things Are!

It really helps save time if you can keep the following together in one place, so you have it all at your fingertips when it comes to doing your year-end figures:

  • Receipts
  • Invoices
  • Bank & credit card statements
  • All correspondence from HMRC

HMRC provides more details about what records you need to keep: http://www.hmrc.gov.uk/sa/rec-keep-self-emp.htm#4

4. Ask for help

Don’t forget you can ring HMRC and ask for help with record-keeping and filling in your tax return. And it’s free. Contacts are here: http://search2.hmrc.gov.uk/kb5/hmrc/contactus/view.page?record=OILdX1VAnlM

5. Get your money’s worth

If you do decide to use an accountant, it will increase your knowledge and understanding of your business if you ask them to explain how they have worked things out. Rather than leaving it all to the accountant, if you take ownership of your finances, you are likely to make wiser decisions and make more money in the long run. It may also give you more confidence to do your own tax returns in future years.

Good luck!

Love your work but hate the finance aspects?

If the work you do is something you’re passionate about then the business side of it can often take a back seat. I’ve worked with many owners of small businesses who work all the hours and are talented at what they do but don’t even know if their business is profitable.  Being ignorant about the financial performance of your business is risky and many small businesses fail as a result.

There are many reasons people stick their head in the sand including:

  • Fear and loathing of anything to do with “boring” business or finance
  • Lack of knowledge and unsure where to get help
  • Secretly know that the business isn’t making enough money but don’t want to give it up

There’s no reason why you can’t love your work AND be in control of the business side. You could start by getting to grips with whether your business is financially viable. It’s worth asking yourself why you want to run your business in the first place. What are your goals?

  • Do you need the business to make you a certain amount of money each month?
  • Do you just want to be your own boss?
  • Do you want to fulfil a long held aspiration?

Whether or not money is your first priority, it can only be helpful to know how much money you’re likely to make – or lose! This will help you decide longer term, whether running this business is right for you. To help you get to grips with the maths, we’ll use the example of Jane who is returning to work and is considering launching a cake-making business …

1. Estimate a realistic monthly figure for the sales of your product or services

For Jane, the number of cakes she thinks will sell multiplied by the amount she will charge per cake.

12 celebration cakes per month @ £45
70 simple cakes per month @ £4

Total = £820

2.Work out as accurately as possible, how much it will cost you to sell those products

This includes not only the cost of the product itself but a proportion of other associated costs such as electricity, premises, equipment and marketing. For Jane this means the cost of all the cake ingredients plus kitchen equipment, packaging, delivery and a proportion of her household fuel bills.

Cake ingredients = £220
Additional costs – £75

3. Subtract the product costs from the sales figure

Jane’s figures are £820 – £295 = £525

4. Work out the number of hours of your time you will spend on your business

For Jane this is 4 hours per day = 20 hours per week = 80 hours per month

5. Calculate your hourly wage

To do this, divide your figure in 3) by the number of hours in 4)

Jane’s is £525 divided by 80 = £6.56 per hour which is around the minimum wage mark.

Seeing your figures in this way, may prompt other ideas about how you can earn more from your business. For example, if there is only one of you doing the work such as with Jane’s business, there may be ways of maximising your time. Jane could invest in a bigger oven and time-saving kitchen equipment in order to increase the number of cakes she produces in the same number of hours. Or, you may be happy enough earning a minimal amount in exchange for the added benefits of being your own boss and being able to fit your work around family commitments.

Whatever your take on it, knowing your figures means you can make informed decisions about the business you love.

System.Web.Mvc.HtmlHelper does not contain a definition for Kendo

While trying to add the KendoUI jQuery framework to an existing MVC project I cam across the following error when loading a page that used the KendoUI Grid HTML Helper:

‘System.Web.Mvc.HtmlHelper<dynamic>’ does not contain a definition for ‘Kendo’

I should have realised I was going to get an ASP.Net runtime error for the page as the Razor intellisense couldn’t find the Kendo Grid helper either:

@(Html.Kendo().Grid

The problem stumped me for a while as the only help I could find on how to solve the problem was that I had to add the following to the namespaces in the web.config:

<add namespace=”Kendo.Mvc.UI” />

However, even after adding this namespace to the web.config, the same problem continued.

The solution to the problem became apparent when I noticed that there was more than one web.config in my project and I had added the namespace to the wrong one. I had added the namespace to the web.config in the root folder of the project but when I added the same namespace to the web.config in the Views folder the intellisense began to work and my Kendo UI grid worked OK. Here’s a pic. showing the location of the web.config file I had to edit in my Visual Studio 2012 project:

kendo-mvc-ui

and here is a pic. of the namespace reference added into the web.config:

kendo-mvc-ui-namespace

ASP.Net MVC Disable Cache To Keep Ajax Working OK

After coming back to my ASP.Net MVC project where I was using the Html.DropDownList scheme I had written about earlier on this blog, I cam across a bug where my dialog containing the dropdownlist wouldn’t show the correct selected item. I could choose a new selected item and submit the form back to the server OK but on reloading the dialog, the first item in the dropdown was always selected. My initial though was that my example code was incorrect and that I needed to start hunting again to find out how dropdownlists really work. However, while debugging, I noticed that the controller action that was returning the partial view for the Jquery dialog containing the dropdownlist seemed to only run once. I had placed a breakpoint in the action and noticed that the breakpoint was only hit when the dialog was loaded for the first time.

I was loading the view into containing the dropdownlist into a Jquery dialog using a load call like this:

$(this).load("@Url.Action("CreateCustomer", "Customers")"

A little research found out that these type of Ajax calls can be cached by browsers. This explained why the load resulted in my action being called once but not a second time – since the IE browser had cached the response.

To get the partial view to load reliably, I ad to disable the cache. To do this I put an OutputCache attribute on the controller action as follows:

[OutputCache(Duration = 0, VaryByParam = "*")]
[HttpGet]
public ActionResult CreateCustomer()

This attribute could be applied at the controller level in order to disable caching for the entire controller:

[OutputCache(Duration = 0, VaryByParam = "*")]
 public class CustomersController : Controller

but for the specific problem I had, it works fine just being applied to my specific controller action.

ASP.NET MVC Html.DropDownList Example

I’ve been struggling for a while to find a decent example of how dropdown lists work in ASP.Net MVC. It seems like a pretty simple thing to do – show a dropdown list with a selected item, allow the user to select a different item then save the new selection back on the server when the user submits the form containing the dropdown. However, it took me a few hours of searching and experimenting to get my dropdown working.

Here’s how I got it working …

1. In the model used to pass data to the view, ensure there are two fields – one containing the list of items to show in the list on the web page, the other field containing the value of the selected item. Here’s a cut down version of my model class:

public class CustomerModelData
{
    // The list of payment terms. This is a list of strings
    // converted into the SelectList type for use by the
    // Html.DropDownList HTML helper.
    //
    public SelectList PaymentTerms { get; set; }

    // The value of the selected item. Note that this is
    // a string, i.e. the same type as the list members.
    //
    // Note that the name of this field is used by the
    // Html.DropDownList helper later in the example.
    //
    public String PaymentTermID { get; set; }
}

2. In the controller, when the view is initially loaded, populate the model fields above with the list of items for the dropdown and the value of the selected item.

// Load the data from the database.
//
CustomerModelData Model = new CustomerModelData();

List<PaymentTermData> DBTerms = DatabaseManager.PaymentTerms;
List<String> DBTermsText = new List<string>();

foreach (PaymentTermData PT in DBTerms)
{
    DBTermsText.Add(PT.ToString());
}

PaymentTermData SelectedTerm = DatabaseManager.SelectedTerm(); 

// Set the list of items for display converting from a
// list of strings to a SelectList.
//
Model.PaymentTerms = new SelectList(DBTermsText);

// Set the selected item for the drop down.
//
Model.PaymentTermID = SelectedTerm.ToString();

3. In the view, plase the Html.DropDownList helper:

@Html.DropDownList("PaymentTermID", Model.PaymentTerms)

Note that there are two parameters to the DropDownList call:

a. “PaymentTermID” – This is the name of the field in the model that contains the selected item.

b.  Model.PaymentTerms – This is the list of items for the drop down.

4. When the user makes a selection on the drop down and then submits the form containing the drop down, e.g. by pressing the Save or Submit button on the form, the same model class (CustomerModelData) can be used to pass data back to the controller:

[HttpPost]
public ActionResult CustomerDetails(CustomerModelData Data)
{
    // The value chosen by the user is now held in the model.
    //
    String TheSelectedValue = Data.PaymentTermID;
    // The list of values is NOT passed back to the controller.
    // This field is now null.
    //
    SelectList TheValues = Data.PaymentTerms;

Note that the value selected by the user has been updated in the model BUT that the list of values is now null. If the view is reloaded at the end of the controller action, the list will need to be repopulated in the model.

There may be other, more efficient ways of handling dropdown lists in ASP.Net MVC but this example works for me and took a surprising amount of time and trials to get to a working state. Initially, I had tried to think of the DropDownList helper as though it was a Winforms combo box where I could pass a list of objects, e.g. the actual PaymentTermData class, together with an instance of the class as the selected item. However this didn’t work and in the end I reverted to a simple type (String) for both the list and selected item in the drop down.

Also check out this post http://www.sliqtools.co.uk/blog/net/asp-net-mvc-disable-cache-to-keep-ajax-working-ok/ for tips on disabling the cache with Ajax requests as I have come across situations where the dropdownlist (and other stuff) appears not to work with the caching enabled.