C# Generic Type and Aliased Type to string

C# code, that uses reflection, for translating a type to a pretty class name. Solving the problem that Type.Name returns a really ugly string:

  • typeof(int?).ToString() = System.Nullable`1[System.Int32]
  • typeof(List<string>).ToString() = System.Collections.Generic.List`1[System.String]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IdentityAudit.Utilities
{
    public static class TypePrettyName
    {
        public static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
        {
            while (toCheck != typeof(object) && toCheck != null)
            {
                var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
                if (generic == cur)
                {
                    return true;
                }
                toCheck = toCheck.BaseType;
            }
            return false;
        }

        public static string GetTypePrettyName(Type type)
        {
            if (type.IsGenericType)
            {
                if (IsSubclassOfRawGeneric(typeof(Nullable<>), type))
                {
                    return GetTypePrettyName(type.GetGenericArguments()[0]) + "?";
                }

                string typeName = type.Name.Remove(type.Name.IndexOf('`'));
                string args =
                    string.Join(
                        ",",
                        type.GetGenericArguments().Select(arg => GetTypePrettyName(arg)));
                return typeName + "            }
            else
            {
                return SimpleTypeNameUseAlias(type);
            }
        }

        public static string SimpleTypeNameUseAlias(Type type)
        {
            switch (type.Name)
            {
                case "String": return "string";
                case "Object": return "object";
                case "Boolean": return "bool";
                case "Byte": return "bool";
                case "SByte": return "sbyte";
                case "Int16": return "short";
                case "UInt16": return "ushort";
                case "Int32": return "int";
                case "UInt32": return "uint";
                case "Int64": return "long";
                case "UInt64": return "ulong";
                case "Single": return "float";
                case "Double": return "double";
                case "Decimal": return "decimal";
                case "Char": return "char";
                default:
                    return type.Name;
            }
        }
    }
}

How to publish a Microsoft MVC app in a WordPress blog (in IIS7)

If you have a wordpress blog and you wish to publish an MVC application (or probably any other kind of asp application) as a sub-directory of the blog, this post will describe how to do it.

This post assumes that

  • You have a WordPress site hosted on a computer you control
  • The WordPress site is hosted on a iis7
  • You wish to add the MVC app as a subdirectory to the blog
    If you wish to host the blog inside the app instead of the other way around – then this post isn’t for you.

Set your application to appear in a virtual directory

First, make sure that your MVC expects to be placed in a virtual directory. This doesn’t make the application deploy into a virtual directory (that’s the next step), but it makes your application use “/Verktyg” in all it’s urls.

    • Select the project
    • Select properties
    • Select the “Web” tab
    • Enter the name of the virtual path in the appropriate box – in this case it’s called “/Verktyg” (which means “Tools” in swedish)
    • Test your application, make sure all your links still work.

image

Make your application deploy to a virtual path

Now you tell your application where on the IIS to deploy – both the web site and the virtual directory.

  • Select the project
  • Select properties
  • Select the “Package/Publish Web” tab
  • Enter the name of the site and the virtual path
    image
  • Hit save

Build a deployment package

  • Select the project
  • Right-click on the project
  • Select the menu option “Build deployment package”
  • Copy the deployment package to the server hosting the IIS 7 server

Configure Web.config on the WordPress site

You must configure the Web.config file of the blog to ignore anything that’s intended for the MVC application.

      By default, the Web.config file of the wordpress site is inherited by the MVC application – that’s something that we don’t want – and that’s fixed by adding a

location

      tag inside the configuration tag. The location tag must have the attribute “

inheritInChildApplications

      ” to false.
<configuration>
	<location inheritInChildApplications="false">
		<system.webServer>
			<rewrite>
				<rules>
					<rule name="wordpress" patternSyntax="Wildcard">
						<match url="*" negate="false" />
							<conditions>
							<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
							<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
							</conditions>
						<action type="Rewrite" url="index.php" />
					</rule>
				</rules>
			</rewrite>
		</system.webServer>
	</location>
</configuration>

So locate your Web.config file – it’s stored in the same directory as the site;

image

And add the location tag. Remember to include the closing tag.

Create and configure Virtual path on WordPress site

Before we can install the app, we must make sure that IIS7 has the appropriate Virtual Path (called Verktyg in our example) and that the correct application pool is serving the requests.

  • Create a directory for the virtual path
  • Open “Internet Information Services (IIS) Manager”
  • Select the site;image
  • Right-click on the site and select “Add application”image
  • Make sure that the application pool you select  uses .NET framework 4.
  • Press ok

Install the application

Now it’s time to install the application. As you copied the installation package in one of the previous steps, you should have a directory on the IIS machine that looks something like this;

image

Running “Seo.deploy.cmd” will install the application – I usually use the /y flag to skip the questions. Actually, for deployment convenience, I typically create two .bat files, one for copying the deployment package from the development machine and one for deploying the new code. That way I can quickly update the application.

image

1.copy.bat (relies on the fact that I’m using Remote Desktop to access the web server and that I’m sharing my local drives with the web server):

xcopy \\tsclient\C\Dev\Seo\Seo.Web\obj\Debug\Package\*.* package /D /Y

2.install.bat

package\Seo.Web.deploy.cmd /y

Start cmd as Administrator by right-clicking (in the start menu) and selecting “Run as administrator”

image

Go to the directory where you’ve stored the batch files described above and press “1” and tab – the shell will automatically suggest the 1.copy.bat file;

image

Press 2 and tab – the shell will automatically suggest the “2.install.bat” – it should look something like this;

image

If installation fails with the message below “Site ‘Default Web Site’ does not exist” then you’ve failed with the step called “Make your application deploy to a virtual path”. Make sure to build and copy a new deployment package.

image

Visit the site

You should now be able to visit the site; like this Tools for SEO optimizing – in Swedish.

C# Reflection AttributeHelper

AttributeHelper is a collection of methods I’ve developed to help me retrieve Attribute information for Types and methods in C# (through Reflection). I’m publishing it on my blog because it’s too small to create a CodePlex project for and it’s something I want access to from wherever I am. If you find use for it too, then thats great.

It uses caching of attributes to speed up access, because retrieving type information is typically quite time consuming. For caching it uses a trivial Dictionary.

Here’s the code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace IdentityAudit.Utilities
{
    public static class AttributeHelper
    {
        private static Dictionary<object, List<Attribute>> _attributeCache = new Dictionary<object, List<Attribute>>();

        public static Dictionary<object, List<Attribute>> AttributeCache { get { return _attributeCache; } }

        // Types
        public static List<Attribute> GetTypeAttributes<TType>()
        {
            return GetTypeAttributes(typeof(TType));
        }

        public static List<Attribute> GetTypeAttributes(Type type)
        {
            return LockAndGetAttributes(type, tp => ((Type)tp).GetCustomAttributes(true));
        }

        public static List<TAttributeType> GetTypeAttributes<TAttributeType>(Type type, Func<TAttributeType, bool> predicate = null)
        {
            return
                GetTypeAttributes(type)
                    .Where<Attribute, TAttributeType>()
                    .Where(attr => predicate == null || predicate(attr))
                    .ToList();
        }

        public static List<TAttributeType> GetTypeAttributes<TType, TAttributeType>(Func<TAttributeType, bool> predicate = null)
        {
            return GetTypeAttributes(typeof(TType), predicate);
        }

        public static TAttributeType GetTypeAttribute<TType, TAttributeType>(Func<TAttributeType, bool> predicate = null)
        {
            return
                GetTypeAttribute(typeof(TType), predicate);
        }

        public static TAttributeType GetTypeAttribute<TAttributeType>(Type type, Func<TAttributeType, bool> predicate = null)
        {
            return
                GetTypeAttributes<TAttributeType>(type, predicate)
                    .FirstOrDefault();
        }

        public static bool HasTypeAttribute<TType, TAttributeType>(Func<TAttributeType, bool> predicate = null)
        {
            return HasTypeAttribute<TAttributeType>(typeof(TType), predicate);
        }

        public static bool HasTypeAttribute<TAttributeType>(Type type, Func<TAttributeType, bool> predicate = null)
        {
            return GetTypeAttribute<TAttributeType>(type, predicate) != null;
        }

        // Members and properties
        public static List<Attribute> GetMemberAttributes<TType>(Expression<Func<TType, object>> action)
        {
            return GetMemberAttributes(GetMember(action));
        }

        public static List<TAttributeType> GetMemberAttributes<TType, TAttributeType>(
            Expression<Func<TType, object>> action,
            Func<TAttributeType, bool> predicate = null)
            where TAttributeType : Attribute
        {
            return GetMemberAttributes<TAttributeType>(GetMember(action), predicate);
        }

        public static TAttributeType GetMemberAttribute<TType, TAttributeType>(
            Expression<Func<TType, object>> action,
            Func<TAttributeType, bool> predicate = null)
            where TAttributeType : Attribute
        {
            return GetMemberAttribute<TAttributeType>(GetMember(action), predicate);
        }

        public static bool HasMemberAttribute<TType, TAttributeType>(Expression<Func<TType, object>> action, Func<TAttributeType, bool> predicate = null) where TAttributeType : Attribute
        {
            return GetMemberAttribute(GetMember(action), predicate) != null;
        }

        // MemberInfo (and PropertyInfo since PropertyInfo inherits from MemberInfo)
        public static List<Attribute> GetMemberAttributes(this MemberInfo memberInfo)
        {
            return
                LockAndGetAttributes(memberInfo, mi => ((MemberInfo)mi).GetCustomAttributes(true));
        }

        public static List<TAttributeType> GetMemberAttributes<TAttributeType>(this MemberInfo memberInfo, Func<TAttributeType, bool> predicate = null) where TAttributeType : Attribute
        {
            return
                GetMemberAttributes(memberInfo)
                    .Where<Attribute, TAttributeType>()
                    .Where(attr => predicate == null || predicate(attr))
                    .ToList();
        }

        public static TAttributeType GetMemberAttribute<TAttributeType>(this MemberInfo memberInfo, Func<TAttributeType, bool> predicate = null) where TAttributeType : Attribute
        {
            return
                GetMemberAttributes<TAttributeType>(memberInfo, predicate)
                    .FirstOrDefault();
        }

        public static bool HasMemberAttribute<TAttributeType>(this MemberInfo memberInfo, Func<TAttributeType, bool> predicate = null) where TAttributeType : Attribute
        {
            return
                memberInfo.GetMemberAttribute<TAttributeType>(predicate) != null;
        }

        // Internal stuff
        private static IEnumerable<TType> Where<X, TType>(this IEnumerable<X> list)
        {
            return
                list
                    .Where(item => item is TType)
                    .Cast<TType>();
        }

        private static TType FirstOrDefault<X, TType>(this IEnumerable<X> list)
        {
            return
                list
                    .Where<X, TType>()
                    .FirstOrDefault();
        }

        private static List<Attribute> LockAndGetAttributes(object key, Func<object, object[]> retrieveValue)
        {
            return
                LockAndGet<object, List<Attribute>>(_attributeCache, key, mi => retrieveValue(mi).Cast<Attribute>().ToList());
        }

        // Method for thread safely executing slow method and storing the result in a dictionary
        private static TValue LockAndGet<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key, Func<TKey, TValue> retrieveValue)
        {
            TValue value = default(TValue);
            lock (dictionary)
            {
                if (dictionary.TryGetValue(key, out value))
                {
                    return value;
                }
            }

            value = retrieveValue(key);

            lock (dictionary)
            {
                if (dictionary.ContainsKey(key) == false)
                {
                    dictionary.Add(key, value);
                }

                return value;
            }
        }

        private static MemberInfo GetMember<T>(Expression<Func<T, object>> expression)
        {
            MemberExpression memberExpression = expression.Body as MemberExpression;

            if (memberExpression != null)
            {
                return memberExpression.Member;
            }

            UnaryExpression unaryExpression = expression.Body as UnaryExpression;

            if (unaryExpression != null)
            {
                memberExpression = unaryExpression.Operand as MemberExpression;

                if (memberExpression != null)
                {
                    return memberExpression.Member;
                }

                MethodCallExpression methodCall = unaryExpression.Operand as MethodCallExpression;
                if (methodCall != null)
                {
                    return methodCall.Method;
                }
            }

            return null;
        }
    }
}

