Monday, February 15, 2010

Down and dirty with Trace Listerners for SOAP Messages

1 comment:
Recently I was trying to implement a web service call for a client who had another firm implementing a very secure web service using client certificates (Ill blog about how to get that working sometime soon). However once Id got the security sorted I was getting a Method not allowed 403 error in order to diagnose the problem I needed ot get at the raw data travelling across the wire. as it happens dot net has a brilliant diagnostics suite which is really simple to implement. Simply add the following into your web.config file underneath the system.web node and presto youll get a trace.log file will all that lovely low level info in!

Original Article here on StackOverflow; http://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet


<system.diagnostics>

    <trace autoflush="true"/>
    <sources>
      <source name="System.Net" maxdatasize="1024">
        <listeners>
          <add name="TraceFile"/>
        </listeners>
      </source>
      <source name="System.Net.Sockets" maxdatasize="1024">
        <listeners>
          <add name="TraceFile"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/>
    </sharedListeners>
    <switches>
      <add name="System.Net" value="Verbose"/>
      <add name="System.Net.Sockets" value="Verbose"/>
    </switches>
  </system.diagnostics>
Read More

Friday, November 06, 2009

A simple way to add OnUnload to the body of a page

No comments:

Page.ClientScript.RegisterStartupScript(typeof(string),"AutoCloseWindow","window.onunload = function () { window.opener.location.href = window.opener.location.href; window.close(); };", true);

Read More

Monday, September 14, 2009

Old Skool - Classic ASP ServerVariables List

2 comments:
This is an oldie but a goodie – I don’t know how many times in my career I’ve rewritten these few lines of code but I’ve preserved it here to save me writing it yet again! A simple method for outputting all the server variables, query string parameters and form variables in Classic ASP!

response.Write("<hr/>SERVER VARIABLES COLLECTION<br/>")
Dim variableName
for each variableName in Request.ServerVariables
response.write(variableName & ": " & Request.ServerVariables(variableName) & "<br/>")
next
response.Write("<hr/>QUERY STRING COLLECTION<br/>")
for each variableName in Request.QueryString
response.write(variableName & ": " & Request.QueryString(variableName) & "<br/>")
next
response.Write("<hr/>FORM COLLECTION<br/>")
for each variableName in Request.Form
response.write(variableName & ": " & Request.Form(variableName) & "<br/>")
next
response.Write("<hr/>SESSION COLLECTION<br/>")
for each variableName in Session.Contents
response.write(variableName & ": " & Session(variableName) & "<br/>")
next
response.Write("<hr/>")

Read More

Tuesday, September 01, 2009

Useful code to properly record and redirect an unhandled exception from Global.asax Application_Error Handler

No comments:

    void Application_Error(object sender, EventArgs e)

    {

        // Code that runs when an unhandled error occurs

        string httpCode = ((HttpException) Server.GetLastError()).GetHttpCode().ToString();

        if (HttpContext.Current.Session != null)

        {

            HttpContext.Current.Session["LastError"] = Server.GetLastError();

            Server.ClearError();

        }

        switch (httpCode)

        {

            case "404":

                Response.Redirect("/Error/Error404.aspx");

                break;

            default:

                Response.Redirect("/Error/Error.aspx");

                break;

        }

    }

Read More

Wednesday, August 12, 2009

GridView (non-object/sql DataSource) Paging and Sorting

No comments:

This is just a quick reminder post about how to do things and in what order to get Paging and Sorting working together on a GridView Control when you’re datasource is NOT a SqlDataSource or ObjectDataSource reference by DataSourceId in the ASPX file but rather a (collection of) POCO objects or other datasource!

 

.ASPX file

    <asp:GridView CssClass="tableStyle1" HeaderStyle-CssClass="bgA" RowStyle-CssClass="bgB"

        DataKeyNames="Id" AlternatingRowStyle-CssClass="bgB" AllowPaging="true"

        AllowSorting="true" PageSize="50" OnPageIndexChanging="ResultsGrid_PageIndexChanging"

        AutoGenerateColumns="false" runat="server" ID="ResultsGrid" OnRowDataBound="ResultsGrid_RowDataBound"

        OnSorting="ResultsGrid_Sorting" PagerStyle-ForeColor="White">

        <Columns>

            <asp:BoundField DataFi

 

 

.CS file

protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

        {

            ViewState["SortExpression"] = "Title";

            ViewState["SortDirection"] = "ASC";

        }

    }

 

    public void ResultsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        ResultsGrid.PageIndex = e.NewPageIndex;

        BindResultGrid();

    }

 

    private void BindResultGrid()

    {

        SqlDataAdapter da = new SqlDataAdapter("ReportingSelect", new SqlConnection(connectionString));

        GetSqlParametersForFilter(PrepareFilterTerms(), da.SelectCommand);

        DataSet results = new DataSet();

        da.Fill(results);

        ResultsGrid.DataSource = ApplySorting(results.Tables[0].DefaultView);

        ResultsGrid.DataBind();

    }

 

    private DataView ApplySorting(DataView dataViewForSorting)

    {

        dataViewForSorting.Sort = ViewState["SortExpression"].ToString() + " " + ViewState["SortDirection"].ToString();

        return dataViewForSorting;

    }

 

    public void ResultsGrid_Sorting(object sender, GridViewSortEventArgs e)

    {

        if (e.SortExpression.ToString() == ViewState["SortExpression"].ToString())

        {

            if (ViewState["SortDirection"].ToString().StartsWith("ASC"))

            {

                ViewState["SortDirection"] = "DESC";

            }

            else

            {

                ViewState["SortDirection"] = "ASC";

            }

        }

        else

        {

            ViewState["SortExpression"] = e.SortExpression.ToString();

            if (e.SortDirection == SortDirection.Ascending)

            {

                ViewState["SortDirection"] = "ASC";

            }

            else

            {

                ViewState["SortDirection"] = "DESC";

            }

        }

 

        BindResultGrid();

    }

Read More

Monday, August 03, 2009

ASCII Encoded/Binary String Automated SQL Injection Attack

No comments:
Useful code for preventing SQL injections in .NET Querystrings, lifted from the following page:
http://www.bloombit.com/Articles/2008/05/ASCII-Encoded-Binary-String-Automated-SQL-Injection.aspx

/// /// global.asax/// public class Global : System.Web.HttpApplication{
...
private static string[] SQLKeywords = new string[]
{
"EXEC", "SELECT", "INSERT", "UPDATE", "DELETE",
"CAST", "DECLARE", "NVARCHAR", "VARCHAR"
};
...
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context != null)
{
string queryString =
context.Request.ServerVariables["QUERY_STRING"];
if (string.IsNullOrEmpty(queryString) == false)
{
if (queryString.Length > 500)
throw new SQLInjectionException(string.Format("Unexpected 'QUERY_STRING' length ({0}).", queryString));
queryString = Server.UrlDecode(queryString);
queryString =
queryString.Replace(" ", string.Empty).ToUpper();
foreach (string keyword in SQLKeywords)
{
if (queryString.IndexOf(keyword) != (-1))
throw new SQLInjectionException(string.Format("Unexpected T-SQL keyword ('{0}') has been detected ({1})", keyword, queryString));
}
}
}
}
...}
Read More

My 30th birthday is looming....

No comments:
...so I've written a list of things I'd like!

Stuff I’d Like for my Birthday:

Framework Design Guidelines: Conventions, Idioms, and Patterns for re-useable .NET Libraries 2nd Edition, Book/DVD Package
http://www.compman.co.uk/scripts/browse.asp?ref=895703
£22.34

Hitman DVD – Unrated
http://www.movietyme.com/catalog/product_info.php?products_id=39063&osCsid=dd991dc5d4a98e3f30952bf39550ad0c
£15.99

HMV Vouchers!

Iomega 1TB desktop hard drive - Catalogue number: 204-6510
http://direct.tesco.com/q/R.204-6510.aspx
£69.94

Philips SPC1330NC Webcam pro
http://shop.philips.co.uk/servlet/ControllerServlet?Action=DisplayProductDetailsPage&Locale=en_GB&SiteID=rpeeub2c&productID=124455100&s_kwcid=TC9368philips%20spc1330ncS3385570448
£69.99

Subscription to WebUser Magazine
http://www.magazinesubscriptionsipc.com/ipc/subs/subsorder.asp?title=XWU&promcode=i272&ctryID=NONE
About £25 I think

CLR via C#, 3rd Edition by Jeffrey Richter (I’ve already got the 2nd Edition)
Not out yet!
£TBC

