Category Archives: .NET

.NET HttpRequest.ValidateInput()

I mentioned that v1.1 of ASP.NET by default validates input received from QueryString, Form and Cookie scope. You can turn off this validation site wide by tweaking the web.config:

<configuration>
  <system.web>
    <pages validateRequest=”false” />
  </system.web>
</configuration>

But then you’re left with no validation right? Wrong. You can use the ValidateInput() method of the HttpRequest object programmatically in any code that has access to the HttpRequest instance. Very useful stuff.

One question though: What is potentially dangerous data according to Microsoft? And can you modify that definition? I’m guessing the answers are: a) we’ll never know and b) no. Given their track record, does it make sense to trust Microsoft to validate the input you receive from client browsers when the browser they created can’t be trusted?

More on the out method parameter

I’m sure this is boring for about 99% of you, but I’m writing for my own benefit anyway. I mentioned the ‘out method parameter’ yesterday because I saw it used in a custom library I’m using and then today I found out that the Double class uses it as well. I think it’s a great example of how it should be used. It’s used in the TryParse method:

public static bool TryParse(
   string s,
   NumberStyles style,
   IFormatProvider provider,
   out double result
);

The TryParse method is like the Parse method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero.

I like it because throwing an exception (ie: what the Parse() method does) violates rule #39 of Effective Java Programming which says to “… Use exceptions only for exceptional conditions.” Using an out parameter feels cleaner and simpler. Anyone else think so?

out method parameter in C#

Just discovered this C# tidbit called the out method parameter. Let’s say you have a method:

public String ReplaceAll(String toReplace, String replaceWith)

and you want to know how many replacements were actually made. With a regular method you can only return the modified string. The out method parameter gives you the ability to return another variable. The modified method would look like this:

public String ReplaceAll(String toReplace, String replaceWith, out int numReplaced)

and then concretely:

String myString = “aaron”;
int replaced;
myString.ReplaceAll(“a”, “k”, out replaced);
Console.WriteLine(“The method ReplaceAll() replaced ” + replaced + ” characters.”);

Similar idea in the ref method parameter, but you have to initialize the variable before sending it to the method.

Extending web.config in ASP.NET

Last March I wrote about how handy it is that ASP.NET enables you to add your own custom settings to the web.config file using syntax like this:

<appSettings>
<add key=”connString” value=”user id=sa;password=mypassword;” />
</appSettings>

This is nice, but can quickly get unwieldy if you have alot application settings to maintain. Back in March I failed to mentioned (because I didn’t know about it) that you can extend your web.config even further by creating your own custom configuration sections. You can read more about the ConfigurationSettingsSchema on msdn, but here’s a quick example. First you define the custom application settings:

<configSections>
   <sectionGroup name=”myapplication”>
      <section name=”types” type=”System.Configuration.NameValueSectionHandler”/>
      <section name=”security” type=”System.Configuration.NameValueSectionHandler”/>
    </sectionGroup>
</configSections>

and then you add the actual settings:

<myapplication>
   <types>
      <add key=”section” value=”com.ignitionlabs.Section” />
      <add key=”template” value=”com.ignitionlabs.Template” />
   </types>
   <security>
      <add key=”/controlpanel/” value=”Systems Administrators,Project Managers” />
      <add key=”/members/” value=”members” />   
   </security>
</myapplication>

Finally, you can use the exact same XPATH syntax that you use when retrieving other application settings. In the above example, there are multiple ‘type’ elements, so I’d first get a NameValueCollection object:

NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig(“myapplication/types”);

and then retrieve the value of the “section” key using the name:

string section = config[“section”];

Enjoy!

ASP.NET HttpModule Security Example

I wrote a short bit about HttpHandlers and HttpModules a couple weeks ago and recently had decided to use an HttpModule to function as a security gateway for specific parts of the application I’m developing.

If you have any experience with ASP.NET, you’ll wonder why I didn’t just use the declarative Forms security. The one shortcoming that I could see of Forms security is that it requires that you only have one form for your application. For example, in your web.config, you’d have something like this:

<authentication mode="Forms">
  <forms name=".ASPXAUTH" loginUrl="/login.aspx" />
</authentication>
<authorization>
  <allow users="*"/>
</authorization>

and then users that access any directory you protected using the <location path=”administrators”> syntax would be redirected to the /login.aspx script. If you have two different types of users though, each requiring a different login page, you’re stuck. The web.config XML schema only allows you to have one <forms> element per application. I could have split up the applications in IIS, but then I’d have to replicate application settings and libraries to each application’s bin directory. So, long story short, I wrote a short bit of code that authenticates and authorizes users in the Application BeginRequest event. Pseudo code looks like this:

public class SecurityHttpModule : IHttpModule {
// implemented per the interface
public String ModuleName {
   get { return "SecurityHttpModule"; }
}   
// register for the HttpApplication BeginRequest event
public void Init(HttpApplication application) {
   application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
// handle the begin request event
private void Application_BeginRequest(Object source, EventArgs e) {
   HttpApplication application = (HttpApplication)source;
   HttpContext context = application.Context;
   // get the user, populate the Thread.CurrentUser...
   HttpCookie cookie = context.Request.Cookies.Get(".ASPXAUTH");
   if (peanutButterCookie != null) {
      FormsAuthenticationTicket fat = FormsAuthentication.Decrypt(cookie.Value);
      // get the user & the roles that this user is in using your own logic
      string[] roles = User.Roles;
      GenericIdentity identity = new GenericIdentity(fat.Name);
      GenericPrincipal principal = new GenericPrincipal(identity, roles);
      context.User = principal;
   }
   // find out if the section we're viewing is meant to be secure
   // pessimistic: default to forcing a login
   Boolean forceLogin = true;
   // if the section has security and we're not on the login form for this section
   if (s.isSecure() && thisSection.LoginForm != scriptName) {
      // groups allowed in this section
      ArrayList groups = s.GroupsAllowed();
      // loop over all allowed groups, see if this user is in one of those groups
      for (int x=0; x
I left out some of the implementation as well as the import statements, so this obviously won't compile if you drop it into your favorite IDE. Couple things to note in this example:

a) the use of GenericPrincipal and GenericIdentity. GenericIdentity is a concrete implementation of the IIdentity interface, that allows you to specify information about the current user. GenericPrincipal is a concrete implementation of the IPrincipal interface, it contains a reference to the GenericIdentity as well as an array of roles that the current user is in, as well as a method to determine is a user is in a specific role. You can choose to use the concrete implementations (like I did in the example above) or you can choose to create your own implementations of those interfaces, adding your own custom properties and methods to your users identities & roles.

b) the HttpContext, which maintains a reference to the current User, which contains the IsInRole() method. Every ASP.NET page can access information about the currently logged in user and what roles this user has.

c) the use of the utility class FormsAuthenticationTicket, which provides the means of creating and reading the values of a forms authentication cookie.

Just for kicks, how does this compare to ColdFusion? In ColdFusion MX (previous versions of CF used SiteMinder, which gives me the shivers), the <cflogin> tag provides similar functionality to the GenericPrincipal and GenericIdentity classes. which you can then use with the IsUserInRole() and getAuthUser() functions. Out of the box it's probably easier to use, but it (in my humble opinion) sacrifices ease of use for extensibility. You can't add additional properties or methods to the logged in user (for instance a last name or a method that returned how long the user has been logged in). Correct me if I'm wrong!

Migrating from ColdFusion to ASP.NET

Microsoft has put together an extensive article for developers migrating from CFMX to ASP.NET, including a pretty fair feature comparison chart. Probably the most obvious thing that the feature comparison table lacks is the mention of the close integration of Java with CFMX, in fact it says this:

It can also access Java class libraries with some extra work.

which is true and false… it requires extra work in the same way that it requires extra work to compile a C# file to an assembly, place the assembly in the /bin/ folder of the application and then import that assemblies namespace into an ASP.NET page.

Nonetheless, check it out if you have worked with CFMX before and are just getting started with ASP.NET.

ASP.NET Request Validation – Preventing Script Attacks

Yesterday I was working with self posting form that contained html characters as of a content management implementation using ASP.NET and I came across an error message I’d not seen from any application server. It said:

“A potentially dangerous Request.Form value was detected from the client..”

In short, as of ASP.NET 1.1, Microsoft is by default not allowing clients to post client script code or HTML to a form. As a developer, you have to either explicitly allow it for a page by including this:

<%@ Page validateRequest=”false” %>

in your ASP.NET page or by turning it off sitewide in the web.config file:

<configuration>
  <system.web>
    <pages validateRequest=”false” />
  </system.web>
</configuration>

Automatic request validation, in my humble opinion, is pretty nice. Way to go Microsoft. You can read more about this feature on the official ASP.NET site.

Delegates, Components, and Simplexity on artima.com

Delegates, Components, and Simplexity, great quote:

.. There’s one kind of simplicity that I like to call simplexity. When you take something incredibly complex and try to wrap it in something simpler, you often just shroud the complexity. You don’t actually design a truly simple system. And in some ways you make it even more complex, because now the user has to understand what was omitted that they might sometimes need. That’s simplexity. So to me, simplicity has to be true, in the sense that the further down you go the simpler it gets. It shouldn’t get more complicated as you delve down.

ASP.NET Tracing

ASP.NET has a feature called tracing, which according to the ASP.NET Trace documentation… allows you to view diagnostic information about a single request for an ASP.NET page simply by enabling it for your page or application.” If you’ve used ColdFusion before, you’re probably yawning, “.. we’ve had debugging since version 3.0..”, but wait, it gets cooler. You can also view the information from a page (Trace.axd) called the “trace viewer”, which allows you to view detailed information the last N requests (read: requests that other people have made to your site), which would/could be extremely helpful during any phase of development, including production. Unlike ColdFusion, you configure this per application in the web.config file:

<trace
   enabled=”true”
 traceMode=”SortByCategory”
 requestLimit=”40″
 pageOutput=”false”
 localOnly=”false”
/>

Anyone know if there is a tool like this for servlet containers? Or if certain servlet containers support something like this?

NAnt

I mentioned a couple days ago that my current project is based on a C# and ASP.NET. I don’t have access to Visual Studio (should I try to get it? is it worth it?) so I’ve been using the Improv C# plugin with Eclipse. The combination works alright, but there are a couple things that need improvement. First, when compiling an assembly in C#, you have to specify each module that it references per class, there isn’t a way to to say that MyProject.dll should be included in the classpath for the entire C# project. Second, there’s no way to say that you want all the compiled assemblies to be placed in ../classes/ instead of ../build (ie: you can’t specify an output folder). But that’s where NAnt comes to the rescue. I downloaded NAnt today and was able to get a build script running within a couple minutes that accomplishes the two things I needed above.

I do have a question for those of you who have done .NET programming before. In Java, you compile .java files to .class files. Using C#, you compile a .cs file to a .dll (or .exe, etc..) which is called an assembly. Then in Java you’d usually package up your class files into a jar file. After using NAnt today, I see that you can compile a bunch of .cs files into a single dll, also called an assembly, which you can then use just like a jar file. Do I have that right? Are there different ways of doing this?