Using Reflection to get Assembly Information in C#

I've been working on improving my debug/error reporting capabilities (which includes unit testing, automation, etc.). One of the items on that list though, is what I actually record. Up until now that has included system information (OS, memory, etc.), basic profiling, error message, etc. However one of the items that would have been helpful and I simply wasn't recording was information about what assemblies were currently loaded by the system. It's usually easy to figure out (just look at the references list), but sometimes a few get in there that you aren't expecting. So to help out, I created a couple functions to find out this information:


        public static string DumpAllAssembliesAndProperties()
        {
            StringBuilder Builder = new StringBuilder();
            Assembly[] Assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly Assembly in Assemblies)
            {
                Builder.Append("<strong>" + Assembly.GetName().Name + "</strong><br />");
                Builder.Append(DumpProperties(Assembly)+"<br /><br />");
            }
            return Builder.ToString();
        }

        public static string DumpProperties(object Object)
        {
            try
            {
                StringBuilder TempValue = new StringBuilder();
                TempValue.Append("<table><thead><tr><th>Property Name</th><th>Property Value</th></tr></thead><tbody>");
                Type ObjectType = Object.GetType();
                PropertyInfo[] Properties = ObjectType.GetProperties();
                foreach (PropertyInfo Property in Properties)
                {
                    TempValue.Append("<tr><td>" + Property.Name + "</td><td>");
                    if (Property.GetIndexParameters().Length == 0)
                    {
                        try
                        {
                            TempValue.Append(Property.GetValue(Object, null) == null ? "null" : Property.GetValue(Object, null).ToString());
                        }
                        catch { }
                    }
                    TempValue.Append("</td></tr>");
                }
                TempValue.Append("</tbody></table>");
                return TempValue.ToString();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }

The above function DumpAllAssembliesAndProperties is the one you want to call. It in turn will figure out what assemblies are loaded and output (in an HTML formatted string) the name as well as property information (file name, etc.). It's pretty basic but thanks to the function I was able to find a couple dependencies and remove them and in one case discovered I was using the wrong version. Also note that the DumpProperties function will allow you to take any object and dump the properties of it along with their current values (another useful function to have around when debugging). Anyway, I hope this helps you out. So try out the code, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 11/26/2008 at 1:27 PM
Tags: , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Random String/Password Generation in C#

I'm guessing that someone out there has been in my position at some point in time... Basically I needed a password generator for a web site that I'm working on. I've seen a number of password generators out there and to be honest, I'm not a big fan of most of them. At the same time I couldn't use the default membership providers (long story as to why not). So basically I was stuck finding a way to generate my own random passwords (not to mention my own membership provider).

It's not a difficult task mind you, just annoying. That being said, I came up with the following class:

    public class Random:System.Random
    {
        public Random()
            : base()
        {
        }

        public Random(int Seed)
            : base(Seed)
        {
        }

        public string NextString(int Length)
        {
            if(Length<1)
                return "";
            StringBuilder TempBuilder=new StringBuilder();
            while(TempBuilder.Length<Length)
            {
                TempBuilder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(94*NextDouble()+32))));
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length,string AllowedCharacters)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer=new Regex(AllowedCharacters);
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if(Comparer.IsMatch(TempValue))
                    TempBuilder.Append(TempValue);
            }
            return TempBuilder.ToString();
        }

        public string NextString(int Length, string AllowedCharacters,int NumberOfNonAlphaNumericsAllowed)
        {
            if (Length < 1)
                return "";
            StringBuilder TempBuilder = new StringBuilder();
            Regex Comparer = new Regex(AllowedCharacters);
            Regex AlphaNumbericComparer=new Regex("[0-9a-zA-z]");
            int Counter = 0;
            while (TempBuilder.Length < Length)
            {
                string TempValue = new string(Convert.ToChar(Convert.ToInt32(Math.Floor(94 * NextDouble() + 32))), 1);
                if (Comparer.IsMatch(TempValue))
                {
                    if (!AlphaNumbericComparer.IsMatch(TempValue) && NumberOfNonAlphaNumericsAllowed > Counter)
                    {
                        TempBuilder.Append(TempValue);
                        ++Counter;
                    }
                    else if (AlphaNumbericComparer.IsMatch(TempValue))
                    {
                        TempBuilder.Append(TempValue);
                    }
                }
            }
            return TempBuilder.ToString();
        }
    }

This class has three functions that it adds to the Random classes normal ones (NextDouble, etc.). The one that is probably of most interest is going to be the last one. That function takes in the length of the string that you want, a regular expression stating what characters are allowed, and the number of non alpha numeric characters. So for instance calling the function with this:

NextString(10,"[0-9a-zA-Z_]",1);

That would create a random string of 10 characters that contained letters, numbers, and up to one underscore. The other functions are similar but with less control. For instance the one that just takes the length will use all characters on the ASCII table from 32 (space) up to 126 (~). But you can use this for quite a few items, passwords, testing, blog post generation when you're extremely bored and lazy... The list is rather endless... Anyway, I hope this helps someone out, so try out the code, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 11/24/2008 at 11:27 AM
Tags: , , ,
Categories: ASP.Net | C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Connecting to GMail using Pop3, plus MIME Format Reader in C#

That's a long title but it's the best description of what I have for you today. I'll be up front about it as well, I took code from here and here to figure this out because to be honest, the MIME format seems as though it was designed by some evil genius to bring pain and destruction to the world (a decent header structure would have been nice. I understand the logic behind it all, but still some more structure would be nice). The code for both has been modified though. For instance there were a number of issues with the Pop3 client code when trying to connect to GMail, response issues, some blocking and error issues, etc. The MIME code on the other hand had other issues with regard to decoding content, couldn't tell "To" and "to" were the same thing in the header, etc. (I'm still not 100% there either), plus I wasn't a big fan of the layout of the classes (I'm not that happy with my own either but it's slowly getting there). Anyway, here's my version of the code:

Pop3.zip (14.99 kb)

The code is divided into Pop3 (which is commented) and MIME code (which is not commented because I'm not done with it yet and I plan to refactor it completely). The classes that you're going to deal with (even though there are quite a few) are Pop3Client and MIMEMessage. Pop3Client connects to the server and has the ability to get a list of messages, their content, delete messages, and disconnect from the server. The MIMEMessage class actually contains the message (a simple ToString() on it will get the entire text of the message) and has properties for getting whom it is to, whom it is from, the subject, and the body of the message (although I don't have the decoding 100% yet on that, plus it spits out the first body text it finds which could be HTML or plain text). Anyway, lets look at some example code:

            Utilities.Email.Pop3.Pop3Client Client=new Utilities.Email.Pop3.Pop3Client();
            Client.UseSSL = true;
            Client.Connect(emailaddress,password,"pop.gmail.com",995);
            List<Utilities.Email.Pop3.Message> Messages = Client.GetMessageList();
            if (Messages.Count > 0)
            {
                Utilities.Email.Pop3.Message Message=Client.GetMessage(Messages[0]);
                DivContentHolder.InnerHtml = Message.MessageBody.To + "<br />";
                DivContentHolder.InnerHtml += Message.MessageBody.From + "<br />";
                DivContentHolder.InnerHtml += Message.MessageBody.Subject + "<br />";
                DivContentHolder.InnerHtml += Message.MessageBody.BodyText;
            }
            Client.Disconnect();

Note that DivContentHolder is simply a div that I put the information into. But all the code above does is creates a Pop3Client object, tells it we're using SSL, connects to the server (make sure to set up the login info), asks for a list of messages, and puts the first message it gets into a div on a web page after which it disconnects from the server. That's pretty much it as far as using the code. There are a few things to keep in mind though when connecting to GMail:

  1. Google requires you to use SSL to connect to their server. That is why we set UseSSL to true. If you're connecting somewhere else, you may not need to do this.
  2. They use pop.gmail.com as the server, and port number 995. Not 110 like most Pop3 servers (once again due to SSL).
  3. Every time you connect message 0 may not be the same message each time.
  4. This retrieves messages you've sent as well as messages you've received (at least in my experiments).
  5. ALWAYS DISCONNECT PROPERLY.

That's all there is to it really. So download the code, leave feedback, and happy coding.

kick it on DotNetKicks.com   Shout it
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListEmail

Posted by: James Craig
Posted on: 11/21/2008 at 10:23 AM
Tags: , , ,
Categories: C#
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed