Archives

Tagged ‘C#‘

Using C# to Generate Random String with Character Filter

I haven’t posted anything for awhile, and today while toying around with a few different things I decided to tweak my random string generator.  So I thought I’d share.

So here we have two methods; one for Unicode and one for ASCII. My thought was that when generating a simple password for US English keyboards, I’d just use a simple ASCII generator using characters available on the keyboard. For for the rest of you folks who don’t have a US English keyboard, maybe there are some options to generate a random string with a custom range filter. 

public static string GetRandomUnicodeString(int length, int maxValue, Predicate<int> valueFilter)
{
    byte[] seedBuff = new byte[4];
    byte[] charBuff;

    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    rng.GetBytes(seedBuff); // The array is now filled with cryptographically strong random bytes.

    using (MemoryStream ms = new MemoryStream())
    {
        using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false, false)))
        {
            var random = new Random(BitConverter.ToInt32(seedBuff, 0));

            for (int i = 0; i < length; i++)
            {
                int temp = random.Next(maxValue); //should we cap? 

                while (!valueFilter(temp))
                    temp = random.Next(maxValue);

                sw.Write((char)temp);
            }
        }
        charBuff = ms.ToArray();
    }
    return new System.Text.UTF8Encoding(false, false).GetString(charBuff);
}

public static string GetRandomASCIIString(int length)
{
    return GetRandomUnicodeString(length, 0x7E, o => o >= 0x21 && o <= 0x7E);
    //return GetRandomUnicodeString(length, 126, o => o >= 33 && o <= 126); //could use integers instead
}

So when using the Unicode method, you have to specify a max value; otherwise, the random generator will choke if you want a small range of numbers when randomizing a pool of 65,535 values. So the cap will help performance. The filter expression should filter out the random results so you only get the characters you want.

The ASCII method is a pretty simple example of how this works.  I want a max value of 126, and I want characters in the range of 33 through 126. I used hex (because the Windows character map uses hex).

Hope you all find it useful.  Let me know how it goes.

Setting up Mono 2.8 with Asp.Net 4.0 and MVC2 on Ubuntu with MySql Membership

I’ve had a few requests to write a full walk-through installing Mono 2.8 w/ Asp.Net 4.0 since I posted an install script for Mono 2.8 on Ubuntu and Fedora.  So here it is! We’re going to be setting up a new server from scratch then installing just the basics of Mono 2.8 (Mono, GTK, GDI, XSP, & Mod_Mono). Then we’ll use that to setup a new Apache server with a basic Asp.Net 4.0 MVC2 application w/ MySql Membership.  That sounds like a lot, but it’s really very straight forward. So lets get started!

Read more →

WCF Data Contracts and "k__BackingField" Property Naming

So recently, I was playing around with WCF, and I created a few classes that I wanted to expose in operations. Usually when I play with plain old objects, I tend to type them up pretty lazily and use any code shortcut I can. In this case I defined my properties using the 3.0 auto-generated field method, which looks like an interface property. The C# compiler automatically generates the backing field on the fly for me at compile time.  Here is a sample class I’m using in the silverlight music project.

[Serializable]
public class FileBrowser
{
    public string LocalMusicRoot { get; set; }
    public string WebMusicRoot { get; set; }
    public List<string> Files { get; set; }
}

imageThe catch comes in when you expose it to WCF. When serializing these objects, the serializer will look at all FIELDS of the class no matter their scope:  public, private, etc.  This is because it uses System.Runtime.Serialization, not System.Xml.Serialization. It does not serialize properties since properties really are just accessor functions.  So what you get is a funky looking proxy class with some properties you didn’t want and some cryptic naming. I.E. k__BackingField appended to your field names. The serializer simply takes what it has which is the auto-generated field name the C# compiler made for us.

So how do I clean this up?!?!   Easy!  Use a data contract.   By defining your classes using the DataContract attribute from System.Runtime.Serialization, the serializer will interpret your DataMembers as fields on the class and use your naming. It will also ignore anything that’s not defined as a DataMember; so that hidden stuff will remain hidden and not be included in the proxy class. Take a look at this.  We modified our original class with these attributes and the generated proxy class on the right now uses the names and fields we want!  Easy peasy!

Read more →