... all I'm offering is the truth. Nothing more. RSS 2.0
# Tuesday, February 09, 2010

As always my posts are usually based on experiencing some travesty of code that required me either to change or endure it. In this case I was looking at a web page who’s only purpose was to return data … for the more seasoned among us the preceding sentence should scream murder. The truth is a web page has a metric ton of overhead and simply using them as conduits for the delivery of raw unformatted non html information (jpeg, text,xml, etc) is a pure waste of resources. The following is an example of what not to do when you trying to return data:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class WebPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details

        Response.Write(xml);

    }

}

This example takes advantage of the generic handler, which has all the flexibility of a web page but none of the overhead of the web page life cycle. While I am returning text/xml this could be any of your defined MIME types.

<%@ WebHandler Language="C#" Class="SomeHandler" %>

using System;
using System.Web;
using System.Text;

public class SomeHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/xml";
        context.Response.ContentEncoding = Encoding.UTF8;

        string xml = GetXMLString(); //Not interested in the details
        context.Response.Write(xml);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

In my humble opinion the above concept should be known to all senior asp.net developers, in fact this is one of the first interview questions I ask.

Technorati Tags: ,
Tuesday, February 09, 2010 12:16:33 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET | C#
# Thursday, December 03, 2009

I was having a problem with validating two fields in a web page the other day. The two fields were not required but it was necessary that if either field was selected then the other field would also be required.

 

Most of the examples I have come across simply require both fields, or require both fields based on another control. Logically speaking the request we have is an XNOR (where Field1 ='A', To Field2='B'). Only when one text box is filled out should the page flag an error.

clip_image003

 

In order to achieve this I used a CountTrueConditionsValidator from the PeterBlum Validation and More, as follows:

<vam:CountTrueConditionsValidator id="NeedBothFieldsOrNeitherField" runat="server" 
    ErrorMessageLookupID="You need both fields" 
    Minimum="1" Maximum="1" NotCondition="True" EventsThatValidate="OnSubmit"> 
    <Conditions> 
        <vam:RequiredTextCondition ControlIDToEvaluate="Field1" /> 
        <vam:RequiredTextCondition ControlIDToEvaluate="Field2" /> 
    </Conditions> 
</vam:CountTrueConditionsValidator>


In this example it counts the number of required fields from the conditions elements with the Minimum and Maximum both set to 1. This means if only one field is active this constitutes a true scenario (XOR). To make this fulfill our scenario (XNOR) the NotCondition is set to true.

Peter Blum Controls are really flexible and immersive, I will not develop any meaningful website again without them!

 

Technorati Tags:
Thursday, December 03, 2009 10:26:29 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET | Tools
# Monday, August 03, 2009

I was on a website that I use at least once a year, and through a series of steps that I am unable to repeat I got the following message to appear.

 image

I have talked about this before we all need to be as defensive as possible when it comes to errors messages. In this case I am not sure I could use this information to do harm (that is not my motive anyway) but it strikes me as odd that the developers in this case decided to let this kind of error bubble to the top. I now know the server name, database name, table name…

I did not include the name of this site to protect the innocent, they have also made it incredibly difficult to contact them and tell them about the problem. Either way I removed enough information from the above message so that no one else can track down the site or the error.

Monday, August 03, 2009 7:55:15 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
ASP.NET
# Monday, July 14, 2008

I have been doing a fair share of security related audits and programming over the last few years, and the following is a list of my favorite faux pas.

I always feel that giving specific details of errors encountered on your site is a sure fire way to attract trouble. So my first defensive tip is to always use custom error pages.

<customErrors mode="On" defaultRedirect="YourErrorPage.htm" />

Secondly, always ensure that you are capturing application level errors in your application, there are many errors that do not show up within any error handling that you place at the web form level.

void Application_Error(object sender, EventArgs e)
{
   //get reference to the source of the exception chain
   Exception ex = Server.GetLastError().GetBaseException();

   //log the details of the exception!
   EventLog.WriteEntry("PoppaString",
     "MESSAGE: " + ex.Message + 
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() + 
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace, 
     EventLogEntryType.Error);
}

The threat of cross site scripting is real one and could performed in a variety of ways. While most developers tend to check for text input validation I have also seen omission in the the validation of cookies and URLs, these inputs are as open to attack and should be validated before using.

HttpUtility.HtmlEncode(Request.Form["name"]);

