My PhotoBruno Brás Silva

09, April 1986

info@brunosilva.net

Sintra Lisbon Portugal

Category: .NET

Save File Dialog - Firefox and Internet Explorer

Posted on 3:53pm 8/06/2008 by Bruno Silva in .NET, ASP.NET, Programming, Software

Today I had to generate files in ASP.NET for download which was supposed to open a save file dialog in the web brower. The file name was based on a title field extracted from a database. The title had spaces which I allowed to be used in the file name (I replaced accents and other invalid characters). In the source code bellow you can see a simple illustrative example.

Perhaps you have noticed that I am generating a plain text file, but I am not using the “text/plain” mime type. When you use “text/plain” the browser automatically knows which application to use for opening the file. If you use “application/octet-stream” instead, the browser uses the file extension in order to find out which is the operating system default program for that file extension. But when you have spaces in you file name as in the example above, you get different behaviours from different browsers.

In Internet Explorer 7, the spaces are replaced by underscores, the the browser recognizes the file extension “.txt”.

If you download the same generated file using Firefox, it cuts the file name ending at the first space. This way the browser considers that your file name is “Just” which has no extension. As a consequence Firefox doesn’t know which application to suggest you for opening the file.

I haven’t tried other browsers, but I took a safe approach. In the server side, while defining the file name I replace the spaces by underscores, this way the download has a consistent behavior in both browsers.

Multiplatform Games in XNA - Preprocessor Directives

Posted on 7:25pm 6/22/2008 by Bruno Silva in .NET, Programming, Visual Studio, XBox 360, XNA

You probably already know that developing a game that runs both in XBox 360 and Windows is possible and pretty manageable using XNA Game Studio. If you start developing your game for Windows (which is great to compile/debug your code more quickly), you can then duplicate that project as an XBox 360 game. The same files will be used, but during compilation, the assemblies of XNA Framework that are used are chosen based on the target platform.

Create Copy of Project fot XBox 360

Developing a game for both platforms isn’t that trivial. There are a lot of functionalities that are exclusive to each platform. For instance, the Gamercard integration that I talked about in an earlier post, only works in XBox 360. In the other hand, since XNA games targeting Windows are pure .NET managed code, you can use whatever .NET libraries you want (such as WiimoteLib :) )

If you have a game that you want to compile to both platforms, but which has slight differences, you can use the C# Preprocessor Directives. When you create an XBox 360 project, the XBOX and XBOX360 conditional compilation symbols are used by the preprocessor.

XBox 360 Project Properties

Those symbols can be used to create conditions that make the preprocessor able to choose which lines of code of a file to compile. The example bellow is pretty self-explanatory.

Preprocessor Directives

If you compile this game targeting the XBox 360 you’ll get a blue background, otherwise you’ll get a red background.

This is not a XNA or XNA Game Studio feature, but this was the first time I needed to use such feature. More information about C# Preprocessor Directives are available at MSDN.

XNA - Getting GamerCard Info in Xbox 360

Posted on 5:30pm 6/12/2008 by Bruno Silva in .NET, Programming, XBox 360, XNA

Xbox 360 - GamerCard

One nice XNA feature is the ability to manage Xbox 360 users gamer data. This way you can access your gamercard information which include your name, avatar, achievements, played games and list of friend among other things. How can you do that?

In the Initialize method of your game you must add a specific component into the game, in order to prepare the game to access the data.

XNA Gamercard Manipulation

Since while the Initialize and LoadContent methods are executed, the gamer data is not available yet, you must access it in the Update method. There you can check if a variable is set, and if it is not, you load the gamercard information. Be careful, you must not load the gamer data in every iterations of the game loop. Your Xbox will hang if you do that… It is an expensive operation. Try to load this data only one time or so during the game lifetime.

XNA Gamercard Manipulation

This example show your gamer picture in the screen, followed by some of your informations such as your gamer tag.

XNA Gamercard Manipulation

You can download the full source code and deploy it into your Xbox 360 console and give it a try. (I’ve written before about how to get a free XNA Creators Club Membership in order to allow XNA deploying).