Hanns-G 22in HG221AP Wide LCD TFT Black/Silver MonitorMonitor
http://www.svp.co.uk/displays/monitor-22-hanns-g-22-hannsg001_monitor.html
£109.62
Read More

Thursday, June 04, 2009

Search Engine Optimization Toolkit : The Official Microsoft IIS Site
6 comments:
Search Engine Optimization Toolkit : The Official Microsoft IIS Site: "The IIS Search Engine Optimization (SEO) Toolkit helps Web developers, hosting providers, and Web server administrators to improve their Web site’s relevance in search results by recommending how to make the site content more search engine-friendly. The IIS SEO Toolkit includes the Site Analysis module, the Robots Exclusion module, and the Sitemaps and Site Indexes module, which let you perform detailed analysis and offer recommendations and editing tools for managing your Robots and Sitemaps"
Read More
Download details: Visual Studio Team System 2010 Team Suite Beta 1
No comments:
Download details: Visual Studio Team System 2010 Team Suite Beta 1: "Visual Studio Team System 2010 Team Suite Beta 1 - ISO" free download from microsoft now available (Im very late in posting this but still....)
Read More

Wednesday, June 03, 2009

July 2006 - Posts - Tony Rogerson's ramblings on SQL Server
No comments:
July 2006 - Posts - Tony Rogerson's ramblings on SQL Server: "Collations in SQL Server, examples and restrictions" Very handy notes on solving Database Collation Problems!
Read More

Thursday, May 28, 2009

Neighbours' shock as cows invade housing estate - Rugby Today - Back to Home Page
No comments:
Its ol news but only just came across it - wish Id have moved here sooner!
Neighbours' shock as cows invade housing estate - Rugby Today - Back to Home Page: "Neighbours' shock as cows invade housing estate"
Read More

Friday, May 15, 2009

How to use SQL Server T-SQL cursors | Microsoft SQL Server Advisor
No comments:
This is a brilliant little example script what absoluted HAVE TO use a cursor - my take generally on this is "If you have to use a cursor youre doing it wrong", however during some work for a client I needed to "duplicate" a hierarchy of items from different nested tables with foreign key references for a questionnaire something along the lines of
Questionnaire table links to Questions table, Questions table links to QuestionLinking table (Where a dependancy between one question and another is held) and so forth. I spent a while looking for a "clean" solution but the only option I found was to iterate through each Questionnaire, Question and Question link at a time as I needed to update the QuestionnaireId, QuestionId and QuestionLinkId from the Source Questionnaire to the Destination Questionnnaire row equivalents... if you have any patterns or approaches tot his type of thing not involving cursors I would love to hear from you!

How to use SQL Server T-SQL cursors Microsoft SQL Server Advisor
Read More

Wednesday, May 06, 2009

Internet Explorer 8: Videos
No comments:
Internet Explorer 8: Videos: "Internet Explorer 8: Videos" these, whilst very"microsoft", "vision of the future", "overly gloosy with an irritatingly up-beat narrator", if you know what I mean; much like the Windows Tour video (which i always make a bee line for when a new O/S is released), is actually very informative, concise and easy to understand. It shows key new features and how they work giving a very good insight into the lovely new "community" features. Well worth 5 minutes of your time!! Note: Especially useful is the Compatibility feature which, a developer, I might just find ver handy if it does indeed invoke the previous versions' of IE' rendering engines!
Read More

Tuesday, December 11, 2007

HITMAN THE MOVIE