note: This is by no means an exhaustive list and is really only meant to represent a few low hanging fruit in coding securely for ASP.NET.

Technorati tags:

Monday, July 14, 2008 9:46:15 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
ASP.NET | Security
# Tuesday, March 11, 2008

Don and I have been going back and forth on why MVC is so important to Web developers? I must admit I was missing the reasoning. I had been reviewing the demos by various alpha geeks, and I actually got bored with the whole thing, but that was fueled by my lack of understanding. I then came across a great blog post by Rick Strahl, who starts the MVC discussion by building up and subsequently dismantling Web Forms programming based on its weakness' and strengths. He then continues by showing how MVC helps solve the architectural issue.

The problem, in short, with ASP.NET is that it was built with a marked attempt to pull in Windows application developers. As a result mythical creatures sprung from Pandora's box in the form of ViewState, PostBack (event driven model) and the Visual Web Designer. Wonderful as they maybe, they inherently promoted the bloat of the entire ASP.NET paradigm. All these features did allow us to move swiftly into the web development world without really knowing html and simultaneously provided additional complexity to the entire Page execution cycle.

The other problem with ASP.NET is the lack of separation of concerns between business logic and the UI. While most of the work I have done has not included code in the ASPX file, it would be accurate to say that a large portion of the business logic sits in the code behind file, and this can lead to code that is exceptionally difficult to maintain.

It is these problems that MVC is designed to address, so when you watch the next demo and just before your eyes begin to glaze over with the question of why? Remember that ASP.NET does have some serious problems. To quote the Don "How is nice. Why is priceless!"

Technorati tags:

Tuesday, March 11, 2008 6:34:52 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET
# Thursday, February 07, 2008

In my line of work I am often given the solution before the problem, that is to suggest, well meaning engineers often pass on suggestions for problems they have found. Today's example included avoiding some errors we were seeing by setting the ValidateRequest flag to false in the Web.Config file.

For example, when the Validate Request flag is set false you are able to send scripts to the server as follows.

image

The ValidateRequest flag is design to mitigate the problems of cross site scripting (XSS) and produce a much more defensive response to script injections as follows.

image

Now to be safer all headers, cookies, query strings, form fields and hidden fields should be verified for invalid characters and character sequences by the developer regardless of what this flag is set, also if this flag needs to be modified it should be done on a page by page basis and with extreme caution.

Technorati tags: ,
Thursday, February 07, 2008 9:56:12 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET
# Thursday, September 20, 2007

Up until now I have turned my metaphoric back on AJAX for 2 reasons. Firstly we use Peter Blum controls at work which cover, more than adequately, 90 % of the use cases we encounter with our clients. So JavaScript validation continues to be something we do not concentrate on or worry about. Secondly I thought that I would have to get more familiar with Java Script, which was absolutely incorrect. I will not rant here about why I hate JavaScript development, except to say if I had a IDE I would be more receptive.

I have been summarily ignoring a couple of training opportunities provided at work until recently and I have to say that I am completely on board with AJAX, in fact I am now wondering why we are using Peter Blum controls at all? but I digress...

I was given this list of wonderful "How do I?" videos that step you through how to get started, from the point of downloading and installation all the way to making your own AJAX control kit. 

These videos are a must see!

Technorati tags: ,
Thursday, September 20, 2007 8:18:42 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
ASP.NET
# Thursday, July 12, 2007

Due to the simplicity of the XCOPY deployment strategy in ASP.NET you can easily set your self up for dumb mistakes. It took me a good 15 minutes (a little embarrassing) to realize what my deployment issue was below.

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Unrecognized attribute 'xmlns'.
Source Error:

Line 1:  <?xml version="1.0"?>
Line 2:  <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
Line 3:  	<system.web>
Line 4:  		<compilation debug="true">

Source File: C:\Inetpub\wwwroot\TTCOG\web.config    Line: 2


Version Information: Microsoft .NET Framework Version:1.1.4322.2032; ASP.NET Version:1.1.4322.2032

It screamed at me in the red line (and the version information) but I could not quite see it ... then I realized when you manually create a virtual directory for your project it defaults to version 1.1. This was my first official 2.0 deploy so I can be excused for this oversight.

image

"Nothing ever comes to one, that is worth having, except as a result of hard work." - Booker T. Washington

