WIP
DirectOutput framework for virtual pinball cabinets WIP
Go to:
Overview 
StringExtensions.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using System.Collections;
4 using System.Linq;
5 using System.Text;
6 using System.Text.RegularExpressions;
7 
8 using System.IO;
9 using System.Globalization;
10 using System.Xml.Serialization;
11 using System.Xml;
12 //using System.Web;
13 
14 
18 public static class StringExtensions
19 {
26  public static string RemoveLastChars(this string Input, int NumberOfCharsToRemove)
27  {
28  if (NumberOfCharsToRemove <= 0) return Input;
29  return (Input.Length > NumberOfCharsToRemove ? Input.Substring(0, Input.Length - NumberOfCharsToRemove) : "");
30  }
31 
32 
40  public static string RemoveSpecifiedEnd(this string Input, string StringEndToRemove, StringComparison ComparisonType = StringComparison.CurrentCulture)
41  {
42  return Input.EndsWith(StringEndToRemove, ComparisonType) ? Input.RemoveLastChars(StringEndToRemove.Length) : Input;
43  }
44 
45 
46 
52  public static string RemoveRemoveConsecutiveWhiteSpaces(this string Input)
53  {
54  return Regex.Replace(Input, @"\s+", " ");
55  }
56 
62  public static string RemoveWhitespaces(this string input)
63  {
64  return new string(input.ToCharArray()
65  .Where(c => !Char.IsWhiteSpace(c))
66  .ToArray());
67  }
68 
73  public static int HexToInt(this string s)
74  {
75  return int.Parse(s, System.Globalization.NumberStyles.HexNumber);
76  }
81  public static int HexToByte(this string s)
82  {
83  return byte.Parse(s, System.Globalization.NumberStyles.HexNumber);
84  }
89  public static bool IsHexString(this string s)
90  {
91  return s.IsHexString(0, s.Length);
92  }
93 
101  public static bool IsHexString(this string s, int startindex)
102  {
103  return s.IsHexString(startindex, s.Length - startindex);
104  }
105 
114  public static bool IsHexString(this string s, int startindex, int length)
115  {
116  if (string.IsNullOrWhiteSpace(s)) return false;
117 
118  if (startindex + length > s.Length) return false;
119 
120  return System.Text.RegularExpressions.Regex.IsMatch(s.Substring(startindex, length), @"\A\b[0-9a-fA-F]+\b\Z");
121  }
122 
123 
124 
125 
130  public static byte[] ToByteArray(this string s)
131  {
132  System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
133  return encoding.GetBytes(s);
134  }
135 
140  public static StringBuilder ToStringBuilder(this string s)
141  {
142  if (string.IsNullOrEmpty(s))
143  {
144  return new StringBuilder("");
145  }
146  return new StringBuilder(s);
147  }
148 
154  public static string Left(this string s, int length)
155  {
156  return s.Substring(0, length);
157  }
158 
164  public static string Right(this string s, int length)
165  {
166  return s.Substring(s.Length - length, length);
167  }
168 
176  public static string Mid(this string s, int startIndex, int length)
177  {
178  return s.Substring(startIndex, length);
179  }
180 
185  public static int ToInteger(this string s)
186  {
187  int integerValue = 0;
188  int.TryParse(s, out integerValue);
189  return integerValue;
190  }
191 
196  public static uint ToUInt(this string s)
197  {
198  uint uintegerValue = 0;
199  uint.TryParse(s, out uintegerValue);
200  return uintegerValue;
201  }
202 
207  public static bool IsInteger(this string s)
208  {
209  int dummy;
210  if (s.IsNullOrWhiteSpace()) return false;
211  return int.TryParse(s, out dummy);
212  }
213 
218  public static bool IsUInt(this string s)
219  {
220  uint dummy;
221  if (s.IsNullOrWhiteSpace()) return false;
222  return uint.TryParse(s, out dummy);
223  }
224 
229  public static bool IsNullOrEmpty(this string s)
230  {
231  return string.IsNullOrEmpty(s);
232  }
233 
238  public static bool IsNullOrWhiteSpace(this string s)
239  {
240  return string.IsNullOrWhiteSpace(s);
241  }
242 
243 
244 
250  public static string Build(this string s, object arg0)
251  {
252  if (s == null) { return ""; }
253  return string.Format(s, arg0);
254  }
255 
262  public static string Build(this string s, object arg0, object arg1)
263  {
264  if (s == null) { return ""; }
265  return string.Format(s, arg0, arg1);
266  }
267 
275  public static string Build(this string s, object arg0, object arg1, object arg2)
276  {
277  if (s == null) { return ""; }
278  return string.Format(s, arg0, arg1, arg2);
279  }
280 
286  //public static string Build(this string s, object[] args)
287  //{
288  // if (s == null) { return ""; }
289  // return string.Format(s, args);
290  //}
291 
297  public static string Build(this string s, params object[] args)
298  {
299  if (s == null) { return ""; }
300  return string.Format(s, args);
301  }
302 
311  public static string Construct(this string s, Dictionary<string, object> ConstructionValueDictionary, bool ReplaceNullValuesWithEmptyString = true, bool IgnoreMissingConstructionValues = false)
312  {
313  if (s.IsNullOrWhiteSpace()) return s;
314 
315  List<string> L = s.GetConstructionItemsList().Select(S => S.Substring(1, S.Length - 2)).ToList();
316  foreach (string N in L)
317  {
318  string V = "";
319  if (ConstructionValueDictionary.ContainsKey(N))
320  {
321  object O = ConstructionValueDictionary[N];
322  if (O == null && ReplaceNullValuesWithEmptyString)
323  {
324  V = "";
325  }
326  else
327  {
328  V = O.ToString();
329  }
330  s = s.Replace("{{{0}}}".Build(N), V);
331  }
332  else if (!IgnoreMissingConstructionValues)
333  {
334  throw new ArgumentException("The ConstructionValueDictionary does not contain a value for '{0}'".Build(N), "ConstructionValueDictionary");
335  }
336  }
337  return s;
338  }
339 
345  public static List<string> GetConstructionItemsList(this string s)
346  {
347  List<string> L = new List<string>();
348  if (!s.IsNullOrWhiteSpace())
349  {
350  Regex regex = new Regex("{.*?}");
351  MatchCollection matches = regex.Matches(s);
352  foreach (object match in matches)
353  {
354  string N = match.ToString();
355 
356  if (!L.Contains(N))
357  {
358  L.Add(N);
359  }
360 
361  }
362  }
363  return L;
364 
365  }
366 
373  public static Dictionary<string, object> GetConstructionItemsDictionary(this string s)
374  {
375  Dictionary<string, object> D = new Dictionary<string, object>();
376  List<string> L = s.GetConstructionItemsList();
377  L.ForEach(N => D.Add(N, null));
378  L = null;
379  return D;
380 
381  }
382 
383 
384 
390  public static bool IsEmail(this string s)
391  {
392  Regex MailCheck = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
393  return MailCheck.IsMatch(s);
394  }
395 
401  public static void WriteToFile(this string s, string FileName)
402  {
403  s.WriteToFile(FileName, false);
404  }
405 
411  public static void WriteToFile(this string s, string FileName, bool Append)
412  {
413  TextWriter tw = null;
414  try
415  {
416  tw = new StreamWriter(FileName, Append);
417  tw.Write(s);
418  }
419  catch (Exception e)
420  {
421 
422  if (tw != null)
423  {
424  tw.Close();
425  }
426  throw e;
427  }
428 
429  tw.Close();
430 
431  tw.Dispose();
432 
433 
434  }
435 
440  public static void WriteToFile(this string s, FileInfo File)
441  {
442  s.WriteToFile(File.FullName, false);
443  }
444 
451  public static void WriteToFile(this string s, FileInfo File, bool Append)
452  {
453  s.WriteToFile(File.FullName, Append);
454  }
455 
456 
465  static public string Replace(this string originalString, string oldValue, string newValue, StringComparison comparisonType)
466  {
467  StringBuilder sb = new StringBuilder();
468 
469  int previousIndex = 0;
470  int index = originalString.IndexOf(oldValue, comparisonType);
471  while (index != -1)
472  {
473  sb.Append(originalString.Substring(previousIndex, index - previousIndex));
474  sb.Append(newValue);
475  index += oldValue.Length;
476 
477  previousIndex = index;
478  index = originalString.IndexOf(oldValue, index, comparisonType);
479  }
480  sb.Append(originalString.Substring(previousIndex));
481 
482  return sb.ToString();
483 
484  }
485 
486 
493  public static bool IsAlphaNumeric(this string str)
494  {
495  if (string.IsNullOrEmpty(str))
496  return false;
497 
498  return !str.Any(C => !char.IsLetterOrDigit(C));
499 
500  }
501 
507  public static string RemoveDiacritics(this string text)
508  {
509  string normalizedString = text.Normalize(NormalizationForm.FormD);
510  StringBuilder stringBuilder = new StringBuilder();
511 
512  foreach (var c in normalizedString)
513  {
514  UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
515  if (unicodeCategory != UnicodeCategory.NonSpacingMark)
516  {
517  stringBuilder.Append(c);
518  }
519  }
520 
521  return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
522  }
523 
530  public static string AlternativeWhenNullOrWhiteSpace(this string text, string Alternative)
531  {
532  if (text.IsNullOrWhiteSpace()) return Alternative;
533  return text;
534  }
535 
536 
543  public static T XMLDeserialize<T>(this string Xml)
544  {
545  byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
546  using (MemoryStream ms = new MemoryStream(xmlBytes))
547  {
548  try
549  {
550  return (T)new XmlSerializer(typeof(T)).Deserialize(ms);
551  }
552  catch (Exception E)
553  {
554 
555  Exception Ex = new Exception("Could not deserialize {0} from XML data.".Build(typeof(T).Name), E);
556  Ex.Data.Add("XML Data", Xml);
557  throw Ex;
558  }
559  }
560 
561 
562 
563  }
564 
565 
572  public static object XMLDeserialize(this string Xml, Type Type)
573  {
574  byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
575  using (MemoryStream ms = new MemoryStream(xmlBytes))
576  {
577  try
578  {
579  return new XmlSerializer(Type).Deserialize(ms);
580  }
581  catch (Exception E)
582  {
583 
584  Exception Ex = new Exception("Could not deserialize {0} from XML data.".Build(Type.Name), E);
585  Ex.Data.Add("XML Data", Xml);
586  throw Ex;
587  }
588  }
589 
590 
591 
592  }
593 
600  public static T XMLDeserializeInterface<T>(this string Xml)
601  {
602  byte[] xmlBytes = Encoding.Default.GetBytes(Xml);
603  using (MemoryStream ms = new MemoryStream(xmlBytes))
604  {
605  using (XmlReader r = XmlReader.Create(ms))
606  {
607  List<Type> Types = new List<Type>(AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes()).Where(p => typeof(T).IsAssignableFrom(p) && !p.IsAbstract));
608 
609  if (Types.Any(Ty => Ty.FullName == r.LocalName))
610  {
611  throw new Exception("The type {0} specified in the xml cant be assigned to {1}".Build(r.LocalName, typeof(T).FullName));
612  }
613  Type TargetType = Types.First(Ty => Ty.FullName == r.LocalName);
614  try
615  {
616  return (T)new XmlSerializer(TargetType).Deserialize(r);
617  }
618  catch (Exception E)
619  {
620 
621  Exception Ex = new Exception("Could not deserialize {0} from XML data.".Build(typeof(T).Name), E);
622  Ex.Data.Add("XML Data", Xml);
623  throw Ex;
624  }
625  }
626  }
627 
628 
629  }
630 
631 
632 
633 
634 
642  public static bool IsValidPath(this string PathToCheck)
643  {
644  try
645  {
646  Path.GetFullPath(PathToCheck);
647  }
648  catch
649  {
650  return false;
651  }
652  return true;
653  }
654 
662  public static bool IsRelativePath(this string PathToCheck)
663  {
664  if (IsValidPath(PathToCheck))
665  {
666  if (!Path.IsPathRooted(PathToCheck))
667  {
668  return true;
669  }
670  }
671  return false;
672  }
673 
674 
681  public static DateTime ToDateTime(this string DateString, string DateFormat)
682  {
683  return DateTime.ParseExact(DateString, DateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
684  }
685 
686 
693  public static DateTime ToDateTime(this string DateString, string[] DateFormats)
694  {
695  return DateTime.ParseExact(DateString, DateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
696  }
697 
706  public static bool IsDateTime(this string DateString, string[] DateFormats)
707  {
708  if (DateString == null) return false;
709  DateTime Dummy;
710  return (DateTime.TryParseExact(DateString, DateFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out Dummy));
711  }
712 
721  public static bool IsDateTime(this string DateString, string DateFormat)
722  {
723  if (DateString == null) return false;
724  DateTime Dummy;
725  return (DateTime.TryParseExact(DateString, DateFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out Dummy));
726  }
727 
728 
735  public static string IndentString(this string StringToIndent, string IndentionString)
736  {
737  if (StringToIndent == null) { return null; }
738  string[] Parts = StringToIndent.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
739  return IndentionString + string.Join(Environment.NewLine + IndentionString, Parts);
740  }
741 
746  static public byte[] GetBytes(this string str)
747  {
748  byte[] bytes = new byte[str.Length * sizeof(char)];
749  System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
750  return bytes;
751  }
752 }
753 
754 
755 
756 
757 
758 
Animation steps from left to right through the source image