development blog.

Copy Images from Clipboard in Javascript

by Aaron Friday, January 20th, 2012

One of the pretty common in a Windows environment is copy/pasting image data across programs. In recent versions of chrome, this is now possible in the browser. Here is a quick demo of the javascript we’ll be starting from — you can copy image data from anywhere (Paint, Word, Screenshot, etc) and paste it into the div to have it appended.

http://jsfiddle.net/H9wgv/

This just appends an image that looks something like:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIkAAAAqCAYAAACHr...C">

Which is pretty powerful in it’s own right, but it’s not terribly well supported across browsers – for Foliotek Presentation, ideally we would create a file they can manage just like any of their other files from the paste data, so, with a quick change to the reader.onload, we’ll upload the image to the server:

reader.onload = function(evt) {

var result = evt.target.result;
var arr = result.split(",");
var data = arr[1]; // raw base64
var contentType = arr[0].split(";")[0].split(":")[1]; // image/png, image/gif, etc

$.post("imageupload", {
    data: data,
    contenttype: contentType,
}, function (ev) {
    var img = $("<img style='display:none;' src='" + ev.URL + "' />");
    img[0].onload = function () {
        var width = img.width();
        var height = img.height();
        var src = "<img src='" + ev.URL + "' width='" + width + "' height='" + height + "' />";
        div.append($(src));
        img.remove();
    };

    $("body").append(img);
});

};

And the content of the “imageupload” server route is pretty straightforward, and not too different than what you’d have for uploading an image from Post data:

public JsonResult imageupload(string data, string contenttype)
{
    byte[] bytes = Convert.FromBase64String(data);
    var ms = new MemoryStream(bytes, 0, bytes.Length);
    UserFile file = SaveByteArrayAsUserFile(User, bytes, contentType); // saves the content as a file associated with that user
    return Json(new {
        file.Name,
        file.URL
    });
}
 

Pretty powerful, and definitely one further step in making web-apps feel like native OS apps.

iText SimSun Degree Symbol Spacing

by Andrew Miller Thursday, December 29th, 2011

I had a rather odd issue come up a few weeks ago for a client that generates data sheets for it’s Chinese distributors. These data sheets are generated via iText pdf using the SimSun font.

Below is a screen shot of the issue that came up when SimSun renders the degree symbol notice the trailing white space.

Since this was an actual issue with the font and the client requested that we not change the font due to Chinese standards I came up with the following solution.

SimSun supports the ‘Masculine Ordinal’ symbol. This symbol does not have the trailing white space that the ‘degree’ symbol does. So on the fly when it comes time for iText to generate a Chinese Datasheet I replace all Degree symbols with Masculine Ordinals. A little hacky but def the best solution available at the time.


myString.Replace('\u00B0', '\u00BA'); //replace degree with masculine ordinal

Selenium 2 Tips

by Luke Daffron Friday, November 11th, 2011

In previous posts, I described our use of Selenium for functional and regression testing – and I included some tips on how to use it effectively.   We used the Firefox plugin Selenium IDE to run our tests.

Since that time, we’ve moved on to use Selenium 2 (now, Selenium Server) – which uses a completely different architecture built on top of a merged project called WebDriver.  Now, instead of the custom ‘selenese’ scripts – our tests are driven with C#.  This allows for much more effective branching, looping, etc. scenarios that are sometimes necessary for robust testing.

Some of the tips for selenese tests still apply, but in addition here are some specific Selenium 2 Server pointers:

  1. If you are having trouble getting an element clicked, sometimes it helps to have the test explicitly move the mouse to the element beforehand. Use:
    new OpenQA.Selenium.Interaction.Actions(thewebdriver).MoveToElement(theelement).Perform();
  2. Selenium 2 will not interact with elements that are hidden or off screen.  Because of this – each click/etc action implicitly performs a scroll-to-element action.  Usually, this makes things easier, but occasionally it breaks.  If you have a scrollable element with tight spaces, it might scroll it just out of range before the click, and it will silently fail.  There currently isn’t a great way around this in the test – you can attempt to change your site to deal with it instead (by giving more room, or locking scrolling, etc).
  3. It can be a hassle to deal with nested frames.
    1. Things will fail if you don’t keep the Selenium context updated.  XPath selections in FireFox will throw exceptions, and events won’t fire.  Make sure you do the following to always use the proper context:
      Driver.SwitchTo().DefaultContent().SwitchTo().Frame("fremename");
  4. When things are failing differently on different machines, there are a couple of things to try:
    1. Set a consistent resolution at the beginning of the test:
      ((IJavaScriptExecutor)Driver).ExecuteScript("window.moveTo(0, 1); window.resizeTo(1200,1000);");
    2. Retry clicks until success.  This tends to be necessary right after a iframe context change.  Hacky, but this psuedocode handles some performance/timing issues:
      do{click;sleep;}while(testforchange){}

Datagrid Checkbox Column

by Dustin Smith Wednesday, October 26th, 2011

