Archive

Posts Tagged ‘String’

Gotcha: don’t use ‘{$…}’ syntax or ‘$…’ syntax in XSL-XPath’s concat

<xsl:template match="cxml:Item" mode="col">
  <xsl:variable name="FILENAME" select="…someXPathQuery…"/>
  <xsl:variable name="IMAGE" select="concat(‘http://gallery.clipflair.net/activity/image/’, $FILENAME, ‘.png’)"/>

I got confused a bit today after a long day of fiddling with XSL and ClipFlair Activity Gallery’s CXML (Collection XML) data (as used in PivotViewer control), and didn’t understand why I couldn’t use an XSL variable’s (FILENAME in the sample above) calculated value inside the definition of another variable.

That other variable (IMAGE) was using “concat” function of XPath and I was getting a literal string concatenated, instead of the value of the FILENAME one.

After a while I noticed that I was using string quotes arround the respective argument passed to the “concat” function. One needs to use $FILENAME there, not ‘$FILENAME’ and of course not ‘{$FILENAME}’ (the last one is used inside say HTML argument values used for output, like <img href=”{$IMAGE}” />)

Gotcha: .NET Point and PointConverter inconsistency in string format used

I have submitted the following issue to Microsoft Connect (product feedback center):

http://connect.microsoft.com/VisualStudio/feedback/details/809084/point-class-issue-with-two-way-databinding

Point class issue with two-way databinding

 

In Silverlight, when using databinding code like the following:
<StackPanel Orientation="Vertical" Name="propPosition">
    <sdk:Label Style="{StaticResource PropertyLabelStyle}" Content="Position:" Target="{Binding ElementName=edPosition}" />
     <TextBox Name="edPosition" Text="{Binding Position, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=true}" />
</StackPanel>

and binding (via DataContext) to a View that has the following property:

Point Position { get; set; }

then what you see on the UI is values like 500; 100