And here’s a number of nunit tests;

[TestFixture]
class AttributeHelperTests
{
[MyAttribute(Name = "Steve")]
internal class Attributed
{
[MyAttribute(Name = "Bob")]
public bool HasAttributeProperty { get; set; }
public bool HasNoAttributeProperty { get; set; }

[MyAttribute(Name = "Stevie")]
public bool HasAttributeMember(int x)
{
return true;
}

public bool HasNoAttributeMember(int x)
{
return true;
}
}

internal class MyAttribute : Attribute
{
public string Name { get; set; }
}

[Test]
public void GetTypeAttributes_works()
{
Assert.That(AttributeHelper.GetTypeAttributes<Attributed>().Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetTypeAttributes<Attributed, MyAttribute>().Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetTypeAttributes<Attributed, MyAttribute>(attr => attr.Name == "Jane").Count, Is.EqualTo(0));
Assert.That(AttributeHelper.GetTypeAttributes<Attributed, MyAttribute>(attr => attr.Name == "Steve").Count, Is.EqualTo(1));
}

[Test]
public void GetTypeAttribute_works()
{
Assert.That(AttributeHelper.GetTypeAttribute<Attributed, MyAttribute>(), Is.Not.Null);
Assert.That(AttributeHelper.GetTypeAttribute<Attributed, SequentialAttribute>(), Is.Null);

Assert.That(AttributeHelper.GetTypeAttribute<Attributed, MyAttribute>(attr => attr.Name == "Jane"), Is.Null);
Assert.That(AttributeHelper.GetTypeAttribute<Attributed, MyAttribute>(attr => attr.Name == "Steve"), Is.Not.Null);
}

[Test]
public void HasTypeAttribute_works()
{
Assert.That(AttributeHelper.HasTypeAttribute<Attributed, MyAttribute>(), Is.True);
Assert.That(AttributeHelper.HasTypeAttribute<Attributed, SequentialAttribute>(), Is.False);

Assert.That(AttributeHelper.HasTypeAttribute<Attributed, MyAttribute>(attr => attr.Name == "Jane"), Is.False);
Assert.That(AttributeHelper.HasTypeAttribute<Attributed, MyAttribute>(attr => attr.Name == "Steve"), Is.True);
}

[Test]
public void GetMemberAttributes_works()
{
Assert.That(AttributeHelper.GetMemberAttributes<Attributed>(x => x.HasAttributeMember(0)).Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeMember(0)).Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed>(x => x.HasNoAttributeMember(0)).Count, Is.EqualTo(0));

Assert.That(AttributeHelper.GetMemberAttributes<Attributed>(x => x.HasAttributeProperty).Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeProperty).Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed>(x => x.HasNoAttributeProperty).Count, Is.EqualTo(0));

Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "Stevie").Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "X").Count, Is.EqualTo(0));

Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeProperty, attr => attr.Name == "Bob").Count, Is.EqualTo(1));
Assert.That(AttributeHelper.GetMemberAttributes<Attributed, MyAttribute>(x => x.HasAttributeProperty, attr => attr.Name == "X").Count, Is.EqualTo(0));
}

[Test]
public void GetMemberAttribute_works()
{
Assert.That(AttributeHelper.GetMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0)), Is.Not.Null);
Assert.That(AttributeHelper.GetMemberAttribute<Attributed, MyAttribute>(x => x.HasNoAttributeMember(0)), Is.Null);

Assert.That(AttributeHelper.GetMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "Stevie"), Is.Not.Null);
Assert.That(AttributeHelper.GetMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "X"), Is.Null);
}

[Test]
public void HasMemberAttribute_works()
{
Assert.That(AttributeHelper.HasMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0)), Is.True);
Assert.That(AttributeHelper.HasMemberAttribute<Attributed, MyAttribute>(x => x.HasNoAttributeMember(0)), Is.False);

Assert.That(AttributeHelper.HasMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "Stevie"), Is.True);
Assert.That(AttributeHelper.HasMemberAttribute<Attributed, MyAttribute>(x => x.HasAttributeMember(0), attr => attr.Name == "X"), Is.False);
}
}

Download Stock Quotes, Free, Easy and with Source Code

Every once in a while, I need stock quotes for some idea I need to try out. There are several methods for downloading quotes that cost money – but the data is freely available from  Yahoo so I figured I’d use that.

Turns out that 93 rows of code is enough – and that includes downloading a list of Nasdaq stock symbols.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Cluster.ConsoleApp
{
    public static class MinimalStockDownloader
    {
        public static void DownloadStocks(string path)
        {
            // Allows you to download more items in parallel
            ServicePointManager.DefaultConnectionLimit = 10;
            List<string> symbols = GetStockSymbols();

            // Run in parallel - speeds things up considerably...
            Parallel.ForEach(
                symbols,
                symbol =>
                {
                    Console.WriteLine("Downloading {0}: Working...", symbol);
                    string suri = string.Format(
                        "http://ichart.finance.yahoo.com/table.csv?s={0}&g=d&ignore=.csv", 
                        symbol);                    
                    try
                    {
                        string quotes = Get(new Uri(suri));
                        File.WriteAllText(path + @"\" + symbol + ".csv", quotes);                    
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "  Failed to download {0} with exception: \n{1}", 
                            symbol, 
                            e);
                    }
                    
                    Console.WriteLine(
                        "Downloading {0}: Done!", 
                        symbol);
                });
        }

        public static List<string> GetStockSymbols()
        {
            // You'll find a complete list of stocks at
            // http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download
            // referrred to by http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ
            string stocksCsv = Get(new Uri("http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NASDAQ&render=download"));

            List<string> symbols = new List<string>();
            Regex regexObj = new Regex("^\"(.*?)\"", RegexOptions.Singleline | RegexOptions.Multiline);
            Match matchResult = regexObj.Match(stocksCsv);
            while (matchResult.Success)
            {
                symbols.Add(matchResult.Groups[1].Value);
                matchResult = matchResult.NextMatch();
            }

            // First item is the text "Symbol".
            symbols = symbols.Skip(1).ToList();
            Console.WriteLine("Found {0} symbols", symbols.Count);
            return symbols;
        }

        public static string Get(Uri address)
        {
            Console.WriteLine("  Get {0}...", address);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
            request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

            try
            {
                using (WebResponse response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                using (var reader = new StreamReader(stream, Encoding.Default))
                {
                    return reader.ReadToEnd();
                }
            }
            catch
            {
                request.Abort();
                throw;
            }
        }
    }
}

Colored/Shaded Rectangle on a WriteableBitmap

I recently needed a way to render a colored rectangle on a WriteableBitmap in Silverlight – though the code could be used in WPF with minor changes. Typically, you’d not use WriteableBitmaps but different Shapes in WPF, but this time I needed to create my own bitmap.

I’ve submitted the code as a contribution to the WriteableBitmapEx.codeplex.com project, but it hasn’t been accepted nor rejected yet, so I figured I’d post it here in case anyone ever needs something similar.

Drawing a 255×255 shaded block takes 2.06 ms (averaged over 1000 draws).

Shaded rectangle rendered on picture of lena;

WriteableBitmap bitmap = new WriteableBitmap((BitmapSource)Image.Source);
int width = 255;
int start = (512 - width) / 2;
bitmap.DrawFilledRectangle(
 start, start,
 start + width, start + width,
 Colors.White,
 Colors.Red,
 Colors.Green,
 Colors.Blue);

Image.Source = bitmap;
bitmap.Invalidate();

public static void DrawFilledRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, Color color)
{
	// Add one to use mul and cheap bit shift for multiplicaltion
	var a = color.A + 1;
	var col = (color.A << 24)
			 | ((byte)((color.R * a) >> 8 ) << 16)
			 | ((byte)((color.G * a) >> 8 ) << 8 )
			 | ((byte)((color.B * a) >> 8 ));

	bmp.DrawFilledRectangle(x1, y1, x2, y2, col);
}

public static void DrawFilledRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, Color color00, Color color01, Color color10, Color color11)
{
	// Add one to use mul and cheap bit shift for multiplicaltion
	var a00 = color00.A + 1;
	var col00 = (color00.A << 24)
			 | ((byte)((color00.R * a00) >> 8 ) << 16)
			 | ((byte)((color00.G * a00) >> 8 ) << 8 )
			 | ((byte)((color00.B * a00) >> 8 ));

	var a01 = color01.A + 1;
	var col01 = (color01.A << 24)
			 | ((byte)((color01.R * a01) >> 8 ) << 16)
			 | ((byte)((color01.G * a01) >> 8 ) << 8 )
			 | ((byte)((color01.B * a01) >> 8 ));

	var a10 = color10.A + 1;
	var col10 = (color10.A << 24)
			 | ((byte)((color10.R * a10) >> 8 ) << 16)
			 | ((byte)((color10.G * a10) >> 8 ) << 8 )
			 | ((byte)((color10.B * a10) >> 8 ));

	var a11 = color11.A + 1;
	var col11 = (color11.A << 24)
			 | ((byte)((color11.R * a11) >> 8 ) << 16)
			 | ((byte)((color11.G * a11) >> 8 ) << 8 )
			 | ((byte)((color11.B * a11) >> 8 ));

	bmp.DrawFilledRectangle(x1, y1, x2, y2, col00, col01, col10, col11);
}