Technorati tags: , ,
Thursday, July 12, 2007 7:44:23 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
ASP.NET
# Tuesday, May 01, 2007

As I read more about Silverlight from Mix 07 I must admit that I am totally confused as to what this will now mean for AJAX. I thought AJAX was supposed to be the rich GUI that we have been waiting for with baited breath. Am I missing something or does Silverlight spell the end for AJAX?

I have just finished downloading the ASP.NET futures which seems to plug the gap between AJAX and Silverlight but I am wondering why we need AJAX in the middle at all. I guess I will have to wait and see what the fall out for Mix 07 truly reveals!

Tuesday, May 01, 2007 6:49:34 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback
ASP.NET | Visual Studio
# Friday, March 16, 2007

I have been thinking about the detailed plumbing of calling an ASP.NET web page lately due to some weird things that have happened at work. So I thought it wise to refresh myself and my five two faithful readers about what actually goes into displaying a page. 

I briefly described the HTTP traverse from browser to server, and will not delve in at that level. However, when a page request is sent to the Web server it is cycles through a series of events during its creation and disposal. Being able to understand the events (and the order) is critical for any potential ASP.NET developer. Everyone knows we start with an aspx page and end up with a beautifully rendered HTML page, however, we need to know what happens in between.

1. Object Initialization
Controls on a given page are initialized, by declaring the objects in the constructor of the C# code-behind file. If objects are created from within the aspx file they have no attributes or properties available in the code-behind and there is no reliable way to verify the order the controls will be created or if they will be created at all. The initialization event can be overridden using the OnInit method.

2. Load Viewstate Data
After the Init event, controls can be referenced using their IDs only. During LoadViewState event, the initialized controls receive their first properties from the viewstate information (handled by ASP.NET) that was persisted back to the server on the last submission. The event is overridden using the LoadViewState method and is used to modify the data received by the control.

3. LoadPostData, Processes Postback Data
When a page submits a form, the framework will implement the IPostBackDataHandler interface on each control that updated its data. The page then triggers the LoadPostData event and goes through the page to find each control that implements the applied interface and updates the control state with the correct postback data. ASP.NET checks each control by verifying the control's unique ID with the stored name/value pair.

4. Object Load
All object are arranged in the Control Tree (formerly known as the DOM) and can be referenced easily in code. Objects are now at liberty to apply the client-side properties set in the HTML, such as height, visibility, etc. This is generally considered the hardest working event in the process. This event can be overridden by calling OnLoad.

5. Raise PostBack Change Events
This event occurs immediately after all controls that implement the IPostBackDataHandler interface have been updated with the current postback data. This operation flags each control with a true\false based on if it was changed since the last post. ASP.NET looks for this flag and raises RaisePostDataChanged event.

6. Process Client-Side PostBack Event
The object which initiated the postback is handled by the RaisePostBackEvent event. The object is usually a control that posted the page back to the server (autopostback) or a submit from a button. The RaisePostBackEvent is last in the series of postbacks.

7. Prerender the Objects
This event is a critical one, as it marks the last chance the developer has to make any persistable changes to the objects. Immediately after the PreRender event changes to objects are locked and can no longer be saved to the viewstate. This event can be overridden using OnPreRender.

8. ViewState Saved
The viewstate is saved after all changes to the page have finalized. At the SaveViewState event, values can be saved to the ViewState object, but changes to page controls are not persisted.

9. Render To HTML
During the Render event, the page coerces each object into rendering itself into HTML. The page collects the HTML for transport to the client browser. When the Render event is overridden, the developer can write their own HTML to the browser that will actually override the HTML gathered by the page. The Render method uses the HtmlTextWriter to create HTML that will be streamed to the client browser. Changes can still technically be made here, but they will only show up at client browser.

10. Disposal
The Dispose event is the opportunity to destroy any objects or references you have created during the creation of the page.

Phew that is a lot of steps ... Monorail anyone. I think at some point I should also go over HTTPModules and HTTPHandlers. They provide really slick ways of jumping in the middle of a page cycle without necessarily touching every page! During the MCP test I noticed they really flogged the server and user control horse to death. It is a wonder to me that HTTPModules\Handlers were not covered with equal passion.

"Nothing contributes so much to tranquilizing the mind as a steady purpose - a point on which the soul may fix its intellectual eye." - Mary Shelley

Friday, March 16, 2007 4:57:09 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET
# Monday, January 22, 2007

Service oriented development is dominating my current programming landscape. Service Oriented Architecture (SOA) can be defined as loosely coupled software services that support requirements of a business process. SOA is also characterized by being technology agnostic, that is, the underlying service can be implemented in a variety of ways RPC, DCOM, CORBA or Web Services without worrying about the source.

Currently most of the projects I am involved with consume web service where the underlying technology is completely unknown to me. As with all banking systems security is always key so I wanted to review some of the options available for someone using ASP.NET.

Windows - Basic: Used for non-secure identification of clients, as the user name and password are sent in base 64-encoded strings in plain text. Passwords and user names are encoded, but not encrypted, in this type of authentication. A determined, malicious user equipped with a network-monitoring tool can intercept user names and passwords, this type of authentication is generally limited to secure networks.

Windows - Basic over SSL: Used with secure identification of clients in Internet scenarios. The user name and password are sent over the network using Secure Sockets Layer (SSL) encryption, rather than plain text. This is relatively easy to configure and works for Internet scenarios. However, using SSL degrades performance.

Windows - Digest: Used for secure identification of clients in Internet scenarios and uses hashing to transmit client credentials in an encrypted manner so the password is not transmitted in clear text. In addition, Digest authentication can work through proxy servers. However, it is not widely supported on other platforms.

Windows - Integrated Windows: Uses NTLM or Kerberos. Uses a cryptographic exchange with the user's Microsoft Internet Explorer Web browser.

Windows - Client Certificates: Use for secure identification of clients in Internet and intranet scenarios. Requires each client to obtain a certificate from a mutually trusted certificate authority. Certificates are optionally mapped to user accounts, which are used by IIS for authorizing access to the XML Web service.

SOAP headers – Custom: Useful for both secure and non-secure Internet scenarios. User credentials are passed within the SOAP header of the SOAP message. The Web server, regardless of the platform hosting the XML Web service, provides a custom authentication implementation.

"The mystery of government is not how Washington works but how to make it stop." - PJ O'Rourke

Monday, January 22, 2007 2:49:39 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET | Web Services
# Wednesday, November 15, 2006

I have been working with improving some images in ASP.NET and compiled this code from various MSDN sources. Generally I have found the issues revolve around the concept of anti-aliasing.

private void Button1_Click(object sender, System.EventArgs e)
{
    Bitmap bmp = null;
    Graphics g = null;

    try
    {
        bmp = new Bitmap(@"c:\inetpub\wwwroot\MyWebTest\MYimage.jpg");
        g = Graphics.FromImage(bmp);
        g.CompositingMode = CompositingMode.SourceCopy;
        g.SmoothingMode = SmoothingMode.HighQuality;  //Specifies high quality, low speed rendering
        g.InterpolationMode = InterpolationMode.HighQualityBicubic; //This mode produces the highest quality transformed images.

        Response.ContentType = "image/jpeg"

        //Create a parameter collection
        EncoderParameters codecParameters = new EncoderParameters(1);
        //Fill the only parameter
        codecParameters.Param[0] = new EncoderParameter(Encoder.Quality,100L);
        //Get the codec info
        ImageCodecInfo codecInfo = FindEncoder(ImageFormat.Jpeg);
        //Save the image
        bmp.Save(Response.OutputStream,codecInfo, codecParameters);

    }
    catch
(Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        if (g != null)
        {
            g.Dispose();
        }
        if (bmp != null)
        {
            bmp.Dispose();
        }
    }
}

private static ImageCodecInfo FindEncoder(ImageFormat fmt)
{
    ImageCodecInfo[] infoArray1 = ImageCodecInfo.GetImageEncoders();
    ImageCodecInfo[] infoArray2 = infoArray1;
    for (int num1 = 0; num1 < infoArray2.Length; num1++)
    {
        ImageCodecInfo info1 = infoArray2[num1];
        if (info1.FormatID.Equals(fmt.Guid))
        {
            return info1;
        }
    }
    return null;
}

 

Technorati tags: ,
Wednesday, November 15, 2006 1:22:25 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback
ASP.NET
Blogroll
Statistics
Total Posts: 334
This Year: 22
This Month: 0
This Week: 0
Comments: 32
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Mark Downie
Sign In
All Content © 2010, Mark Downie
DasBlog theme 'Business' created by Christoph De Baene (delarou)