Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

Using Regular Expressions in C# vs PHP

Posted by Keith Elder | Posted in .Net, PHP | Posted on 05-12-2007

4

Recently at work I made a call out to all of the engineers to send me code they thought should be placed in the common library for .Net development.  In one of the responses I got an email from a PHP developer that shared a regular expression to check the format of money.  He stated he didn’t know how often we use them (referring to regular expressions) in C# but he thought he’d pass it along anyway.  That got me to thinking.  Do I use regular expressions as much in C# as I did in PHP? 

For those that are curious, the regular expression that was sent over works perfectly well in C#, no problems.  I think developers will find regular expressions will easily move from one to another.  If you happen to be porting PHP regular expressions to C# and vice versa you shouldn’t run into too many problems.  For example here is a quick test I threw together with the regular expression to make sure it worked.

using System;
using System.Text.RegularExpressions;

class Money
{
    public static void Main()
    {
        Regex exp = new Regex(@"^[1-9][0-9]{0,2}(,{0,1}[0-9]{3})*(\.[0-9]{0,2})$");
        Console.WriteLine(exp.IsMatch("123.23").ToString());
    }
}

When complied and ran it yielded the following result:

image

It worked.  When it comes to regular expressions within C# I have used them.  I find they are more like pepper sprinkled in a good stew rather than a main course meal.  That is how I would state the difference in use of them between the two languages.  If I had to give a percentage of how much less I use regular expressions I would definitely say more than half as much, and maybe go higher to 90% depending on the situation.  Why? 

I think it boils down to the reason that C# is strongly typed and PHP is loosely typed.  For example, the following code could never be written in C#. 

<?php
$x = 1;
$y = '2keith';

echo $x + $y;  // will print 3 (yes you can add strings and numbers in php)
// set $x to something completely different
$x = array('a', 'b', 'c', 'd');

echo $x[1]; // will print b
?>
Running the entire thing will result in:  3b

To some this example may be scary, others may look at it as a feature.  Whichever way you think, most developers when asked what the result will provide respond with all sorts of various answers.  When I taught PHP classes as a consultant I would use a similar example with the class.  To no exception, no one could ever predict the out come.  Answers given ranged from, it should throw an exception since you can’t add a string and a number.  Or it should throw an exception because the variable $x was reassigned to a different type.  

Do you see “why” PHP code relies on regular expressions more now?  Since $x can literally become any type at any time, a PHP developer can never rely on the fact that $x is an INT.  About the only way to check that value is the use of a regular expression.  In the PHP world it is called Type Juggling.  Conversely in C#, once the variable x is assigned a type, it cannot be changed and only valid numbers can be assigned to that type therefore eliminating the need to use a regular expression to check the value of the variable.

The question then becomes though, is this the C# way to test for the money value?  I would probably argue it isn’t the “best” way to handle money in C#.  While it certainly works there are other things to take into consideration when adding money.  For example two different types of money such as US Dollars and Euros cannot be added together.  It must first be exchanged and then added.  The same thing could be said of other operators performed against a variable of type money.  This is where it would be suitable to use a struct and create a new type called Money.

We can in C# declare a variable as the type of decimal and use it as money if we choose.  In this case we still don’t need a regular expression to validate the value of our variable.  Here’s a sample showing one way to handle a rogue value:

            decimal money;
            if (Decimal.TryParse("123.a234", out money))
            {
                Console.WriteLine("money is valid");
            }
            else
            {
                Console.WriteLine("money is invalid");
            }

I suspect a lot of programmers use this method but again a struct is more desirable.  Andre de Cavaignac has a great example of building a struct for a money type.  He provides these examples:

            Money eur10 = new Money(MoneyCurrency.Euro, 10);
            Money eurNeg10 = new Money(MoneyCurrency.USDollar, -10);
            Money usd10 = new Money(MoneyCurrency.USDollar, 10);
            Money usdZero = new Money(MoneyCurrency.USDollar, 0);

            bool result = (eur10 == usd10); // returns false;
            bool result = (eur10 > usd10); // throws InvalidOperationException (comparison not valid)
            bool result = (eur10 > Money.Zero); // returns true
            bool result = (eur10 > usd0); // returns true
            bool result = (usd10 > eurNeg10); // returns true (positive always greater than negative)

Obviously he’s put a lot of thought into how money should be handled and if you look at his library you’ll see he accounts for all different type of currencies. 

For those wondering the differences about regular expressions in PHP and C# I hope that gives you some insight into how the different languages respectively handle different situations.  It all boils down to strong typing vs loose typing and the ability to create new types based on structs.  Happy Holidays!

Open Source to .Net Transition – Mac or PC?

Posted by Keith Elder | Posted in .Net, Linux, Open Source, PHP | Posted on 23-10-2007

2

It seems that an article I wrote a while back is making its way around the Internet once again.  It never fails that once a year or every 6 months it pokes it’s head up from the ashes, dusts itself off and finds new readers.  The article I’m talking about is this one:

How an Open Source Developer Transitioned to .Net

It is an interesting read and if you haven’t read it, check it out.

I started getting lots of emails from readers last night and this morning as the article was passed around.  One person emailed me a question that was particular interesting after reading it:

Thanks for sharing your story on your transition from .php to .net. My main question is; did you also change from working on Macs to the inferior PC’s?

Obviously by the reference of “inferior PC’s” in the question we know where this reader stands.  It is sort of like one of those interview questions you get that is completely loaded.  For example, “So Mr. Person Wanting a Job…. things around here are really busy.  A lot of the times you have to switch tasks very quickly.  How would it make you feel if you were working on a project and then your manager asked you to stop it and move onto something else?”  Obviously the question has already been answered.  Or rather loaded up for you to respond in the way the person asking the question wants to hear.  By the way, if you ask these type of interview questions, stop.  They get you no where.  I digress though. 

I don’t know if this question is the same loaded type of question but my first reaction was, wait, aren’t Macs made up of the same parts that are in PCs?  It is a hard drive, processor, video card and memory.  Apple looks at various vendors and plugs in the best deal / bang for the buck just like any other PC manufacturer.  Are PCs really inferior just because Apple has a better looking plastic cover than most PCs?  I don’t think so since they are essentially made up of the same parts.  Case in point I recently upgraded the wife from an aging iBook to a HP notebook.  I think she got a far superior product for a whole lot less money compared to a Mac.  That’s another post that I’m working on though. 

Maybe he was talking about the PC operating system being inferior?  What if I am running FreeBSD on my PC, does that make it more superior to the Mac since OS X is really just FreeBSD under-the-hood?  Or what if I’m running an Intel version of BEOS?  Maybe it was a OS X vs Windows comment?  The reader didn’t say so I am totally speculating on what he’s “really” trying to ask and also infer.

Here is the bottom line folks.  When you chose a technology you ultimately chose a platform.  We all do it and to say we don’t is just wrong.  When I was writing PHP/MySQL I used Linux for years since I thought it was important to develop applications on the same OS the application was going to run on the server.  I knew the Linux platform inside and out.  Even enough to teach it at the college level.  Today I write .Net code and I write that on Windows for Windows.  Again, I think it is important to write software on the same platform it is going to run on.  The difference is when you chose .Net you are married to the Windows platform, at least today.

Whether you want it to be or not, there is a huge platform investment made as a developer to understand the full potential of our applications.  I have a buddy at work that has been doing Windows IT infrastructure related stuff for years.  He understands a lot of things under the hood of Windows that I don’t even understand.  For me he is a resource I use often to pick his brain to solve a problem.  More times than not, he has an easier way to solve a problem than I was thinking just because he knows the platform.   For .Net development it means that those of us doing .Net development are married to the platform of Windows.  That is not a bad thing though since from a business standpoint the platform as a whole provides a lot of value.  

Yes, I use PCs today as opposed to Macs.  I’d be completely non-productive and probably lacking brain cells to development enterprise applications on a Mac and boot Visual Studio in a virtual machine.  I’d also be completely non-productive trying to write .Net code using Mono with VI.   I’ve seen lots of Macs at conferences and even friends of mine that are fellow MVPs have purchased Macs and run Visual Studio in a VM or just run Windows on the Mac 100% of the time because they like the Apple notebook better.   For those running Windows on an Apple, if you want to pay the Apple tax and spend a lot more money for your shiny toy fine, at least you understand that you are ultimately writing .Net on Windows.   For those that boot virtual machines and do .Net development God bless you, you must have the patience of Job.  I’ve done it and ultimately I came to the conclusion of:  Damn this slow and non-productive.  BTW, if you are a client of a consultant and he/she walks in with a Mac and is doing .Net development for you.  Run!  They just doubled your billable hours haha!  I poke fun in jest obviously but hey, it is something to think about if you are footing the bill no?

The thing is I still like OS X.  Notice I didn’t say Apple, because I don’t like the Apple hardware tax having built computers for years.  The operating system I like, nay, completely admire still to this day.  I’ve spent many hours looking at XCode on Mac OS X wishing it could be my development platform of choice.  Wishfully thinking that I could get a job as an Enterprise OS X developer at one time.  I wrote a few programs for Mac OS X and found it to be 5-10 steps and way more complicated than it needed to be just to do something simple like put a button on a form using Cocoa.  Compared to Visual Studio dragging and dropping a button onto a form and double clicking to wire up an event is apples and oranges (pun intended).  I’m sorry, but Apple spends all their time on making their OS shiny and adding features for end users but doesn’t do a damn thing to help developers embrace their platform at all.  At least that is how I see it.  If you don’t agree, then feel free to shine some light on my short sightedness, I’m all ears.

So yes, I use PCs today, not a Mac, and I don’t feel when I wake up in the morning and sit down at my computer I’m using an inferior product.  As a matter of fact I feel I have more options using the Windows Platform than I do using a Mac, especially since there isn’t an Apple store within 300 miles from me.  Not only that but professionally I have all sorts of nice haves that run and are supported with the Windows platform such as integrated authentication for applications, SQL Server, Biztalk, Windows Presentation Foundation, Winforms, Asp.Net, Windows Communication Foundation, Workflow Foundation, Silverlight, Visual Studio, Ado.Net, Windows Mobile, Office (Word, Powerpoint, Excel, Infopath, Publisher), Sharepoint, built-in analysis and data mining features, OLAP, Report Services and much more.  Based on all of that reader, which platform seems inferior now?

 

How an open source developer transitioned to .Net

Posted by Keith Elder | Posted in .Net, Asp.Net, Open Source, PHP, Programming | Posted on 11-03-2006

0

For a long time I’ve been wanting to put this together.  A lot of my friends who were open source advocates like myself are perplexed with my transition to what they call the “Dark Side” of development.  Referring of course to Microsoft as the evil empire.  I took some time this morning to finish how and why I migrated from programming mainly in PHP to .Net.  I didn’t want to put this information into a blog post because as I was writing it, it just didn’t feel right so I created an article out of it.  In order to give you the full picture I give some information on my background to cement how firmly planted I was in open source technologies.  Then I give you some of my thoughts on the conversion process.  In the end, I give some advice for others that might be curious as how to make this conversion.

NOTE: This is the original article below (thank you wayback machine!)

Intro
Let me be the first to point out that I haven’t always done .Net. No one really has since it has been around for only a few years, let’s be honest.  For all practical purposes the technology is still fairly new.  Before .Net I was primarily developing web-based applications using LAMP (linux, apache, php, mysql).  The $1,000,000.00 question is how does one transition from LAMP to .Net?  And more important is why?  After all, aren’t those technologies left and right brian technologies?  These are the questions I hope to answer in this article.

My Background
Let’s first start out back in 1993 when I was in college.  In 1993 most computers were  Windows 3.1 and a few people were holding onto their Amigas while others were running a Mac.  486 computers reigned supreme and Doom 2 was the big hit.  I was bored with my Windows 3.1 486 computer though.  I had read just about every help file in the whole system and knew all the command line switches to programs that the average computer user didn’t even know existed.  I then got introduced to Linux by the primary Unix Administrator at the college.  I remember the day vividly because he called me into his office because I had taken over the X11 terminals in the lab and he wanted to know how I did it.  Sitting in his office he had a Gateway P133 machine running X11 (the primary graphics front-end to unix operating systems).  I of course questioned how he was running it on a standard PC because up until this time, standard PC equipment couldn’t be used.  Even though I was in trouble I was still curious.  He explained it was a new unix like operating system that was free.  He then showed me how he was using it and I was hooked.  The thought of running multiple programs at the same time on my PC and using the same tools the college was using (mainly so I could hack my friends shell accounts) was appealing.  I immediately went out and bought 50 floppy discs, download Slackware and started compiling.  Trying to get things to compile and work were just fun.  I spent 6 months just getting my Trident 1MB video card to work with XWindows.  I have no idea why at the time but looking back on it I guess this more challenging than the assignments I was getting from the teachers.

By 1994 I was working for the college IT department and we setup one of the first known Linux labs.  I think it was the first Linux lab in the country but I don’t have any proof, let’s just say we were an early adopter.  In the lab students could browse the web, write papers, all within their shell accounts on the cluster, or they could dual boot the computer into Windows.  Pretty cool stuff for 1994.  After I graduated college with a music degree and a computer science minior, I continued playing with Linux and open source software.  When my wife and I moved to Ann Arbor, MI, I joined a local Linux User Group.  It wasn’t long after joining I started presenting at the group with topics ranging from how to get your TV Tuner card to work in Linux to “Migrating Business Processes to the Web Using Open Source Technologies”.  I spent a lot of time coding and doing system administration in the open source world and in 1997 started my own web hosting company which I still have today.  Most everything I did after 1997 was based on what the community calls the LAMP model (Linux, Apache, Mysql, PHP).  I didn’t even have a Windows PC, except for my wife’s computer.  After doing so many Linux presentations and becoming somewhat of a go to guy based on my professional experience I was invited to teach at a local college.  There I taught four classes on Linux which led students to a Linux Certification.  The classes included an introduction, system administration, networking and security.  I also taught the first PHP class at the college and continued to do so until it got taken over by another professor.

After using Linux for years, I had taken the OS just about as far as I could take it.  I was growing tired of reading Howto’s, compiling code, posting to newsgroups, loading untested software and drivers and bringing down my PC for days at a time.  For me the experience was about learning.  In other words, why break a production server when I can break my own?  I was growing tired of this routine nevertheless.  Using a computer with Linux on it was like, well, work.  Using Linux on servers I was happy as a lark.  But, for my personal day to day machine, it was work.  Why couldn’t I just plug something into my personal PC  and it work?  Why did I have to touch the command line all the time?  Why did I have to compile or hack a driver just to plugin a digital camera and transfer a picture to the PC?

Once Apple announced Mac OS X I started watching it pretty closely.  I was waiting on the moment their new operating system (which was unix based) was ready for prime time.  In 2002 I decided to switch from Linux as my primary OS to OS X.  I acquired a Powerbook and an Ipod and was very pleased.  OS X was such a blessing over Linux.  I was a true convert even though my attempts to get into the switch commercials at the time failed.  I was shouting OS X from the roof tops.  I no longer had to fight Linux on a laptop to get work done and was able to do so much more.  During my Mac OS X switch I was working for a consulting company who focused on building web applications using the LAMP model. We held PHP User Group meetings at the company and several other members were moving to OS X as well.  It was a great combination.

In 2004 I was hired as a PHP developer for Quicken Loans.  When I joined the company I was given a dual processor Mac running OS X and told to write PHP code.  This was great!  I was working for one of the best companies in the country and getting to do what I loved.

