HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Link to WinRT XAML code optimization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
xamloptimizationwinrtcodelink

Problem

I need a method which will parse text to RichTextBlock-compatible XAML markup with clickable links.

Example:

Input:

"Hello, check new service for students! Check edusty.ru and http://edusty.ru/test?text1=abc&args=123 sites. Check edusty.ru/privacy.html to read privacy policy."


Output:


      
     edusty.ru 
     
     http://edusty.ru/test?text1=abc&args=123 
     
     edusty.ru/privacy.html
     


I wrote this method:

public static string ParseLinksToXaml(this string source)
        {
            var transformedText = Regex.Replace(source,
                @"((https?:\/\/)?(ftps?:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/\S*)?)",
                @"""/> $1 ");
            foreach (Match match in matches)
            {
                var link = match.Groups[1].ToString();
                link = link.Replace("&", "&");
                link = link.Contains("://") ? link : "http://" + link;
                transformedText = transformedText.ReplaceFirst("\"" + match.Groups[1] + "\"", "\"" + link + "\"");
            }
            var xaml = @"
                                    ";
            return xaml;
        }


It works, but the code really looks bad. Can anyone help rewrite/optimize this?

Solution

Whenever you're concatenating strings inside a loop's body, +-concatenation should be ruled out; transformedText would be a StringBuilder instance, to which each iteration would Append.

However XAML is a subset of XML; as such, there is no reason to treat your output as purely strings: using the classes in the System.Linq.Xml namespace (otherwise known as "Linq-to-Xml"), you can rewrite this in a much more elegant and object-oriented way.

Extending System.String like this is a bit overkill, too. I'm not sure I'd like working in a code base where every single string out there has this ParseLinksToXaml extension method: that functionality is very specialized, and IMO deserves its own class where the client code is actually explicit about what's going on:

var parser = new StringLinksToXamlConverter();
var xaml = parser.ParseLinksToXaml(myString);


The string-building stuff going on under the hood should be an implementation detail - the returned value would be potentially much more useful to the client code if an XDocument was returned, leaving it up to the client code to query or output as a string.

Code Snippets

var parser = new StringLinksToXamlConverter();
var xaml = parser.ParseLinksToXaml(myString);

Context

StackExchange Code Review Q#84186, answer score: 3

Revisions (0)

No revisions yet.