Archive

Posts Tagged ‘Conversion’

Gotcha: no prefix increment/decrement VB.net operators, but get parsed

In C/C++ and C# one has useful prefix (++index) and postfix (index++) increment operators and corresponding decrement ones.

Although they have a single operant, they’re not working like functions as single + or – prefix would do, but instead they cause side-effects – they edit the variable passed to them. The prefix increment operator first increases a variable’s value, then returns it as result, while the postfix one first returns a variable’s value, then increases it.

Visual Basic.net doesn’t have such operators (and they don’t seem to plan to add such from their response on related feedback at Microsoft Connect.

However, if you type-in

Dim x = ++y

the compiler won’t complain. In fact, it won’t complain even if you type

Dim x = +++++y

The reason is because it thinks this last crazy-looking expression is:

Dim x = +(+(+(+(+y))))

Similarly, it accepts expressions like

Dim x = –y

and

Dim x = —–y

So a programmer coming from C# or converting C# code to VB.net has to be extra careful when converting ++index expressions to use their own implementation as a function that takes a ByRef parameter

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.

%d bloggers like this: