Using OnClientClick with Chrome causes server side submit to fail.

If you embed an asp.net page as an IFrame in a page, where the submit button jumps out of that frame, i.e. in the case of a search form, then you could end up using code like this:

 <asp:Button id="btnSearch" runat="server" Text="Search" onclick="btnSearch_Click" OnClientClick="javascript:pageSubmit()" />

<script language="javascript">
    function pageSubmit() {
        var SearchForm = document.forms[0];
        SearchForm.target = ‘_top’;
        SearchForm.submit();
    }
</script>

However, btnSearch_click doesn’t fire when running under google Chrome …

This is a bit of a hack that I’ve used to get round this:

protected void Page_Load(object sender, EventArgs e)
{
            if (Page.IsPostBack && string.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
            {
                    btnSearch_Click(sender, e);
             }
}

No marks for elegance, but it seems to work in Chrome, IE and Firefox.

        }

Categories: Uncategorized

Genetic algorithims in C#

Genetic algorithms are basically where random operations are applied to solve problems, and the ‘fittest’ of these random collections bias the generation of the next collection of random operations.

The beauty of this, is that there is no need to understand the underlying problem, just throw lots of computing power at it, until the solution is approximated.

This is the same way that nature uses to solve problems, where random organic mutations discover the best, or at least a suitable, creature for any hospitable environment. However, that doesn’t need to be the basis for computer algorithms.

For example, let’s take a set (x) of 5 (n) numbers [1,2,3,4,5], what comes next? 6?, yes, pretty obvious, but how would a computer solve that?  x[n-1]+1, is the solution if you understand the sequence, but if you didn’t….

Let’s say our objects can be x[1],x[2]…x[n], and the whole numbers 1 to n, then we have 5 basic operations, +, -, /, *, %, and we put our operation complexity (c) to 3, for instance.

Pick c random operations, between the range of 1 to n*2, followed by c-1 random operations in the range 1 to 5, this gives us a "bytecode" sequence of
5,5,4,3,10
which gives
x[5] % x[4] / 10  =  0.1

Nowehere near 6, but lets say we kept randomly doing that until we got the number 6. From this we then create a "population" of similar algorithms, by just
tweaking one digit of the byte code up or down, or replacing an operation.

Then the logic goes, we change the sequence [2,3,4,5,6] with the next number being 7, and the closest of the "population" goes on to create the next generation.

What I’ve described above is akin to Asexual reproduction in nature, where the genetic code of any organism is inherited from one parent only. This is only used for simple organisms in nature, and it is more normal for genetic code to be inherited from two parents.

To apply this analogy to the code, it would mean that the two closest operations, i.e. resulting in 6.03 and 5.98 in the first generation would have their byte-code merged, either by averaging, or substitution.

To extend this analogy beyond nature, it would be quite possible, to take the top 3 fittest operations, and merge them, resulting in trisexual reproduction, although evidence could only be garnered from experimentation at this point, it would stand to reason that if 2 parent genetic inheritance is more effective than single parent inheritance at creating advanced life, perhaps the same can be applied to genetic algorithms?

Categories: Uncategorized

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