Saturday, November 28, 2009

StackOverflowException overriding Page in custom class

I was overriding the Page in a custom class that defined user control specific things that my app would do while being run. Each user control inherited from this UserControl class that inherited from System.Web.UI.UserControl. The problem was every time I tried to access the property, I would get a StackOverflowException. My code:


public new VolatileMinds.Web.Common.Page Page { get { return this.Page as VolatileMinds.Web.Common.Page; } }


ended up looking like this;


public new VolatileMinds.Web.Common.Page { get { return System.Web.HttpContext.Current.Handler as VolatileMinds.Web.Common.Page; } }



The problem was that it was trying to recursively cast the Page over and over again, causing the StackOverflowException. Using the Current.Handler sovles this issue.

NOTE: I don't really use absolute namespaces when doing this stuff, I thought it would be easier, however, to understand what was happening if I did.

Friday, November 13, 2009

Cannot add an entity with a key that is already in use.

I got this error today while working with Linq2Sql.

I had an object "Person".

Person person = new Person();

Person has a property called Child, but the child already exists in the database. I thought that assigning the current child in the DB to the person.Child property would just set the value for the Person and not mess with child. It doesn't quite work that way.


person.Child = dc.Childs.Where(c => c.ChildID == childID).SingleOrDefault();


dc.Persons.InsertOnSubmit(person);
dc.SubmitChanges();


The last line will fail with the aformentioned error. I ended up using the ChildID property instead (the former was the better way for the problem at hand, but setting the child ID worked after adding some additional code) so it looked like this.


person.ChildID = childID;

dc.Persons.InsertOnSubmit(person);
dc.SubmitChanges();


The reason this happens is because  you are trying to save an object that is already in the database.
Nifty.

Wednesday, November 11, 2009

gnump3d on Karmic

Go here: http://packages.debian.org/etch/all/gnump3d/download

download from your favorite mirror.

sudo dpkg -i gnump3d*.deb


rejoice!

Sunday, November 8, 2009

Credit Card Validator in C#

I needed a credit card validator for a few of my projects. I found a few snippets of code throughout google, but nothing really just giving me what I needed, so I wanted to post my class. Maybe it will help others doing the same thing I did.

    public class CardValidator
    {
        public string CardType { get; private set; }
        public bool IsValid { get; private set; }
        public string ResultingError { get; private set; }
       
        public string CardNumber { get; set; }
        public DateTime CardExpiration { get; set; }

        public void Validate()
        {
            IsValid = false;

            if (string.IsNullOrEmpty(CardNumber))
            {
                ResultingError = "Card number empty....";
                return;
            }

            if (CardNumber.Length > 16)
            {
                ResultingError = "Card number too long";
                return;
            }

            foreach (char digit in CardNumber)
            {
                if (!char.IsDigit(digit))
                {
                    ResultingError = "Card number contains invalid characters";
                    return;
                }
            }

            if (CardExpiration < DateTime.Today)
            {
                ResultingError = "Card has expired.";
                return;
            }

            int sum = 0;
            for (int i = CardNumber.Length - 1; i >= 0; i--)
            {
                if (i % 2 == CardNumber.Length % 2)
                {
                    int n = int.Parse(CardNumber.Substring(i, 1)) * 2;
                    sum += (n / 10) + (n % 10);
                }
                else
                {
                    sum += int.Parse(CardNumber.Substring(i, 1));
                }
            }

            IsValid = (sum % 10 == 0);

            if (IsValid == true)
            {
                switch (CardNumber.Substring(0, 1))
                {
                    case "3":
                        CardType = "AMEX/Diners Club/JCB";
                        break;
                    case "4":
                        CardType = "VISA";
                        break;
                    case "5":
                        CardType = "MasterCard";
                        break;
                    case "6":
                        CardType = "Discover";
                        break;
                    default:
                        CardType = "Unknown";
                        break;
                }
            }
            else
            {
                CardType = "Invalid";
            }
        }
    }

Sunday, October 4, 2009

Getting an XmlElement from string in C#

I had a bunch of Xml coming at me in a POST response and needed it to be an XmlElement. I ended up doing writing a quick method that does the trick, but I am not sure if it is the best way (making it an extension method made sense in context).

public XmlElement ToXmlElement (this string xml)
{
XmlDocumentFragment frag = new XmlDocument().CreateDocumentFragment();

frag.InnerXml = xml;

return frag.FirstChild as XmlElement;
}

The problem with this is you have to assume the string you are passing in is well-f0rmed XML.

Friday, September 25, 2009

New ClamAV Live CD update

I updated the ClamAV Live CD to 0.95.2 today (finally). I have been wondering what I want to do with this project the past few months. When I first created the CD, I wanted it to be as small as possible so that I could put it on a 128 MB thumbdrive (or 150 MB mini-cd), so I worked extremely hard trying to get it as small as I could. I needed the CD to run on computers with as little as 128 MB of ram! I also didn't know it would be such a popular tool when I released the iso on my website, so I never included documentation on how to use it, prettied it up, things like that. I liked it the way it was, completely minimal and still gets the job done.

I have, however, gotten requests from a few people (five or so) that ask for it to be more user friendly. I am torn between the ease of use vs portability aspects of the project, so I ask you fellow Ubunteers your opinion. Of those who have used it, do you like the minimal approach, or would you prefer a prettier, more user friendly/graphical tool? Maybe two versions? If I went with the more graphical tool, I would look to utilize the full extent of a normal CD, so I would be including many more tools and such.