public static void DrawFilledRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, int color)
{
	// Use refs for faster access (really important!) speeds up a lot!
	int w = bmp.PixelWidth;
	int h = bmp.PixelHeight;
	int[] pixels = bmp.Pixels;

	// Check boundaries
	if (x1 < 0) { x1 = 0; }
	if (y1 < 0) { y1 = 0; }
	if (x2 < 0) { x2 = 0; }
	if (y2 < 0) { y2 = 0; }
	if (x1 >= w) { x1 = w - 1; }
	if (y1 >= h) { y1 = h - 1; }
	if (x2 >= w) { x2 = w - 1; }
	if (y2 >= h) { y2 = h - 1; }

	int i = y1 * w;
	for (int y = y1; y < y2; y++)
	{
		int i2 = i + x1;
		while (i2 < i + x2)
		{
			pixels[i2++] = color;
		}
		i += w;
	}
}

public static void DrawFilledRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, int color00, int color01, int color10, int color11)
{
	// Use refs for faster access (really important!) speeds up a lot!
	int w = bmp.PixelWidth;
	int h = bmp.PixelHeight;
	int[] pixels = bmp.Pixels;

	// Check boundaries
	if (x1 < 0) { x1 = 0; }
	if (y1 < 0) { y1 = 0; }
	if (x2 < 0) { x2 = 0; }
	if (y2 < 0) { y2 = 0; }
	if (x1 >= w) { x1 = w - 1; }
	if (y1 >= h) { y1 = h - 1; }
	if (x2 >= w) { x2 = w - 1; }
	if (y2 >= h) { y2 = h - 1; }

	// Retrieve the color channels
	byte a00 = (byte)(color00 >> 24); byte r00 = (byte)(color00 >> 16); byte g00 = (byte)(color00 >> 8 ); byte b00 = (byte)(color00);
	byte a10 = (byte)(color10 >> 24); byte r10 = (byte)(color10 >> 16); byte g10 = (byte)(color10 >> 8 ); byte b10 = (byte)(color10);
	byte a01 = (byte)(color01 >> 24); byte r01 = (byte)(color01 >> 16); byte g01 = (byte)(color01 >> 8 ); byte b01 = (byte)(color01);
	byte a11 = (byte)(color11 >> 24); byte r11 = (byte)(color11 >> 16); byte g11 = (byte)(color11 >> 8 ); byte b11 = (byte)(color11);

	//r01, r10
	int xrange = x2 - x1;
	int yrange = y2 - y1;

	for (int x = 0; x < xrange; x++)
	{
		int negx = xrange - x;
		byte atop = (byte)((a00 * negx + a01 * x) / xrange);
		byte rtop = (byte)((r00 * negx + r01 * x) / xrange);
		byte gtop = (byte)((g00 * negx + g01 * x) / xrange);
		byte btop = (byte)((b00 * negx + b01 * x) / xrange);

		byte abottom = (byte)((a10 * negx + a11 * x) / xrange);
		byte rbottom = (byte)((r10 * negx + r11 * x) / xrange);
		byte gbottom = (byte)((g10 * negx + g11 * x) / xrange);
		byte bbottom = (byte)((b10 * negx + b11 * x) / xrange);

		for (int y = 0; y < yrange; y++)
		{
			int negy = yrange - y;
			int p = (y + y1) * w + x + x1;

			int color =
				(byte)((atop * negy + abottom * y) / yrange) << 24 |
				(byte)((rtop * negy + rbottom * y) / yrange) << 16 |
				(byte)((gtop * negy + gbottom * y) / yrange) << 8 |
				(byte)((btop * negy + bbottom * y) / yrange);

			pixels[p] = color;
		}
	}
}

Redust SEO Rules

I’m proud to announce a new site that focuses on Search Engine Optimization tools that I’m working on with a team of developers that’s called redust.com. Our first tool, SEO-Rules automatically validates a page against a large number of Search Engine Optimization Rules.

The redust.com application, which will host several different tools, we’re currently have very specific plans for two more tools.

Remove Google Stopwords From String

If you’re anything like me, you’ve often wondered “how do I remove google stopwords from my strings”? Well, maybe you haven’t, but this is the method I came up with to do just that.

Google stopwords are words that are ignored in your query and on indexing your web pages, things like “a”, “about”, “above”. Here’s a list of stopwords assumed to be used by search-engines; http://www.ranks.nl/resources/stopwords.html and here’s another; http://www.link-assistant.com/seo-stop-words.html.

My method converts this text;

This is a text with lots and lots of stopwords. It also talks
a bit about load balancing. Load balancing is not a stopword.

To this text;

      text   lots   lots   stopwords.
talks   bit   load balancing. Load balancing       stopword.

Note that there are many double spaces, which we’ll take care of next.

The actual regex for clearing out stopwords looks like this (I’m only using a few of the words here);

(?<=(\A|\s|\.|,|!|\?))(a|able|about|above|abroad)(?=(\s|\z|\.|,|!|\?))

Btw, I use the awesome Regex Buddy for all my Regex needs- Regex Buddy, you’re my buddy too!

The Regex uses look-ahead and look-behind which not all Regex engines supports, and Regex formats may be differ. The reason it uses look-ahead and look-behind is that we don’t want the regex to “eat” the word separators, because if it did it would lose every second word that matches the regex. Believe me, it’s true, or use – you guessed it – Regex buddy to confirm.

If you’re clever, like me, you’ll be able to read the regex like it was plain english… ok, it’s obtuse and obfuscated, but it works.

I generated it like this (after using aforementioned Regex Buddy to determine the format);

string[] stopwords = File.ReadAllLines("EnglishStopwords.txt");

string regexCode = 
  @"(?<=(\A|\s|\.|,|!|\?))(" + 
  string.Join("|", stopwords) + 
  @")(?=(\s|\z|\.|,|!|\?))";

Regex regex = new Regex(regexCode, RegexOptions.Singleline | RegexOptions.IgnoreCase);

string cleaned = regex.Replace(indata, " ");

As for removing the double spaces, use this;

Regex removeDoubleWhiteSpace = 
  new Regex(@"\s{2,}", RegexOptions.Singleline | RegexOptions.IgnoreCase);

string cleaned = 
  removeDoubleWhiteSpace.Replace(cleaned, " ");

So, this is a rather compact version of what I’m doing;

public static void Test()
{
    string text =
        @"This is a text with lots and lots of stopwords. It also" + Environment.NewLine +
            "talks a bit about load balancing. Load balancing is not a stopword.";

    Console.WriteLine("Before:");
    Console.WriteLine(text);

    string[] stopwords = File.ReadAllLines(@"c:\slask\EnglishStopwords.txt");

    string regexCode = 
        @"(?<=(\A|\s|\.|,|!|\?))(" + 
        string.Join("|", stopwords) + 
        @")(?=(\s|\z|\.|,|!|\?))";

    Regex regex = new Regex(regexCode, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            
    string cleaned = regex.Replace(text, " ");

    Console.WriteLine("\nAfter remove stopwords:");
    Console.WriteLine(text);

    Regex removeDoubleWhiteSpace = 
        new Regex(@"\s{2,}", RegexOptions.Singleline | RegexOptions.IgnoreCase);

    cleaned = 
        removeDoubleWhiteSpace.Replace(cleaned, " ");

    Console.WriteLine("\nAfter remove double white spaces:");
    Console.WriteLine(cleaned);
}

and the output looks like this;

Before:

This is a text with lots and lots of stopwords. It also

talks a bit about load balancing. Load balancing is not a stopword.

After remove stopwords:

This is a text with lots and lots of stopwords. It also

talks a bit about load balancing. Load balancing is not a stopword.

After remove double white spaces:

text lots lots stopwords. talks bit load balancing. Load balancing stopword.