In Foliotek, there are a lot of instances where we have a table with a check box column that allows users to select rows and do some sort of action to them. This leads to a lot of redundancy in our markup and code. For example, here is what our datagrids looked like when we placed a checkbox in them (we’re using a custom server control for our datagrid):

Datagrid with a checkbox


<Components:ExtendedDataGrid runat="server" id="dgItems">
	<Columns>
		<asp:TemplateColumn>
			<HeaderTemplate>
				<input class="check" onclick="FLTK.checkbox.selectAll(this.checked, 'chkSelect');" type="checkbox" />
			</HeaderTemplate>
			<ItemTemplate>
				<input class="check" type="checkbox" id="chkSelect" runat="server" />
			</ItemTemplate>
		</asp:TemplateColumn>
		<asp:TemplateColumn>
			<ItemTemplate>
				<%# Eval("ItemName") %>
			</ItemTemplate>
		</asp:TemplateColumn>
	</Columns>
</Components:ExtendedDataGrid>

Check All JS

Here’s our javascript code that controls the select/deselect all functionality. See this blog post in reference to the :asp() selector, and this post for more information on the select all functionality.


FLTK.checkbox = {
    selectAll: function (checked, endingwith) {
        var $checkboxes = $(":asp(" + endingwith + ")");
		// we don't want to check a box that is hidden on the page
        if (checked) {
            $checkboxes = $checkboxes.filter(":visible").not(":disabled");
        }
        $checkboxes.attr("checked", checked);
    }
}

Get selected rows (C#)

Then, to get the selected items in the code behind and perform some action on them, we’d have to do the following:


foreach(DataGridItem item in dgItems.Items)
{
	if(((HtmlInputCheckBox)item.FindControl("chkSelect")).Checked)
	{
		// perform action
	}
}

// which can also be written as...

foreach(DataGridItem in dgItems.Items.Cast<DataGridItem>().Where(i => ((HtmlInputCheckBox)i.FindControl("chkSelect")).Checked))
{
	// perform action
}

Creating the Custom Datagrid Checkbox Column

Since the above code and markup is used so frequently in Foliotek, we wanted to abstract this logic into something that was easier to use. As I stated above, we use a custom server control that extends the datagrid control, but if you don’t have a custom server control it shouldn’t be hard to create one.

I would suggest reading up on custom server controls, if you’re interested in how the following code works.

Below is our server controls for the custom DataGrid, CheckBoxColumn, and CheckBoxTemplate. Keep in mind the Checked and VisibilityDataField on the CheckBoxColumn are optional.


namespace Components
{
	// here is our custom datagrid control
    public class ExtendedDataGrid : DataGrid
    {
		public IEnumerable<DataGridItem> GetSelectedItems()
        {
            if (!this.Columns.Cast<DataGridColumn>().Any(c => c is CheckBoxColumn))
            {
                throw new Exception("ExtendedDataGrid must have a 'CheckBoxColumn' in order to use GetSelectedItems");
            }

            return this.Items.Cast<DataGridItem>().Where(i => ((CheckBox)i.FindControl("cb_" + this.ID)).Checked);
        }
    }

	// Usage: <Components:CheckBoxColumn Checked="false" VisibilityDataField="Show"></Components:CheckBoxColumn>
	// Alternative Usage: VisiblityDataField="!Hide"
	public class CheckBoxColumn : TemplateColumn
    {
        public string VisibilityDataField { get; set; }
        public bool Checked { get; set; }

        public CheckBoxColumn() : base()
        {
        }

        public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType)
        {
            if (this.Owner != null)
            {
                this.HeaderTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, true, Checked);
                this.ItemTemplate = new CheckBoxTemplate(this.Owner.ID, VisibilityDataField, false, Checked);
            }
            base.InitializeCell(cell, columnIndex, itemType);
        }
    }

    public class CheckBoxTemplate : ITemplate
    {
        private string _tableID;
        private bool _isHeader;
        private string _visibilityDataField;
        private bool _isChecked;

        public CheckBoxTemplate(string tableID, string visibilityDataField, bool isHeader, bool isChecked)
        {
            _tableID = tableID;
            _isHeader = isHeader;
            _visibilityDataField = visibilityDataField;
            _isChecked = isChecked;
        }

        public void InstantiateIn(Control c)
        {
            if (_isHeader)
            {
				// If the template container is the header, then we need to add the check all functionality to the checkbox
                HtmlInputCheckBox input = new HtmlInputCheckBox();
                input.Attributes["onclick"] = "FLTK.checkbox.selectAll(this.checked, 'cb_" + this._tableID + "');"; // This id is determined below.
                input.Checked = _isChecked; // Set the checked status by default
                c.Controls.Add(input);
            }
            else
            {
                CheckBox cb = new CheckBox();
                cb.ID = "cb_" + this._tableID;
                if (!String.IsNullOrEmpty(_visibilityDataField))
                {
                    cb.DataBinding += new EventHandler(cb_DataBinding); // doing this in the databind event allows us to access properties in the dataitem.
                }
                cb.Checked = _isChecked;
                c.Controls.Add(cb);
            }
        }

        void cb_DataBinding(object sender, EventArgs e)
        {
            var cb = (CheckBox)sender;
            var dataitem = ((DataGridItem)cb.NamingContainer).DataItem;

            bool show = true;
            if (!String.IsNullOrEmpty(this._visibilityDataField))
            {
                bool not = this._visibilityDataField.StartsWith("!");
                show = (bool)DataBinder.Eval(dataitem, (not ? this._visibilityDataField.Substring(1) : this._visibilityDataField));

                show = not ? !show : show;
            }

            cb.Visible = show;
        }
    }
}

New markup and code behind

Here’s our new markup. Notice how we only have one line now for the checkbox column, compared to 8 lines before.


<Components:ExtendedDataGrid runat="server" id="dgItems">
	<Columns>
		<Components:CheckBoxColumn></Components:CheckBoxColumn>
		<asp:TemplateColumn>
			<ItemTemplate>
				<%# Eval("ItemName") %>
			</ItemTemplate>
		</asp:TemplateColum>
	</Columns>
</Components:ExtendedDataGrid>

… and our code behind, which definitely simplifies the prior statement…


foreach(DataGridItem item in dgItems.GetSelectedItems())
{
	//perform action
}

Simplifying C# Selenium 2 Tests for ASP.NET WebForms

by John Pasquet Thursday, October 20th, 2011

Our company uses Selenium to automate regression testing of important functionality on our products. One of the products uses ASP.NET Web Forms. Since the ID for controls gets changed from “txtName” to something like “ct100$contentMain$txtName”, we were using the xPath methods (ClickByXPath(), sendKeysByXPath(), anyByXPath(), etc).

The code looked like this:

Previous Test Code


Tester.Driver.clickByXPath("//input[contains(@id, 'btnSearch')]");
Tester.Driver.clickByXPath("//select[contains(@id, 'drpPrograms')]/option[contains(text(), '" + programName + "')]");
Tester.Driver.clickByXPath("//input[contains(@id, 'rblOption_2')]");
Tester.Driver.clickByXPath("//input[contains(@id, 'cbOption_1')]");
Tester.Driver.sendKeysByXPath("//input[contains(@id, 'txtName')]", name);

Tester.Driver.clickByLinkText("Next");

Writing xPath may be enjoyable for some, but for me it got a bit tedious. So, I created some wrapper methods to make this a lot easier to create and read.

New Test Code


ClickButton("btnSearch");
SelectDropDownOption("drpPrograms", optionName);
SelectRadio("rblOption_2");
SelectCheckBox("cbOption_1");
EnterTextBox("txtName", name);

Wrapper Methods


/// Select a RadioButton or an option on a RadioButtonList.
/// If optionText is specified for a RadioButtonList, this will select that option.  Otherwise it works for native RadioButtons
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectRadio(string radioButtonID, string optionText = "", string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + radioButtonID + "')]";

    if (optionText != "")
        path += "/option[contains(text(), '" + optionText + "')]";

    ClickByXPath(path);
}

/// Select a CheckBox
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectCheckbox(string checkboxID, string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + checkboxID + "')]";

    ClickByXPath(path);
}

/// Select an option on a DropDownList
/// prefix = html filter e.g.  "p/" or "tr/td/"
public void SelectDropDownOption(string dropdownID, string optionText = "", string prefix = "")
{
    string path = "//" + prefix + "select[contains(@id, '" + dropdownID + "')]";

    if (optionText != "")
        path += "/option[contains(text(), '" + optionText + "')]";

    ClickByXPath(path);
}

/// Enter text into a TextBox and optionally clear it out first.
public void EnterTextBox(string txtName, string value, bool clearField = false)
{
    Tester.Driver.sendKeysByXPath("//input[contains(@id,'" + txtName + "')]", value, clearField);
}

/// Confirm if a condition is true.  If it is, output the confirmationMessage.
public void ConfirmTrue(bool test, string confirmationMessage)
{
    Tester.Assert(test, confirmationMessage);
}

/// Test to see if a control exists on the page.
/// Control type = input, div, td or whatever
public bool ControlExists(string controlType, string controlID)
{
    string path = "//" + controlType + "[contains(@id,'" + controlID + "')]";
    return Tester.Driver.anyByXPath(path);
}

/// Click a Button
public void ClickButton(string buttonName, string prefix = "")
{
    string path = "//" + prefix + "input[contains(@id, '" + buttonName + "')]";

    ClickByXPath(path);
}

public void ClickByXPath(string xPath)
{
    Tester.Driver.ClickByXPath(xPath);
}

public void ClickByLinkText(string linkText)
{
    Tester.Driver.clickByLinkText(linkText);
}

For more posts, see Tips and Tricks or Functional Regression Testing