Author Archives: admin

How to Capture a Screenshot and Send it via Email

There are many ways to capture a screenshot, save the captured image to disk and then attach it to an email. Some versions of Windows come with built-in image capture tools such as the Snipping Tool in Windows 7.

Another alternative is to use SliQ Screen Capture. This is a free, very simple tool from SliQTools that provides easy options for capturing screenshots of your complete desktop, the current application running in Windows or even a control within an application. By default, when a screenshot is captured, SliQ Screen Capture opens the captured image in Microsoft Paint. In later versions, Microsoft Paint includes a Send in e-mail option that quickly allows you attach the image to an email.

If you want to use SliQ Screen Capture to send a screenshot by email, take these steps:

1. Download and install SliQ Screen Capture from this page:

http://www.sliqtools.co.uk/screen-capture-utility.aspx

2. Run SliQ Screen Capture.

SliQ Screen Capture always sits on top of all other windows. You can still work with other applications but SliQ Screen Capture stays visible so you can click on one of its capture image buttons.

3. Click on the window of which you want take an image.

For example, if you want to take a screenshot of a window in SliQ Invoicing, click on the window in SliQ Invoicing Plus with your mouse.

4. In SliQ Screen Capture, press the Capture Foreground Window button.

The button is highlighted with a red square in the following picture.

capture-foreground-window-as-image

Then wait for Microsoft Paint to launch.

5. In Microsoft Paint, open the File menu and choose the Send in email option.

paint-send-in-email-file-menu

A new email window should then open with the captured image attached.

6. Edit the email as normal – enter the email address you want to send the picture to, the subject and email message – and press the Send button to send the email.

If you are looking for help on taking a screenshot on an Apple Mac, see this blog post: http://www.sliqtools.co.uk/blog/apple-mac/apple-mac-how-to-take-a-screenshot/

SQL Server Express: Login failed for user X: Error 18456

After creating a new SQL server login with a password in SQL Server Management Studio and then adding a user with the same name as the login to a database, I was having a lot of trouble getting my code first entity framework model to connect to the database. Every time I tried to specify the connection for a context then get a list of objects from the context, I got a SQL exception indicating that the login/ password did not work and could not be logged into the database.

After some research, I found that by default SQL Express only works with Windows Authentication for logins and you have to configure the server to work with both Windows Authentication and SQL Server logins with passwords. To access the configuration setting, right-click the topmost tree node (the server name) in SQL Server Management Studio and show the Server Properties.

In the Server Properties dialog, click the Security settings node in the Select a page panel, then under the Server authentication settings, check the SQL Server and Windows Authentication mode. Then press OK to close the dialog.

sql-server-properties

To get SQL Server Express to pick up the new setting you need to stop and start the server. To do this, again right-click the server name in SQL Server Management Studio and choose Restart from the popup menu. OK and dialogs that come up asking for permission to restart the server. You should then be able to create a connection string to use with an entity framework context using the server name, login/ user id and password you have set. The connection string will be of the form:

Data Source=<server name>;Database=<Database name>;User Id=<Login>;Password=<Password>

Configuring Email Read Receipt Options in Outlook

Microsoft Outlook allows you to configure options for how read receipt requests are handled. When you receive an email for which the sender has requested a read receipt you can configure Outlook to ignore the read receipt request, always automatically send a read receipt or ask you email by email whether to respond with a receipt or not.

To configure the read receipt options, choose the Options option in the Tools menu.

The, in the Outlook Options dialog, choose the Email Options … button near the top of the Preferences tab.

outlook-email-options

In the Options dialog, then press the Tracking Options … button.outlook-email-tracking-options

Finally, in the Tracking Options dialog, choose the desired option before pressing the OK button.

outlook-ask-for-read-receipt

For more Outlook tips, see Configuring the Default Email Account in Microsoft Outlook.

ASP.NET MVC : Accessing String Resources in CSHTML files

When writing web pages in ASP.NET MVC, the standard way of outputting label names is often unsatisfactory as you end up with a label that follows a variable name, e.g. including a line like:

@Html.LabelFor(model => model.PadNumberLength)

ends up showing a label:

PadNumberLength

where you really want:

Pad Number Length

There are a number of other ways of changing the label, e.g. you could put a DisplayName attribute on the property in the model, e.g.

[DisplayName("Pad Number Length")]
public int PadNumberLength { get; set; }

However, especially if you have come to ASP.NET MVC programming from a desktop environment such as Winforms or WPF, the most natural way to get a label name is from a resource file. This also makes it easier to localise your pages in the future.

An ASP.NET MVC project contains a Resources file under the Properties node in the solution explorer. You can put all your string resources in this file. To access the resources in a CSHTML file, include the following HTML helper in your solution:

public static MvcHtmlString ResourceString<T>
    (this HtmlHelper<T> html, string ResourceName)
{
    var Manager = new ResourceManager(typeof(Properties.Resources));
    return MvcHtmlString.Create(Manager.GetString(ResourceName));
}

This means you can then write labels such as:

<label>@Html.ResourceString("PAD_NUMBER_LENGTH")</label>

that output the resource strings from your Properties.Resources file.

Easy Way of Examining Exception Details in Visual Studio

When an exception is raised while debugging an application in Visual Studio, a dialog like the following appears showing a number of options to get more detail on the exception, e.g. the stack trace and line number on which the exception occurred:

One way of digging into the exception to find out more details is to click on the View Detail … link in the dialog. This shows a watch window like view that lets you tunnel into the exception fields.

However, an easy way of scanning all the exception details, is to click the Copy exception detail to the clipboard option, then paste the copied data into Notepad. You then get all the available exception details in a form you can easily scroll through or even search.

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;
   }
}