Pages - Menu

Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

C# - Convert string to alphanumeric only

Task

Today I have a task to strip off characters from a string that are not alphabets or numbers. I implemented it as extension method so that it is reusable.

Code

public static string ToAlphaNumericString(this string inString)
{
    if (string.IsNullOrEmpty(inString))
        return string.Empty;

    return new string(inString.Where(c => char.IsLetterOrDigit(c)).ToArray());
}

With linq, the code is short and simple. There are 2 interesting points in this.

char.IsLetterOrDigit()


One of the magic part of our magic line is the char.IsLetterOrDigit(). It checks if a character is letter or digit, then it will return as part of the list via linq.

ToArray()


The Where clause from linq returns IEnumerable. Normally we use ToList() to write the result to the memory for later use. However, because string is an array of chars in C#, we try to convert the linq result to an array, we then pass char[] to the constructor of string to instantiate a new object.


Thoughts

You probably already noticed by now. What I have done was checking up the characters one by one and instantiate a new string object with the characters. This has a potential performance issue as create an object is an expensive operation, at least for the purpose of stripping illegal characters. I have not done my benchmark yet, but I think StringBuilder will be faster.

EDIT: It turns out Linq is actually pretty good in performance according to some benchmarks.
Ref: http://stackoverflow.com/questions/11395775/clean-the-string-is-there-any-better-way-of-doing-it/11396039#11396039

Return XML Datafeed in a MVC Action Result

Scope

We are trying to export our products in an xml feed. This will be provided to 3rd party vendor so they can provide search or product reviews for our products, or simply froogle.

I am building a MVC action that will return the XML result in the page when a url is called (so it should display the xml as content in the browser, and view source of the page should show the actual xml file).


Problem

During this exercise, I encountered the following errors:-
  • Error message about prefix '' cannot be redefined from '' tag
  • Missing XML Declaration
  • Getting a declaration of UTF-16 instead of UTF-8
  • '', hexadecimal value 0x03, is an invalid character
It is a multiple failure and apparently they are all common and valid errors.

Solutions



This "little" piece of code fixed quite a few things.

Name Space Prefix

Initially, I tried to put namespace in the XDocument as a XAttribute, that was causing error and the correct way is to add XDeclaration to the Element name.

Declaration

I intentionally put the declaration in string with the xml.ToString(), there were other solutions like using MemoryStream and Save() to "conserve" the declaration, I just found that is overkilling for such a simple thing.

This also resolve the issue where conversations of MemoryStream that caused UTF-8 became UTF-16.

Invalid Character 

This is because the object (string) that I pass in to the XElement has invalid character. There easiest way and most effective way is to Sanitize the input. I wrote an extension method for this.

CDATA

Another issue that might arise is the value for XElement might have HTML tags in it. Again, this can be done by another extension method to wrap the value in a CDATA object, the reason for the extension method is this will cater for null value and it looks neater.