Friday 25 July 2014

Integer Extension

When using Linq & Lambda expressions I find it easier to write a word based approach than writing long hand. Take for example this query
var something = (from myObject in myTable where myObject.Number > 1 && myObject.Number < 10 select myObject);
We could simply make this code cleaner and easier to read by writing
var something = (from myObject in myTable where myObject.Number.IsWithin(1,10) select myObject);
And the brains behind this method is this little extension method.
namespace FieldOfSheep
{
public static class IntegerExtensions
    {
        public static bool IsWithin(this int value, int minimum, int maximum)
        {
            return value >= minimum && value <= maximum;
        }
    }
}

Thursday 24 July 2014

Sanity Checker

Some times I need to run RegEx Scripts on text boxes. Here is a simple RegEx Sanity Checker for ASP.NET - You can download this from my SourceForge Page
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FieldOfSheep
{
    [ToolboxData("<{0}:SanityChecker runat=server>")]
    public class SanityChecker : TextBox
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Page.ClientScript.RegisterClientScriptBlock(typeof(string), "SanityChecker.js", JScript.SanityChecker, true);

            this.Attributes.Add("onkeyup", string.Format("return SanityChecker(event,'{0}');", this.ClientID));

       }
    }
}
And the JavaScript code for this is
function SanityChecker(evt, element)
{
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if(charCode > 93 && charCode < 112 || charCode > 46 && charCode < 91 || charCode > 185 && charCode < 223)
    {
        var rex = /^[^<>&\"\';]*$/;
        var value = document.getElementById(element).value;
        if(rex.test(str))
        {
            return true;
        }
        else
        {
            
            value = str.substring(0,value.length -1);
            document.getElementById(element).value = value;
        }
    }
}