Sep142011

New blog post address

Published by Marino at 1:58 PM under

Okay, after some blog posts I found out it's far easier to move my blog to WordPress! Why? Because I do not have to maintain the system myself. :-)

So no new blog posts will appear on my site! Instead, go to my new blog page: http://marinovdh.wordpress.com/ 

Enjoy!!



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Aug152011

Use the iPhone UIPickerView control as a selectbox on your website with jQuery

Published by Marino at 9:37 PM under iPhone | jQuery | UI | UIPickerView

For some time I'd been searching for a control simulating the iPhone UIPickerView control. My client likes the UI (and especially the UX) of it and loved to see it in an internal web application. So before inventing the wheel myself I searched the web for any similar control, either with javascript or Silverlight. But unfortunately I couldn't find any existing control that filled my needs. And therefore I spent some time building it myself. A great exercise with a nice learning curve for jQuery which I have not used enough lately.

Okay, what do I want? On a webpage I want a control like this:



be transformed to this:



And also I need the following features:
  • - The original control (with it’s original ID) needs to be available on the page;
  • - The original control needs to be invisible of course;
  • - The selectedIndex of the original control should also be the selectedIndex of the new control;
  • - Changing the selected value on the new picker-control should change the selected value on the original control;
  • - I want to be able to change the width on the new control (actually also the height but that’s more something for version 2 ;-)
  • - The css class on the original control should be used on the new control as well;