As you can see I was an open source developer.  It’s the only thing I really knew and the only thing I had ever really done.

The Conversion Begins
After working at Quicken for several months I started to change.  Call it whatever you want but working for a larger company changed how I started to view things.  I can’t explain it but I started to somehow think differently about the technology I was so passionate about.  Was I maturing?  I don’t know.  In retrospect I think once you absorb a technology so deep, two things happen.  One is you get bored.  The otherthing that happens is you know all of the strengths and weaknesses of the technology and you find yourself looking at other technologies to plug into the holes.

Early in 2004, I started playing with .Net while researching Sharepoint Portal Server for the company’s intranet.  The company intranet was written in PHP and I was assigned to the intranet.  We were having lots of problems with single sign on and other things like integrating with Active Directory.   Without giving too many details away, let me just say that our intranet is huge.  Thousands and thousands of pages, applications, content, data, etc.  Basically if you want to know anything, you go to the intranet.  I started researching Sharepoint because I was asked to look at it.  It wasn’t something I would have started looking at on my own given my background that’s for sure.  As I researched Sharepoint and Asp.Net, the more I read, the more I became intrigued by it.  As I mentioned earlier I had become bored and disgruntled with PHP.  I felt I had done just about everything there was to do with the language and the platform.  And, let’s face it, PHP is just for the web.  I wanted something more.  Something that challenged me mentally while also making my life easier.  Something that I could learn that would provide me a one stop shop for whatever I wanted to write as a developer.  I was looking for a Swiss Army Knife. I wanted to be able to learn the ins and outs of one technology and then write either a web application, desktop application,  mobile application, smart phone application or anything in between.

While investigating .Net I decided I was going to take my open source advocate hat off and place it in the floor. I then approached .Net as if I was an unbiased “architect” who had to make a decision which technology he was going to recommend.  Once I made this conscious decision I started to notice how well thought out the platform was.  .Net wasn’t just a scripting language like PHP, this an entire platform full of swiss army knives!  I finally managed to get my hands on Visual Studio and this is where I became even more impressed!  But wait, this is a Microsoft technology!  This can’t be good.  I mean after all Macs rule supreme and open source rocks.  What was going on?  Could it be I was turning to the “dark side” after all of these years of avoiding it?

All the while I was researching .Net I was still writing PHP applications.  This is where I started to differentiate the technologies and this is important.  I started to catch myself saying things like, “I could have done this a lot easier in Asp.Net”, or “Man I wish I could debug this better”, or “Why do I have to build my own session object or cache object and waste my time?”.  I could feel the dark side coming over me as I added more features to our intranet and built additional one off applications.  Writing code in VIM or Zend Studio on my Mac started to become more of a chore or a task and I found myself fighting the tools I had used for years.

Defending the “Dark Side”
Obviously by this point I was at a crossroad.  Then one day I got into a discussion at the water cooler with a coworker.  I found myself in the middle of a .Net vs PHP dual.  My coworker had his PHP pistol drawn and was firing away at me.  Every shot my coworker hurled at me I was able to deflect.  This surprised me.  Speed he mentioned for example.  Asp.Net code is complied I said unlike PHP which is just a scripting language.  I can compile my PHP code to byte code he added, and then I said yes, but you have to purchase Zend’s compiler.  I don’t have to purchase anything I continued adding.  He then drew back his open source pistol and hurled another bullet at me and said, well, PHP is free.  I then said, so is .Net.  Anyone can download the .Net framework, install it and start writing .Net apps.  I then added there was even an open source project called Mono that is taking the .Net framework and building it cross platform.  My coworker had fired two shots and my .Net shield had deflected them.  What was going on?  Why was I defending the technology I had used for years?  He then had one shot left in his open source barrell.  He pulled the trigger and “security” was fired at me.  This was the one I knew he was going to bring up and  I had researched this very topic and was shocked at what I found.  So he states, “well, that doesn’t matter, PHP is still more secure than .Net”.  By this point in the dual he was getting frustrated and had starting moving from fact based arguing to emotional based arguing.  I could just tell by his tone.  Then I said, “That’s interesting you say that because I did some research on it and comparing the .Net framework to PHP since .Net’s first release, it has only had 3 security holes.  PHP has had 43.”.  My coworker then dropped his open source gun and said, “hmm, really?”.

Conversation Complete
At this point I knew my conversion to the “dark side” was complete.  I had evaluated both technologies.  One I knew extremely well, the other I was just scratching the surface but it didn’t matter because the more I dug into .Net the more I moved away from PHP.  By this point my love affair with .Net was starting to spread internally.  When one of your coworkers on the Unix Team starts calling you “Syth Lord Elder”, you know you have turned (true story, and he still calls me this to this day but he’s trying to find a word higher than Syth) to the “dark side”.  To my coworker’s credit who was at the water cooler the day I defended the “dark side” he started researching .Net. Today I am proud to report he and I were founding  members of our internal .Net team.

Since my “re-birth” as a programmer as I like to call it, I’ve done quite a bit with .Net.   I spend most of my time building a Smart Client at work along with a lot of web services and web applications.  I am also building mobile applications and working on a mobile CRM product for all of our bankers in my spare time.  I also spend a lot of time training and mentoring to other programmers who are moving from various languages to .Net too.  I enjoy the training and mentoring since I have an education degree.  I need to use it for something right?

Word of Advice
That’s it.  Now you know how an open source LAMP developer made the transition to .Net.  It has been a long road for me needless to say.  Getting out of your comfort zone and learning new things can be frustrating.  Trust me I know. Things that would take you two minutes, now take you twenty minutes because you have to read how to do it within the new platform.  My recommendation for anyone that wants to learn .Net that is coming from another background as I did is this:

  1. First and foremost throw yourself into a really good C# book.  Don’t bother reading anything else.  Learn the basics of the language first, then learn what the .Net framework provides you as a developer.  Remember that the language and the framework are two seperate things.
  2. Second, dive head first into the framework on MSDN.  Dig into the namespaces of System.Data, System.Collections, System.XML and those type of things that you are going to use all the time.
  3. After that, download Visual Studio Express for free and learn how to use the IDE.  This is where you’ll really start to see how complex things turn into simple drag and drop operations.
  4. Lastly, don’t get discouraged or overwhelmed at the amount of information on .Net.  There is tons of information about .Net on the Internet and it is easy to get overwhelmed.  Remember that Microsoft is a big company and they have 1,000’s of developers pumping out code everyday.  Don’t let it discourage you.

Drop me a Line
I was speaking to one of the Microsoft reps in Jackson, MS at the launch event and he says I’m the only person that he knows of doing .Net programming in Hattiesburg, MS.  That doesn’t surprise me, but by the slim chance that someone from Hattiesburg reads this for the love of a good framework contact me!  Just take my first name and this domain and you’ve got my email address (decrypt that spam engines!).

Scaling PHP

Posted by Keith Elder | Posted in Open Source, PHP, Programming | Posted on 24-05-2004

0

I found a really good article which outlines some nice tips to scaling PHP. The article is written by George Schlossnagle. In his article he explains why you do not need large DB abstraction layers like PEAR and ADODB and why you should NEVER use relative paths to images. The article can be found here.

LogiCreate Application Server Open Sourced

Posted by Keith Elder | Posted in Open Source, PHP, Programming | Posted on 07-06-2003

1

The LogiCreate Applicaton Server built with PHP was released as open source on June 5th, 2003. LogiCreate is a framework to build portals, CMS, CRM or custom web applications. It is extremely fast to start developing applications with, very little code for the developer to start writing and is extremely different from pretty much anything else out there right now. You can download the PDF presentation on the LogiCreate site as well as register on the site to download the system. We’ve been using it for several years now and will start offering hosting accounts pre-packaged with it soon.