but when you try to edit the position and enter say 400; 100 it shows a red message that it is invalid format (caught an exception that is and showing on the UI automatically cause of ValidatesOnExceptions and NotifyOnValidationError being true)
if you enter 400, 100 it works ok (it moves a ClipFlair Studio [http://ClipFlair.net] window arround in my case), so it outputs the two numbers (X, Y) with a ";" but expects to get them separated with a "," (also wonder if it copes OK with numbers in say format used in Greece where decimal point separator is , instead of .)

 

I managed to reproduce the same behaviour in a .NET console program:

//Console program in C# to demonstrate Point.ToString and PointConverter (from string) inconsistency in string format
//(the former outputs X;Y, the later expects X,Y)

using System;
using System.Windows; //for "Point" class (needs WindowsBase.dll reference)

namespace ConsoleApplication1
{
  class Program
  {

    static PointConverter conv = new PointConverter();

    static void Main(string[] args)
    {
      Point p = new Point(10, 20);
      Console.WriteLine(p); //outputs "10;20"
           
      //——————

      Point p1 = (Point)conv.ConvertFrom("10, 20");
      Console.WriteLine(p1); //outputs "10;20"

      //——————

      Point p2 = (Point)conv.ConvertFrom("10; 20"); //unhandled exception "System.FormatException" in mscorlib.dll
      Console.WriteLine(p2); //never reached cause of exception above
    }

  }
}

HowTo: Remove invalid filename characters in .NET

In ClipFlair Studio I use DotNetZip (Ionic.Zip) library for storing components (like the activity and its nested child components) to ZIP archives (.clipflair or .clipflair.zip files). Inside the ZIP archive its child components have their own .clipflair.zip file and so on (so that you could even nest activities at any depth) which construct their filename based on the component’s Title and ID (a GUID)

However, when the component Title used characters like " (double-quote) which are not allowed in filenames, then although Ionic.Zip created the archive with the double-quotes in the nested .clipflair.zip filenames, when trying to load those ZipEntries into a memory stream it failed. Obviously I had to filter those invalid filename characters (I opted to remove them to make those ZipEntry filenames a bit more readable/smaller).

So I added one more extension method for string type at StringExtensions static class (Utils.Silverlight project), based on info gathered from the links from related stackoverflow question. To calculated version of a string s without invalid file name characters, one can do s.ReplaceInvalidFileNameChars() or optionally pass a replacement token parameter (a string) to insert at the position of each char removed.

public static string ReplaceInvalidFileNameChars(this string s,
string replacement = "") { return Regex.Replace(s, "[" + Regex.Escape(new String(System.IO.Path.GetInvalidPathChars())) + "]", replacement, //can even use a replacement string of any length RegexOptions.IgnoreCase); //not using System.IO.Path.InvalidPathChars (deprecated insecure API) }

For more info on Regular Expressions see http://www.regular-expressions.info/ and http://msdn.microsoft.com/en-us/library/hs600312.aspx


BTW, note that to convert the char[] returned by System.IO.Path.GetInvalidPathChars() to string we use new String(System.IO.Path.GetInvalidPathChars()).

It’s unfortunate that one can’t use ToString() method of char[] (using Visual Studio to go to definition of char[].ToString() takes us to Object.ToString() which means the array types don’t overload the virtual ToString() method of Object class to return something useful).


Another thing to note is that we don’t use System.IO.Path.InvalidPathChars field which is deprecated for security reasons, but use System.IO.Path.GetInvalidPathChars() method instead. MSDN explains the security issue, so better avoid that insecure API to be safe:

Do not use InvalidPathChars if you think your code might execute in the same application domain as untrusted code. InvalidPathChars is an array, so its elements can be overwritten. If untrusted code overwrites elements of InvalidPathChars, it might cause your code to malfunction in ways that could be exploited.

.NET String extension methods to check for array of prefixes or suffixes

Seems StartsWith and EndsWith methods of String class in .NET are missing a version that accepts multiple (as an array) prefixes or suffixes respectively when testing the string. To achieve this I just added the following extension methods to StringExtensions class (of Utils.Extensions namespace) under Utils.Silverlight project at the ClipFlair source code.

public static bool StartsWith(
this string s,
string[] suffixes,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in suffixes) if (s.StartsWith(suffix, comparisonType)) return true; return false; } public static bool EndsWith(
this string s,
string[] suffixes,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in suffixes) if (s.EndsWith(suffix, comparisonType)) return true; return false; }

 

To use them, you add a reference to Utils.Silverlight project to your own one and then add a using clause for the namespace that hosts a static class with these extension methods (e.g. “using Utils.Extensions;”) and then you can use them on any String at the respective source file. Can even use them on literal strings, since most .NET compilers support Boxing of literals into respective types.

I’m using a default value for the comparisonType method argument to make it optional. I use StringComparison.CurrentCulture as the default value for it (performing a word case-sensitive and culture-sensitive comparison using the current culture), as Microsoft is doing at “String.StartsWith(String)” method. However, do note the following text from that method’s documentation:

Notes to Callers

As explained in Best Practices for Using Strings in the .NET Framework, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string begins with a particular substring by using the string comparison rules of the current culture, call the StartsWith(String, StringComparison) method overload with a value of StringComparison.CurrentCulture for its comparisonType parameter.

.NET String class extensions to replace prefix or suffix

Just added the following extension methods to StringExtensions class (of Utils.Extensions namespace) under Utils.Silverlight project at the ClipFlair source code.

public static string ReplacePrefix(
this string s,
string fromPrefix,
string toPrefix,
StringComparison comparisonType = StringComparison.CurrentCulture) { return (s.StartsWith(fromPrefix, comparisonType)) ?
toPrefix + s.Substring(fromPrefix.Length) : s; } public static string ReplacePrefix(
this string s,
string[] fromPrefix,
string toPrefix,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string prefix in fromPrefix) if (s.StartsWith(prefix, comparisonType)) return toPrefix + s.Substring(prefix.Length); return s; } public static string ReplaceSuffix(
this string s,
string fromSuffix,
string toSuffix,
StringComparison comparisonType = StringComparison.CurrentCulture) { return (s.EndsWith(fromSuffix, comparisonType)) ?
s.Substring(0, s.Length - fromSuffix.Length) + toSuffix : s; } public static string ReplaceSuffix(
this string s,
string[] fromSuffix,
string toSuffix,
StringComparison comparisonType = StringComparison.CurrentCulture) { foreach (string suffix in fromSuffix) if (s.EndsWith(suffix, comparisonType)) return s.Substring(0, s.Length - suffix.Length) + toSuffix; return s; }

 

To use them, you add a reference to Utils.Silverlight project to your own one and then add a using clause for the namespace that hosts a static class with these extension methods (e.g. “using Utils.Extensions;”) and then you can use them on any String at the respective source file. Can even use them on literal strings, since most .NET compilers support Boxing of literals into respective types.

e.g.

s = s.ReplacePrefix("https://&quot;, "http://&quot;, StringComparison.OrdinalIgnoreCase);

//– converts https:// prefix to http:// ignoring character case

or

s = s.ReplacePrefix(new String[]{"https://&quot;, "http://&quot;}, "", StringComparison.OrdinalIgnoreCase);

//– removes https:// or http:// prefix ignoring character case

 

Update:

I added a default value for the comparisonType method argument to make it optional. I use StringComparison.CurrentCulture as the default value for it (performing a word case-sensitive and culture-sensitive comparison using the current culture), as Microsoft is doing at “String.StartsWith(String)” method. However, do note the following text from that method’s documentation:

Notes to Callers

As explained in Best Practices for Using Strings in the .NET Framework, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. To determine whether a string begins with a particular substring by using the string comparison rules of the current culture, call the StartsWith(String, StringComparison) method overload with a value of StringComparison.CurrentCulture for its comparisonType parameter.

%d bloggers like this: