This post has been imported from the old blog and has not yet been converted to the new syntax yet.
It has been a long time since I posted something, but here I am again. It's a very busy time right now, some exams, loads of school tasks, some websites, etc..

And also, a talk I had to prepare for class. One that I'm going to share with you.

I'll have to disappoint non-Dutch readers though, the slides are written in Dutch, as it was a local session. You could always look at the code though.

The subject was 'Writing Secure ASP.NET'. Covering :

  • Cross-site Scripting

  • SQL Injection

  • Hashing passwords

  • IOPermissions by default

  • Unsafe DSN (DSN with password included)



The first three demo's code should be obvious. Regarding IOPermissions I showed a file browser that could browse trough the system in default ASP.NET installation. And for the Unsafe DSN, I listed system DSNs, or used a demo DSN, showed the tables in it (MySQL only) and executed a query against it.

You can find all files here: SecureASPNET.ppt (227k) and Demo.zip (205k).

 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
I started working with NUnit a couple of days ago and here is my first attempt at creating something in this new style:

Error Reporting To The EventLog - NUnit.

It's very weird to switch to Test Driven Development, still have to get the hang of it.

If anybody has any comments on what I created so far, if it's good or bad, please say so, I'd like to know if that's the way others use NUnit.
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
For this article, we're going to write a class to write to the EventLog. To allow us for easy error logging.

I'm going to use NUnit as well to test our class. You can get NUnint at http://www.nunit.org/. Install it.

Start by creating a new project called 'EventLogTests', this is a class library. Add a reference to nunit.framework.dll located in the NUnit bin directory.

Throw out the constructor and add the attribute TestFixture to the class. This will tell NUnit about a new set of tests.

[csharp]
namespace EventLogTests {
using System;
using NUnit.Framework;
using CumpsD.Tools;
using System.Diagnostics;

[TestFixture()]
public class EventLogTests {

} /* EventLogTests */
} /* EventLogTests */
[/csharp]

Now we'll add a method called Initialise, which we mark with the SetUp attribute. This method will be run at the beginning of each test. In here we will create our EventLogger object (which doesn't exist yet).

[csharp]
private EventLogger _ErrorLog;

[SetUp]
public void Initialise() {
this._ErrorLog = new EventLogger("MyCatastrophicError");
}
[/csharp]

Next thing is setting up NUnit. You can find Visual Studio add-ins for NUnit, but as I'm having some problems with getting them to work properly I'm using an alternate method. Go to the project properties, configuration properties, debugging. And set Debug Mode to Program, and Start Application to nunit-gui.exe, each time we'll press F5 NUnit will now launch.

The way of test driven development is to first write a test that fails and then add some code to make the test pass. We have already written a failing SetUp, because the EventLogger class doesn't exist yet, this counts as a failed test as well. So, let's make it pass.

Create a new class library called EventLogger and create the constructor.

[csharp]
namespace CumpsD.Tools {
using System;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;
using System.Globalization;

public class EventLogger {
private string _ApplicationName;
private EventLog _Log;

public string ApplicationName {
get { return this._ApplicationName; }
} /* ApplicationName */

private EventLog Log {
get { return this._Log; }
} /* Log */

public EventLogger(string applicationName) {
this._ApplicationName = applicationName;
this._Log = new EventLog();
this.Log.Source = this.ApplicationName;
} /* EventLogger */
} /* EventLogger */
} /* CumpsD.Tools */
[/csharp]

Let's create our first test. We want to read an EventLog.

[csharp]
[Test]
[ExpectedException(typeof(InvalidEventLogException))]
public void ReadLog1() {
EventLogEntry[] EventLogs = this._ErrorLog.ReadLog(this._BadLog);
}
[/csharp]

We mark our method with the Test attribute, along with the ExcpectedException, because this._BadLog contains a non-existant logfile, and we want our class to throw an exception when trying that.

This test fails, because the ReadLog method doesn't exist yet. Let's create it, this requires some more coding, we'll have some private helper methods. SetLog to specify the EventLog we want to read from, and IsLog to check if the EventLog actually exists.

[csharp]
private bool IsLog(string logName) {
return EventLog.Exists(logName);
} /* IsLog */

private void SetLog(string logName) {
if (this.IsLog(logName)) {
this._Log.Log = logName;
} else {
throw new InvalidEventLogException("Invalid Logfile.");
}
} /* SetLog */

public EventLogEntry[] ReadLog(string logName) {
this.SetLog(logName);
EventLogEntry[] EventLogs = new EventLogEntry[this.Log.Entries.Count];
this.Log.Entries.CopyTo(EventLogs, 0);
return EventLogs;
} /* ReadLog */
[/csharp]

This code on it's own will still fail, because there is no InvalidEventLogException! Let's add a class in the same file defining the Exception.

[csharp]
[Serializable()]
public class InvalidEventLogException: Exception, ISerializable {
public InvalidEventLogException(): base() { }

public InvalidEventLogException(string message): base(message) { }

public InvalidEventLogException(string message, Exception innerException): base (message, innerException) { }

protected InvalidEventLogException(SerializationInfo info, StreamingContext context): base(info, context) { }

[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter=true)]
public new void GetObjectData(SerializationInfo info, StreamingContext context) {
base.GetObjectData(info, context);
}
} /* InvalidEventLogException */
[/csharp]

When we run our test now, the EventLogger will throw an Exception and our test will pass, because we were expecting an exception.

Write a test with a valid EventLog name as well, and make it pass, the code shown above will work.

We also want a WriteLog method, to actually log our errors, so let's make a test for that.

[csharp]
[Test]
[ExpectedException(typeof(InvalidEventLogException))]
public void WriteLog1() {
this._ErrorLog.WriteLog(this._BadLog, "This is a test entry");
}

[Test]
public void WriteLog2() {
string ErrorMessage = this._ErrorLog.WriteLog(this._GoodLog, "I have encountered a catastrophic error!");
EventLogEntry[] EventLogs = this._ErrorLog.ReadLog(this._GoodLog);
Assert.AreEqual(ErrorMessage, EventLogs[EventLogs.Length-1].Message, "Wrong Error.");
}
[/csharp]

The WriteLog1 method is similar to the ReadLog1 method, it tries to write to an invalid EventLog and will fail. The WriteLog2 method however tries to write to a valid EventLog, and checks if the error is actually written afterwards.

Both tests will fail, because we'll write the methods now.

I have created an enum for the three types of EventLogEntries, Information, Warning and Error. Along with an overload for WriteLog so it would write an Error by default.

[csharp]
public enum ErrorType { Information, Warning, Error }

public string WriteLog(string logName, string errorMessage) {
return this.WriteLog(logName, errorMessage, ErrorType.Error);
} /* WriteLog */
[/csharp]

Our real WriteLog method will check for a valid EventLog and then write the Entry to the EventLog and return the error message it has written, so we can compare in our test.

[csharp]
public string WriteLog(string logName, string errorMessage, ErrorType errorType) {
this.SetLog(logName);
EventLogEntryType LogType;
switch (errorType) {
case ErrorType.Information: LogType = EventLogEntryType.Information; break;
case ErrorType.Warning: LogType = EventLogEntryType.Warning; break;
case ErrorType.Error: LogType = EventLogEntryType.Error; break;
default: LogType = EventLogEntryType.Error; break;
}
this.Log.WriteEntry(String.Format(CultureInfo.InvariantCulture, "{0} caused the following error:\n{1}", this.ApplicationName, errorMessage), LogType);
return String.Format(CultureInfo.InvariantCulture, "{0} caused the following error:\n{1}", this.ApplicationName, errorMessage);
} /* WriteLog */
[/csharp]

If we run our tests now, we'll see they succeed. I have added some more tests to check if the Entry type was written correctly.

At the end you should have something like this:



And when you check eventvwr.msc you will see something like:



As always, I've uploaded the sources so you can check them on your own.
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
Currently I'm playing around with IIS and C#, and something I discovered is the following:

First, take a look at the FrontPageWeb property available in the IIS Metabase.

This says 'Setting FrontPageWeb to true causes FrontPage Manager to create the files required for FrontPage Server Extensions. Setting FrontPageWeb to false causes these files to be deleted.'.

Everything seems alright, just like every other property I set this to true and except it to work. Like this:

[csharp]
// First we get the AD object representing our webserver
DirectoryEntry iisServerRoot = new DirectoryEntry("IIS://localhost/W3SVC");

// We create a new site on the specified siteId
DirectoryEntry deNewWwwSite = (DirectoryEntry)iisServerRoot.Invoke("Create", "IIsWebServer", 10);

// Takes care of FrontPage Manager providing files for FrontPage Extensions
deNewWwwSite.Properties["FrontPageWeb"][0] = true;

deNewWwwSite.Invoke("SetInfo");
deNewWwwSite.CommitChanges();

deNewWwwSite.Close();
deNewWwwSite.Dispose();
[/csharp]

(Most stuff left out)

Well, it didn't work. In IIS it would still say FrontPage Extensions were not present, and the directories didn't get made.

I looked everywhere to find something else involving FrontPage, without any luck.

But then I found this KB article (300543). And although it's talking about IIS 4.0, 5.0 and 5.1, it does work on IIS 6.0 as well.

So here you go, to install FrontPage Extensions you have to run:

"C:\Program Files\Common Files\Microsoft Shared\web server extensions\50\bin\owsadm.exe" -o install -p /LM/W3SVC/SITEID -u USERNAME -sp publish

And to uninstall them:
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\50\bin\owsadm.exe" -o fulluninstall -p /LM/W3SVC/SITEID -u USERNAME
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
Today I was looking over a project I'm working on currently, more specifically, at the SQL queries in it.

I come from a PHP background, where there is no such thing as parameterized queries. You simply build your own SQL string and make sure it doesn't contain anything harmful.

So, not having heard of such thing as parameterized queries, I created my SQL statements the same way in C#, until I read about this practice being "not done". So, I wanted to fix it.

I'm using MySQL with the MyODBC driver. But MySQL is tricky, it doesn't support named parameters, so you have to use a question mark and add parameters in the right order.

No problem I thought, this would be a one-minute fix.

This is what I had (I returned an SQL query string at first):

[csharp]
return String.Format("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES('{0}', '{1}', {2}, {3});", strFName, strGeslacht, intKlas, klKlas.Id);
[/csharp]

And I changed it to:

[csharp]
OdbcCommand insertCmd = new OdbcCommand("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES('?', '?', ?, ?);", zosaDb);
insertCmd.Parameters.Add(new OdbcParameter("", strFName));
insertCmd.Parameters.Add(new OdbcParameter("", strGeslacht));
insertCmd.Parameters.Add(new OdbcParameter("", intKlas));
insertCmd.Parameters.Add(new OdbcParameter("", klKlas.Id));
return insertCmd;
[/csharp]

What did this insert in my database? Well it added a question mark ;)


So, I went looking for what was wrong... Did I add my parameters in a wrong way? Is there something wrong with MyODBC? After having done about everything I could think of, it was in the middle of the night and I went to bed. But today I tried something else, remove the single quotes. And it worked!

[csharp]
OdbcCommand insertCmd = new OdbcCommand("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES(?, ?, ?, ?);", zosaDb);
insertCmd.Parameters.Add(new OdbcParameter("", strFName));
insertCmd.Parameters.Add(new OdbcParameter("", strGeslacht));
insertCmd.Parameters.Add(new OdbcParameter("", intKlas));
insertCmd.Parameters.Add(new OdbcParameter("", klKlas.Id));
return insertCmd;
[/csharp]

Such a small thing, but nowhere I managed to find this, nobody ever posted to watch out for this. Having no previous experiences with parameters and the question mark, I simply thought it would safely replace the ? with my value, but still would require the quotes for string values.

Don't make the same mistake! It's a stupid one ;)