This summer I worked on a project where I needed to produce Edifact files, mainly in the Cpaym or the Coplat format. Short story long story, in the Coplat format, when you write a string with a specified length, you must pad the string with spaces to match the exact length required, with the string aligned to the left. For example if the string is "hello" and the length is 20 then you write the following: "hello ", and for numbers they must be preceded with ‘0’s like: 12345 on 20 characters : "00000000000000012345", of course the number should be aligned to the right.
The idea was to overload the Append method of the StringBuilder class with two extension methods to handle the spaces or zeros automatically, here is the code :
- public static void Append(this StringBuilder sb,string text, int len)
- {
- string s = text ;
- if (text.Length > len)
- {
- s = truncate(text, len);
- //Ilog.Info("data : " + text + " truncated to : " + s);
- }
- s = s.PadRight(len, ' ');
- sb.Append(s);
- }
- public static void Append(this StringBuilder sb, int num, int len)
- {
- string s = num.ToString();
- if (s.Length > len)
- {
- s = truncate(s, len);
- //Ilog.Info("data : " + num.ToString() + " truncated to : " + s);
- }
- s = s.PadLeft(len, '0');
- sb.Append(s);
- }
- public static string truncate(string s, int len)
- {
- if (s.Length > len)
- return s.Substring(0, len);
- else
- return s;
- }
- //The default Append method
- sb.Append("FIN");
- //This will result in '00000001'
- sb.Append(1, 8);
- //This will result in 'cool '
- sb.Append("cool", 15);
So what about you? have you ever faced a situation where extension methods were handful for you? share your experience with us in the comments.
Since it’s really rare to find useful introductions to the EDI standards, I recommend this blog to start with http://gekseppe.blogspot.com/