Enough wishes. To create this control I started with the Overscroll jQuery PlugIn that Jonathan Azoff has built (http://www.azoffdesign.com/overscroll). I added some wrapper divs that include a content div which got scrollable by Azoff’s PlugIn. I also added some design (images and styles, without the need of an external stylesheet). Then I tweaked my new control so that a value is always selected. This was the big challenge because a selected value needs to be exactly in the middle of the control after scrolling in it.

How to implement
It's rather simple to use my PlugIn. It's been designed just like other jQuery extensions so al you have to do is insert a script and call a method.
<select id="countries2">
	<option value="6">Austria</option>
	<option value="2">Belgium</option>
	<option value="5">France</option>
	<option value="3">Germany</option>
	<option value="8">Great Britain</option>
	<option value="4">Luxembourg</option>
	<option selected="selected" value="1">Netherlands</option>
	<option value="10">Spain</option>
	<option value="9">Sweden</option>
	<option value="7">Switserland</option>
</select>

<script type="text/javascript" src="/Scripts/jquery.iphonepicker.js"></script>
<script type="text/javascript">
	$(document).ready(function () {
		$('#countries2').iPhonePicker({ width: '100px', imgRoot: '/Images/UIPickerView/' }); 
	});
</script>
 
So all you need is this javascript-file and you're ready to go!
 
Disclaimer: I cannot guarantee the images will stay available on my blog/site. So if you use the control, you probably want to download the images (perhaps enhance them J) and then save them locally. Use the option “imgRoot” to redirect to your images directory. There are also more features possible, like many design options could be added, but I have chosen not to build a fully features control. I needed one myself and it's not commercially.  


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 2 Responses

Jul042011

Wrap that .Net RegEx to get the easy 80/20-rule

Published by Marino at 1:25 PM under C# | Programming

Too many times I want to use a Regular Expression to solve a simple string-problem and have to dive into regex's again. And most of the times I basically want the same thing: find or replace a piece of text within a line of text. Because I don't use regular expressions on a daily bases it always takes some time and Googling before I have my answer. So today I finally decided to write a little wrapper for it so I can reuse it whenever I want. This will save me a lot of time in the future, that's for sure!

 

So here's the code, perhaps you can use it and take your advantage. :-) Any feedback is welcome (because most likely it can be improved...).

 

The goal here is to get a wrapper method that can be used to find a particular string in a piece of text with the use of wildcard search. Since TDD it a good way to show what I want, I first give you 3 test-methods: 

[TestMethod]
public void TestContainsPattern()
{
	const string text = "Hello world [User002].";

	bool patternFound1 = text.IsPatternMatch("[user*]");
	Assert.IsTrue(patternFound1);

	bool patternFound2 = text.IsPatternMatch("[user??2]");
	Assert.IsTrue(patternFound2);

	bool patternFound3 = text.IsPatternMatch("[User??2]", true);	// Case sensitive
	Assert.IsTrue(patternFound3);

	bool patternNotFound1 = text.IsPatternMatch("(user*)");
	Assert.IsFalse(patternNotFound1);

	bool patternNotFound2 = text.IsPatternMatch("(user*)", true);	// Case sensitive
	Assert.IsFalse(patternNotFound2);
}

[TestMethod]
public void TestSearchPattern()
{
	const string text = "Hello world [USER002].";

	string msg1 = text.PatternSearch("[user*]");
	Assert.AreEqual(msg1, "[USER002]");

	string msg2 = text.PatternSearch("[user*]", false, true);	// Exclude pattern so result is the wildcard replacement	
	Assert.AreEqual(msg2, "002");

	string msg3 = text.PatternSearch("[user*]", true, false);	// Case sensitive search so no result
	Assert.AreEqual(msg3, "");

	string msg4 = text.PatternSearch("[user*]", true, true);	// Case sensitive so doesn't have impact on pattern showing
	Assert.AreEqual(msg4, "");

	string msg5 = text.PatternSearch("[user00?]", false, true);	// Exclude pattern so result is the wildcard replacement
	Assert.AreEqual(msg5, "2");

	string msg6 = text.PatternSearch("[user???]", false, true);	// Same here, result is the wildcard replacement
	Assert.AreEqual(msg6, "002");

	const string text2 = "Codes [USER002], [USER008]...";

	string msg7 = text2.PatternSearch("[user*]");
	Assert.AreEqual(msg7, "[USER002], [USER008]");	// Pity, I wanted the first match but apparently an 'outer' match yields
}

[TestMethod]
public void TestReplacePattern()
{
	const string text = "Hello world [USER002].";

	string msg1 = text.PatternReplace("[user*]", "and Marino");
	Assert.AreEqual("Hello world and Marino.", msg1);

	string msg2 = text.PatternReplace("[user00?]", "and Marino");
	Assert.AreEqual("Hello world and Marino.", msg2);

	string msg3 = text.PatternReplace("Daffy Duck", "XXX");		// Text to replace won't be found, so no change
	Assert.AreEqual("Hello world [USER002].", msg3);

	string msg4 = text.PatternReplace("[user00?]", "and Marino", true);	// Case sensitive search without match, so no change
	Assert.AreEqual("Hello world [USER002].", msg4);
}
Now you've seen what I mean, it's time for the implementation.
/// <summary>
/// Simple search for a pattern in the given text. The pattern can contain '*' and '?' signs for wildcard searches. 
/// A '*' can replace multiple characters while a '?' replaces one single character.
/// </summary>
/// <param name="text">Text string</param>
/// <param name="pattern">Pattern to search for</param>
/// <param name="searchCaseSensitive">True if the search should be Case Sensitive (false is the default value)</param>
/// <returns>True if the pattern was found in the text</returns>
public static bool IsPatternMatch(this string text, string pattern, bool searchCaseSensitive = false)
{
	RegexOptions option = (searchCaseSensitive == false) ? RegexOptions.IgnoreCase : RegexOptions.None;
	string regexPattern = ReplaceRegexChars(pattern);

	Regex regex = new Regex(regexPattern, option);
			
	return regex.IsMatch(text);
}

/// <summary>
/// Simple search for a pattern in the given text. The pattern can contain '*' and '?' signs for wildcard searches. 
/// A '*' can replace multiple characters while a '?' replaces one single character.
/// <example>
///	PatternSearch("code [User002]", "[user???]")				=> "[User002]"	- Pattern is recognized and the result is returned
///	PatternSearch("code [User002]", "[user???]", false)		=> ""			- Pattern is not recognized because of case insensitive was set off for search
///	PatternSearch("code [User002]", "[user???]", true, true)	=> "002"		- Pattern is recognized and only the wildcard result is returned
///	PatternSearch("code [User002]", "[User???]", false, true)	=> "002"		- Same as above but now also the case sensitive search was succesful
///	PatternSearch("code [User002]", "[user*]")					=> "[User002]"	- The * wildcard can be used as well
///	PatternSearch("codes [User002], [User008]", "[user*]")		=> "[User002], [User008]"	- It's a SIMPLE search so (unfortunately) the first OUTER result is returned
/// </example>
/// </summary>
/// <param name="text">The given text to search in</param>
/// <param name="pattern">A text pattern to look for, possibly with wildcards ("*" or "?")</param>
/// <param name="searchCaseSensitive">True if the search should be Case Sensitive (false is the default value)</param>
/// <param name="excludePatternInResult">True is a wildcard search is made and only the wildcard result should be returned (false is the default value)</param>
/// <returns>The found result as a string</returns>
public static string PatternSearch(this string text, string pattern, bool searchCaseSensitive = false, bool excludePatternInResult = false)
{
	string regexPattern = ReplaceRegexChars(pattern);
	RegexOptions options = (searchCaseSensitive == false) 
		? RegexOptions.IgnoreCase | RegexOptions.CultureInvariant 
		: RegexOptions.CultureInvariant;

	Regex regex = new Regex(regexPattern, options);

	Match match = regex.Match(text);

	if (match.Success && excludePatternInResult == false)
		return match.ToString();
	if (match.Success && match.Groups.Count > 1)
		return match.Groups[1].Value;
	return String.Empty;
}

/// <summary>
/// Simple replace for a pattern in the given text. The pattern can contain '*' and '?' signs for wildcard searches. 
/// A '*' can replace multiple characters while a '?' replaces one single character.
/// <example>
///	PatternReplace("Hello world [User002]", "[user*]", "and Marino")	=> "Hello World and Marino." - Pattern is recognized and the result is returned
///	PatternReplace("Hello world [User002]", "[user00?]", "and Marino")	=> "Hello World and Marino." - Pattern is recognized and the result is returned
///	PatternReplace("Hello world [User002]", "Daffy Duck", "XXX")		=> "Hello World [USER002]."	- Pattern is NOT recognized so no change
///	PatternReplace("Hello world [User002]", "[user00?]", "and Marino", true)	=> "Hello World [USER002]."	- Case sensitive search so pattern is NOT recognized thus no change
/// </example>
/// </summary>
/// <param name="text">The given text to search in</param>
/// <param name="pattern">A text pattern to look for, possibly with wildcards ("*" or "?")</param>
/// <param name="replacement">A string used for replacing the pattern if a match is found</param>
/// <param name="searchCaseSensitive">True if the search should be Case Sensitive (false is the default value)</param>
/// <returns>The given text with a possible found pattern replaced by another text</returns>
public static string PatternReplace(this string text, string pattern, string replacement, bool searchCaseSensitive = false)
{
	string regexPattern = ReplaceRegexChars(pattern);
	RegexOptions options = RegexOptions.CultureInvariant;

	if (searchCaseSensitive == false)
		options |=  RegexOptions.IgnoreCase;

	string result = Regex.Replace(text, regexPattern, replacement, options);

	return result;
}

/// <summary>
/// A rather dirty method to replace a user pattern with a Regex-pattern. For the 'normal' cases it will work,
/// but I can imagine a more exotic string pattern will cause unexpected results.
/// </summary>
/// <param name="text">A given pattern string</param>
/// <returns>The text rewritten as RegEx pattern</returns>
private static string ReplaceRegexChars(this IEnumerable<char> text)
{
	const string regexChars = @"+.^$|\{}[]()-";
	string retVal = String.Empty;
	bool isInWildcardChar = false;

	foreach (var c in text)
	{
		switch (c.ToString())
		{
			case "*":
				retVal += isInWildcardChar ? ".+" : "(.+";
				isInWildcardChar = true;
				break;

			case "?":
				retVal += isInWildcardChar ? "." : "(.";
				isInWildcardChar = true;
				break;

			case " ":
				if (isInWildcardChar)
				{
					retVal += ")";  // Close the wildcard search
					isInWildcardChar = false;
				}
				retVal += @"\s";
				break;

			default:
				if (isInWildcardChar)
				{
					retVal += ")";  // Close the wildcard search
					isInWildcardChar = false;
				}
				if (regexChars.Contains(c.ToString()))
					retVal += @"\";
				retVal += c;
				break;
		}
	}

	if (isInWildcardChar)
	{
		retVal += ")";  // Close the wildcard search
	}

	return retVal;
}
Btw, since a year or so I have my own reference-project in which I save all my hand-written, reusably code. I should have started this much earlier because it's an enormous time-saver! The only overhead you have is copy/pasting reusably methods from your working solution to your reference solution. My previous thought of having complete customer's solutions as a reference didn't work out that well. In the time needed to find some implementation (if even found) I could have written it again, and even better ;-)


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 1 Responses

Feb102011

Validating Joomla 1.5 passwords with C#

Published by Marino at 11:18 AM under Programming

This week I was integrating a Joomla website with my backend system. I am writing the backend system in C# 4.0 and for this I wanted to use the Joomla user management for the backend as well. The only challenge was being able to validate the Joomla hashed passwords with a given username and password.

I couldn't find any C# reference code on the web, only a java implementation at the Joomla forum by daud.lambert. Therefore I rewrote his implementation and share my code here with you.

/// <summary>
/// Joomla 1.5 used MD5 for hashing including a salt option
/// </summary>
public class Joomla15PasswordHash
{
    public static bool Check(String localpassword, String passwordInDb)
    {
        if (localpassword == null || string.IsNullOrEmpty(passwordInDb))
            throw new ArgumentException();

        String[] arr = passwordInDb
            .Split(":".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries);

        if (arr.Length == 2)
        {
            // new format as {HASH}:{SALT}
            String cryptpass = arr[0];
            String salt = arr[1];

            return CreateMd5Hash(localpassword + salt).Equals(cryptpass);
        }
        else
        {
            // old format as {HASH} just like PHPbb and many other apps
            String cryptpass = passwordInDb;

            return CreateMd5Hash(localpassword).Equals(cryptpass);
        }
    }


    public static String Create(String passwd)
    {
        var rnd = new Random();
        var saltBuf = new StringBuilder();
        const string seedList = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
        for (int i = 0; i < 32; i++) 
        { 
                int rndIndex = rnd.Next(62); 
                saltBuf.Append(seedList.Substring(rndIndex, 1)); 
        } 

        String salt = saltBuf.ToString();

        return CreateMd5Hash(passwd + salt) + ":" + salt;
    }

    /** Takes the MD5 hash of a sequence of ASCII or LATIN1 characters,
    *  and returns it as a 32-character lowercase hex string.
    *
    *  Equivalent to MySQL's MD5() function 
    *  and to perl's Digest::MD5::md5_hex(),
    *  and to PHP's md5().
    *
    *  Does no error-checking of the input,  but only uses the low 8 bits
    *  from each input character.
    */
    private static String CreateMd5Hash(String data)
    {
        byte[] bdata = new byte[data.Length];
        byte[] hash;

        for (int i = 0; i < data.Length; i++)
        {
            bdata[i] = (byte)(data[i] & 0xff);
        }

        try
        {
            MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
            hash = md5Provider.ComputeHash(bdata);
        }
        catch (SecurityException e)
        {
            throw new ApplicationException("A security encryption error occured.", e);
        }

        var result = new StringBuilder(32);

        foreach (byte t in hash)
        {
            String x = (t & 0xff).ToString("X").ToLowerInvariant();

            if (x.Length < 2)
            {
                result.Append("0");
            }
            result.Append(x);
        }

        return result.ToString();
    }
}


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 4 Responses