#programmierung

Posts tagged programmierung

Validation Controls in ASP.NET

So, yesterday I noticed something funny while doing some data-driven ASP.NET programming.

There are those really great Validation controls that really reduce the amount of code you need to write on average input forms.

So, imagine you have quite usual code like this:

<asp:TextBox runat="server" ID="MyTextbox"></asp:TextBox><br />
<asp:RequiredFieldValidator ControlToValidate="MyTextbox" runat="server"><br />
    Textbox shouldn't be empty
</asp:RequiredFieldValidator>

<asp:Button runat="server" Text="Submit" OnClick="Submit_Click" />

This will result in a simple form with a textbox and a submit button. The handler code for the button looks like this:

public void Submit_Click(object sender, EventArgs e)
{
    this.Title = "Hello World";
}

Now, if you click on the button while leaving the textbox blank, you'll see the red message that the field needs to be filled.

If you disable Javascript in your browser, the handler code will get executed without getting validated!

Actually, the validation is done solely on the client if you don't manually check for the Page.isValid property on the Webform.

So, here is the revised handler code:

public void Submit_Click(object sender, EventArgs e)
{
    if (this.IsValid)
    {
        this.Title = "Hello World";
    }
}

This isn't something unknown, MSDN points it out on some occasions. But yet, something you might overlook too easily.

Keep this in mind when working with validator controls, hope this helps!

Read more →

Custom ASP.NET Membership provider

I've been ranting too much lately, so I guess it's time to get back into coding.

This time around I've been challenged with a new project that involves a legacy database, while my task is to rewrite the ASP.NET application that runs ontop of that database without actually touching the database.

So first: What is ASP.NET Membership?

Simple answer: A great way to build authentication with little to zero coding effort with very cool draggy-droppy developer experience :). You simply drag a Login control to your ASP.NET page and your application just learned how to authenticate and keep the session of users.

To achieve this on a already existing database you simply need to do one thing:

Implement the abstract class MembershipProvider and implement just one method: ValidateUser

public override bool ValidateUser(string username, string password)
{
    if (username == "tigraine" && password == "tigraine")
        return true;
    return false;
}
You see where I'm going here, you basically just need to return true or false given a username and a password. How you do it is entirely up to you as long as you return either true or false.

To make the magic actually work you need to add the new MembershipProvider (i've called it DBMembershipProvider) to your root web.config:

<authentication mode="Forms">
	<forms loginUrl="Login.aspx"></forms>
</authentication>
<membership defaultProvider="DBMembershipProvider">
	<providers>
		<add name="DBMembershipProvider" type="DBMembershipProvider" />
	</providers>
</membership>
The <authentication mode="Forms"> is quite important because it tells asp.net to actually use forms driven authentication instead of windows authentication or microsoft passport. I also defined the loginUrl attribute to tell the app where to redirect anonymous users, but that's optional.

The membership stuff now is important, because here we glue the new provider into our system.

We just add a new provider in the <providers> section and name it conveniently, and most important: we tell .net what type to instantiate.

The defaultProvider property then tells .net what provider to use (if you've got multiple providers to log into your website, eg: Windows and Forms auth)

And, that's it. As long as the ValidateUser method returns true/false, your users can now use a fancy Login form to authenticate and their login session will get stored in a cookie. You can now drag LoginStatus and LoginName controls to your form and watch the goodness work :).

Hey! How do you actually secure something with this?

Yeah, I was so happy with that login working so I almost forgot to do this part. Usually you want to protect some files or directories from unregistered users. This also happens at the web.config level and is quite easy.

In case of a folder, just put a blank web.config in there and add the following directives:

<system.web>
	<authorization>
		<deny users="?"/>
	</authorization>
</system.web>
Now only registered users have access to this directory and you're done.

If you don't want to lock the whole directory but only some files in there you can do this through the verb attribute by either specifying a regex or a filename to be affected by your rule. (You could also use the <allow> tag to add exceptions to your deny tag I think)

Actually, if you look at the MembershipProvider, there's a ton more functionality I just skipped here. But this has been everything I needed to get login and user restriction for my current project, so I thought it's worth sharing how darn easy this actually is. If you want to delve deeper into the topic I'd suggest you either read 4GuyFromRolla or search through MSDN.

Read more →

Polluting Userspace

Once in a while I actually use the "My Documents" folder to retrieve files I've put there. Or worse, I sometimes store files there!
Gosh, impossible? Hell yes! Impossible due to the shitload of folders all sorts of software vendors think I need in MY user space! Who in the hell allowed ICQ to start storing received files in there? Do I really want that? Did they ask me?
Who actually decided that every damn game out there you install has the right to just go into your "My Documents" and place it's save games in there? If I open up my documents I get a almost 100% accurate view of what I've been playing over the last few months or so.

That's unacceptable! Sorry to say that, but I have 3 folders in there where I "dare" to put my data, while the total folder count in my "My Documents" is 19! So that's 16 folders I didn't create and I don't need in there.

But why did it get that bad?

The answer is simple: Because backup is painful.
Even an IT pro has a hard time collecting all those config files from the various C:\Program Files\config folders, imagine a home user going through those steps. So software vendors thought: Users may know how to back up their "My Documents" folder, if we put our stuff in there we're safe!

Guess what? They made the opposite true: Users simply don't use this folder any more, most people I know keep their data on locations like "D:\" or some other place where they can access them conveniently without seeing unwanted folders pop up.
And, I'm inclined to do the same. Screening through 16 unknown/irrelevant folders isn't something I want to be doing in a folder I thought was for my private use only!

But where to put those files?

By far the most convenient location for configuration files imo is the program directory where you've installed the application. But to be honest, I don't think the average end-user app should really need a config file. Most applications we currently use just work out of the box with very little need for configuration.

Secondly, there's still the AppData folder that's intended to hold application data, and by definition config files are application data. Why in the hell didn't they use this??
AppData is also located in the users's profile folder so it might get backed up.

PLEASE:

If you're writing software, either omit configuration files (best solution!) or keep them out of my user space and save them in a location that actually makes sense!

Oh, and by the way. With user space I don't mean only the "My Documents" folder. I really can't understand why some applications (namely eclipse, oracle, visual paradigm, virtual box) decided that it's ok to put them in my C:\users\<username>\ instead! That folder was intended to give me quick access to my Documents, Desktop, Favorites, Downloads, Images, Music, Videos. Not to scan through those .eclipse/.sqldeveloper etc etc folders. Please guys out there, understand that windows isn't hiding folders that start with a dot from the user! That's linux and we Windows users don't want those folders to be in the root of our profile!

image

Read more →

ASP.NET HttpModule that detects debug mode on production servers

So, after reading some stuff about HttpModules lately I thought it would be fun to create one myself. And, so I came up with something that might be useful in some scenarios.

A HttpModule that will cry foul when you try to put up a ASP.NET website with debug="true" onto a production server.
It is actually rather simple. Just a standard HttpModule that will check wether the request is local and wether debug is enabled. The local request check is done to make the module transparent to you while developing the app on cassini, while you'll see it instantly when you copy it over to your web server.

The code is rather simple:

public class DebugWarner : IHttpModule
{

    public void Dispose()     {    }

    public void Init(HttpApplication context)     {         context.BeginRequest += new EventHandler(context_BeginRequest);     }

    void context_BeginRequest(object sender, EventArgs e)     {         if (!HttpContext.Current.Request.IsLocal &&             HttpContext.Current.IsDebuggingEnabled)         {             HttpContext.Current.Response.Write(                 "<div style=\"background: #ea999d; border: 1px solid black; width: 500px; text-align: center;\">\n" +                 "<h1>Debug Mode is enabled!</h1><p>This severely impacts Webserver performance<br />" +                 "Set <compilation debug="false"> in your web.config</p>" +                 "</div>");         }     } }

Making this work is quite easy too, simply put the above class in your App_Code directory and add this line to your <httpModules> (or <modules> on IIS7) section:

<add name="DebugWarner" type="DebugWarner"/>

If you now try to access the page with debug="true" you'll get:

image

Read more →

IT-Camp at Klagenfurt University

As Mathias has already hinted, today was the final presentation of the ongoing computer games implementation week I was instructing at klagenfurt university. During the last week I and Christian where working together with a small group of 7 high school students (of age 15-17) on some pretty amazing computer games with Microsoft's XNA framework.

We started out with some basic talk about computer games in general and introduced the students to Microsoft XNA on the second day. Most of them had some basic Java experience and absolutely no knowledge of C# or XNA. After pointing out some syntax differences between Java and C# we started with a very basic boulder game tutorial from the XNA creators club website that should teach 2D rectangle collision detection with XNA. Afterwards the students were asked to expand on this idea and create their own 2D computer game.

And now I am very happy to show some of their great work they did during the last 4 days!

This is where we started out:

And these are screen shots from our student's projects (click to get the full view):

Argon Abwechslungsreiche Einöde Block Fighters Space Impact Sweet Sattelites

 

I also promised Mathias to create videos from the projects that we did so he can show them at future computer games courses, I'll post these videos on YouTube once I've recorded them.
We will also be releasing the games source code, but I am still trying to figure out the license for some of them.

I've had a great time with those talented kids and hope they enjoyed learning as much as I did enjoy teaching!

Read more →

Exporting Data to CVS in ASP.NET

So, today I tried the ASP.NET Wiki that's currently in Beta and thought, best way to do so is to expand an article. I'll blog about my Wiki experience later, but for now I'd like to share my code on this one.

I started out with the Wiki Article Export to CSV file (revision 3) and thought on how to improve it.

As you may have noticed, the topic at hand is so simple, it doesn't really need improving, except for the main flaw where you have to specify all column headers in code.

My take on this was to use the DataBinder API from the System.Web.UI namespace and remove the whole HttpContext.Current stuff to an instance variable so it's easier to test the stuff and you can put it into a class library (if you want that).

Let's assume I have a list of type Person I want to write to CSV

public class Person
{
    public String Name
    { get; set; }
    public String Family
    { get; set; }
    public int Age
    { get; set; }
    public decimal Salary
    { get; set; }
}

Now here's the CVSExporter class that you just need to pass 3 things: Your List<Person>, your HttpContext.Current and a List<String> that specifies what columns you want printed out (eg. Name, Family).

public class CSVExporter
{
    public static void WriteToCSV(List<Object> dataList, HttpContext httpContext, List<String> columnNames)
    {
        InitializeHeaders(httpContext);

        WriteColumnNames(httpContext, columnNames);                  foreach (Object data in dataList)         {             WriteData(data, httpContext, columnNames);         }                  httpContext.Response.End(); //Everything has to end..     }

    private static void InitializeHeaders(HttpContext httpContext)     {         string attachment = "attachment; filename=PersonList.csv";         httpContext.Response.Clear();         httpContext.Response.ClearHeaders();         httpContext.Response.ClearContent();         httpContext.Response.AddHeader("content-disposition", attachment);         httpContext.Response.ContentType = "text/csv";         httpContext.Response.AddHeader("Pragma", "public");     }

    private static void WriteData(Object data, HttpContext httpContext, List<String> columnNames)     {         StringBuilder stringBuilder = new StringBuilder();         foreach (String column in columnNames)         {             AddComma(                 System.Web.UI.DataBinder.Eval(data, column).ToString(),                 stringBuilder);         }         httpContext.Response.Write(stringBuilder.ToString());         httpContext.Response.Write(Environment.NewLine);     }

    private static void AddComma(string value, StringBuilder stringBuilder)     {         stringBuilder.AppendFormat("{0}, ", value.Replace(',', ' '));     }

    private static void WriteColumnNames(HttpContext httpContext, List<String> columnNames)     {         StringBuilder stringBuilder = new StringBuilder();         foreach (String column in columnNames)         {             stringBuilder.AppendFormat("{0}, ", column);         }         httpContext.Response.Write(stringBuilder.ToString());         httpContext.Response.Write(Environment.NewLine);     }

}

So that's it for now. I guess there is still room for improvement, and if you need performance you should go with the original solution, DataBinder.Eval does some type-casting internally so it won't run at lightning speeds, but you get the idea of what can be done with the DataBinder control :).

And now I'm off to writing a Windows Live Writer Plugin that will allow me to paste longer code without jumping through loops like a madman (I posted the code in my Wordpress admin-gui because doing it from wlv simply didn't work!)

Read more →

Post Code with Dignity

After finally getting really really fed up with Windows Live Writer about the way it tries to tidy up your HTML code I decided that I need to do something about it.

So I did, writing a Live Writer plugin is very easy and straight forward, so I did a plugin that will take your clipboard, replace typical things like < > through &lt; &gt; and replace every 2 spaces through 2 &nbsp;.
So make sure you are using a even number of spaces for source indentation in your IDE.

The plugin is far away from perfect, and I think I'll make it a bit more configurable tomorrow. I also think I'll put it up on Google code and maybe release it to the Windows Live Gallery.

They key? Windows Live Writer fucks up your markup no matter what you do. So I simply departet from posting pure text as a ContentSource, yet the plugin is treating HTML as a SmartContentSource that will appear as a block inside Windows Live Writer, saving it from it's catastrophic markup-killing html-tidy algorithm.

Update: I already released the source at CodePlex and you can get the most up to date binary from there:

CodePlex Project Page: http://www.codeplex.com/wlwPostCode

Installation:
Simply put the dll into your Live\Writer\Plugins directory and start WLV!
It will now show up in your Insert-List as Insert Code..

Btw: The Plugin assumes you are using the same syntax highlighting script as I do and will put your code into a <pre> tag.

Read more →

Setting up Cruise Control .NET

logo

Wow, what a day! After starting a new project today (I'll discuss that in another post) I decided that it is time to get serious with source control and continous integration. This time I thought I'd skip the java stuff and pass on JetBrains Teamcity, and instead went for the SourceControl.NET by ThoughtWorks that I heard of on Hanselminutes.

First things first: I am totally stunned of how great this has turned out. If you don't have a CI server yet, go get yourself one immediately. Even if you are programming by yourself, having someone run the build process and all unit tests for you never hurts and will save you time in the long run. Set-up of CruiseControl and the whole stuff was quite time-consuming (meaning 3 hours), but doing it on another project now really is a piece of cake, once you're done it feels quite natural.

So, to get started you should set up Subversion by simply installing VisualSVN, the server is running in less than 30 seconds, your users and repositories are in place after a mere minute. I can't think of any easier way to install Subversion, kudos to the VisualSVN team!

Now, this isn't quite standard, but really helps: Create a file called svn.bat in your C:\WINDOWS\system32\ folder with the following content:

@echo off
"C:\Programme\VisualSVN Server\bin\svn.exe" %*
Cool huh? Now you've got svn in your %PATH% without having to edit the variable itself. This will save you some time on the CCnet configuration.

The next thing was to install the newest CCnet version, and here I suggest you get the latest and hottest stuff directly from the svn. I ran into some troubles with some msbuild reports in version 1.3. Updating to 1.4 worked wonders.

Now that everything is set up (you can now access the WebDashboard through the http://<yourserver>/ccnet/ url), you need to get the whole thing configured. (The only painful thing in this installation).

A good starting point is the documentation that explains almost everything.

I won't go through everything in the ccnet.config file, just some things I want to point out:

  • Make sure to either run the latest CCnet build or use the doc that came with your binaries. New not used settings will stop the server from running.
  • While testing your build process go ahead and try to run the same commands from a shell. Especially with msbuild it took some time to sort out the quirks :)
  • Don't forget to blindly incorporate the whole list of <publishers>. I can't think of a scenario where I don't want almost all of those running, and if you skip some (like xmllogger and statistics) you will get some broken links on your dashboard.
  • VisualSVN sets up a https server. CCnet runs svn with the --non-interactive switch, so it will quietly break due to a unsigned SSL certificate. To bypass this simply run a svn list <repo> from a shell and accept the certificate permanently. And make sure the CCnet service is running under your login credentials, svn stores the certificate setting per user.
So, enough wisdom from my part on CCnet. I really had a blast in setting it up, and I can only recommend it. After the break I've postet my ccnet.config if you want to have a look.

<cruisecontrol>
      <project name="Valet">
        <workingDirectory>valet/WorkingDirectory</workingDirectory>
        <artifactDirectory>valet/ArtifactDirectory</artifactDirectory>
        <webURL>http://plato/ccnet/server/local/project/Valet/ViewProjectReport.aspx</webURL>
        <modificationDelaySeconds>10</modificationDelaySeconds>
        <sourcecontrol type="svn">
            <trunkUrl>https://plato:8443/svn/valet/trunk/</trunkUrl>
            <username>ccnet</username>
            <password>xEs6S-uW</password>
            <autoGetSource>true</autoGetSource>
            <!--<tagOnSuccess>true</tagOnSuccess>-->
        </sourcecontrol>
        <state type="state" />
        <labeller type="defaultlabeller">
            <prefix>Valet-alpha-0.</prefix>
            <incrementOnFailure>false</incrementOnFailure>
        </labeller>
        <triggers>
          <intervalTrigger name="continuous" seconds="30" />
        </triggers>
        <tasks>
            <msbuild>
              <executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
              <projectFile>Valet.sln</projectFile>
              <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs>
              <targets>Build</targets>
              <timeout>900</timeout>
              <logger>C:\Programme\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger>
            </msbuild>
            <nunit path="C:\Programme\NUnit 2.4.7\bin\nunit-console.exe">
                <assemblies>
                  <assembly>C:\Programme\CruiseControl.NET\server\valet\WorkingDirectory\ValetServerTest\bin\Debug\ValetServerTest.dll</assembly>
                </assemblies>
            </nunit>
        </tasks>
        <publishers>
          <xmllogger />
          <statistics />
          <modificationHistory  onlyLogWhenChangesFound="true" />
          <rss/>
          <modificationWriter />
        </publishers>
    </project>
</cruisecontrol>
Man, I hate my blog theme. I need to get this thing wider sometimes soon!

Read more →

Working till late...

The weather has been pretty great the last days, and I used the last weekend for some relaxing and even some bathing in Wörthersee.
I also discovered my new favorite relax location (although it doesn't serve coffee) and I also managed to make some photos (click the image for the flickr photo gallery):

Unterkreuth

But after coming home today (chilled to the bone, Wörthersee is still way too cold for bathing!), I figured out I need to do an java assignment for university till Tuesday.

Needless to say that I thought I'd be done in 2 hours doing some simple hash table implementations.
What happened? They managed to throw 10 pages of mostly meaningless gibberish that specifies how my classes should behave and how the underlying algorithms work. While detailed instructions isn't something bad per se, omitting the UML diagram IS BAD! After going through the doc 2-3 times I still haven't identified all of the "added complexity" that should be teaching us OO-design and am searching the course forums for answers to questions that aren't answered by a 10 page long assignment paper :(.

So, yeah: I started at 21:00 and now it's 3 in the morning and my concentration has hit rock bottom so I am reading through specs and their explanation without being able to see the sense in it.

If you can't remember what word preceded the one you just read - go to bed.

And while we're at it. If you bother with Visual Paradigm: Get yourself a real-edition. Doing everything twice (in code and in UML) really sucks. Especially since code stubs can be exactly derived from UML and vice-versa it sucks doing it in a so terribly clumsy tool as Visual Paradigm for UML. (VP works great, it's just a lengthy process to create a damn operation (public void main(String args[]) is easier to type than to click 30 check boxes and drop downs!)

Read more →

LinQ, LinQ to SQL etc explained

I've been talking to a lot of people about LinQ and LinQ to SQL lately and always had trouble explaining them the difference between those concepts. So, obviously I could simply point you to ScottGu's posts on LinQ and Linq to SQL, but that would be cheap wouldn't it?

So, what is LinQ in the first place? People usually mix it up with LinQ to SQL and see it as a new syntax to query databases (but that's LinQ to SQL).

In a nutshell, LinQ stands for Language integrated Query and is a great way to retrieve objects from lists, arrays etc.
Basically, LinQ works an everything that implements IEnumerable, so it's quite safe to say that it works with every .NET collection out there ;).

So, the magic?
LinQ consists of 2 things.

Extension methods

First: By importing the System.LinQ namespace you get some extension methods for your collections.

linq1

The above screenshot shows some of the extension methods you get by importing System.LinQ.
Those methods are very useful when working with collections and have become something I won't want to miss.
Here are my most used ones:

Select: Takes a lambda and returns an IEnumerable<> of all items that match the lambda.
Example:

linqselect

This statement will only return an IEnumerable with Tigraine and Tig.

Single: I love this one! Takes a lambda and returns the single item matching the lambda (failing if there is more than one).
This really shines when doing stuff with unique id's.
Example:

linqselect2

Any and All: Any checks if one or more items of the collection match the lambda, and All returns true if all items in the collection match the lambda.

Query syntax

So, besides all those great overloads the LinQ namespace provides the real magic is a query like this:

linqselect3

Needless to say that this query syntax works on every collection of objects and provides a great strongly typed query syntax for objects.

LinQ to SQL

So, now that we know what LinQ is we could easily go ahead and write tons of boilerplate code that maps objects to database tables etc etc.. And then use LinQ to query all those objects we created.

But that wouldn't ever work, because having the whole database in memory won't work on any fairly large db. So LinQ to SQL jumps in on this.

LinQ to SQL consists mainly of a graphical OR/M designer in Visual Studio 2008 that allows you to simply drag and drop tables from your database to create the mappings.

linqsqlguiOnce the mappings are created LinQ to SQL provides you with a DataContext class that represent the objects in your database.
The Users table from my database to the left result in a new collection in your data context called Users that can be queried either through extension methods or through the query syntax.

linqsql

What happens under the hood is that LinQ to SQL translates your LinQ query into SQL. The generated queries can be viewed while debugging:

linqsql2

The difference to normal LinQ is that LinQ to SQL gets executed once you are using the query data, not when doing the query. The query definition is just the generation of the SQL, while a foreach(var u in users) would actually trigger the query.

And, obviously LinQ to SQL also handles changes to the database through transactions. You just need to modify a value and hit dbContext.SubmitChanges() and LinQ packs any changes back into your database.

Conclusion:
LinQ is a clever way to query objects in memory.
LinQ to SQL is a new strong OR/M that takes advantage of the new query syntax and extending it to a database.

This post was never intended to be an exhaustive write-up about LinQ and LinQ to SQL, if you want to know more about those two please refer to ScottGu's posts.

Read more →