HTTP Request and HTML Parsing in .NET

Posted on 7:26pm 5/17/2008 by Bruno Silva in .NET, Open Source, Programming, Utilities, Web

I’ve been working in college assignment which goal is to integrate several information systems. One of those is a website where we can see the flight schedules from/to Portuguese airports.

The website URL is http://www.innovata-llc.com/ana/default.asp. Me and a colleague of mine had to write a web service that was used by BizTalk as a wrapper of this web site’s form. It was supposed to send an HTTP request passing some request parameters using POST parameters, and to parse the HTML response in order to extract the flight list for a given destination city and departure date.

First of all lets see the code we used to get the response.

Uri address = new Uri(requestURL);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = “POST”;
request.ContentType = “application/x-www-form-urlencoded”;
StringBuilder data = new StringBuilder();

data.Append(“DPT_Date=” + “17-05-2008″);
data.Append(“&RET_Date=” + “20-05-2008″);
data.Append(“&dpt_station=” + “LIS”);
data.Append(“&arv_station=” + “LHR”);
data.Append(“&non_stops=” + “on”);

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}

// Get response
String htmlResponse;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Get the response string
htmlResponse = reader.ReadToEnd();
}

After getting the response content is time to use a nice HTML parser helper library. It is called HTML Agility Pack and it is open-source. You can find it at Codeplex.com/htmlagilitypack.

Now it is time to create an HtmlDocument (a class which ships with HTML Agility Pack) and load the response into this new instance. //Load HTML as XHTML
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(htmlResponse);

After looking to the HTML source code, we got the right Xpath expressions to extract the flight list.
//Get flight lines
HtmlNodeCollection flights = htmlDoc.DocumentNode.SelectNodes(
“//body/div/table[3]/tr[position()>=4 and position()<last()-1]“);

foreach (HtmlNode flight in flights)
{
//Get attributes
string departureTime = flight.ChildNodes[1].FirstChild.InnerText;
string arrivalTime = flight.ChildNodes[3].FirstChild.InnerText;
//Do some stuff …
}

That’s almost it. The next step was adding the extracted information into some data structures, and returning that data. But these details are out of this post scope.

Preventing client-side caching

Posted on 3:46pm 4/25/2008 by Bruno Silva in .NET, ASP.NET, Programming, Web

During this week I’ve been experiencing some problems with browser caching.

I’ve a dynamically generated XML file which contents change a lot (it is a photo gallery based on Slide.Show), and I want the people who see this gallery to see newly added photos immediately. Today someone asked me how to prevent the client-side caching (regarding Slide.Show too), so I did some searches and testing in order to enlight us both. :)

I’ve found reference to a few lines of code which should be used in ASP.NET web pages to prevent caching.

Response.CacheControl = “no-cache”;
Response.AddHeader(”Pragma”, “no-cache”);
Response.Expires = 0;

I tried the first one alone both in IE 7 and Firefox 2 and it seamed to be enough, nevertheless, being care is never enough,so I’ll probably use the 3 lines together!

Just try to be careful and don’t feel tempted to prevent caching in every single web page in your web site, it leads to poor perfomance in both your servers and in the client side. And every one likes to see the content of a previously visited page rendered quickly, right? :)

MCTS - Windows Workflow Foundation

Posted on 5:58pm 4/20/2008 by Bruno Silva in .NET, My Life, Programming

MCTS - .NET Framework 3.5, Windows Workflow Foundation Applications

Yesterday I had a nice surprise in my e-mail inbox! I passed in the certification exame I took in January. It is great news, since I just took this exam just as a first time experience with Microsoft Certification Exams.

I took part in the Beta Program of this exam, so I took it for free. And another great thing was the background that the preparation gave me in workflow engines, pretty useful now that I am learning about Microsoft BizTalk.

A great book that I read was Microsoft Windows Workflow Foundation Step by Step.

More details about the certification can be found in the Preparation Guide.

© Bruno Silva | Powered by Wordpress