Timing SQL statements

Often, when comparing two SQL statements for speed, you end up relying on the counter in the bottom left counter of SQL Management studio,
but if you’re trying to shave milliseconds off a query that takes under a second than the result "00:00:00" doesn’t give you anything to go on.

So; instead, if you declare a @timeStart as a datetime, run your query, then get a datediff in milliseconds against the current time, then you get something more meaningful.

declare @timeStart as datetime
set @timeStart = getdate()
select count(*) from foo
select datediff(ms,@timestart,getdate())

In the above code block "select count(*) from foo" is the query I want to test.

Categories: Uncategorized

‘Not a real geek Goodbye my friends’ – Skyscanner’s Geek of the Week

SkyScanner’s Geek of the week had this puzzle:

 here’s a message for anyone fluent in
Regex:

import re
re.sub("(?si)z", " ",
re.sub("(?si)[^abdefgiklmnorstyz]", "", """NcoHjptXzuQvaJqPzu
rCeUhxaClHpqzJgWupeheCPxkczWXhGJoUvpocdHQubVyWjpecjzHpmXuyQvzH
wfPcrXuijepHnqVdjs"""))

Couldn’t help myself with the challenge:

C:Python26>python.exe
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.sub("(?si)z", " ", re.sub("(?si)[^abdefgiklmnorstyz]", "", """NcoHjptXzuQ
vaJqPzu
… rCeUhxaClHpqzJgWupeheCPxkczWXhGJoUvpocdHQubVyWjpecjzHpmXuyQvzH
… wfPcrXuijepHnqVdjs"""))
‘Not a real geek Goodbye my friends’

Categories: Uncategorized

.NET PHP Interop – Evaluate C# from PHP

Download: http://sites.google.com/site/appanalyzecomponent/phptodotnet

This code allows you to evaluate C# code in PHP.

Download the code above, import the DLL into the GAC, and create a PHP file as below:

<?php

//create an instance of the  ADO connection object
 $phpdotnet = new COM ("PhpDotNet.PhpDotNet")
  or die("Cannot start PhpDotNet.PhpDotNet");

 echo $phpdotnet->Info();
 echo ‘<br> ‘;
 echo ‘Windows folder is located at: ‘;
 echo $phpdotnet->Eval(‘Environment.GetEnvironmentVariable("SystemRoot")’);

?>

— See that Environment.GetEnvironmentVariable("SystemRoot") is C# code, not PHP.

using System.CodeDom.Compiler;
using System.Runtime.InteropServices;
using System.Text;

namespace PhpDotNet
{
    /// <summary>
    /// COM Interface
    /// </summary>
    [Guid("D5FA3365-D97F-49a9-A970-CDD5E0A3609F")]
    public interface IPhpDotNet
    {
        [DispId(1)]
        string Info();

        [DispId(2)]
        object Eval(string sCSCode);
    }
   
    /// <summary>
    /// COM Events interface
    /// </summary>
    [Guid("13F93C05-C751-4691-8888-BD72F13DCF04"),
    InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IPhpDotNetEvents
    {
    }

    /// <summary>
    /// Implemintation
    /// </summary>
    public class PhpDotNet : IPhpDotNet
    {

        public string Info()
        {
            return "Php.NET is now working";
        }

        /// <summary>
        /// Evaluate custom c# Code.
        /// http://www.codeproject.com/KB/cs/evalcscode.aspx
        /// </summary>
        /// <param name="sCSCode"></param>
        /// <returns></returns>
        public object Eval(string sCSCode)
        {
            var provider = CodeDomProvider.CreateProvider("CSharp");
            var cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.ReferencedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("system.windows.forms.dll");
            cp.ReferencedAssemblies.Add("system.drawing.dll");
            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;
            var sb = new StringBuilder("");
            sb.Append("using System;n");
            sb.Append("using System.Xml;n");
            sb.Append("using System.Data;n");
            sb.Append("using System.Data.SqlClient;n");
            sb.Append("using System.Windows.Forms;n");
            sb.Append("using System.Drawing;n");
            sb.Append("namespace CSCodeEvaler{ n");
            sb.Append("public class CSCodeEvaler{ n");
            sb.Append("public object EvalCode(){n");
            sb.Append("return " + sCSCode + "; n");
            sb.Append("} n");
            sb.Append("} n");
            sb.Append("}n");
            var cr = provider.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                return cr.Errors[0].ErrorText;
            }
            var a = cr.CompiledAssembly;
            var o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
            var t = o.GetType();
            var mi = t.GetMethod("EvalCode");
            var s = mi.Invoke(o, null);
            return s;
        }
    }
}

Categories: Uncategorized

Read Web.Config from PHP

Here is some code to read a setting from an ASP.NET web.config file using PHP

<?php
try
{
    function GetSetting($key)
    {
     $sxe = simplexml_load_file("C:Inetpubwwwrootweb.config");
     foreach($sxe->xpath(‘/configuration/appSettings/add’) as $item) {
        if ($item[‘key’] ==$key) return $item[‘value’];
     }
    }
    echo GetSetting(‘sqlclient’);
}
catch(Exception $e)
{
  echo ‘Message: ‘ .$e->getMessage();
}
?>

Categories: Uncategorized

Site down for a month!

Categories: Uncategorized

GD Library Error: imagecreatetruecolor does not exist (FIX)

I got the Timthumb php script image resizer installed this morning on my windows (IIS) machine, with about an hour of fiddling, here’s what I went through

1. At the start, all php pages were throwing up a php_via_fastcgi error

Reading some blog posts, the diagnostic step was to do this
%WINDIR%system32inetsrvappcmd.exe list config /section:handlers
/text:* | findstr /i PHP
and I got this result;
path:"*.php"
scriptProcessor:"C:Program Files (x86)phpphp-cgi.exe"

Funnily enough that php-cgi.exe file was missing, even though I appeared to have a partial installation of php on my pc.
So I downloaded the manual installer from PHP, and unzipped the files ontop of my php directory.

Now PHP was working

2. After installing timthumb, I saw that no images were appearing, and navigating directly to the PHP script gave this error

GD Library Error: imagecreatetruecolor does not exist – please contact your webhost and ask them to install the GD library
TimThumb version : VERSION

So, the trick was to open PHP.INI with notepad *IN ADMINISTRATOR MODE*

and add the lines
[PHP_GD2]
extension=php_gd2.dll

IISReset, then it worked!

Categories: Uncategorized

Use IIS under VS 2008, rather than the development server, Casini

If you want to use IIS rather than the development server casini – which starts all projects on some high port, i.e. localhost:54324,

Set up a new application in IIS, point it to the root of your project, and check that it works, by going to a browser, and type localhost/myApp

Then right click your web applicaiton in Visual Studio, select "Property Pages", then "Start Option", set Start URL to localhost/myApp,
check "Use custom webserver", then base URL to "http://localhost/SellSwapBuy&quot;.

When you run your app now, you can still debug, but it will be under IIS not Casini.

Categories: Uncategorized

As String, ToString and (string)

Three ways to cast an object to a string .ToString(), as String, and (string), what’s the difference?

((object)1).ToString()  equals "1"
((object)1) as string  equals null
(string)((object)1) throws an exception

Basically, "ToString()" calls a method on "object" or in the closest derived class that overrides the ToString() method.

"As string" performs a cast, but returns null rather than an exception is the cast is not implicitly possible.

(string) peroforms the same cast, but throws an exception on failure.

Categories: Uncategorized

Hash codes for Realex payment processing

Might be of interest to anybody using the Realex payment system in ASP.NET / C#, this is the code to generate MD5 checksums for it:

 // Create an md5 sum string of this string
        static public string GetMd5Sum(string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();
            // Create a buffer large enough to hold the string
            byte[] unicodeText = new byte[str.Length];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);
            // Now that we have a byte array we can ask the CSP to hash it
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(unicodeText);
            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }
            // And return it
            return sb.ToString().ToLower();
        }

Categories: Uncategorized

XmlSerializer Cache

Some benchmarks that shows the overhead of the XMLSerializerCache

var xs = new XmlSerializer(typeof(DataSet));

On a first call, this generates a cached serialization assembly. On my PC, this takes 0.2 seconds. However, on subsequent calls,
this line executes in 0.00006959 seconds.

This is how I timed this;

        private TimeSpan CreateXMLSerializer(int numberOf)
        {
            var dtStart = DateTime.Now;
            var lNumber = Enumerable.Range(1, numberOf);
            foreach (var intIteration in lNumber)
            {
                var xs = new XmlSerializer(typeof(DataSet));
            }
            var dtEnd = DateTime.Now;
            return dtEnd – dtStart;
        }

Categories: Uncategorized