Thanks for any feedback!

Wednesday, September 16, 2009

AudibleManager in Ubuntu

So, it turns out that the AudibleManager software that Audible.com uses for it's audiobooks runs in wine for the most part. The one part that doesn't work is the one part that makes the actual software useful to install, and it looks like it is a bad API implemenation of InternetCrackUrlW() within the Windows inet libraries. It is taking a TLS session and assuming it is SSL, making an SSL request on the audible servers, with no SSL port being used on the Audible servers in the first place, causing a time out on authentication.

A few patches have been proposed on the bug page (http://bugs.winehq.org/show_bug.cgi?id=16831), but I was hoping that the last patch that seems to work had been employed into the latest stable version (it hasn't, quite a disappointment), so even using the wine apt repos rather than the ubuntu ones doesn't fix this for you. You have to patch it yourself.

No esta bien. And I am a big fan of audiobooks, so, please, no posts on how Audible.com is evil for it's DRM.

Tuesday, July 7, 2009

First recording with audacity underway!

So, I have decided to start recording some of my music. I am using Audacity atm until either A) I hit a brick wall with it and can no longer use it or B) I finish this song.

It is kind of Tool/NIN-y, so it isn't really the music _everyone_ likes.

Just the intro to the song for the time being, haven't gotten the whole thing worked out yet... It's about 3 minutes long (calculations tell me the whole song should be about 10 minute slong total when I am done).
http://files.volatileminds.net/nothing_intro.mp3

Criticisms and comments are much appreciated! /me looks at jono.

Saturday, June 6, 2009

Man, I love my internet....


the internet in my apt.

Friday, June 5, 2009

Looking for a job in germany....

Hello Planet, I am hoping you can help me!

I am currently looking for a new job. I have always wanted to live and work in Germany. I know people in Germany read the planet, so maybe, if anyone out there in Deutschland is looking for a .NET programmer/Systems Administrator/All around computer tech guy and is willing to sponsor a work visa, let me know in the comments or email me at bperry.volatile[at]gmail[dot]com and I will get you a resume.

I have managed Linux and Windows servers for the past three years, written .NET professionally for about one and a half years, and have excellent recommendations!

Thanks a bunch!

Monday, June 1, 2009

Running SQL scripts in order from C# code

I have a folder of SQL scripts being compiled as embedded resources. They are named as such:

01 FirstTable.sql
02 SecondTable.sql
etc...

so that way I can run them in the order they need to be run in when say, resetting a database. The problem I ran into was getting the resources through reflection gave them to me in the wrong order... the second script was trying to be run first and it relies on the first script, so that obviously didn't work. Running Array.Sort() on the script list fixed this problem. The code ended up looking like:


public void Reset()
{
if (string.IsNullOrEmpty(ConnectionString) && Connection == null)
throw new Exception("Connection string and connection are null.");
else
{
if (Connection == null)
Connection = new MySqlConnection(ConnectionString);

Connection.Open();

MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "DROP DATABASE SystemsLogica; CREATE DATABASE SystemsLogica; USE SystemsLogica;";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = Connection;

cmd.ExecuteNonQuery();

Assembly asm = Assembly.GetExecutingAssembly();

string[] scripts = asm.GetManifestResourceNames();
Array.Sort(scripts);

foreach (string file in scripts)
{
Stream res = asm.GetManifestResourceStream(file);
byte[] resbytes = new byte[res.Length];

res.Read(resbytes, 0, (int)res.Length);

Console.WriteLine(file);
Console.WriteLine("-----------------");
Console.WriteLine(Encoding.ASCII.GetString(resbytes));
Console.Write("\n\n\n");


using (cmd = new MySqlCommand())
{
cmd.CommandText = Encoding.ASCII.GetString(resbytes);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = Connection;

cmd.ExecuteNonQuery();
}

}

Connection.Close();
}
}


This works great in mono. This was just a test method, so there is no real error checking, so be careful.

Tuesday, May 5, 2009

2 things

Reset mac password without CD:

[Apple|Super]-S after chime
mount -uw /
rm /var/db/.AppleSetupDone
shutdown -h now

Office 2003 source doesn't match installation source.

Uninstall from the setup binary on the CD.
Go to Control Panel -> Add/Remove programs -> Remove Office 2003. For some reason, it isn't removed from this list. this causes many headaches later and took me a few hours to figure out.
Reinstall from CD.

Wednesday, April 22, 2009

Gdk.Color -> HTML hex string

String.Format("#{0:X2}{1:X2}{2:X2}", (byte)(colorSelector.CurrentColor.Red >> 8), (byte)(colorSelector.CurrentColor.Green >> 8), (byte)(colorSelector.CurrentColor.Blue >> 8));


or a better way:

currentEntry.Text = String.Format("#{0:X2}{1:X2}{2:X2}", (int)Math.Truncate(colorSelector.CurrentColor.Red / 256.00), (int)Math.Truncate(colorSelector.CurrentColor.Green / 256.00), (int)Math.Truncate(colorSelector.CurrentColor.Blue / 256.00));

Monday, January 19, 2009

Can you spot the bug?