Fog of war in XNA

January 24th, 2009 No comments

Just thought I should show one of the effects I’ve been working on for my towerdefence-game lately. It’s a simple (but quite nice looking) “fog of war” effect that hides any enemies that are out of sight from the towers. I’ve also added a nice radar tower to demonstrate this (with a cool sweep-effect).

The youtube video sucks I’m afraid, it blurs everything down even though I uploaded a really nice looking highres video. Will update this post with a download link for the original video file later on for those interested in seeing what it should look like.

Update: Here is a link to the original video that I submitted to youtube. It looks A LOT better.

httpvh://www.youtube.com/watch?v=f8NihfHALkY

Towerdefence in XNA

December 25th, 2008 No comments

Just thought I should write a short one about a current project of mine. I decided that I wanted to try to make a game (a real game, not just that old pong-clone I made while learning C++ all those years ago) and since I work mostly with managed code it felt quite natural to build my game using a managed framework. For those who don’t know about the XNA Framework I would recommend a visit to XNA Creators Club for some more information.

The game I’m working on (with a tiny bit of help of a friend of mine who still has about 70 lines of code that I haven’t touched in the project) is a realtime strategygame built around the towerdefence concept. Some sort of enemies tries to get from point A to point B without getting killed. To kill them you build different types of towers along the way that hurt them in different ways and hopefully enough to not let them through. For each creature that get to point B you lose a life and when enough get there it’s game over for you. If you want to know more about this type of game http://www.towerdefence.net/ is a great place to go looking.

Below is a short video I recorded from the latest build of the game. It currently only features one type of tower and one type of enemy and they both use some placeholder graphics I made in Paint.Net so don’t expect to much of that. If you happen to have some graphics skills and would like to help out then you are very welcome!

httpvh://www.youtube.com/watch?v=Q5wPSRH5xTk

And another thing, it’s also best viewed in fullscreen mode since the video was recorded in 800×600 resolution. Hope you enjoy it!

Categories: .Net, Beaver, c#, xna Tags: , , , ,

State of everything

December 22nd, 2008 No comments

It’s been three weeks since I quit my old job now. Three weeks and I finally feel that I’m getting back to coding for the fun of it. I’m currently going through my old projects seeing what needs to be completed, tidying up my svn repositories, fixing this blog (more on that below) and so on. I’m also working on a small techdemo for a small game I’ve been working on with a friend of mine using XNA that hopefully will turn out as a really fun project and a really cool game. More on that in a later post though.

I’ve been doing some work on this blog the last few days, I changed the url to get it closer to my main site, updated WordPress to 2.7 (whoa, suddenly I’ll want to write things just to see their awsome GUI), added some stubs to articles and codesnippets that I feel I want to post and I’ve finally added my feed to feedburner to get some stats on my subscribers aswell (and avoid the hassle for everyone to change their subscription url if I decide to move again). The new url to subscribe to is http://feeds.feedburner.com/crazybeavers/blog.

Oh, and I’m home sick today so if this post doesn’t make any sense to you I’ll blame it on my cold.

New url

December 21st, 2008 2 comments

I’ve decided to move the blog to a new adress at http://blog.crazybeavers.se/. The old url is still valid for a month or so but I decided not to renew the domain. If you subscribe to my rss-feed (yeah right, like someone does) then you’ll have to update the url to that one as soon as possible.

Categories: Beaver, Misc Tags: , ,

ASP.Net and metadata

December 19th, 2008 No comments

Building great websites have several parts to it. First of all you need a great idea of what to fill the site with, then you’ll need some great technology in the background (sloppy code can achieve lots of great things aswell, but you won’t want to go in there and add things afterwards) and then a great presentation to the users of your site. In this article I will touch two parts of this, the technology (ASP.Net) and the presentation (metadata).

First of all I just want to state that I’m not a believer in all the SEO crap thats out there. I simply believe that if you have a great site that people visit and link to it will rank higher in search engines. A great site though will incorporate lots of things that “SEO experts” are chattering about like validating markup, good titles and things like that but that doesn’t mean it is those parts that put it high in the searchresults.

When working on a new version the CMS I use for CrazyBeaver Softwares website I ran into a really disturbing problem with how ASP.Net handles metadata. Look at the sample below.

<head runat="server">
    <title>My website</title>
    <meta name="keywords" content="" />
</head>

It looks alright doesn’t it? Well if you browse to that page you’ll see that the generated source is different.

<head>
    <title>My website</title>
    <meta name="keywords" />
</head>

Where did my content go? Just because it is empty doesn’t mean it can be removed just like that. If you pay a quick visit to www.w3.org and look at the xhtml specification you’ll see that the content attribute is a REQUIRED attribute of the meta element and therefore shouldn’t be removed. Now I hear you say that it shouldn’t matter since it didn’t convey any information anyway and while that is true the removal of that attribute also made sure that the page won’t generate valid html. Sure, it’s a very small error and won’t stop anything that doesn’t require a strict DTD validation to display the page (and no browsers do that since they wouldn’t be able to browse large parts of the web) but start out small and soon you won’t even bother to close tags properly since the page doesn’t validate anyway.

So, this is a behavior of ASP.Net that we need to work around somehow. There are a few choices here. You could simply loop through the HtmlMeta controls during Page_Load and check if they have empty content. It would look something like this.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Control[] headerControls = new Control[Page.Header.Controls.Count];
        Page.Header.Controls.CopyTo(headerControls, 0);

        foreach (Control control in headerControls)
        {
            HtmlMeta meta = control as HtmlMeta;

            if (meta == null)
                continue;

            if (string.IsNullOrEmpty(meta.Content))
            {
                Page.Header.Controls.Remove(control);
                break;
            }
        }
    }
}

Does this look as a good enough solution for you? It will do the work needed for most parts (it won’t remove a completely empty meta for some reason though so a <meta name=”" content=”" />will still fail your validation..) but it isn’t the nicest solution since you’ll need to loop through all controls in your header for every pageview that isn’t a postback. Also, maybe you want to specify an empty content for some reason since you have some other piece of code or application that relies on them being there. So what would be a nicer solution? Well writing an adapter of course! In ASP.Net 2.0 they introduced a cool thing called control adapters which basicly let you override the rendering of an existing webcontrol. In this case we will use it to force the HtmlMeta control to always render a content attribute.

using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.HtmlControls;

namespace CrazyBeavers.Web.UI.Adapters
{
    public class HtmlMetaAdapter : ControlAdapter
    {
        private static string[] _i8nAttributes = new string[] { "lang", "xml:lang", "dir" };

        protected override void Render(HtmlTextWriter writer)
        {
            HtmlMeta meta = this.Control as HtmlMeta;

            writer.WriteBeginTag("meta");

            if (!string.IsNullOrEmpty(meta.HttpEquiv))
                writer.WriteAttribute("http-equiv", meta.HttpEquiv);

            if (!string.IsNullOrEmpty(meta.Scheme))
                writer.WriteAttribute("scheme", meta.Scheme);

            if (!string.IsNullOrEmpty(meta.Name))
                writer.WriteAttribute("name", meta.Name);

            foreach (string attr in meta.Attributes.Keys)
                foreach (string i18n in _i8nAttributes)
                    if (attr.Equals(i18n, System.StringComparison.InvariantCultureIgnoreCase))
                        writer.WriteAttribute(i18n, meta.Attributes[i18n]);

            writer.WriteAttribute("content", meta.Content);

            writer.Write(HtmlTextWriter.SelfClosingTagEnd);
        }
    }
}

Just drop that piece of code in your App_Code or compile it as an assembly and put it in the Bin-folder on your site. There is still one step that needs to be completed for this to work though. All control adapters needs to be referenced via an browser-file in App_Browsers aswell (which is a really cool thing since you can set conditions and use adapters on certain controls for certain browsers, but more on that some other time). Below is a short sample of my Default.browser-file, it doesn’t use any extra features of the browser-file and just say that I want to use my adapter everywhere.

<browsers>
  <browser refID="Default">
    <controladapters>
      <adapter controlType="System.Web.UI.HtmlControls.HtmlMeta"
               adapterType="CrazyBeavers.Web.UI.Adapters.HtmlMetaAdapter" />
    </controladapters>
  </browser>
</browsers>

There you go, now all your MetaCotrol should always render properly for you even though you don’t put any data at all in them. Feel free to comment on this article if you have other solutions or ideas on how to work around this problem.

Pretty fine beaver!

November 12th, 2008 No comments

I found this link ages ago and wrote a post with just the link but never came around to publish it. It’s still one of the coolest things I’ve found on the internet the last years so I hope you enjoy it!

http://compubeaver.com/

Categories: Beaver Tags:

Recursive generic extensionmethods are fun! (Recursive FindControl)

November 12th, 2008 No comments

Just thought I should share a little piece of code with you this evening. It’s a little extension method (i.e it requires .Net 3.5) that extends Control and helps you find all instances of a certain controltype under the Control on which you invoke the method. Just put the following code in an assembly (or a .cs-file in App_Code).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

/// <summary>
/// Holderclass for extension methods
/// </summary>
public static class ExtensionMethods
{
    /// <summary>
    /// Recursively searchs for all instances of a specified control type.
    /// </summary>
    /// <typeparam name="T">The type of control to search for.</typeparam>
    /// <param name="control">The control to search from.</param>
    /// <returns>A List<> with the found controls.</returns>
    public static List<T> FindControls<T>(this Control control) where T : Control
    {
        List<T> myList = new List<t>();
        FindControls</t><t>(control, ref myList);
        return myList;
    }

    private static void FindControls<T>(Control control, ref List<T> controlList) where T : Control
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control currentControl = control.Controls[i];
            if (currentControl is T)
            {
                T typedControl = control.Controls[i] as T;
                controlList.Add(typedControl);
            }

            FindControls<T>(currentControl, ref controlList);
        }

    }
}

To call it you just invoke FindControls<Control>() on any object that derives from Control (i.e. Page, Label, Calendar, the list can go on forever), see the sample below. Hope you find some use for it!

List<HtmlMeta> meta = Page.FindControls<HtmlMeta>();

My most downloaded resource

April 25th, 2008 3 comments

Last week I started wondering how many downloads my products really had had throughout the years. Seeing that I didn’t have complete statistics over the downloads since I’ve rebuilt the sites lots of times and moved servers and such. Currently, these are the download stats from CrazyBeaver Softwares homepage:

  • BeaverSFV 1.1 – 167
  • CrazyBeavers YouTube Downloader 1.01 – 6
  • CrazyBeavers Calendar Class 1.1 – 143
  • CrazyBeavers RSS Class 1.3 – 188
  • CrazyBeavers Upload Class 1.2 – 233
  • CrazyBeavers Chat 1.3 – 123
  • Imager Gallery 5.5 Prerelease – 1276
  • CrazyBeavers Upload 2.4 – 207
  • CrazyBeavers ZIP 1.0 Prerelease 3 – 69
  • Imager Resizer 2.4 – 957

Looking at this it seems quite clear that Imager Gallery and Imager Resizer would be the best candidates for downloaded products. These stats are just for the past few months though but if they’ve had similar numbers since they were released during 2004-2005 it would give quite a lot of downloads. Lets elaborate a bit further though, most of my old ASP and ISAPI/COM applications are listed on HotScripts and Aspin aswell, lets look at their popularity there to the calculation.

  • CrazyBeavers Calendar Class 1.1 – 5 565 views on HotScripts with 3 votes (4.33 average)
  • CrazyBeavers RSS Class 1.3 – 2 175 views on HotScripts with 2 votes (5.00 average)
  • Imager Gallery 5.5 Prerelease – 22 271 views on HotScripts with 74 votes (4.39 average)
  • CrazyBeavers Upload 2.4 – 3 415 views on HotScripts with 15 votes (4.20 average)
  • CrazyBeavers ZIP 1.0 Prerelease 3 – 651 views on HotScripts with 2 votes (5.00 average) – Listed under CGI & Perl though, wasn’t allowed in the ASP category
  • Imager Resizer 2.4 – 6 246 views on HotScripts with 176 votes (4.78 average)
  • Imager Gallery 5.5 Prerelease – 26 940 views on Aspin with 9 votes (5 stars)
  • CrazyBeavers 2.4 – 6 147 views on Aspin with 1 votes (5 stars)
  • Imager Resizer 2.4 – 17 325 views on Aspin with 37 votes (5 stars)

