adamkdean

software engineering

Regex split by spaces except inside quote marks

By Adam K Dean on

Here's a nifty little bit of code I just wrote while writing a console input handler. Sometimes you will want to split up a string by a space, but then how do you input more than one word as a single argument? You put it in quote marks, but then how do you split those separately? Like this:

MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");

Yep, one line of code. Don't forget to include System.Text.RegularExpressions though!

Lets take it further for a little test (actually the test code I was using):

MatchCollection matches = Regex.Matches(p, "[^\\s\"']+|\"[^\"]*\"|'[^']*'");
WriteToConsole("Match Count: {0}", matches.Count);

foreach (Match match in matches) WriteToConsole(match.ToString());

Input:

The "quick brown fox" jumps over "the lazy dog"

Output:

Match Count: 5 The "quick brown fox" jumps over "the lazy dog"

So there you have it, probably the easiest way to do it.

Enjoy

Fibonacci Numbers & The Golden Ratio

By Adam K Dean on

So here I am doing some designs when I think, hmm, maybe I will use the golden ratio to lay out the design, Fibonacci's Spiral and what not, but the amount of tedious workings out.. (having to use a pencil..tedious...physical movement you see..) so I wrote a script. I don't really like using C# for scripts, being it isn't a script but.. sometimes you just want something like putty in your hands to quickly test a hypothesis or whatnot, and PHP is great for that. Big project, ASP.NET but a little versatile albeit-unable-to-really-report-errors-very-well scripting language, PHP is the don.

So, Fibonacci's numbers, very nice and easy to do:

<?php

$numbers[] = 0;
$numbers[] = 1;

$a = 0;
$b = 1;

for ($i = 0; $i < 10; $i++)
{
 $c = $a + $b;
 $a = $b;
 $b = $c;

 $numbers[] = $c;
}

// output
foreach($numbers as $n) echo "$n, ";

?>

and then for the golden ratio, a slightly bigger script.

<?php

error_reporting(E_ALL);

$width = 1024;
$height = 768;

$phi = 0.6180339887;

$boxes[] = array($width, $height);

for($i = 1; $i < 10; $i++)
    {
    $w = round($boxes[$i - 1][0] * $phi, 4);
    $h = round($boxes[$i - 1][1] * $phi, 4);
    $boxes[] = array($w, $h);
}

echo "<pre>";
for($i = 0; $i < count($boxes); $i++)
{
    $box = $boxes[$i];
    $w = sprintf("%-10s", $box[0]);
    $h = sprintf("%-10s", $box[1]);

    echo "W: $w H: $h "; 
    if ($i > 0)
    {
        $pbox = $boxes[$i - 1];
        $tw = sprintf("%-10s", $box[0] + $pbox[0]);
        $th = sprintf("%-10s", $box[1] + $pbox[1]);
        echo "TW: $tw TH: $th";
    }
    echo "\r\n";
}
echo "</pre>";

?>

You'll see I supply three variables, the initial width, height and then phi, which shouldn't really need to change. This script gives us a nice output, which works out the desired width and height for each new box, allowing you to quickly code that, rather than working it out and all that..tedious work..

W: 1024       H: 768        
W: 632.8668   H: 474.6501   TW: 1656.8668  TH: 1242.6501 
W: 391.1332   H: 293.3499   TW: 1024       TH: 768       
W: 241.7336   H: 181.3002   TW: 632.8668   TH: 474.6501  
W: 149.3996   H: 112.0497   TW: 391.1332   TH: 293.3499  
W: 92.334     H: 69.2505    TW: 241.7336   TH: 181.3002  
W: 57.0656    H: 42.7992    TW: 149.3996   TH: 112.0497  
W: 35.2685    H: 26.4514    TW: 92.3341    TH: 69.2506   
W: 21.7971    H: 16.3479    TW: 57.0656    TH: 42.7993   
W: 13.4713    H: 10.1036    TW: 35.2684    TH: 26.4515 

Simples, simply take your new width and height (W & H) and check the values add up (TW & TH add up the current and the previous width and height), and you're set.

Enjoy.

SQL INSERT with WHERE clause

By Adam K Dean on

So here I am, again, resigned to having to deal with SQL. I don't like SQL and it doesn't like me. One of the main reasons is because when I put a nicely formatted piece of code into Management Studio, it mangles it and disfigures it horribly as if saying "not only does this SQL not work but I have chewed it up and spat it back out at you."

I am currently writing a util to extract email addresses from a customer database and generate the SQL to insert them into our mailing list database. Rather than risk having two email addresses and therefore maybe spamming a customer, I wanted the get some SQL that would first check if the email existed within the database, and if not, then insert it.

After lots of horribly small examples SQL and about 45 Googles, I finally came up with some working code! Below you will see that I first check if a select statement does not exist. And then if it doesn't, I run the insert code. Nice and simple, yeah ...once it's done and working..

IF NOT EXISTS (SELECT EmailAddress FROM t_MailingList
 WHERE EmailAddress = 'test') 
BEGIN
 INSERT INTO t_MailingList
 (EmailAddress, AcceptsPostal, AcceptsEmail)
 VALUES ('test', 0, 1) 
END

P.S, if you get the compound errors like I did, then I suggest either 1) asking an experienced sqler, 2) keeping calm or my preferred method 3) a hammer. Enjoy!

Detect printing with CSS & ASP.NET

By Adam K Dean on

So, as in my previous post, I had an awesome idea of how to detect people printing a page of a website. Basically, when they go to print from our site, they get a different layout, that doesn't have anything that looks like a site. So surely if I just put a little tracker file in between the CSS file and the request, that'd work like a charm, right?

Wrong. In order to protect peoples privacy, all css files are now downloaded at page load, so every view registered as a print. Naturally, I checked what the bearded men of Google had to say, which wasn't much. HTC files, printer drivers and one even suggested something about an intranet...

So I posted on Dream.In.Code, asked the masses, and even RDC'd into my server to ask in #css on freenode irc.. then my own question gave me the answer.

To detect when someone prints a page on your site you just use CSS, it's really simple actually. Think, they will load the CSS when the page loads, but they won't process it unless someone prints, and you can use css to request images.. but .. how does CSS know if an image is an image or if it is a microwave meal? It doesn't until it requests it!

Don't forget to reference your stylesheet!

<link rel="stylesheet" href="print.css" media="print" type="text/css" />

So you just put your script inside an url()!!

body { background: url(PrintTracker.aspx); }

Works brilliantly, and the 'image' is requested every single time a page is printed, even the same one twice!

Awesome? I agree.

Update: It has been noted that print preview will fire this also. Bear that in mind.

Dynamic CSS with ASP.NET - in one line of code

By Adam K Dean on

Whether you want a separate sheet for each browser, or you want to track when people print a page from your site (as is my case), how do you get code to run in a CSS file? You can't. How do you get an ASPX file to serve up CSS? Well, you can't. But like House MD, I have the answer and I'll tell you eventually.

What you want to do is create an ASPX file, and in the Page_Load event, write whatever tracking or logic code you want, then simply redirect the page without any output.

protected void Page_Load(object sender, EventArgs e)
{
    // code here
    Response.Redirect("style.css", true);
}

And there you have it, Dynamic CSS with ASP.NET - in one line of code.