C# Reverse String

2009 September 14

I was helping someone out on the asp.net forums and they needed an easy way to do a substring going from right to left and came up with a pretty easy way to reverse a string. I wrapped it in an extension method for ease of use, but it basically breaks up the string into a char array reverses it and returns a new string. You could then just do a SubString on the reversed string, accomplishing the substring going from right to left.


public static class StringExtensions
{
public static string ReverseString(this string str)
{
return String.IsNullOrEmpty(str) ? string.Empty : new string(str.ToCharArray().Reverse().ToArray());
}
}

- Matti

Simple File Download

2009 August 19

Ever use file:///c:\mystuff\myfile.txt in your html to download a file? Well, here is a slightly more secure and robust way of doing this via an HTTPHandler. This post is not going to explain how to create and use the handler, but merely the code required within the ProcessRequest() method.

First things first, the only parameter that is required is the path to the file, which can be passed in via a param using an HTTP POST or via a query string param using an HTTP GET.

Now, walking through the code the first thing we do in the ProcessRequest method is to try and get the FilePath and make sure it is valid, note that you can add in your own validation here to make sure the file is from a given directory or is a given type and so on.

if (!context.Request.Params.AllKeys.Any(p => string.Compare(p, "FilePath", true) == 0))
{
context.Response.Write("Invalid request.");
context.Response.End();
return;
}
string filePath = HttpUtility.UrlDecode(context.Request["FilePath"]);
if (String.IsNullOrEmpty(filePath))
{
context.Response.Write("File path cannot be empty.");
context.Response.End();
return;
}

Next, we need to write back the file. This is pretty straight forward, two things to note is that we set the content type to “application/octet-stream” which is standard for binary files and also by adding the Content-Disposition header we can set what filename is displayed in the Download prompt dialog, so you can change this to whatever you want, i’m using the filename by default.

// Write back file
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(filePath) + "\"");
context.Response.Clear();
context.Response.WriteFile(filePath);
context.Response.End();

Here is the completed ProcessRequest method:


public void ProcessRequest(HttpContext context)
{
try
{
// Retrieve file path from request
if (!context.Request.Params.AllKeys.Any(p => string.Compare(p, "FilePath", true) == 0))
{
context.Response.Write("Invalid request.");
context.Response.End();
return;
}
string filePath = HttpUtility.UrlDecode(context.Request["FilePath"]);
if (String.IsNullOrEmpty(filePath))
{
context.Response.Write("File path cannot be empty.");
context.Response.End();
return;
}

// Write back file
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(filePath) + "\"");
context.Response.Clear();
context.Response.WriteFile(filePath);
context.Response.End();
}
catch (Exception ex)
{
context.Response.Write("Failed to process your request.");
context.Response.End();
}
}

Lastly, here is an example as to how you might use this:


<a href="myhandler.ashx?FilePath=C:\testfile.txt">Download File</a>

Thanks and hope this helps, if you have any questions feel free to comment.

.matti

Why I love simple design

2009 July 27
by Matti

The answer is ironically simple. Ease of use. Web sites should not be an easter egg hunt. Nor should websites be a novel. There are kindles for that. Any web site I go to I should be able to immediately answer 2 questions off the bat:

1. What is it?
2. How do I do it?

One site that captures this quite well is Vimeo.com. Upon entering the site it is clear that it is a web site for sharing videos. And to get started the have a nice big green button labeled “Sign up for Vimeo”. Besides the fact that big green buttons are awesome (Who doesn’t like clicking big green buttons?), it is very clear and easy to see the “How”.

Now to be completely counter-intuitive, simple design is hard. Widdling down a whole list of requirements and coming up with a design that works for all parties is not easy and often times results in a design built upon the result of many compromises over many a lengthly battles between designers, developers and other project stake holders. Same ol’ story, right? Yup and it sucks. I’m not going to delve into that subject as it is outside the scope of my post and i’m trying to keep things simple. ;]

So, next time you do a design or land on a new web site, see how long it takes you to answer the “What?” and the “How?”. Ask other people to look at it too. See if they get it and how long it takes them. If they don’t get it or it takes them 5-10 seconds to figure it out, you may want to take another look at your design.

.matti

VS.NET Tip – Easily Resolve Unknown or Ambiguous Namespace

2009 March 7

This is one of those little things that I use in Visual Studio.NET a lot and has made my life much easier when resolving unknown or ambiguous namespaces in VS. It’s funny, because I’ve used this so much that I thought everyone knew about it until I showed someone at work who had never used it before. Then I asked another person and they had never used it before. I felt like I was in the twilight zone…no matter…here it is.

How:

  1. Right click on your unknown type
  2. Select Resolve
  3. Select the correct Namespace

Example:
1.  We have an unknown type of XmlDocument
unknownnamespace

 

 

2. Right-click, select “Resolve”, then “using System.Xml;”

 
 
 
 
 
And vuala “using System.Xml;” is added to your using statements at the top of your class! No more searching for the correct namespace. Just a 2-click operation now…hope that helps you out.

- Matti

Cast XmlNodeList to XmlElement[]

2009 February 6

Given you already have a System.Xml.XmlDocument object called “document”…

document.DocumentElement.ChildNodes.Cast<XmlElement>().ToArray<XmlElement>();

or if you want the direct children of the root…

document.DocumentElement.ChildNodes[0].ChildNodes.Cast<XmlElement>().ToArray<XmlElement>();

If you know of an easier way please feel free to share.

.matti read more…

IE6 – “The PNG Killer”

2009 January 6
by Matti

Let me first start off by explaining some basics on PNG’s and the GIF.  In GIF’s every pixel in the image is a solid color.  When you create a transparent GIF you are actually just telling it to make some pixels transparent and to leave the others a single color, which is why it usually looks like crap.  With PNG’s there is actually another factor at play called an alpha channel, which adds a transparency level to each pixel.  So, essentially the pixels closer to the transparent background in a PNG will have a higher transparency level, which is why PNG’s look so much better than GIF’s.

Enter Internet Explorer 6, the 2nd most popular browser with IE 7 in the lead.  One of many problems with IE6 is that it does not support PNG’s.  So, what are you to do?  Here are some options below….

AlphaImageLoader

This is an activeX solution introduced by Microsoft that you can use to have your PNG’s render in IE6.  This works fairly well if you have a single image and are not trying to repeat a background image thats a PNG.  I’ve used a couple javascript libraries that wrapped this functionaly very nicely, which i’ve listed below.

http://24ways.org/2007/supersleight-transparent-png-in-ie6

http://www.campbellsdigitalsoup.co.uk/2007/11/27/a-new-png-fix-with-jquerys-helping-hand/

Matted Gifs

This is another option that uses a Matte with a GIF.  What this does is makes that crappy looking white border on your Transparent GIF’s match the background color of its container.  Instructions for created a Matted GIF in Photoshop are below…

  1. Go to File -> Save for Web & Devices
  2. Change your Eyedropper color to whatever color you want
  3. In the Matte dropdown (right-hand side) select eyedropper color. 
  4. Save it.

Note that you can play with the colors that are actually displayed in the Color Table by turning them on/off if you need to further refine your image, but usually the default works fairly well.

I hope these help you out a bit if you are struggling with transparent images and IE 6.

.matti

Javascript Trim String

2008 December 23

You can find this or something similar nearly anywhere by simply googling it, the only reason why i’m blogging this is so I don’t have to google it. So, here it is, the javascript trim string function.

function TrimString(str) {
return str.replace(/^\s+|\s+$/g, '');
}

.matti

JQuery “each()” == Coolest thing since sliced bread

2008 December 5

Alright, I only starting using JQuery a few months ago so i’m still learning, so if i’m beating the “dead horse” I apologize, but I just had to share JQuery’s each() function.

As defined by JQuery’s documention…

“Takes a function as an argument. Applies it to each element that matches the selector. The function can take up to two arguments. The first argument passed to the function is an index, beginning with 0. The second argument passed to the function is the element itself. In addition, inside the function the keyword ‘this’ also refers to the current element.”
 

Basically it allows you to do a for each loop on a JQuery selector and execute a function in the context of each matched element.

Example:
$(“#MyId .subItem”).each(function(){
this.onmouseover = function() { this.style.backgroundColor = ‘#369′; this.style.color = ‘#fff’; }
this.onmouseout = function() { this.style.backgroundColor = ‘#fff’; this.style.color = ‘#369′; }
});

The example above wires up the onmouseover and onmouseout of each child element of MyId. This is a very simple example, but the potential is awesome. Very cool!!

.matti

70-536 Certification

2008 December 4

I’ve decided to start studying for the 70-536 certification exam. I have the exam study guide book, which is currently serving as a great door stop considering it weighs 25 pounds. Am curious as to other people’s experiences with this exam and if they have any suggestions for studying. I started studying for it before and was scoring around 80-90% on the practice exams, but am not sure how realistic they are with the actual exam. Any insight, experiences or advice would be greatly appreciated!

Thank you.

.matti

Get Element Position

2008 November 14
by Matti

I needed a quick and easy function to get an element’s position in javascript today so I wrote a function that returns the top and left coordinates. I’ve tested this in IE 6/7, FF3+ and Chrome.

function getPosition(element) {
var top = left = 0;
while (element) {
top += element.offsetTop;
left += element.offsetLeft;
element = element.offsetParent;
}
return [top, left];
}

.matti