Now thats some numbers, over 22 000 views of Imager Gallery on HotScripts and almost 27 000 on Aspin. If we go a bit crazy and assume that a third the of people (probably it would be closer to a quarter of the people but that isn’t as fun to count with) also downloaded the script we would have 16 000 downloads of Imager Gallery there! If we then add the numbers we would have 17 000 assumed downloads which is quite a lot. Still, Imager Gallery is only the second most downloaded of my products. The true winner, and the only product which I know for sure how many times it has been downloaded, is CrazyBeavers Winamp Controller. Counting in at 25 239 downloads since January 27th, 2005 its by far the most downloaded product I ever created and one of the few that I don’t use myself!

This article was just a little ego boost for myself but it feels so damn good that people actually seem to appreciate my work enough to download it over 20 000 times!

Categories: Articles, Beaver Tags:

CrazyBeavers YouTube Downloader

April 19th, 2008 No comments

It’s been a while now since there was a new release from CrazyBeaver Software so I thought I should make some fuzz about it and talk about it here as well.

A few weeks ago a friend of mine asked if I knew any way to save a video from YouTube onto his harddrive so he could use it in his school presentation. A quick search on google turned up few services that could download the .flv for you which was pretty neat though not enough since it would require that the schools computers could play .flv, which they can’t. My idea then was to make a simple wrapper for FFmpeg (a great open-source tool for recording and converting audio and video streams) and let him use that for conversion. The goal at this time was to make it easy for him to do this without my help in the future and maybe to let my other classmates do it as well. It worked out pretty well in the end and I now have a really neat C# wrapper for FFmpeg.exe which I hope to release some day for everyone to use. It was however not really satisfied with this, my application only did half the job, and the easy part was what was missing. I went looking around the net a bit for solutions on how to download the .flv-files from YouTube and found several ways which had their advantages and drawbacks. In the end, I borrowed a few ideas from most of them and got my own working solution for getting the .flv-files.

CrazyBeavers YouTube Downloader 1.01

The result of this was the brand new CrazyBeavers YouTube Downloader which was released yesterday as version 1.0 and earlier today as 1.01 (just love the early bugs, so simple, so devastating). I’ve seen another program out there that does the same as mine but seeing the page I found it on i didn’t really want to download and run that .exe so hopefully this will be of use to more then just my class now.

With this release I also returned to NSIS (NullSoft Install System) for the installation which works a ton better then the Visual Studio setup projects I’ve used for BeaverSFV. I’ve scripted it to check for .Net 2.0 and if not it will download and install it. It also checks if the system is x86 or x64 to decide which package to get. Hopefully I’ll get around to discuss that one some day as well since it turned out really great. But until then, enjoy my new application!

Categories: .Net, Beaver, c# Tags:

Uploading multiple files and form fields in .Net

January 23rd, 2008 No comments

Recently while building a small application for a friend of mine I came across a part where I needed something that I just couldn’t find in the .Net framework. I needed to upload two files (and specify their fieldnames) and a few form fields to a webpage. I thought this would be easy just using the provided WebClient class but after looking closer at it I found that it didn’t really offer anything of what I needed. Trying not to feel let down by this I started to write my own extended version of WebClient with a few new tricks that the old one couldn’t do.

I tried to keep it as simple as possible so instead of writing new classes to hold form and file data I used two Dictionary<string, string> to pass the values. The Key is the fieldname and the Value the value or the path to the file. An example of uploading a few files and adding a few fields to that could look like this:

Dictionary<string, string> FormFiles = new Dictionary<string, string>();

FormFiles.Add("mypet", "C:\\cat.jpg");
FormFiles.Add("me", "C:\\myself.jpg");

Dictionary<string, string> FormFields = new Dictionary<string, string>();

FormFields.Add("age", "22");
FormFields.Add("location", "Sweden");

WebClientEx WC = new WebClientEx();

try
{
    WC.UploadData("http://www.myserver.com/upload.aspx", FormFiles, FormFields);
}
catch(WebException E)
{
    System.Console.WriteLine("Upload failed with HTTP-Code" + ((HttpWebResponse)E.Response).StatusCode.ToString());
    System.Console.ReadKey();
    return;
}

It doesn’t look that hard does it? It’s perfect to use if you need to “submit” a form on a webpage from your c# application or just need to send several files to a webserver in the same request. Below is the complete code for WebClientEx displayed. You may use it for anything you want as long as you don’t claim it as your own. If you use it in a project of yours then please write a comment or send me an email about it!

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using CrazyBeavers.Utils;

namespace CrazyBeavers.Net
{
    /// <summary>
    /// Provides common methods for sending data to and receiving data from a resource identified by a URI. This version comes with extended support for uploading files and formfields.
    /// </summary>
    public class WebClientEx : WebClient
    {
        public byte[] UploadData(string Address, Dictionary<string, string> Files, Dictionary<string, string> Fields)
        {
            string Boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] BoundaryEnd = Encoding.ASCII.GetBytes("\r\n--" + Boundary + "--");

            MemoryStream MS = new MemoryStream();
            byte[] Buffer;

            foreach (KeyValuePair<string, string> Field in Fields)
            {
                StringBuilder Header = new StringBuilder();
                Header.Append("\r\n");
                Header.Append("--");
                Header.Append(Boundary);
                Header.Append("\r\n");
                Header.Append("Content-Disposition: form-data; name=\"");
                Header.Append(Field.Key);
                Header.Append("\"");
                Header.Append("\r\n");
                Header.Append("\r\n");
                Header.Append(Field.Value);

                byte[] PostHeaderBytes = Encoding.UTF8.GetBytes(Header.ToString());

                MS.Write(PostHeaderBytes, 0, PostHeaderBytes.Length);
            }

            foreach (KeyValuePair<string, string> File in Files)
            {
                StringBuilder Header = new StringBuilder();
                Header.Append("\r\n");
                Header.Append("--");
                Header.Append(Boundary);
                Header.Append("\r\n");
                Header.Append("Content-Disposition: form-data; name=\"");
                Header.Append(File.Key);
                Header.Append("\"; filename=\"");
                Header.Append(Path.GetFileName(File.Value));
                Header.Append("\"");
                Header.Append("\r\n");
                Header.Append("Content-Type: ");
                Header.Append(MimeHelper.GetMimeTypeForExtension(Path.GetExtension(File.Value)));
                Header.Append("\r\n");
                Header.Append("\r\n");

                byte[] PostHeaderBytes = Encoding.UTF8.GetBytes(Header.ToString());

                FileStream FS = new FileStream(File.Value, FileMode.Open, FileAccess.Read);

                MS.Write(PostHeaderBytes, 0, PostHeaderBytes.Length);

                Buffer = new Byte[checked((UInt32)Math.Min(4096, (Int32)FS.Length))];
                Int32 BytesRead = 0;
                while ((BytesRead = FS.Read(Buffer, 0, Buffer.Length)) != 0)
                    MS.Write(Buffer, 0, BytesRead);

                FS.Close();
            }

            MS.Write(BoundaryEnd, 0, BoundaryEnd.Length);
            MS.Position = 0;

            if (this.Headers["Content-Type"] != null)
                this.Headers.Remove("Content-Type");

            this.Headers.Add("Content-Type", "multipart/form-data; boundary=" + Boundary);

            Buffer = new byte[MS.Length];
            MS.Read(Buffer, 0, (Int32)MS.Length);

            return this.UploadData(Address, "POST", Buffer);
        }
    }
}

I won’t go in explaining line of this code as I’ve done in a few other samples. The code isn’t that hard to understand if you have moved beyond the “beginner stage” of coding. The thing worth mentioning is the part with MimeHelper.GetMimeTypeForExtension() which is a small function I wrote which checks the registry for any available mimetype for a given extension. I’ve included that code below aswell since it’s needed for WebClientEx.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace CrazyBeavers.Utils
{
    public static class MimeHelper
    {
        public static string GetMimeTypeForExtension(string FileExt)
        {
            if (!FileExt.StartsWith("."))
                FileExt = "." + FileExt;

            string Mime = "application/octet-stream";

            RegistryKey Classes = Registry.ClassesRoot;

            RegistryKey FileKey = Classes.OpenSubKey(FileExt);
            if (FileKey != null)
            {
                Mime = (string)FileKey.GetValue("Content Type", "application/octet-stream");
                FileKey.Close();
            }
            Classes.Close();
            return Mime;
        }
    }
}

Enjoy!