No comments:
Well, Im not one for blogging about general everyday stuff but after reading some of the reviews of Hitman I felt I had to my two penneth in. Firstly thes think about those other not-so-great films of computer games, Street Fighter, Tomb Raider, Mario Bros, Mortal Kombat (to a
lesser extent) were all, well, not to be unkind but quite poor. So by that benchmark given the genre anything better than quite poor is a big plus. OK, so nmow we have a general benchmark lets consider some other mitigating factors - whilst Hitman has some superb stunts, special
effects and action sequences you should not go to this film with "This is another Borne Identity/James Bond type of film", it not, firstly the main character is more reminiscent of Leon than either of the two previously mentioned, think World Cinema, Darkened Eastern
European/Russian location, think World Cinema with a bigger budget. There are also some nice "in jokes" - at one point Agent 47 crashes thru a window into a hotel room with two kids playing Hitman the game on the telly - quite amusing if you catch the reference. Now the leading lady
isn't your typical "Bond Girl" shes dark, damaged, sassy and gothic AND she appears partially naked now and again - in my book all these things make her much more intriguing and interesting and indeed more sexy than anything the Bond franchise has produced. The main character IS NOT A "GOODIE" as with Borne and Bond, this guy has been trained from birth to be an assassin and it is his sole purpose, no sleeping with anything that moves, no witty repartee just a case full of weaponry and some bad-ass hand to hand combat get this guy thru life. The gadgets whilst fanciful in places have at least the potential to exist and are generally believable and used judiciously. Personally I thought that this film was one of the best Ive seen so far this year and, even if you don't go and see it at the cinema its certainly worth a rental - especially if you have surround sound and a hi-def telly to enjoy all the gun fights and explosions! Its efinitely a lads movie but not so much your "I like guns and stuff blowing up me" type of lad film more a "Im interested in see some alternative characters play out an intercontinental game of cat and mouse with high violence and some reasonable character development". The leading man, though Ive forgotten his name, must have been able to memorise his lines in an afternoon - he remains mostly silent throughout the film, punctuated occaisionally by some direct instruction which generally either ends or saves someones life, this guy however is not devoid of character, you are left with the distinct impression that theres a world of torment and angst behind those eyes and that whilst he never expresses it in words his facial reactions say it all whilst giving away nothing!

All in all a FIVE STAR film - SEE IT NOW!
Read More

Wednesday, November 28, 2007

Javascript Goodies

No comments:


I’ve recently had to deal with some very run of the mill client side validation, namely validation a comma separated list of email addresses – I was so pleased with my cobble together of bits of code I found on the net that I thought Id post it here for the next time! Also a handy bit of script to “trim” a string in javascript and adding the trim method to the String object… NICE!

String.prototype.trim = function() { return this.replace(/^\s+\s+$/g, ''); }

function CheckEmailAddresses()
{
var recipients = document.getElementById('recipients').getAttribute('innerText').split(',');
var emailRegEx = /^(("[\w-\s]+")([\w-]+(?:\.[\w-]+)*)("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)(@\[?((25[0-5]\.2[0-4][0-9]\.1[0-9]{2}\.[0-9]{1,2}\.))((25[0-5]2[0-4][0-9]1[0-9]{2}[0-9]{1,2})\.){2}(25[0-5]2[0-4][0-9]1[0-9]{2}[0-9]{1,2})\]?$)/i
for (var email in recipients)
{
if(emailRegEx.test(recipients[email].trim()))
{
alert('good');
} else {
alert('bad');
}
}
}

Thanx go to the following locations:
Trim function: http://www.nicknettleton.com/zine/javascript/trim-a-string-in-javascript
Email Regex: http://xyfer.blogspot.com/2005/01/javascript-regexp-email-validator.html

Read More

Monday, April 30, 2007

The Brooba Revolution!

No comments:
I just thought Id drop in a quick note about my new project, Brooba.com , the concept behind this site is quite simple - Why shoudl you have to pay extra fees when buying/selling/exchanging/searching for a house - this site puts users together giving them the tools necessary to end their Housing woes - do check it out and pre-register - more info to follow!

http://www,brooba.com
Read More

Monday, March 05, 2007

New Website

No comments:
Please please please checkout my new creation for a friend of mine who's set up a landscape gardening business - the website I created for him can be found at www.newmanlandscapesltd.co.uk

Cheers!
Read More

Tuesday, August 01, 2006

Javascript - Strpping CrLf

2 comments:
I've just been hunting round the internet for this so I thought Id share! This is a simple function to remove the CrLf characters from a string (Handy if you're receiving HTML in a Javascript variable and you want a HTML <BR/> instead) .
Simply add the following to the end of your variable and all will be well!

.replace(/(\r\n)/g, "<br/>");

Read More

Tuesday, July 11, 2006

ASP.NET Web.Config from IIS

No comments:
Just a little tip for those that dont like hacking the XML in web.config on ASP.NET 2.0 projects manually theres a handy little tool built into IIS:
If you right click on the website in IIS then click properties then go to the ASP.NET tab theres a button at the bottom called Edit Configuration, if you go in there theres a nice little interface for the web.config file which saves you hacking the XML directly!
Read More