Professional Applications Programmers/Consultants برمجة واستشارات تطبيقات الإنترنت
Skip Navigation LinksHome » Code Library » Default

Public general use code classes and xml files that we've compiled and used over the years:

General use static class of common functions used by most applications.

   1:  using System;
   2:  using System.Data;
   3:  using System.Globalization;
   4:  using System.Text;
   5:  using System.Collections;
   6:  using System.Collections.Generic;
   7:  using System.Text.RegularExpressions;
   8:  using System.Xml;
   9:  using System.Xml.Linq;
  10:  using System.Configuration;
  11:  using System.Net;
  12:  using System.Linq;
  13:  using System.ComponentModel;
  14:  using System.Reflection;
  15:  using System.IO;
  16:   
  17:  #if WINDOWS_FORM
  18:  #else
  19:  using System.Web;
  20:  using System.Web.UI;
  21:  using System.Web.UI.WebControls;
  22:  using System.Web.Caching;
  23:  #endif
  24:   
  25:  namespace Ia.Cl.Model
  26:  {
  27:      ////////////////////////////////////////////////////////////////////////////
  28:   
  29:      /// <summary publish="true">
  30:      /// General use static class of common functions used by most applications.
  31:      /// 
  32:      /// </summary>
  33:      /// <remarks> 
  34:      /// Copyright © 2001-2015 Jasem Y. Al-Shamlan (info@ia.com.kw), Internet Applications - Kuwait. All Rights Reserved.
  35:      ///
  36:      /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
  37:      /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  38:      ///
  39:      /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  40:      /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  41:      /// 
  42:      /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
  43:      /// 
  44:      /// Copyright notice: This notice may not be removed or altered from any source distribution.
  45:      /// </remarks> 
  46:      public static class Default
  47:      {
  48:          static Random random = new Random();
  49:          // very important that you declare random here then use random.Next() elsewhere, otherwise you will have duplicate results
  50:   
  51:          ////////////////////////////////////////////////////////////////////////////
  52:   
  53:          /// <summary>
  54:          /// Splits CSV file lines
  55:          /// </summary>
  56:          public static IEnumerable<string> CsvLineSplitter(string line)
  57:          {
  58:              int fieldStart = 0;
  59:   
  60:              for (int i = 0; i < line.Length; i++)
  61:              {
  62:                  if (line[i] == ',')
  63:                  {
  64:                      yield return line.Substring(fieldStart, i - fieldStart);
  65:   
  66:                      fieldStart = i + 1;
  67:                  }
  68:   
  69:                  if (line[i] == '"') for (i++; line[i] != '"'; i++) { }
  70:              }
  71:          }
  72:   
  73:          ////////////////////////////////////////////////////////////////////////////
  74:   
  75:          /// <summary>
  76:          ///
  77:          /// </summary>
  78:          public static string Substring(string str, int len)
  79:          {
  80:              if (str.Length >= len - 3) str = str.Substring(0, len - 3) + "... ";
  81:              else if (str.Length > 0) str = str.Substring(0, str.Length);
  82:              else str = "";
  83:   
  84:              return str;
  85:          }
  86:   
  87:          ////////////////////////////////////////////////////////////////////////////
  88:   
  89:          /// <summary>
  90:          ///
  91:          /// </summary>
  92:          public static string Url(string text, string url)
  93:          {
  94:              return "<a href=" + url + ">" + text + "</a>";
  95:          }
  96:   
  97:          ////////////////////////////////////////////////////////////////////////////
  98:   
  99:          /// <summary>
 100:          ///
 101:          /// </summary>
 102:          public static string YesNo(bool checkValue)
 103:          {
 104:              string text;
 105:   
 106:              if (checkValue) text = "<span class=\"yes\">Yes</span>";
 107:              else text = "<span class=\"no\">No</span>";
 108:   
 109:              return text;
 110:          }
 111:   
 112:          ////////////////////////////////////////////////////////////////////////////
 113:   
 114:          /// <summary>
 115:          ///
 116:          /// </summary>
 117:          public static string YesNoText(bool checkValue)
 118:          {
 119:              string text;
 120:   
 121:              if (checkValue) text = "Yes";
 122:              else text = "No";
 123:   
 124:              return text;
 125:          }
 126:   
 127:          ////////////////////////////////////////////////////////////////////////////
 128:   
 129:          /// <summary>
 130:          ///
 131:          /// </summary>
 132:          public static string YesNoInArabic(bool checkValue)
 133:          {
 134:              string text;
 135:   
 136:              if (checkValue) text = "<span class=\"yes\">نعم</span>";
 137:              else text = "<span class=\"no\">لا</span>";
 138:   
 139:              return text;
 140:          }
 141:   
 142:          ////////////////////////////////////////////////////////////////////////////
 143:   
 144:          /// <summary>
 145:          ///
 146:          /// </summary>
 147:          public static string ActiveIdle(object o)
 148:          {
 149:              bool b;
 150:              string s;
 151:   
 152:              if (o != null && o.ToString().Length > 0)
 153:              {
 154:                  b = (bool)o;
 155:   
 156:                  if (b) s = "<span style=\"color:Green\">Active</span>";
 157:                  else s = "<span style=\"color:DarkGoldenRod\">Idle</span>";
 158:              }
 159:              else s = "";
 160:   
 161:              return s;
 162:          }
 163:   
 164:          ////////////////////////////////////////////////////////////////////////////
 165:   
 166:          /// <summary>
 167:          ///
 168:          /// </summary>
 169:          public static string ActiveIdleInArabic(object o)
 170:          {
 171:              bool b;
 172:              string s;
 173:   
 174:              if (o != null && o.ToString().Length > 0)
 175:              {
 176:                  b = (bool)o;
 177:   
 178:                  if (b) s = "<span style=\"color:Green\">فعال</span>";
 179:                  else s = "<span style=\"color:DarkGoldenRod\">مطفأ</span>";
 180:              }
 181:              else s = "";
 182:   
 183:              return s;
 184:          }
 185:   
 186:          ////////////////////////////////////////////////////////////////////////////
 187:          ////////////////////////////////////////////////////////////////////////////
 188:   
 189:          /// <summary>
 190:          /// Return a random number n where maxValue > n >= 0
 191:          /// <param name="maxValue">integer</param>
 192:          /// <returns>int where maxValue > n >= 0</returns>
 193:          /// </summary>
 194:          public static int Random(int maxValue)
 195:          {
 196:              int num;
 197:   
 198:              num = random.Next(maxValue);
 199:   
 200:              return num;
 201:          }
 202:   
 203:          ////////////////////////////////////////////////////////////////////////////
 204:   
 205:          /// <summary>
 206:          /// Return a random number n, with seed, where ra > num >= 0
 207:          /// <param name="seed">integer</param>
 208:          /// <param name="ra">integer</param>
 209:          /// <returns>int where ra > num >=0</returns>
 210:          /// </summary>
 211:          public static int RandomWithSeed(int seed, int ra)
 212:          {
 213:              // return a random number num: ra > num >= 0
 214:              int num;
 215:   
 216:              num = random.Next(ra);
 217:   
 218:              return num;
 219:          }
 220:   
 221:          ////////////////////////////////////////////////////////////////////////////
 222:   
 223:          /// <summary>
 224:          /// Return a random number n where r1 > num >= r0
 225:          /// <param name="r1">integer max</param>
 226:          /// <param name="r0">integer min</param>
 227:          /// <returns>int where r1 >= num >= r0</returns>
 228:          /// </summary>
 229:          public static int Random(int r0, int r1)
 230:          {
 231:              // return a random number num: r1 >= num >= r0
 232:              int num;
 233:   
 234:              num = random.Next(r1) + r0;
 235:   
 236:              return num;
 237:          }
 238:   
 239:          ////////////////////////////////////////////////////////////////////////////
 240:   
 241:          /// <summary>
 242:          /// Return a pseudo-random item from list
 243:          /// </summary>
 244:          public static string Random(string s)
 245:          {
 246:              // take a list of comma seperated values in s and return one pseudo-random value
 247:              int n;
 248:              string[] sp;
 249:   
 250:              sp = s.Split(',');
 251:   
 252:              n = Random(sp.Length);
 253:   
 254:              return sp[n].ToString();
 255:          }
 256:   
 257:          ////////////////////////////////////////////////////////////////////////////
 258:   
 259:          /// <summary>
 260:          ///
 261:          /// </summary>
 262:          public static bool RandomBool
 263:          {
 264:              get
 265:              {
 266:                  bool b;
 267:                  int n;
 268:   
 269:                  n = random.Next(2);
 270:   
 271:                  if (n == 1) b = true;
 272:                  else b = false;
 273:   
 274:                  return b;
 275:              }
 276:          }
 277:   
 278:          ////////////////////////////////////////////////////////////////////////////
 279:   
 280:          /// <summary>
 281:          /// Return a random weighted bool value between 0 and 100
 282:          /// </summary>
 283:          public static bool RandomPercentWeightedBool(int weight)
 284:          {
 285:              bool b;
 286:   
 287:              weight = weight > 100 ? 100 : weight;
 288:              weight = weight < 0 ? 0 : weight;
 289:   
 290:              b = (random.Next(0, 100) < weight);
 291:   
 292:              return b;
 293:          }
 294:   
 295:          ////////////////////////////////////////////////////////////////////////////
 296:   
 297:          /// <summary>
 298:          /// Return a random percent value between 0 and 100
 299:          /// </summary>
 300:          public static int RandomPercent()
 301:          {
 302:              return random.Next(0, 100);
 303:          }
 304:   
 305:          ////////////////////////////////////////////////////////////////////////////
 306:   
 307:          /// <summary>
 308:          ///
 309:          /// </summary>
 310:          public static string RandomAlphanumeric(int length)
 311:          {
 312:              const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 313:   
 314:              return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
 315:          }
 316:   
 317:          ////////////////////////////////////////////////////////////////////////////
 318:   
 319:          /// <summary>
 320:          ///
 321:          /// </summary>
 322:          public static string RandomNumber(int length)
 323:          {
 324:              const string chars = "0123456789";
 325:   
 326:              return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
 327:          }
 328:   
 329:          ////////////////////////////////////////////////////////////////////////////
 330:          ////////////////////////////////////////////////////////////////////////////
 331:   
 332:          /// <summary>
 333:          ///
 334:          /// </summary>
 335:          public static List<int> RandomList(int start, int end, int count)
 336:          {
 337:              int n;
 338:              List<int> list;
 339:              HashSet<int> hashset;
 340:   
 341:              hashset = new HashSet<int>();
 342:              list = new List<int>();
 343:   
 344:              while (list.Count < count)
 345:              {
 346:                  n = random.Next(start, end);
 347:   
 348:                  if (!hashset.Contains(n))
 349:                  {
 350:                      hashset.Add(n);
 351:                      list.Add(n);
 352:                  }
 353:              }
 354:   
 355:              list.Sort();
 356:   
 357:              return list;
 358:          }
 359:   
 360:          ////////////////////////////////////////////////////////////////////////////
 361:   
 362:          /// <summary>
 363:          /// Return at tick + count long
 364:          /// </summary>
 365:          public static long TickAndCountId(int count)
 366:          {
 367:              return DateTime.UtcNow.AddHours(3).Ticks + count;
 368:          }
 369:   
 370:          ////////////////////////////////////////////////////////////////////////////
 371:   
 372:          /// <summary>
 373:          /// Return at second + count long
 374:          /// </summary>
 375:          public static long TickSecondAndCountId(int count)
 376:          {
 377:              return DateTimeSecond() + count;
 378:          }
 379:   
 380:          ////////////////////////////////////////////////////////////////////////////
 381:   
 382:          /// <summary>
 383:          ///
 384:          /// </summary>
 385:          public static string TickDateTime(string tick)
 386:          {
 387:              // reads a tick count and returns the date time as string
 388:              string line;
 389:   
 390:              try
 391:              {
 392:                  DateTime t = new DateTime(long.Parse(tick));
 393:                  line = t.ToString("dd/MM/yyyy HH:mm");
 394:              }
 395:              catch (Exception)
 396:              {
 397:                  line = "";
 398:              }
 399:   
 400:              return line;
 401:          }
 402:   
 403:          ////////////////////////////////////////////////////////////////////////////
 404:   
 405:          /// <summary>
 406:          ///
 407:          /// </summary>
 408:          public static long DateTimeSecond(DateTime dt)
 409:          {
 410:              // return the number of seconds (total) in datetime
 411:              long l;
 412:   
 413:              // A single tick represents one hundred nanoseconds or one ten-millionth of a second
 414:   
 415:              l = dt.Ticks / 10000000;
 416:   
 417:              return l;
 418:          }
 419:   
 420:          ////////////////////////////////////////////////////////////////////////////
 421:   
 422:          /// <summary>
 423:          /// Return the number of seconds (total) in datetime. A single tick represents one hundred nanoseconds or one ten-millionth of a second.
 424:          /// </summary>
 425:          public static int DateTimeSecond()
 426:          {
 427:              return (int)(DateTime.UtcNow.AddHours(3).Ticks / 10000000);
 428:          }
 429:   
 430:  #if WINDOWS_FORM
 431:  #else
 432:          ////////////////////////////////////////////////////////////////////////////
 433:   
 434:          /// <summary>
 435:          ///
 436:          /// </summary>
 437:          public static void InitializeDropDownList(DropDownList ddl, DataTable source_dt, string text_field, string value_field, int selected_index)
 438:          {
 439:              int index;
 440:   
 441:              if (selected_index == -1) index = ddl.SelectedIndex;
 442:              else index = selected_index;
 443:   
 444:              ddl.Items.Clear();
 445:              //ddl.Items.Add(new ListItem("XXX","0"));
 446:              ddl.DataSource = source_dt;
 447:              ddl.DataTextField = text_field;
 448:              ddl.DataValueField = value_field;
 449:              ddl.DataBind();
 450:              ddl.SelectedIndex = index;
 451:          }
 452:  #endif
 453:          ////////////////////////////////////////////////////////////////////////////
 454:   
 455:          /// <summary>
 456:          ///
 457:          /// </summary>
 458:          public static bool IsFloat(string line)
 459:          {
 460:              // this check if line is floating point number. 
 461:              bool ni = false;
 462:   
 463:              try { float x = float.Parse(line); ni = true; }
 464:              catch (Exception) { ni = false; }
 465:   
 466:              return ni;
 467:          }
 468:   
 469:          ////////////////////////////////////////////////////////////////////////////
 470:   
 471:          /// <summary>
 472:          ///
 473:          /// </summary>
 474:          public static bool IsDecimal(string line)
 475:          {
 476:              // this check if line is a decimal number. 
 477:              bool ni = false;
 478:   
 479:              try { decimal x = decimal.Parse(line); ni = true; }
 480:              catch (Exception) { ni = false; }
 481:   
 482:              return ni;
 483:          }
 484:   
 485:          ////////////////////////////////////////////////////////////////////////////
 486:   
 487:          /// <summary>
 488:          ///
 489:          /// </summary>
 490:          public static bool IsInt(string line)
 491:          {
 492:              // this check if line is an integer
 493:              bool ni = false;
 494:   
 495:              try { int x = int.Parse(line); ni = true; }
 496:              catch (Exception) { ni = false; }
 497:   
 498:              return ni;
 499:          }
 500:   
 501:          ////////////////////////////////////////////////////////////////////////////
 502:   
 503:          /// <summary>
 504:          ///
 505:          /// </summary>
 506:          public static string ByteToHex(byte[] bytes)
 507:          {
 508:              StringBuilder sb = new StringBuilder(2500);
 509:   
 510:              UTF8Encoding utf8 = new UTF8Encoding();
 511:              foreach (byte b in bytes) sb.Append(b.ToString("x2"));
 512:   
 513:              return sb.ToString();
 514:          }
 515:   
 516:          ////////////////////////////////////////////////////////////////////////////
 517:   
 518:          /// <summary>
 519:          ///
 520:          /// </summary>
 521:          public static byte[] HexToByte(string hex_str)
 522:          {
 523:              int i, n;
 524:              byte[] bytes;
 525:              char[] chars;
 526:              string c_str = "";
 527:              UTF8Encoding utf8 = new UTF8Encoding();
 528:   
 529:              chars = hex_str.ToCharArray();
 530:   
 531:              bytes = new byte[chars.Length / 2];  // since hex_str has two chars for every byte
 532:   
 533:              n = 0;
 534:              for (i = 0; i < chars.Length; i += 2)
 535:              {
 536:                  c_str = chars[i].ToString() + chars[i + 1].ToString();
 537:                  bytes[n++] = (byte)Convert.ToInt32(c_str, 16);
 538:              }
 539:   
 540:              return bytes;
 541:          }
 542:   
 543:          ////////////////////////////////////////////////////////////////////////////
 544:   
 545:          /// <summary>
 546:          ///
 547:          /// </summary>
 548:          public static string DecToHex(int dec)
 549:          {
 550:              uint uiDecimal = 0;
 551:              string hex;
 552:   
 553:              try
 554:              {
 555:                  // convert text string to unsigned integer
 556:                  uiDecimal = checked((uint)System.Convert.ToUInt32(dec));
 557:   
 558:                  hex = String.Format("{0:x2}", uiDecimal);
 559:              }
 560:              catch (System.OverflowException)
 561:              {
 562:                  // Show overflow message and return
 563:                  hex = "";
 564:              }
 565:   
 566:              return hex;
 567:          }
 568:   
 569:          ////////////////////////////////////////////////////////////////////////////
 570:   
 571:          /// <summary>
 572:          ///
 573:          /// </summary>
 574:          public static int HexToDec(string hex)
 575:          {
 576:              // To hold our converted unsigned integer32 value
 577:              uint dec;
 578:   
 579:              try
 580:              {
 581:                  // Convert hex string to unsigned integer
 582:                  dec = System.Convert.ToUInt32(hex, 16);
 583:              }
 584:              catch (System.OverflowException)
 585:              {
 586:                  // Show overflow message and return
 587:                  return 0;
 588:              }
 589:   
 590:              return (int)dec;
 591:          }
 592:   
 593:          ////////////////////////////////////////////////////////////////////////////
 594:   
 595:          /// <summary>
 596:          /// http://stackoverflow.com/questions/3702216/how-to-convert-integer-to-binary-string-in-c
 597:          /// </summary>
 598:          public static string IntegerToBinaryString(int x)
 599:          {
 600:              return Convert.ToString(x, 2);
 601:          }
 602:   
 603:          ////////////////////////////////////////////////////////////////////////////
 604:   
 605:          /// <summary>
 606:          /// pos 0 is least significant bit, pos 7 is most
 607:          /// http://stackoverflow.com/questions/2431732/checking-if-a-bit-is-set-or-not
 608:          /// </summary>
 609:          public static bool IsBitSet(byte b, int pos)
 610:          {
 611:              return (b & (1 << pos)) != 0;
 612:          }
 613:   
 614:          ////////////////////////////////////////////////////////////////////////////
 615:   
 616:          /// <summary>
 617:          ///
 618:          /// </summary>
 619:          public static DataTable GenerateEmptyDataTable(DataTable dt)
 620:          {
 621:              // this function is used to produce a single empty DataTable line to make the GridView look nicer.
 622:              // this will simply clone the in_dt and create a completly empty line
 623:              DataRow dr;
 624:   
 625:              if (dt.Rows.Count == 0)
 626:              {
 627:   
 628:                  try
 629:                  {
 630:                      dr = dt.NewRow();
 631:   
 632:                      foreach (DataColumn dc in dt.Columns)
 633:                      {
 634:                          dr[dc.ColumnName] = DBNull.Value;
 635:                      }
 636:   
 637:                      dt.Rows.Add(dr);
 638:                  }
 639:                  catch (Exception)
 640:                  {
 641:                      return null;
 642:                  }
 643:              }
 644:   
 645:              return dt;
 646:          }
 647:   
 648:  #if WINDOWS_FORM
 649:  #else
 650:          ////////////////////////////////////////////////////////////////////////////
 651:   
 652:          /// <summary>
 653:          /// 
 654:          /// </summary>
 655:          public static string GetPostBackControl(Page page)
 656:          {
 657:              // return the name of control that fired the postback
 658:              // this is strange, sometimes it fills the ID with real name of control and sometimes the TEXT
 659:   
 660:              string s = "";
 661:              Control c = null;
 662:   
 663:              string ctrlname = page.Request.Params.Get("__EVENTTARGET");
 664:              if (ctrlname != null && ctrlname != string.Empty)
 665:              {
 666:                  c = page.FindControl(ctrlname);
 667:              }
 668:              else
 669:              {
 670:                  foreach (string ctl in page.Request.Form)
 671:                  {
 672:                      Control ci = page.FindControl(ctl);
 673:                      if (ci is System.Web.UI.WebControls.Button)
 674:                      {
 675:                          c = ci;
 676:                          break;
 677:                      }
 678:                  }
 679:              }
 680:   
 681:              if (c != null)
 682:              {
 683:                  if (c.GetType().ToString() == "System.Web.UI.WebControls.Button")
 684:                  {
 685:                      s = ((System.Web.UI.WebControls.Button)c).ID;
 686:                  }
 687:                  else if (c.GetType().ToString() == "System.Web.UI.WebControls.DropDownList")
 688:                  {
 689:                      s = ((System.Web.UI.WebControls.DropDownList)c).ID;
 690:                  }
 691:                  else s = "";
 692:              }
 693:              else s = "";
 694:   
 695:              return s;
 696:          }
 697:   
 698:          ////////////////////////////////////////////////////////////////////////////
 699:  #endif
 700:          /// <summary>
 701:          ///
 702:          /// </summary>
 703:          public static string Color(int count, int index)
 704:          {
 705:              string s;
 706:   
 707:              // rainbow:
 708:              string[] color = { "#f00", "#f10", "#f20", "#f30", "#f40", "#f50", "#f60", "#f70", "#f80", "#f90", "#fa0", "#fb0", "#fc0", "#fd0", "#fe0", "#ff0", "#ef0", "#df0", "#cf0", "#bf0", "#af0", "#9f0", "#8f0", "#7f0", "#6f0", "#5f0", "#4f0", "#3f0", "#2f0", "#1f0", "#0f0", "#0f1", "#0f2", "#0f3", "#0f4", "#0f5", "#0f6", "#0f7", "#0f8", "#0f9", "#0fa", "#0fb", "#0fc", "#0fd", "#0fe", "#0ff", "#0ef", "#0df", "#0cf", "#0bf", "#0af", "#09f", "#08f", "#07f", "#06f", "#05f", "#04f", "#03f", "#02f", "#01f", "#00f", "#10f", "#20f", "#30f", "#40f", "#50f", "#60f", "#70f", "#80f", "#90f", "#a0f", "#b0f", "#c0f", "#d0f", "#e0f" };
 709:   
 710:              // random clear
 711:              //string[] color = {"Black","Blue","BlueViolet","Brown","CadetBlue","CornFlowerBlue","Crimson","DarkBlue","DarkCyan","DarkGoldenRod","DarkGreen","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkRed","DarkSlateBlue","DarkSlateGray","DarkViolet","Firebrick","ForestGreen","Green","IndianRed","Indigo","LightGray","LightSeaGreen","LightSkyBlue","LightSlateGray","Maroon","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumVioletRed","MidnightBlue","Navy","Olive","OliveDrab"," Orange","OrangeRed","Orchid","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","SlateBlue","SlateGray","Teal","Tomato","Transparent" };
 712:   
 713:              if (index > 0) index--;
 714:   
 715:              s = color[color.Length / count * index];
 716:   
 717:              return s;
 718:          }
 719:   
 720:          ////////////////////////////////////////////////////////////////////////////
 721:   
 722:          /// <summary>
 723:          ///
 724:          /// </summary>
 725:          public static string FormatHtml(string text)
 726:          {
 727:              text = Regex.Replace(text, @"[\n|\r]+", "</p><p>");
 728:              text = "<p>" + text + "</p>";
 729:   
 730:              return text;
 731:          }
 732:   
 733:          ////////////////////////////////////////////////////////////////////////////
 734:          ////////////////////////////////////////////////////////////////////////////
 735:   
 736:          /// <summary>
 737:          ///
 738:          /// </summary>
 739:          public static bool IsValidIp(string ip)
 740:          {
 741:              bool isValid;
 742:   
 743:              IPAddress address;
 744:   
 745:              isValid = IPAddress.TryParse(ip, out address);
 746:   
 747:              //if (Regex.IsMatch(ip, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) b = true;
 748:              //else b = false;
 749:   
 750:              return isValid;
 751:          }
 752:   
 753:          ////////////////////////////////////////////////////////////////////////////
 754:   
 755:          /// <summary>
 756:          ///
 757:          /// </summary>
 758:          public static bool IsPrivateIp(string ip)
 759:          {
 760:              bool isPrivate;
 761:              int[] ipParts;
 762:   
 763:              ipParts = ip.Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s)).ToArray();
 764:   
 765:              if (ipParts[0] == 10 || (ipParts[0] == 192 && ipParts[1] == 168) || (ipParts[0] == 172 && (ipParts[1] >= 16 && ipParts[1] <= 31)))
 766:              {
 767:                  // private IP range
 768:                  isPrivate = true;
 769:              }
 770:              else
 771:              {
 772:                  // IP address is probably public. This doesn't catch some VPN ranges like OpenVPN and Hamachi.
 773:                  isPrivate = false;
 774:              }
 775:   
 776:              return isPrivate;
 777:          }
 778:   
 779:          ////////////////////////////////////////////////////////////////////////////
 780:   
 781:          /// <summary>
 782:          ///
 783:          /// </summary>
 784:          public static uint IpToUint(string ip)
 785:          {
 786:              uint uintAddress;
 787:   
 788:              IPAddress address = IPAddress.Parse(ip);
 789:              byte[] bytes = address.GetAddressBytes();
 790:              Array.Reverse(bytes); // flip big-endian(network order) to little-endian
 791:              uintAddress = BitConverter.ToUInt32(bytes, 0);
 792:   
 793:              return uintAddress;
 794:   
 795:              /*
 796:              string delimStr = ".";
 797:              char[] delimiter = delimStr.ToCharArray();
 798:              string[] ip_addr = null;
 799:              long ip_num = 0;
 800:  
 801:              try
 802:              {
 803:                  ip_addr = ip.Split(delimiter, 4);
 804:                  ip_num = (long.Parse(ip_addr[0]) * 16777216) + (long.Parse(ip_addr[1]) * 65536) + (long.Parse(ip_addr[2]) * 256) + (long.Parse(ip_addr[3]));
 805:              }
 806:              catch (Exception)
 807:              {
 808:              }
 809:  
 810:              return ip_num;
 811:              */
 812:   
 813:              /*
 814:              long l;
 815:              string r;
 816:              Match m;
 817:  
 818:              m = Regex.Match(ip, @"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})");
 819:  
 820:              if (m.Success)
 821:              {
 822:                  r = m.Groups[1].Captures[0].Value.PadLeft(3, '0') + m.Groups[2].Captures[0].Value.PadLeft(3, '0') + m.Groups[3].Captures[0].Value.PadLeft(3, '0') + m.Groups[4].Captures[0].Value.PadLeft(3, '0');
 823:                  l = long.Parse(r);
 824:              }
 825:              else l = 0;
 826:  
 827:              return l;
 828:              */
 829:          }
 830:   
 831:          ////////////////////////////////////////////////////////////////////////////
 832:   
 833:          /// <summary>
 834:          ///
 835:          /// </summary>
 836:          public static string UintToIp(uint ui)
 837:          {
 838:              string ipAddress;
 839:   
 840:              byte[] bytes = BitConverter.GetBytes(ui);
 841:              Array.Reverse(bytes); // flip little-endian to big-endian(network order)
 842:              ipAddress = new IPAddress(bytes).ToString();
 843:   
 844:              return ipAddress;
 845:   
 846:              /*
 847:              string s, s1, s2, s3, s4;
 848:  
 849:              s = l.ToString();
 850:              s = s.PadLeft(12, '0');
 851:  
 852:              s1 = s.Substring(0, 3);
 853:              s2 = s.Substring(3, 3);
 854:              s3 = s.Substring(6, 3);
 855:              s4 = s.Substring(9, 3);
 856:  
 857:              s = s1 + "." + s2 + "." + s3 + "." + s4;
 858:  
 859:              s = Regex.Replace(s, @"\.0+", ".");
 860:              s = Regex.Replace(s, @"^0+", "");
 861:              if (s[s.Length - 1] == '.') s = s + "0";
 862:  
 863:              return s;
 864:              */
 865:          }
 866:   
 867:          ////////////////////////////////////////////////////////////////////////////
 868:   
 869:          /// <summary>
 870:          ///
 871:          /// </summary>
 872:          public static string IpToHex(string ip)
 873:          {
 874:              string h;
 875:              Match m;
 876:   
 877:              h = "";
 878:   
 879:              m = Regex.Match(ip, @"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})");
 880:   
 881:              if (m.Success)
 882:              {
 883:                  h = DecToHex(int.Parse(m.Groups[1].Captures[0].Value)) + DecToHex(int.Parse(m.Groups[2].Captures[0].Value)) + DecToHex(int.Parse(m.Groups[3].Captures[0].Value)) + DecToHex(int.Parse(m.Groups[4].Captures[0].Value));
 884:              }
 885:              else h = "";
 886:   
 887:              return h;
 888:          }
 889:   
 890:          ////////////////////////////////////////////////////////////////////////////
 891:   
 892:          /// <summary>
 893:          ///
 894:          /// </summary>
 895:          public static string HexToIp(string h)
 896:          {
 897:              string s, s1, s2, s3, s4;
 898:   
 899:              h = h.PadLeft(8, '0');
 900:   
 901:              s1 = h.Substring(0, 2);
 902:              s2 = h.Substring(2, 2);
 903:              s3 = h.Substring(4, 2);
 904:              s4 = h.Substring(6, 2);
 905:   
 906:              s = HexToDec(s1) + "." + HexToDec(s2) + "." + HexToDec(s3) + "." + HexToDec(s4);
 907:   
 908:              return s;
 909:          }
 910:   
 911:          ////////////////////////////////////////////////////////////////////////////
 912:   
 913:          /// <summary>
 914:          ///
 915:          /// </summary>
 916:          public static string DecToIp(int i)
 917:          {
 918:              return HexToIp(DecToHex(i));
 919:          }
 920:   
 921:          ////////////////////////////////////////////////////////////////////////////
 922:   
 923:          /// <summary>
 924:          ///
 925:          /// </summary>
 926:          public static int IpToDec(string s)
 927:          {
 928:              return HexToDec(IpToHex(s));
 929:          }
 930:   
 931:          ////////////////////////////////////////////////////////////////////////////
 932:   
 933:          /// <summary>
 934:          /// Check a string to see if all characters are hexadecimal values
 935:          /// <see cref="https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values"/>
 936:          /// </summary>
 937:          public static bool IsHex(string term)
 938:          {
 939:              // For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"
 940:              return System.Text.RegularExpressions.Regex.IsMatch(term, @"\A\b[0-9a-fA-F]+\b\Z");
 941:          }
 942:   
 943:          ////////////////////////////////////////////////////////////////////////////
 944:   
 945:          /// <summary>
 946:          ///
 947:          /// </summary>
 948:          public static string NetworkNumberFromIp(string ip)
 949:          {
 950:              string[] ipp;
 951:              string networkNumber;
 952:   
 953:              networkNumber = "";
 954:   
 955:              if (IsValidIp(ip))
 956:              {
 957:                  ipp = ip.Split('.');
 958:   
 959:                  networkNumber = (ipp[0] + "." + ipp[1] + "." + ipp[2] + ".0");
 960:              }
 961:   
 962:              return networkNumber;
 963:          }
 964:   
 965:          ////////////////////////////////////////////////////////////////////////////
 966:   
 967:          /// <summary>
 968:          ///
 969:          /// </summary>
 970:          public static List<string> NetworkNumberStrippedList(string startIp, string endIp)
 971:          {
 972:              int startIpI, endIpI;
 973:              string s;
 974:              List<long> li;
 975:              List<string> list;
 976:   
 977:              li = new List<long>();
 978:              list = new List<string>();
 979:   
 980:              // change network number to a real IP
 981:              if (Regex.IsMatch(startIp, @"^.+\.0$")) startIp = Regex.Replace(startIp, @"^(.+)\.0$", "$1.1");
 982:              if (Regex.IsMatch(endIp, @"^.+\.0$")) endIp = Regex.Replace(endIp, @"^(.+)\.0$", "$1.1");
 983:   
 984:              startIpI = IpToDec(startIp);
 985:              endIpI = IpToDec(endIp);
 986:   
 987:              for (int i = startIpI; i <= endIpI; i += 256)
 988:              {
 989:                  s = DecToIp(i);
 990:                  s = NetworkNumberFromIp(s);
 991:   
 992:                  s = Regex.Replace(s, @"^(.+)\.0$", "$1");
 993:   
 994:                  list.Add(s);
 995:              }
 996:   
 997:              return list;
 998:          }
 999:   
1000:          ////////////////////////////////////////////////////////////////////////////
1001:   
1002:          /// <summary>
1003:          /// Check if the passed IP address belongs to Kuwait
1004:          /// </summary>
1005:          public static bool IsKuwaitIp(string ip)
1006:          {
1007:              bool b;
1008:              uint ui;
1009:   
1010:              ui = global::Ia.Cl.Model.Default.IpToUint(ip);
1011:   
1012:              if (
1013:              (ui >= 1044742144 && ui <= 1044750335)
1014:              || (ui >= 1050017792 && ui <= 1050083327)
1015:              || (ui >= 1054277632 && ui <= 1054343167)
1016:              || (ui >= 1075513152 && ui <= 1075513183)
1017:              || (ui >= 1125110400 && ui <= 1125110463)
1018:              || (ui >= 1161630912 && ui <= 1161630919)
1019:              || (ui >= 1161641888 && ui <= 1161641911)
1020:              || (ui >= 1163558016 && ui <= 1163558028)
1021:              || (ui >= 1308094464 && ui <= 1308096511)
1022:              || (ui >= 1314455552 && ui <= 1314521087)
1023:              || (ui >= 1318764544 && ui <= 1318780927)
1024:              || (ui >= 1319084032 && ui <= 1319092223)
1025:              || (ui >= 1347219456 && ui <= 1347223551)
1026:              || (ui >= 1347294424 && ui <= 1347294431)
1027:              || (ui >= 1347321856 && ui <= 1347323775)
1028:              || (ui >= 1347323904 && ui <= 1347325183)
1029:              || (ui >= 1347325440 && ui <= 1347325951)
1030:              || (ui >= 1354235904 && ui <= 1354301439)
1031:              || (ui >= 1361035904 && ui <= 1361035907)
1032:              || (ui >= 1361036764 && ui <= 1361036767)
1033:              || (ui >= 1361036792 && ui <= 1361036795)
1034:              || (ui >= 1365220792 && ui <= 1365220799)
1035:              || (ui >= 1383273984 && ui <= 1383276543)
1036:              || (ui >= 1383367168 && ui <= 1383367679)
1037:              || (ui >= 1383368848 && ui <= 1383368895)
1038:              || (ui >= 1383369120 && ui <= 1383369231)
1039:              || (ui >= 1383369248 && ui <= 1383369535)
1040:              || (ui >= 1383369600 && ui <= 1383370751)
1041:              || (ui >= 1383371776 && ui <= 1383374591)
1042:              || (ui >= 1385283584 && ui <= 1385291775)
1043:              || (ui >= 1397006336 && ui <= 1397014527)
1044:              || (ui >= 1398800384 && ui <= 1398833151)
1045:              || (ui >= 1403658528 && ui <= 1403658559)
1046:              || (ui >= 1410013696 && ui <= 1410013727)
1047:              || (ui >= 1410013920 && ui <= 1410013951)
1048:              || (ui >= 1410014016 && ui <= 1410014047)
1049:              || (ui >= 1410014464 && ui <= 1410014495)
1050:              || (ui >= 1410027008 && ui <= 1410027263)
1051:              || (ui >= 1410035200 && ui <= 1410035231)
1052:              || (ui >= 1410035264 && ui <= 1410035295)
1053:              || (ui >= 1425426432 && ui <= 1425428479)
1054:              || (ui >= 1441726464 && ui <= 1441729023)
1055:              || (ui >= 1441729536 && ui <= 1441734655)
1056:              || (ui >= 1475115008 && ui <= 1475117055)
1057:              || (ui >= 1500186624 && ui <= 1500188671)
1058:              || (ui >= 1506476032 && ui <= 1506508799)
1059:              || (ui >= 1509642240 && ui <= 1509644351)
1060:              || (ui >= 1509644384 && ui <= 1509646335)
1061:              || (ui >= 1533419520 && ui <= 1533419775)
1062:              || (ui >= 1533420032 && ui <= 1533420287)
1063:              || (ui >= 1533420544 && ui <= 1533421567)
1064:              || (ui >= 1533448192 && ui <= 1533450239)
1065:              || (ui >= 1533470720 && ui <= 1533472767)
1066:              || (ui >= 1533513728 && ui <= 1533515775)
1067:              || (ui >= 1535934464 && ui <= 1535967231)
1068:              || (ui >= 1536660016 && ui <= 1536660019)
1069:              || (ui >= 1536663424 && ui <= 1536663551)
1070:              || (ui >= 1539227648 && ui <= 1539229695)
1071:              || (ui >= 1539466752 && ui <= 1539467263)
1072:              || (ui >= 1539473920 && ui <= 1539474431)
1073:              || (ui >= 1539737088 && ui <= 1539737343)
1074:              || (ui >= 1540410112 && ui <= 1540410367)
1075:              || (ui >= 1540467712 && ui <= 1540467967)
1076:              || (ui >= 1540622336 && ui <= 1540622591)
1077:              || (ui >= 1540628480 && ui <= 1540628735)
1078:              || (ui >= 1540790272 && ui <= 1540791295)
1079:              || (ui >= 1572814848 && ui <= 1572816895)
1080:              || (ui >= 1578991616 && ui <= 1579024383)
1081:              || (ui >= 1585446912 && ui <= 1585577983)
1082:              || (ui >= 1589346304 && ui <= 1589379071)
1083:              || (ui >= 1598160896 && ui <= 1598193663)
1084:              || (ui >= 1603137536 && ui <= 1603141631)
1085:              || (ui >= 1605320704 && ui <= 1605328895)
1086:              || (ui >= 1925638656 && ui <= 1925638911)
1087:              || (ui >= 1925639680 && ui <= 1925639935)
1088:              || (ui >= 2341273600 && ui <= 2341339135)
1089:              || (ui >= 2717646848 && ui <= 2717712383)
1090:              || (ui >= 2830827520 && ui <= 2830893055)
1091:              || (ui >= 3169255424 && ui <= 3169271807)
1092:              || (ui >= 3169275904 && ui <= 3169278991)
1093:              || (ui >= 3169279008 && ui <= 3169279231)
1094:              || (ui >= 3169279256 && ui <= 3169279263)
1095:              || (ui >= 3169279296 && ui <= 3169279303)
1096:              || (ui >= 3169279320 && ui <= 3169279743)
1097:              || (ui >= 3169279760 && ui <= 3169281023)
1098:              || (ui >= 3169281280 && ui <= 3169288191)
1099:              || (ui >= 3239285760 && ui <= 3239286783)
1100:              || (ui >= 3239488512 && ui <= 3239488767)
1101:              || (ui >= 3240222720 && ui <= 3240223231)
1102:              || (ui >= 3240812288 && ui <= 3240812543)
1103:              || (ui >= 3245088256 && ui <= 3245088511)
1104:              || (ui >= 3249111552 && ui <= 3249112063)
1105:              || (ui >= 3250335744 && ui <= 3250339839)
1106:              || (ui >= 3250359808 && ui <= 3250362879)
1107:              || (ui >= 3250364416 && ui <= 3250372607)
1108:              || (ui >= 3251120128 && ui <= 3251120639)
1109:              || (ui >= 3252483072 && ui <= 3252483583)
1110:              || (ui >= 3252484096 && ui <= 3252486143)
1111:              || (ui >= 3258368000 && ui <= 3258384383)
1112:              || (ui >= 3262477220 && ui <= 3262477223)
1113:              || (ui >= 3262478601 && ui <= 3262478601)
1114:              || (ui >= 3263045632 && ui <= 3263046847)
1115:              || (ui >= 3263046912 && ui <= 3263047935)
1116:              || (ui >= 3263048192 && ui <= 3263053823)
1117:              || (ui >= 3266341888 && ui <= 3266342143)
1118:              || (ui >= 3274145792 && ui <= 3274162175)
1119:              || (ui >= 3276114944 && ui <= 3276115967)
1120:              || (ui >= 3276687872 && ui <= 3276688383)
1121:              || (ui >= 3276858112 && ui <= 3276858367)
1122:              || (ui >= 3277381120 && ui <= 3277381631)
1123:              || (ui >= 3280580096 && ui <= 3280580351)
1124:              || (ui >= 3285922816 && ui <= 3285923327)
1125:              || (ui >= 3286425600 && ui <= 3286433791)
1126:              || (ui >= 3286566656 && ui <= 3286567423)
1127:              || (ui >= 3286568192 && ui <= 3286568703)
1128:              || (ui >= 3286571008 && ui <= 3286571775)
1129:              || (ui >= 3288417536 && ui <= 3288418047)
1130:              || (ui >= 3340584704 && ui <= 3340584959)
1131:              || (ui >= 3350042880 && ui <= 3350043135)
1132:              || (ui >= 3453376848 && ui <= 3453376887)
1133:              || (ui >= 3487969792 && ui <= 3487970047)
1134:              || (ui >= 3509522432 && ui <= 3509522687)
1135:              || (ui >= 3509559040 && ui <= 3509559295)
1136:              || (ui >= 3512891232 && ui <= 3512891263)
1137:              || (ui >= 3517438880 && ui <= 3517438911)
1138:              || (ui >= 3518894096 && ui <= 3518894103)
1139:              || (ui >= 3523593216 && ui <= 3523593231)
1140:              || (ui >= 3559587840 && ui <= 3559596031)
1141:              || (ui >= 3561742336 && ui <= 3561750527)
1142:              || (ui >= 3575824384 && ui <= 3575832575)
1143:              || (ui >= 3582255104 && ui <= 3582263295)
1144:              || (ui >= 3585949696 && ui <= 3585957887)
1145:              || (ui >= 3628153088 && ui <= 3628153343)
1146:              || (ui >= 3630097664 && ui <= 3630098175)
1147:              || (ui >= 3630100224 && ui <= 3630100479)
1148:              || (ui >= 3632481760 && ui <= 3632481767)
1149:              || (ui >= 3645222912 && ui <= 3645227007)
1150:              ) b = true;
1151:              else b = false;
1152:   
1153:              return b;
1154:          }
1155:   
1156:          ////////////////////////////////////////////////////////////////////////////
1157:   
1158:          /// <summary>
1159:          /// Check if the this.Request.UserHostAddress from the webpage is from the development machine or IP.
1160:          /// <param name="userHostAddress">The this.Request.UserHostAddress from the webpage</param>
1161:          /// </summary>
1162:          public static bool IaHostAddress(string userHostAddress)
1163:          {
1164:              bool b;
1165:              string hostAddress;
1166:   
1167:              hostAddress = ConfigurationManager.AppSettings["iaHostAddress"].ToString();
1168:   
1169:              if (userHostAddress == hostAddress || userHostAddress == "::1") b = true;
1170:              else b = false;
1171:   
1172:              return b;
1173:          }
1174:   
1175:          ////////////////////////////////////////////////////////////////////////////
1176:   
1177:          /// <summary>
1178:          /// Check if the this.Request.UserHostAddress from the webpage is from the development machine or IP.
1179:          /// <param name="userHostAddress">The this.Request.UserHostAddress from the webpage</param>
1180:          /// </summary>
1181:          public static bool NgnOfficeHostAddress(string userHostAddress)
1182:          {
1183:              bool b;
1184:              string hostAddress;
1185:   
1186:              hostAddress = ConfigurationManager.AppSettings["ngnOfficeHostAddress"].ToString();
1187:   
1188:              if (userHostAddress == hostAddress || userHostAddress == "::1") b = true;
1189:              else b = false;
1190:   
1191:              return b;
1192:          }
1193:   
1194:          ////////////////////////////////////////////////////////////////////////////
1195:          ////////////////////////////////////////////////////////////////////////////
1196:   
1197:          /// <summary>
1198:          ///
1199:          /// </summary>
1200:          public static Hashtable DataTableToHashtable(DataTable dt)
1201:          {
1202:              // put the datatable first row value into a hashtable key, and second as value. if the table has only one column we will add it only to keys with 0 value
1203:              Hashtable ht;
1204:   
1205:              if (dt != null)
1206:              {
1207:                  if (dt.Rows.Count > 0)
1208:                  {
1209:   
1210:                      ht = new Hashtable(dt.Rows.Count);
1211:   
1212:                      if (dt.Columns.Count == 1) foreach (DataRow r in dt.Rows) ht[r[0].ToString()] = "0";
1213:                      else if (dt.Columns.Count > 1) foreach (DataRow r in dt.Rows) ht[r[0].ToString()] = r[1].ToString();
1214:                  }
1215:                  else ht = new Hashtable(1);
1216:              }
1217:              else ht = null;
1218:   
1219:              return ht;
1220:          }
1221:   
1222:          ////////////////////////////////////////////////////////////////////////////
1223:   
1224:          /// <summary>
1225:          ///
1226:          /// </summary>
1227:          public static string DataTableToString(DataTable dataTable)
1228:          {
1229:              var output = new StringBuilder();
1230:   
1231:              // write Column titles
1232:              for (int i = 0; i < dataTable.Columns.Count; i++)
1233:              {
1234:                  var text = dataTable.Columns[i].ColumnName;
1235:                  output.Append("\t" + text);
1236:              }
1237:   
1238:              output.Append("|\n" + new string('=', output.Length) + "\n");
1239:   
1240:              // write rows
1241:              foreach (DataRow row in dataTable.Rows)
1242:              {
1243:                  for (int i = 0; i < dataTable.Columns.Count; i++)
1244:                  {
1245:                      var text = row[i].ToString();
1246:                      output.Append("\t" + text);
1247:                  }
1248:   
1249:                  output.Append("|\n");
1250:              }
1251:   
1252:              return output.ToString();
1253:          }
1254:   
1255:          /*
1256:          ////////////////////////////////////////////////////////////////////////////
1257:  
1258:          /// <summary>
1259:          ///
1260:          /// </summary>
1261:          public static ArrayList ArrayList_Limit_Randomize(ArrayList in_al, int max)
1262:          {
1263:              // 
1264:              // parameter: ArrayList with any number of entries, an integer value indicating the max possible number of returned values
1265:              // procedure: randomly select upto max values from al and return max >= num >= 0
1266:  
1267:              int n, o;
1268:              ArrayList al;
1269:              Hashtable ht;
1270:  
1271:              if (max > 0)
1272:              {
1273:                  al = new ArrayList(max);
1274:                  ht = new Hashtable(max);
1275:  
1276:                  o = 0;
1277:  
1278:                  while (o < in_al.Count - 1 && o < max)
1279:                  {
1280:                      foreach (string s in in_al)
1281:                      {
1282:                          n = r.Next(max);
1283:  
1284:                          if (!ht.ContainsKey(n))
1285:                          {
1286:                              al.Add(s);
1287:                              ht[n] = 1;
1288:                              o++;
1289:                          }
1290:                      }
1291:                  }
1292:  
1293:              }
1294:              else al = null;
1295:  
1296:              return al;
1297:          }
1298:          */
1299:   
1300:          ////////////////////////////////////////////////////////////////////////////
1301:   
1302:          /// <summary>
1303:          ///
1304:          /// </summary>
1305:          public static ArrayList SublistArrayList(ArrayList in_al, int n)
1306:          {
1307:              // return the first n values from all
1308:              ArrayList al;
1309:   
1310:              if (n > 0)
1311:              {
1312:                  al = new ArrayList(n);
1313:   
1314:                  for (int i = 0; i < in_al.Count - 1 && i < n; i++)
1315:                  {
1316:                      al.Add(in_al[i]);
1317:                  }
1318:              }
1319:              else al = null;
1320:   
1321:              return al;
1322:          }
1323:   
1324:          ////////////////////////////////////////////////////////////////////////////
1325:   
1326:          /// <summary>
1327:          ///
1328:          /// </summary>
1329:          public static ArrayList ShuffleAndSublistArrayList(ArrayList in_al, int n)
1330:          {
1331:              // 
1332:   
1333:              ShuffleArrayList(in_al);
1334:   
1335:              return SublistArrayList(in_al, n);
1336:          }
1337:   
1338:          ////////////////////////////////////////////////////////////////////////////
1339:   
1340:          /// <summary>
1341:          ///
1342:          /// </summary>
1343:          public static ArrayList KeyArrayHashtableToList(Hashtable ht)
1344:          {
1345:              // 
1346:              ArrayList al;
1347:   
1348:              if (ht != null)
1349:              {
1350:                  if (ht.Count > 0)
1351:                  {
1352:                      al = new ArrayList(ht.Count);
1353:   
1354:                      foreach (string s in ht.Keys) al.Add(s);
1355:                  }
1356:                  else al = new ArrayList(1);
1357:              }
1358:              else al = null;
1359:   
1360:              al.Sort();
1361:   
1362:              return al;
1363:          }
1364:   
1365:          ////////////////////////////////////////////////////////////////////////////
1366:   
1367:          /// <summary>
1368:          ///
1369:          /// </summary>
1370:          public static ArrayList KeyIntegerHashtableToArrayList(Hashtable ht)
1371:          {
1372:              // 
1373:              ArrayList al;
1374:   
1375:              if (ht != null)
1376:              {
1377:                  if (ht.Count > 0)
1378:                  {
1379:                      al = new ArrayList(ht.Count);
1380:   
1381:                      foreach (int i in ht.Keys) al.Add(i);
1382:                  }
1383:                  else al = new ArrayList(1);
1384:              }
1385:              else al = null;
1386:   
1387:              al.Sort();
1388:   
1389:              return al;
1390:          }
1391:   
1392:          ////////////////////////////////////////////////////////////////////////////
1393:   
1394:          /// <summary>
1395:          ///
1396:          /// </summary>
1397:          public static Hashtable ReverseKeyValueInHashtable(Hashtable in_ht)
1398:          {
1399:              // 
1400:              Hashtable ht;
1401:   
1402:              if (in_ht != null)
1403:              {
1404:                  if (in_ht.Count > 0)
1405:                  {
1406:                      ht = new Hashtable(in_ht.Count);
1407:   
1408:                      foreach (string s in in_ht.Keys) ht[in_ht[s].ToString()] = s;
1409:                  }
1410:                  else ht = new Hashtable(1);
1411:              }
1412:              else ht = null;
1413:   
1414:              return ht;
1415:          }
1416:   
1417:          ////////////////////////////////////////////////////////////////////////////
1418:   
1419:          /// <summary>
1420:          ///
1421:          /// </summary>
1422:          public static ArrayList HashtableValueToArrayList(Hashtable ht)
1423:          {
1424:              // 
1425:              ArrayList al;
1426:   
1427:              if (ht != null)
1428:              {
1429:                  if (ht.Count > 0)
1430:                  {
1431:                      al = new ArrayList(ht.Count);
1432:   
1433:                      foreach (string s in ht.Values) al.Add(s);
1434:                  }
1435:                  else al = new ArrayList(1);
1436:              }
1437:              else al = null;
1438:   
1439:              al.Sort();
1440:   
1441:              return al;
1442:          }
1443:   
1444:          ////////////////////////////////////////////////////////////////////////////
1445:   
1446:          /// <summary>
1447:          ///
1448:          /// </summary>
1449:          public static string HashtableKeyString(Hashtable ht)
1450:          {
1451:              // 
1452:              string si;
1453:              StringBuilder sb;
1454:   
1455:              if (ht != null)
1456:              {
1457:                  if (ht.Count > 0)
1458:                  {
1459:                      sb = new StringBuilder(ht.Count);
1460:                      sb.Length = 0;
1461:   
1462:                      foreach (string s in ht.Keys) sb.Append(s + "|");
1463:                  }
1464:                  else sb = new StringBuilder(1);
1465:              }
1466:              else sb = null;
1467:   
1468:              si = sb.ToString();
1469:              si = si.Remove(si.Length - 1, 1);
1470:   
1471:              return si;
1472:          }
1473:   
1474:          ////////////////////////////////////////////////////////////////////////////
1475:   
1476:          /// <summary>
1477:          ///
1478:          /// </summary>
1479:          public static Hashtable SortHashtableKey(Hashtable in_ht)
1480:          {
1481:              // sort the hashtable keys alphabetically
1482:   
1483:              ArrayList al;
1484:              Hashtable ht;
1485:   
1486:              if (in_ht != null)
1487:              {
1488:                  if (in_ht.Count > 0)
1489:                  {
1490:                      al = new ArrayList(in_ht.Count + 1);
1491:                      ht = new Hashtable(in_ht.Count + 1);
1492:   
1493:                      al.Clear();
1494:                      foreach (string s in in_ht.Keys) al.Add(s);
1495:                      al.Sort();
1496:                      foreach (string s in al) ht.Add(s, in_ht[s].ToString());
1497:                  }
1498:                  else ht = in_ht;
1499:              }
1500:              else ht = in_ht;
1501:   
1502:              return ht;
1503:          }
1504:   
1505:          ////////////////////////////////////////////////////////////////////////////
1506:   
1507:          /// <summary>
1508:          ///
1509:          /// </summary>
1510:          public static string HashtableValueString(Hashtable ht)
1511:          {
1512:              // 
1513:              string si;
1514:              StringBuilder sb;
1515:   
1516:              if (ht != null)
1517:              {
1518:                  if (ht.Count > 0)
1519:                  {
1520:                      sb = new StringBuilder(ht.Count);
1521:                      sb.Length = 0;
1522:   
1523:                      foreach (string s in ht.Keys) sb.Append(ht[s].ToString() + "|");
1524:                  }
1525:                  else sb = new StringBuilder(1);
1526:              }
1527:              else sb = null;
1528:   
1529:              si = sb.ToString();
1530:              si = si.Remove(si.Length - 1, 1);
1531:   
1532:              return si;
1533:          }
1534:   
1535:          ////////////////////////////////////////////////////////////////////////////
1536:   
1537:          /// <summary>
1538:          /// 
1539:          /// </summary>
1540:          public static string Match(string text, string regex)
1541:          {
1542:              string matchedText;
1543:              Match m;
1544:   
1545:              m = Regex.Match(text, regex);
1546:   
1547:              if (m.Groups[1].Success) matchedText = m.Groups[1].Captures[0].Value;
1548:              else matchedText = null;
1549:   
1550:              return matchedText;
1551:          }
1552:   
1553:          ////////////////////////////////////////////////////////////////////////////
1554:   
1555:          /// <summary>
1556:          /// 
1557:          /// </summary>
1558:          public static string MatchToLower(string s, string regex)
1559:          {
1560:              string t;
1561:              Match m;
1562:   
1563:              m = Regex.Match(s, regex);
1564:              if (m.Groups[1].Success) t = m.Groups[1].Captures[0].Value.ToLower();
1565:              else t = null;
1566:   
1567:              return t;
1568:          }
1569:   
1570:          ////////////////////////////////////////////////////////////////////////////
1571:   
1572:          /// <summary>
1573:          ///
1574:          /// </summary>
1575:          public static bool IsRegexPatternValid(string pattern)
1576:          {
1577:              bool b;
1578:   
1579:              try
1580:              {
1581:                  new Regex(pattern);
1582:   
1583:                  b = true;
1584:              }
1585:              catch
1586:              {
1587:                  b = false;
1588:              }
1589:   
1590:              return b;
1591:          }
1592:   
1593:  #if WINDOWS_FORM
1594:  #else
1595:          ////////////////////////////////////////////////////////////////////////////
1596:   
1597:          /// <summary>
1598:          /// Store the current time in a cache variable
1599:          /// </summary>
1600:          public static void SetTimeSpan()
1601:          {
1602:              HttpRuntime httpRT = new HttpRuntime();
1603:              Cache cache = HttpRuntime.Cache;
1604:   
1605:              cache["TimeSpan_Set"] = DateTime.UtcNow.AddHours(3).Ticks;
1606:          }
1607:   
1608:          ////////////////////////////////////////////////////////////////////////////
1609:   
1610:          /// <summary>
1611:          /// Check if sec seconds had passed since timespan_set
1612:          /// </summary>
1613:          public static bool CheckTimeSpan(int sec)
1614:          {
1615:              bool b;
1616:              long l;
1617:              HttpRuntime httpRT = new HttpRuntime();
1618:              Cache cache = HttpRuntime.Cache;
1619:   
1620:              if (cache["TimeSpan_Set"] == null) b = true;
1621:              else
1622:              {
1623:                  l = (long)cache["TimeSpan_Set"];
1624:   
1625:                  if (DateTime.UtcNow.AddHours(3).AddSeconds(-sec).Ticks > l) b = true;
1626:                  else b = false;
1627:              }
1628:   
1629:              return b;
1630:          }
1631:   
1632:          ////////////////////////////////////////////////////////////////////////////
1633:   
1634:          /// <summary>
1635:          /// Check if 1 sec seconds had passed since timespan_set
1636:          /// </summary>
1637:          public static bool CheckTimeSpan()
1638:          {
1639:              return CheckTimeSpan(1);
1640:          }
1641:   
1642:  #endif
1643:          ////////////////////////////////////////////////////////////////////////////
1644:   
1645:          /// <summary>
1646:          /// Return the absolute path
1647:          /// </summary>
1648:          public static string AbsolutePath()
1649:          {
1650:              return AbsolutePath(false);
1651:          }
1652:   
1653:          ////////////////////////////////////////////////////////////////////////////
1654:   
1655:          /// <summary>
1656:          /// Return the absolute path to temp folder
1657:          /// </summary>
1658:          public static string AbsoluteTempPath()
1659:          {
1660:              return AbsolutePath(true);
1661:          }
1662:   
1663:          ////////////////////////////////////////////////////////////////////////////
1664:   
1665:          /// <summary>
1666:          /// Return the absolute path
1667:          /// </summary>
1668:          public static string AbsolutePath(bool temp_folder)
1669:          {
1670:              string path;
1671:   
1672:  #if WINDOWS_FORM
1673:              if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) path = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory + @"\";
1674:              else path = AppDomain.CurrentDomain.BaseDirectory;
1675:  #else
1676:              if (temp_folder) path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"app_data\temp\";
1677:              else path = AppDomain.CurrentDomain.BaseDirectory.ToString();
1678:  #endif
1679:   
1680:              //if (path.IndexOf(@"\bin") >= 0) path = path.Remove(path.IndexOf(@"\bin"), path.Length - path.IndexOf(@"\bin"));
1681:   
1682:              return path;
1683:          }
1684:   
1685:          ////////////////////////////////////////////////////////////////////////////
1686:   
1687:          /// <summary>
1688:          /// Return the absolute path parent directory
1689:          /// </summary>
1690:          public static string AbsolutePathParent()
1691:          {
1692:              string s;
1693:   
1694:              s = AbsolutePath(false);
1695:   
1696:              s = s.Remove(s.Length - 1, 1);
1697:   
1698:              s = s.Substring(0, s.LastIndexOf(@"\")) + @"\";
1699:   
1700:              return s;
1701:          }
1702:   
1703:          ////////////////////////////////////////////////////////////////////////////
1704:   
1705:          /// <summary>
1706:          /// Return domain name from page Uri
1707:          /// </summary>
1708:          public static string BasicHost(Uri uri)
1709:          {
1710:              string url, domain, puny, tld;
1711:   
1712:              url = uri.Host;
1713:              url = url.ToLower();
1714:   
1715:              if (uri.Host == "localhost")
1716:              {
1717:                  url = uri.Segments[1].Replace("/", "");
1718:                  url = url.ToLower();
1719:                  url = url.Replace("http://", "");
1720:                  url = url.Replace("https://", "");
1721:                  url = url.Replace("www.", "");
1722:                  url = url.Replace("m.", "");
1723:              }
1724:   
1725:              if (url.Contains("xn--"))
1726:              {
1727:                  // URL is punycode
1728:                  if (url.Contains(".com")) tld = "com";
1729:                  else if (url.Contains(".net")) tld = "net";
1730:                  else if (url.Contains(".org")) tld = "org";
1731:                  else tld = "?";
1732:   
1733:                  url = url.Replace(".com", "");
1734:                  url = url.Replace(".net", "");
1735:                  url = url.Replace(".org", "");
1736:   
1737:                  domain = global::Ia.Cl.Model.Punycode.Decode(url) + "." + tld;
1738:                  puny = url + "." + tld;
1739:              }
1740:              else
1741:              {
1742:                  // URL is not punycode
1743:                  domain = url;
1744:                  puny = url;
1745:              }
1746:   
1747:              return domain;
1748:          }
1749:   
1750:          ////////////////////////////////////////////////////////////////////////////
1751:   
1752:          /// <summary>
1753:          /// Return the absolute URL
1754:          /// </summary>
1755:          public static string AbsoluteUrl(Page p)
1756:          {
1757:              string url;
1758:              Uri uri;
1759:   
1760:              uri = p.Request.Url;
1761:   
1762:              if (uri.Host == "localhost")
1763:              {
1764:                  url = uri.Authority; // +@"/" + uri.Segments[1].Replace("/", "");
1765:                  url = url.ToLower();
1766:                  url = url.Replace("http://", "");
1767:                  url = url.Replace("www.", "");
1768:              }
1769:              else
1770:              {
1771:                  url = uri.Host;
1772:                  url = url.ToLower();
1773:                  url = url.Replace("http://", "");
1774:                  url = url.Replace("www.", "");
1775:              }
1776:   
1777:              return url;
1778:          }
1779:   
1780:          ////////////////////////////////////////////////////////////////////////////
1781:   
1782:          /// <summary>
1783:          /// Return the URL of a file from the path
1784:          /// </summary>
1785:          public static string AbsolutePathUrl(Page page, string file)
1786:          {
1787:              string s, absolute_url, absolute_path;
1788:   
1789:              absolute_url = AbsoluteUrl(page) + "/";
1790:              absolute_path = AbsolutePath();
1791:   
1792:              s = file.Replace(absolute_path, absolute_url);
1793:   
1794:              s = s.Replace(@"\", @"/");
1795:   
1796:              return page.ResolveClientUrl("~/" + s);
1797:          }
1798:   
1799:          ////////////////////////////////////////////////////////////////////////////
1800:          ////////////////////////////////////////////////////////////////////////////
1801:   
1802:          /// <summary>
1803:          /// Shows a client-side JavaScript alert in the browser.
1804:          /// </summary>
1805:          public static void JavasciptSrc(Page p, string relative_url_file)
1806:          {
1807:              // cleans the message to allow single quotation marks
1808:              string script;
1809:   
1810:              relative_url_file = relative_url_file.Replace("'", "\\'");
1811:   
1812:              script = "<script type=\"text/javascript\" src=\"" + global::Ia.Cl.Model.Default.AbsoluteUrl(p) + @"/" + relative_url_file + "\"/>";
1813:   
1814:              // gets the executing web page
1815:              Page page = HttpContext.Current.CurrentHandler as Page;
1816:   
1817:              // checks if the handler is a Page and that the script isn't allready on the Page
1818:              if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
1819:              {
1820:                  page.ClientScript.RegisterClientScriptBlock(typeof(string), "alert", script);
1821:              }
1822:          }
1823:   
1824:          ////////////////////////////////////////////////////////////////////////////
1825:          ////////////////////////////////////////////////////////////////////////////
1826:   
1827:          /// <summary>
1828:          /// Make line in proper title case
1829:          /// </summary>
1830:          public static string ToTitleCase(string line)
1831:          {
1832:              TextInfo textInfo;
1833:              List<string> notToCapitalize = new List<string>(new string[] { "a", "an", "the", "at", "by", "for", "in", "of", "on", "to", "up", "and", "as", "but", "or", "nor" });
1834:   
1835:              textInfo = new CultureInfo("en-US", false).TextInfo;
1836:   
1837:              if (line != null)
1838:              {
1839:                  // changes a string to titlecase.
1840:                  line = textInfo.ToTitleCase(line.ToLower());
1841:   
1842:                  // Rules for Capitalization in Titles of Articles
1843:                  // http://grammar.yourdictionary.com/capitalization/rules-for-capitalization-in-titles.html#S9rKxG2G8gp88qcx.99http://grammar.yourdictionary.com/capitalization/rules-for-capitalization-in-titles.html
1844:   
1845:                  // "Capitalize all words in titles of publications and documents, except a, an, the, at, by, for, in, of, on, to, up, and, as, but, or, and nor.
1846:                  foreach (string s in notToCapitalize)
1847:                  {
1848:                      line = Regex.Replace(line, "\\b" + s + "\\b", s.ToLower(), RegexOptions.IgnoreCase);
1849:                  }
1850:              }
1851:   
1852:              return line;
1853:          }
1854:   
1855:          ////////////////////////////////////////////////////////////////////////////
1856:   
1857:          /// <summary>
1858:          /// Make the first letter of a word an upper letter
1859:          /// </summary>
1860:          public static string FirstLetterToUpper(string s)
1861:          {
1862:              string u;
1863:   
1864:              u = s.Substring(0, 1);
1865:              return u.ToUpper() + s.Remove(0, 1);
1866:          }
1867:   
1868:          ////////////////////////////////////////////////////////////////////////////
1869:   
1870:          /// <summary>
1871:          /// Make the first letter of all words an upper letter and remove underscores
1872:          /// </summary>
1873:          public static string FirstWordLetterToUpperAndRemoveUnderscore(string line)
1874:          {
1875:              string u, v;
1876:   
1877:              v = "";
1878:   
1879:              line = RemoveUnderscore(line);
1880:   
1881:              foreach (string s in line.Split(' '))
1882:              {
1883:                  u = s.Substring(0, 1);
1884:                  v += u.ToUpper() + s.Remove(0, 1) + " ";
1885:              }
1886:   
1887:              if (v.Length > 0) v = v.Remove(v.Length - 1, 1);
1888:   
1889:              return v;
1890:          }
1891:   
1892:          ////////////////////////////////////////////////////////////////////////////
1893:   
1894:          /// <summary>
1895:          /// Convert the string to Pascal case.
1896:          /// </summary>
1897:          /// <remarks>http://csharphelper.com/blog/2014/10/convert-between-pascal-case-camel-case-and-proper-case-in-c/</remarks>
1898:          public static string ToPascalCase(this string s)
1899:          {
1900:              // If there are 0 or 1 characters, just return the string.
1901:              if (s == null) return s;
1902:              if (s.Length < 2) return s.ToUpper();
1903:   
1904:              // Split the string into words.
1905:              string[] words = s.Split(
1906:                  new char[] { },
1907:                  StringSplitOptions.RemoveEmptyEntries);
1908:   
1909:              // Combine the words.
1910:              string result = "";
1911:              foreach (string word in words)
1912:              {
1913:                  result +=
1914:                      word.Substring(0, 1).ToUpper() +
1915:                      word.Substring(1);
1916:              }
1917:   
1918:              return result;
1919:          }
1920:   
1921:          ////////////////////////////////////////////////////////////////////////////
1922:   
1923:          /// <summary>
1924:          /// Convert the string to camel case.
1925:          /// </summary>
1926:          /// <remarks>http://csharphelper.com/blog/2014/10/convert-between-pascal-case-camel-case-and-proper-case-in-c/</remarks>
1927:          public static string ToCamelCase(this string s)
1928:          {
1929:              // If there are 0 or 1 characters, just return the string.
1930:              if (s == null || s.Length < 2)
1931:                  return s;
1932:   
1933:              // Split the string into words.
1934:              string[] words = s.Split(
1935:                  new char[] { },
1936:                  StringSplitOptions.RemoveEmptyEntries);
1937:   
1938:              // Combine the words.
1939:              string result = words[0].ToLower();
1940:              for (int i = 1; i < words.Length; i++)
1941:              {
1942:                  result +=
1943:                      words[i].Substring(0, 1).ToUpper() +
1944:                      words[i].Substring(1);
1945:              }
1946:   
1947:              return result;
1948:          }
1949:   
1950:          ////////////////////////////////////////////////////////////////////////////
1951:   
1952:          /// <summary>
1953:          /// Capitalize the first character and add a space before each capitalized letter (except the first character).
1954:          /// </summary>
1955:          /// <remarks>http://csharphelper.com/blog/2014/10/convert-between-pascal-case-camel-case-and-proper-case-in-c/</remarks>
1956:          public static string ToProperCase(this string s)
1957:          {
1958:              // If there are 0 or 1 characters, just return the string.
1959:              if (s == null) return s;
1960:              if (s.Length < 2) return s.ToUpper();
1961:   
1962:              // Start with the first character.
1963:              string result = s.Substring(0, 1).ToUpper();
1964:   
1965:              // Add the remaining characters.
1966:              for (int i = 1; i < s.Length; i++)
1967:              {
1968:                  if (char.IsUpper(s[i])) result += " ";
1969:                  result += s[i];
1970:              }
1971:   
1972:              return result;
1973:          }
1974:   
1975:          ////////////////////////////////////////////////////////////////////////////
1976:   
1977:          /// <summary>
1978:          /// Convert caps delimited to underscore, lower case string
1979:          /// </summary>
1980:          /// <remarks>http://stackoverflow.com/questions/5796383/insert-spaces-between-words-on-a-camel-cased-token</remarks>
1981:          public static string CapsDelimitedToUnderscoreLowercase(this string s)
1982:          {
1983:              string u;
1984:   
1985:              u = Regex.Replace(s, "(\\B[A-Z])", "_$1");
1986:   
1987:              return u.ToLower();
1988:          }
1989:   
1990:          ////////////////////////////////////////////////////////////////////////////
1991:   
1992:          /// <summary>
1993:          /// Remove underscores
1994:          /// </summary>
1995:          public static string RemoveUnderscore(string line)
1996:          {
1997:              string u;
1998:   
1999:              u = line.Replace('_', ' ');
2000:   
2001:              return u;
2002:          }
2003:   
2004:          ////////////////////////////////////////////////////////////////////////////
2005:          ////////////////////////////////////////////////////////////////////////////
2006:   
2007:          /// <summary>
2008:          /// Regex that defines email
2009:          /// </summary>
2010:          public static string EmailRegex()
2011:          {
2012:              // http://www.regular-expressions.info/email.html
2013:              string s;
2014:   
2015:              s = @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b";
2016:   
2017:              // Text="Invalid e-mail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" runat="server" />
2018:   
2019:              return s;
2020:          }
2021:   
2022:          ////////////////////////////////////////////////////////////////////////////
2023:   
2024:          /// <summary>
2025:          ///
2026:          /// </summary>
2027:          public static bool IsEmail(string s)
2028:          {
2029:              // return true if argument is an email
2030:              bool b;
2031:   
2032:              b = false;
2033:   
2034:              if (Regex.IsMatch(s, global::Ia.Cl.Model.Default.EmailRegex(), RegexOptions.IgnoreCase)) b = true;
2035:   
2036:              return b;
2037:          }
2038:   
2039:          ////////////////////////////////////////////////////////////////////////////
2040:   
2041:          /// <summary>
2042:          ///
2043:          /// </summary>
2044:          public static string Decimal(double d, int dec)
2045:          {
2046:              // 
2047:              string s;
2048:   
2049:              if (dec == 3) s = string.Format("{0:0.000}", d);
2050:              else if (dec == 2) s = string.Format("{0:0.00}", d);
2051:              else if (dec == 1) s = string.Format("{0:0.0}", d);
2052:              else s = d.ToString();
2053:   
2054:              return s;
2055:          }
2056:   
2057:          ////////////////////////////////////////////////////////////////////////////
2058:   
2059:          /// <summary>
2060:          /// Reverse a string
2061:          /// </summary>
2062:          public static string ReverseString(string t)
2063:          {
2064:              string s;
2065:   
2066:              s = "";
2067:   
2068:              foreach (char c in t.ToCharArray()) s = c + " " + s;
2069:   
2070:              return s;
2071:          }
2072:   
2073:          ////////////////////////////////////////////////////////////////////////////
2074:          ////////////////////////////////////////////////////////////////////////////
2075:   
2076:          /// <summary>
2077:          /// Convent the data content of a DataSet to an XmlDocument object for use in API Services.
2078:          /// <param name="ds">DataSet to convert to XmlDocument</param>
2079:          /// <returns>XmlDocument</returns>
2080:          /// </summary>
2081:   
2082:          public static XmlDocument DataSetToXmlDocument(DataSet ds)
2083:          {
2084:              return DataSetToXmlDocument(ds, null);
2085:          }
2086:   
2087:          ////////////////////////////////////////////////////////////////////////////
2088:   
2089:          /// <summary>
2090:          /// Convent the data content of a DataSet to an XmlDocument object for use in API Services.
2091:          /// </summary>
2092:          public static XmlDocument DataSetToXmlDocument(DataSet ds, string item_name)
2093:          {
2094:              XmlText xt;
2095:              XmlElement set_xe, table_xe, row_xe, xe;
2096:              XmlDeclaration xde;
2097:              XmlDocument xd;
2098:   
2099:              xd = new XmlDocument();
2100:   
2101:              if (ds != null)
2102:              {
2103:                  xde = xd.CreateXmlDeclaration("1.0", "utf-8", null);
2104:   
2105:                  // create root element
2106:                  if (ds.DataSetName.Length > 0) set_xe = xd.CreateElement(ds.DataSetName);
2107:                  else set_xe = xd.CreateElement("set");
2108:   
2109:                  xd.InsertBefore(xde, xd.DocumentElement);
2110:                  xd.AppendChild(set_xe);
2111:   
2112:                  if (ds.Tables.Count > 0)
2113:                  {
2114:                      foreach (DataTable dt in ds.Tables)
2115:                      {
2116:                          // create table element
2117:                          if (dt.TableName.Length > 0) table_xe = xd.CreateElement(dt.TableName);
2118:                          else table_xe = xd.CreateElement("table");
2119:   
2120:                          set_xe.AppendChild(table_xe);
2121:   
2122:                          if (dt.Rows.Count > 0)
2123:                          {
2124:                              foreach (DataRow r in dt.Rows)
2125:                              {
2126:                                  // create a new row and add it to the root node
2127:                                  if (item_name == null) item_name = "row";
2128:                                  row_xe = xd.CreateElement(item_name);
2129:   
2130:                                  table_xe.AppendChild(row_xe);
2131:   
2132:                                  foreach (DataColumn dc in dt.Columns)
2133:                                  {
2134:                                      xe = xd.CreateElement(dc.ColumnName);
2135:   
2136:                                      xt = xd.CreateTextNode(r[dc.ColumnName].ToString());
2137:   
2138:                                      xe.AppendChild(xt);
2139:   
2140:                                      row_xe.AppendChild(xe);
2141:                                  }
2142:                              }
2143:                          }
2144:                      }
2145:                  }
2146:                  else
2147:                  {
2148:                  }
2149:              }
2150:              else
2151:              {
2152:              }
2153:   
2154:              return xd;
2155:          }
2156:   
2157:          ////////////////////////////////////////////////////////////////////////////
2158:   
2159:          /// <summary>
2160:          /// Convert the data content of a DataTable to an XmlDocument object for use in API Services.
2161:          /// <param name="dt">DataTable to convert to XmlDocument</param>
2162:          /// <returns>XmlDocument</returns>
2163:          /// </summary>
2164:   
2165:          public static XmlDocument DataTableToXmlDocument(DataTable dt)
2166:          {
2167:              return DataTableToXmlDocument(dt, null);
2168:          }
2169:   
2170:          ////////////////////////////////////////////////////////////////////////////
2171:   
2172:          /// <summary>
2173:          /// Convert the data content of a DataTable to an XmlDocument object for use in API Services.
2174:          /// </summary>
2175:          public static XmlDocument DataTableToXmlDocument(DataTable dt, string itemName)
2176:          {
2177:              XmlText xt;
2178:              XmlElement table_xe, row_xe, xe;
2179:              XmlDeclaration xde;
2180:              XmlDocument xd;
2181:   
2182:              xd = new XmlDocument();
2183:   
2184:              if (dt != null)
2185:              {
2186:                  xde = xd.CreateXmlDeclaration("1.0", "utf-8", null);
2187:   
2188:                  // create root element
2189:                  if (dt.TableName.Length > 0) table_xe = xd.CreateElement(dt.TableName);
2190:                  else table_xe = xd.CreateElement("table");
2191:   
2192:                  xd.InsertBefore(xde, xd.DocumentElement);
2193:                  xd.AppendChild(table_xe);
2194:   
2195:                  if (dt.Rows.Count > 0)
2196:                  {
2197:                      foreach (DataRow r in dt.Rows)
2198:                      {
2199:                          // create a new row and add it to the root node
2200:                          if (itemName == null) itemName = "row";
2201:                          row_xe = xd.CreateElement(itemName);
2202:   
2203:                          table_xe.AppendChild(row_xe);
2204:   
2205:                          foreach (DataColumn dc in dt.Columns)
2206:                          {
2207:                              xe = xd.CreateElement(dc.ColumnName);
2208:   
2209:                              xt = xd.CreateTextNode(r[dc.ColumnName].ToString());
2210:   
2211:                              xe.AppendChild(xt);
2212:   
2213:                              row_xe.AppendChild(xe);
2214:                          }
2215:                      }
2216:                  }
2217:              }
2218:              else
2219:              {
2220:              }
2221:   
2222:              return xd;
2223:          }
2224:   
2225:          ////////////////////////////////////////////////////////////////////////////
2226:   
2227:          /// <summary>
2228:          /// Convert the data content of a DataTable to an XDocument object
2229:          /// <param name="dt">DataTable to convert to XDocument</param>
2230:          /// <returns>XDocument</returns>
2231:          /// </summary>
2232:   
2233:          public static XDocument DataTableToXDocument(DataTable dt)
2234:          {
2235:              return DataTableToXDocument(dt, null);
2236:          }
2237:   
2238:          ////////////////////////////////////////////////////////////////////////////
2239:   
2240:          /// <summary>
2241:          /// Convert the data content of a DataTable to an XDocument object.
2242:          /// </summary>
2243:          public static XDocument DataTableToXDocument(DataTable dt, string itemName)
2244:          {
2245:              XElement tableXElement, rowXElement, xe;
2246:              XDeclaration xde;
2247:              XDocument xd;
2248:   
2249:              if (dt != null)
2250:              {
2251:                  xde = new XDeclaration("1.0", "utf-8", null);
2252:   
2253:                  // create root element
2254:                  if (dt.TableName.Length > 0) tableXElement = new XElement(dt.TableName);
2255:                  else tableXElement = new XElement("table");
2256:   
2257:                  if (dt.Rows.Count > 0)
2258:                  {
2259:                      foreach (DataRow r in dt.Rows)
2260:                      {
2261:                          // create a new row and add it to the root node
2262:                          if (itemName == null) itemName = "row";
2263:                          rowXElement = new XElement(itemName, "");
2264:   
2265:                          tableXElement.Add(rowXElement);
2266:   
2267:                          foreach (DataColumn dc in dt.Columns)
2268:                          {
2269:                              xe = new XElement(dc.ColumnName, r[dc.ColumnName].ToString());
2270:   
2271:                              rowXElement.Add(xe);
2272:                          }
2273:                      }
2274:                  }
2275:   
2276:                  xd = new XDocument(xde, tableXElement);
2277:              }
2278:              else
2279:              {
2280:                  xd = null;
2281:              }
2282:   
2283:              return xd;
2284:          }
2285:   
2286:          ////////////////////////////////////////////////////////////////////////////
2287:          ////////////////////////////////////////////////////////////////////////////
2288:   
2289:          /// <summary>
2290:          /// Takes an XmlNodeList with text and value, and change them into a DataTable usable for databinding with controls
2291:          /// </summary>
2292:          public static DataTable XmlNodeListToDataTable(XmlNodeList xnl, string value, string text)
2293:          {
2294:              DataTable dt;
2295:              DataRow dr;
2296:   
2297:              dt = new DataTable();
2298:              dt.Columns.Add(value);
2299:   
2300:              if (value != text) dt.Columns.Add(text);
2301:   
2302:              foreach (XmlNode n in xnl)
2303:              {
2304:                  dr = dt.NewRow();
2305:                  dr[value] = n.Attributes[value].Value;
2306:                  if (value != text) dr[text] = n.Attributes[text].Value;
2307:                  dt.Rows.Add(dr);
2308:              }
2309:   
2310:              return dt;
2311:          }
2312:   
2313:          ////////////////////////////////////////////////////////////////////////////
2314:   
2315:          /// <summary>
2316:          /// Takes an XmlNodeList with text and value, and change them into a DataTable usable for databinding with controls
2317:          /// </summary>
2318:          public static DataTable XmlNodeListToDataTable(XmlNodeList xnl, string id, string text, string url)
2319:          {
2320:              DataTable dt;
2321:              DataRow dr;
2322:   
2323:              dt = new DataTable();
2324:              dt.Columns.Add(id);
2325:              dt.Columns.Add(text);
2326:              dt.Columns.Add(url);
2327:   
2328:              foreach (XmlNode n in xnl)
2329:              {
2330:                  dr = dt.NewRow();
2331:                  dr[id] = n.Attributes[id].Value;
2332:                  dr[text] = n.Attributes[text].Value;
2333:                  dr[url] = n.Attributes[url].Value;
2334:                  dt.Rows.Add(dr);
2335:              }
2336:   
2337:              return dt;
2338:          }
2339:   
2340:          ////////////////////////////////////////////////////////////////////////////
2341:   
2342:          /// <summary>
2343:          /// Takes an XmlNodeList with text and value, and extra initial entries, and change them into a DataTable usable for databinding with controls
2344:          /// </summary>
2345:          public static DataTable XmlNodeListToDataTable(XmlNodeList xnl, string value, string text, string init_value, string init_text)
2346:          {
2347:              DataTable dt;
2348:              DataRow dr;
2349:   
2350:              dt = new DataTable();
2351:              dt.Columns.Add(value);
2352:              dt.Columns.Add(text);
2353:   
2354:              dr = dt.NewRow();
2355:              dr[value] = init_value;
2356:              dr[text] = init_text;
2357:              dt.Rows.Add(dr);
2358:   
2359:              foreach (XmlNode n in xnl)
2360:              {
2361:                  dr = dt.NewRow();
2362:                  dr[value] = n.Attributes[value].Value;
2363:                  dr[text] = n.Attributes[text].Value;
2364:                  dt.Rows.Add(dr);
2365:              }
2366:   
2367:              return dt;
2368:          }
2369:   
2370:          ////////////////////////////////////////////////////////////////////////////
2371:   
2372:          /// <summary>
2373:          /// Convert XmlDocument to a tab indented simple text format suitable for simple text and emails
2374:          /// </summary>
2375:          /// <remarks>http://stackoverflow.com/questions/10980237/xml-to-text-convert</remarks>
2376:          public static string XmlDocumentToTabIndentedText(XmlDocument xmlDocument)
2377:          {
2378:              string s, name, text;
2379:              StringBuilder stringBuilder = new StringBuilder();
2380:   
2381:              stringBuilder.AppendLine("===================");
2382:   
2383:              name = ToProperCase(xmlDocument.DocumentElement.Name);
2384:   
2385:              stringBuilder.AppendLine(name);
2386:   
2387:              s = XmlDocumentToTabIndentedTextIterator(xmlDocument.DocumentElement, out text);
2388:   
2389:              stringBuilder.AppendLine(s);
2390:   
2391:              stringBuilder.AppendLine("===================");
2392:   
2393:              return stringBuilder.ToString();
2394:          }
2395:   
2396:          private static string XmlDocumentToTabIndentedTextIterator(XmlNode xmlNode, out string text)
2397:          {
2398:              string s, name;
2399:              StringBuilder stringBuilder = new StringBuilder();
2400:   
2401:              text = string.Empty;
2402:   
2403:              if (xmlNode.NodeType == XmlNodeType.Element)
2404:              {
2405:                  foreach (XmlNode node in xmlNode.ChildNodes)
2406:                  {
2407:                      s = XmlDocumentToTabIndentedTextIterator(node, out text);
2408:   
2409:                      name = ToProperCase(node.Name);
2410:   
2411:                      if (!string.IsNullOrEmpty(text))
2412:                      {
2413:                          stringBuilder.AppendLine("\t" + name + ": " + text);
2414:                      }
2415:                      else stringBuilder.AppendLine("\t" + name);
2416:                  }
2417:              }
2418:              else if (xmlNode.NodeType == XmlNodeType.Text)
2419:              {
2420:                  text = xmlNode.InnerText.Trim();
2421:              }
2422:              else
2423:              {
2424:   
2425:              }
2426:   
2427:              return stringBuilder.ToString().TrimEnd();
2428:          }
2429:          ////////////////////////////////////////////////////////////////////////////
2430:          ////////////////////////////////////////////////////////////////////////////
2431:   
2432:  #if WINDOWS_FORM
2433:          ////////////////////////////////////////////////////////////////////////////
2434:   
2435:          /// <summary>
2436:          /// Return the MAC Address of the computer
2437:          /// </summary>
2438:          public static string Get_MAC_Address()
2439:          {
2440:              // This will support IPv4 and IPv6.
2441:   
2442:              string mac_address;
2443:              System.Net.NetworkInformation.NetworkInterface[] nics;
2444:   
2445:              nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
2446:   
2447:              mac_address = string.Empty;
2448:   
2449:              foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics)
2450:              {
2451:                  if (mac_address == string.Empty)// only return MAC Address from first card  
2452:                  {
2453:                      System.Net.NetworkInformation.IPInterfaceProperties properties = adapter.GetIPProperties();
2454:   
2455:                      mac_address = adapter.GetPhysicalAddress().ToString();
2456:                  }
2457:              }
2458:   
2459:              return mac_address;
2460:          }
2461:  #endif
2462:          ////////////////////////////////////////////////////////////////////////////
2463:   
2464:          /// <summary>
2465:          /// Download file
2466:          /// </summary>
2467:          public static bool DownloadFile(string url, string fileName)
2468:          {
2469:              // 
2470:              bool b;
2471:   
2472:              try
2473:              {
2474:                  using (System.Net.WebClient wc = new System.Net.WebClient())
2475:                  {
2476:                      wc.DownloadFile(url, fileName);
2477:                  }
2478:   
2479:                  b = true;
2480:              }
2481:              catch (Exception)
2482:              {
2483:                  b = false;
2484:              }
2485:   
2486:              return b;
2487:          }
2488:   
2489:          ////////////////////////////////////////////////////////////////////////////
2490:   
2491:          /// <summary>
2492:          /// Regular Expression Guid Match
2493:          /// </summary>
2494:          /// </summary>
2495:          /// <remarks> http://www.geekzilla.co.uk/view8AD536EF-BC0D-427F-9F15-3A1BC663848E.htm</remarks>
2496:          public static bool IsGuid(string s)
2497:          {
2498:              bool b = false;
2499:   
2500:              if (!string.IsNullOrEmpty(s))
2501:              {
2502:                  Regex r = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
2503:   
2504:                  b = r.IsMatch(s);
2505:              }
2506:   
2507:              return b;
2508:          }
2509:   
2510:  #if !WINDOWS_FORM
2511:          ////////////////////////////////////////////////////////////////////////////
2512:   
2513:          /// <summary>
2514:          /// Checks the API Service State
2515:          /// </summary>
2516:          public static string ApiServiceState(System.Web.HttpApplicationState has, string name, TimeSpan ts)
2517:          {
2518:              bool b;
2519:              string s;
2520:              DateTime dti;
2521:   
2522:              b = false;
2523:              s = "";
2524:   
2525:              // check if timespan variable is stored and is not null
2526:              if (has[name] != null && has[name + "_ts"] != null)
2527:              {
2528:                  // check if the timespan is cleared since stored value
2529:   
2530:                  s = has[name].ToString();
2531:                  dti = DateTime.Parse(has[name + "_ts"].ToString());
2532:   
2533:                  if (DateTime.UtcNow.AddHours(3) > dti + ts)
2534:                  {
2535:                      // update API Service 
2536:                      b = true;
2537:                  }
2538:                  else
2539:                  {
2540:                      // do nothing
2541:                      b = false;
2542:                  }
2543:              }
2544:              else b = true;
2545:   
2546:              if (b)
2547:              {
2548:                  // update API Service values
2549:                  /*
2550:                  Ia.Ngn.kw.com.i.Ws_Default svc = new Ia.Ngn.kw.com.i.Ws_Default();
2551:                  svc.Timeout = 5000;
2552:  
2553:                  try
2554:                  {
2555:                      s = svc.Echo("Hello!");
2556:                  }
2557:                  catch (Exception)
2558:                  {
2559:                      s = null;
2560:                  }
2561:                  finally
2562:                  {
2563:                      has[name] = s;
2564:                      has[name + "_ts"] = DateTime.UtcNow.AddHours(3).ToString("yyyy-MM-dd hh:mm:ss");
2565:                  }
2566:                  */
2567:              }
2568:   
2569:              return has[name].ToString() + ":" + has[name + "_ts"].ToString();
2570:          }
2571:  #endif
2572:   
2573:          ////////////////////////////////////////////////////////////////////////////
2574:   
2575:          /// <summary>
2576:          /// C# to convert a string to a byte array.
2577:          /// </summary>
2578:          private static byte[] ConvertStringToByteArray(string str)
2579:          {
2580:              System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
2581:              return encoding.GetBytes(str);
2582:   
2583:              /*
2584:          // C# to convert a byte array to a string.
2585:          byte [] dBytes = ...
2586:          string str;
2587:          System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
2588:          str = enc.GetString(dBytes);
2589:               */
2590:          }
2591:   
2592:          ////////////////////////////////////////////////////////////////////////////
2593:   
2594:          /// <summary>
2595:          /// C# to convert an alphnumeric string to an integer
2596:          /// </summary>
2597:          public static int AlphanumericStringToInt(string s)
2598:          {
2599:              int i;
2600:              System.Text.Encoding ascii;
2601:              Byte[] encodedBytes;
2602:   
2603:              i = 0;
2604:              ascii = System.Text.Encoding.ASCII;
2605:              encodedBytes = ascii.GetBytes(s);
2606:   
2607:              foreach (Byte b in encodedBytes) i += b;
2608:   
2609:              return i;
2610:          }
2611:   
2612:          ////////////////////////////////////////////////////////////////////////////
2613:   
2614:          /// <summary>
2615:          ///
2616:          /// </summary>
2617:          public static int IncrementArrayListIndexOrRestart(ArrayList list, int currentIndex)
2618:          {
2619:              int newIndex;
2620:   
2621:              if (currentIndex < list.Count - 1) newIndex = ++currentIndex;
2622:              else newIndex = 0;
2623:   
2624:              return newIndex;
2625:          }
2626:   
2627:          ////////////////////////////////////////////////////////////////////////////
2628:   
2629:          /// <summary>
2630:          ///
2631:          /// </summary>
2632:          public static int IncrementListIndexOrRestart<T>(List<T> list, int currentIndex)
2633:          {
2634:              int newIndex;
2635:   
2636:              if (currentIndex < list.Count - 1) newIndex = ++currentIndex;
2637:              else newIndex = 0;
2638:   
2639:              return newIndex;
2640:          }
2641:   
2642:          ////////////////////////////////////////////////////////////////////////////
2643:   
2644:          /// <summary>
2645:          ///
2646:          /// </summary>
2647:          public static void IncrementIndexOrReset(int listCount, ref int currentIndex)
2648:          {
2649:              currentIndex = (currentIndex < listCount - 1) ? ++currentIndex : 0;
2650:          }
2651:   
2652:          /*
2653:          ////////////////////////////////////////////////////////////////////////////
2654:  
2655:          /// <summary>
2656:          ///
2657:          /// </summary>
2658:          public static void ShuffleArrayList(ArrayList al)
2659:          {
2660:              for (int inx = al.Count - 1; inx > 0; --inx)
2661:              {
2662:                  int position = r.Next(inx);
2663:                  object temp = al[inx];
2664:                  al[inx] = al[position];
2665:                  al[position] = temp;
2666:              }
2667:          }
2668:           */
2669:   
2670:          ////////////////////////////////////////////////////////////////////////////
2671:   
2672:          /// <summary>
2673:          ///
2674:          /// </summary>
2675:          public static ArrayList ShuffleArrayList(ArrayList inputList)
2676:          {
2677:              ArrayList randomList = new ArrayList();
2678:   
2679:              int randomIndex = 0;
2680:   
2681:              while (inputList.Count > 0)
2682:              {
2683:                  randomIndex = random.Next(0, inputList.Count); //Choose a random object in the list
2684:                  randomList.Add(inputList[randomIndex]); //add it to the new, random list
2685:                  inputList.RemoveAt(randomIndex); //remove to avoid duplicates
2686:              }
2687:   
2688:              return randomList; //return the new random list
2689:          }
2690:   
2691:          ////////////////////////////////////////////////////////////////////////////
2692:   
2693:          /// <summary>
2694:          ///
2695:          /// </summary>
2696:          public static ArrayList IntegerListRange(ArrayList a_al)
2697:          {
2698:              // this will take an ArrayList of integer, remove duplicates, sort, then construct an ArrayList with ranges defined, if available. For example
2699:              // a_al = [1,2,4,6,7,15,20,21,22,34,35,36,38]
2700:              // b_al = [1,2,4,6,7,15,20-22,34-36,38]
2701:   
2702:              bool range, range_old;
2703:              int u, v;
2704:              int start, end;
2705:              ArrayList b_al, c_al;
2706:              Hashtable ht;
2707:   
2708:              // a_al = [1,2,4,6,7,15,20,21,22,34,35,36,38]
2709:              // b_al = [1,2,4,6,7,15,20-22,34-36,38]
2710:   
2711:              start = end = 0;
2712:   
2713:              b_al = new ArrayList(a_al.Count + 1);
2714:              c_al = new ArrayList(a_al.Count + 1);
2715:   
2716:              if (a_al.Count > 0)
2717:              {
2718:                  // remove duplicates
2719:                  ht = new Hashtable(a_al.Count + 1);
2720:   
2721:                  foreach (int i in a_al) ht[i] = 1;
2722:   
2723:                  foreach (int i in ht.Keys) b_al.Add(i);
2724:   
2725:                  // sort
2726:                  b_al.Sort();
2727:   
2728:                  if (b_al.Count > 0)
2729:                  {
2730:                      range = range_old = false;
2731:                      u = (int)b_al[0];
2732:   
2733:                      for (int i = 1; i <= b_al.Count; i++)
2734:                      {
2735:                          if (i < b_al.Count) v = (int)b_al[i];
2736:                          else v = (int)b_al[i - 1];
2737:   
2738:                          if (v - u == 1)
2739:                          {
2740:                              if (range) end = v;
2741:                              else
2742:                              {
2743:                                  start = u;
2744:                                  range = true;
2745:                              }
2746:                          }
2747:                          else
2748:                          {
2749:                              if (range)
2750:                              {
2751:                                  end = u;
2752:                                  range = false;
2753:                              }
2754:                              else c_al.Add(u.ToString());
2755:                          }
2756:   
2757:                          if (range != range_old && range == false)
2758:                          {
2759:                              if (end - start == 1)
2760:                              {
2761:                                  c_al.Add(start.ToString());
2762:                                  c_al.Add(end.ToString());
2763:                              }
2764:                              else c_al.Add(start + "-" + end);
2765:                          }
2766:   
2767:                          u = v;
2768:                          range_old = range;
2769:                      }
2770:                  }
2771:                  else
2772:                  {
2773:   
2774:                  }
2775:              }
2776:              else
2777:              {
2778:              }
2779:   
2780:              return c_al;
2781:          }
2782:   
2783:          ////////////////////////////////////////////////////////////////////////////
2784:   
2785:          /// <summary>
2786:          /// Generate a list of start-end count optimized to read around count number of values from passed number string list. 
2787:          /// </summary>
2788:          public static List<Tuple<string, string>> OptimizedStartEndRangeTupleList(List<string> list, int count)
2789:          {
2790:              bool done;
2791:              int c;
2792:              string start, end;
2793:              Tuple<string, string> tuple;
2794:              List<Tuple<string, string>> tupleList;
2795:   
2796:              tupleList = new List<Tuple<string, string>>();
2797:   
2798:              done = false;
2799:              c = 0;
2800:              start = string.Empty;
2801:   
2802:              if (list.Count > 0 && count > 0)
2803:              {
2804:                  foreach (string s in list)
2805:                  {
2806:                      if (c == 0)
2807:                      {
2808:                          start = s;
2809:                          done = false;
2810:                      }
2811:   
2812:                      if (c == count - 1)
2813:                      {
2814:                          end = s;
2815:   
2816:                          tuple = new Tuple<string, string>(start, end);
2817:   
2818:                          tupleList.Add(tuple);
2819:   
2820:                          done = true;
2821:                          c = 0;
2822:                      }
2823:                      else c++;
2824:                  }
2825:   
2826:                  if (!done)
2827:                  {
2828:                      end = list[list.Count - 1];
2829:   
2830:                      tuple = new Tuple<string, string>(start, end);
2831:   
2832:                      tupleList.Add(tuple);
2833:                  }
2834:              }
2835:              else throw new System.ArgumentException("List empty or range too short. ");
2836:   
2837:              tupleList.Sort();
2838:   
2839:              return tupleList;
2840:          }
2841:   
2842:          ////////////////////////////////////////////////////////////////////////////
2843:   
2844:          /// <summary>
2845:          /// Generate a list of start-end count optimized to read around count number of values from passed list. 
2846:          /// </summary>
2847:          public static List<Tuple<int, int>> OptimizedStartEndRangeTupleList(List<int> list, int count)
2848:          {
2849:              bool done;
2850:              int c, start, end;
2851:              Tuple<int, int> tuple;
2852:              List<Tuple<int, int>> tupleList;
2853:   
2854:              tupleList = new List<Tuple<int, int>>();
2855:   
2856:              done = false;
2857:              c = start = 0;
2858:   
2859:              if (list.Count > 0 && count > 0)
2860:              {
2861:                  foreach (int i in list)
2862:                  {
2863:                      if (c == 0)
2864:                      {
2865:                          start = i;
2866:                          done = false;
2867:                      }
2868:   
2869:                      if (c == count - 1)
2870:                      {
2871:                          end = i;
2872:   
2873:                          tuple = new Tuple<int, int>(start, end);
2874:   
2875:                          tupleList.Add(tuple);
2876:   
2877:                          done = true;
2878:                          c = 0;
2879:                      }
2880:                      else c++;
2881:                  }
2882:   
2883:                  if (!done)
2884:                  {
2885:                      end = list[list.Count - 1];
2886:   
2887:                      tuple = new Tuple<int, int>(start, end);
2888:   
2889:                      tupleList.Add(tuple);
2890:                  }
2891:              }
2892:              else throw new System.ArgumentException("List empty or range too short. ");
2893:   
2894:              tupleList.Sort();
2895:   
2896:              return tupleList;
2897:          }
2898:   
2899:          ////////////////////////////////////////////////////////////////////////////
2900:   
2901:          /// <summary>
2902:          /// Generate a OptimizedStartEndRangeList() but with a range buffer before start and after end.
2903:          /// </summary>
2904:          public static List<Tuple<int, int>> OptimizedStartEndRangeBufferedList(List<int> list, int count, int bufferRange)
2905:          {
2906:              int start, end;
2907:              List<Tuple<int, int>> tupleList;
2908:   
2909:              tupleList = OptimizedStartEndRangeTupleList(list, count);
2910:   
2911:              if (tupleList != null && tupleList.Count > 0)
2912:              {
2913:                  start = tupleList[0].Item1;
2914:                  end = tupleList[tupleList.Count - 1].Item1;
2915:   
2916:                  tupleList.Insert(0, new Tuple<int, int>(start - bufferRange, start - 1));
2917:                  tupleList.Insert(tupleList.Count - 1, new Tuple<int, int>(end + 1, end + bufferRange + 1));
2918:              }
2919:   
2920:              tupleList.Sort();
2921:   
2922:              return tupleList;
2923:          }
2924:   
2925:          ////////////////////////////////////////////////////////////////////////////
2926:   
2927:          /// <summary>
2928:          /// Generate a list of start, end points of all integer ranges with given start, end and range. End included in range.
2929:          /// </summary>
2930:          public static List<Tuple<int, int>> StartEndRangeList(int start, int end, int range)
2931:          {
2932:              Tuple<int, int> tuple;
2933:              List<Tuple<int, int>> tupleList;
2934:   
2935:              tupleList = new List<Tuple<int, int>>();
2936:   
2937:              if (end > start && range < (end - start))
2938:              {
2939:                  for (int i = start; i <= end; i += range)
2940:                  {
2941:                      if (i + range - 1 < end) tuple = new Tuple<int, int>(i, i + range - 1);
2942:                      else tuple = new Tuple<int, int>(i, end);
2943:   
2944:                      tupleList.Add(tuple);
2945:                  }
2946:              }
2947:              else throw new System.ArgumentException("Start, end, or range is/are invalid. ");
2948:   
2949:              tupleList.Sort();
2950:   
2951:              return tupleList;
2952:          }
2953:   
2954:          ////////////////////////////////////////////////////////////////////////////
2955:   
2956:          /// <summary>
2957:          /// Generate a StartEndRangeList() but with a range buffer before start and after end.
2958:          /// </summary>
2959:          public static List<Tuple<int, int>> StartEndRangeBufferedList(int start, int end, int range, int bufferRange)
2960:          {
2961:              List<Tuple<int, int>> tupleList;
2962:   
2963:              tupleList = StartEndRangeList(start, end, range);
2964:   
2965:              if (tupleList != null && tupleList.Count > 0)
2966:              {
2967:                  tupleList.Insert(0, new Tuple<int, int>(start - bufferRange, start - 1));
2968:                  tupleList.Insert(tupleList.Count - 1, new Tuple<int, int>(end + 1, end + bufferRange + 1));
2969:              }
2970:   
2971:              tupleList.Sort();
2972:   
2973:              return tupleList;
2974:          }
2975:   
2976:          ////////////////////////////////////////////////////////////////////////////
2977:   
2978:          /// <summary>
2979:          ///
2980:          /// </summary>
2981:          public static List<int> ConvertHyphenAndCommaSeperatedNumberStringToNumberList(string listStringAbbriviation)
2982:          {
2983:              int j, start, end;
2984:              string abbriviation, u;
2985:              List<int> list;
2986:              MatchCollection matchCollection;
2987:   
2988:              // change number range (e.g. "1-5") to comma seperated numbers like "1,2,3,4,5"
2989:   
2990:              list = new List<int>();
2991:   
2992:              abbriviation = listStringAbbriviation;
2993:   
2994:              matchCollection = Regex.Matches(abbriviation, @"(\d{1,4})\-(\d{1,4})");
2995:   
2996:              foreach (Match match in matchCollection)
2997:              {
2998:                  start = int.Parse(match.Groups[1].Value);
2999:                  end = int.Parse(match.Groups[2].Value);
3000:   
3001:                  u = "";
3002:                  for (int i = start; i <= end; i++) u += i + ",";
3003:   
3004:                  u = u.TrimEnd(',');
3005:   
3006:                  // remove the matched string from the main string
3007:                  abbriviation = abbriviation.Replace(match.Groups[0].Value, u);
3008:              }
3009:   
3010:              foreach (string s in abbriviation.Split(','))
3011:              {
3012:                  if (int.TryParse(s, out j)) list.Add(j);
3013:              }
3014:   
3015:              return list;
3016:          }
3017:   
3018:          ////////////////////////////////////////////////////////////////////////////
3019:          ////////////////////////////////////////////////////////////////////////////
3020:   
3021:          /// <summary>
3022:          ///
3023:          /// <see cref="https://stackoverflow.com/questions/7688881/convert-list-to-number-range-string"/>
3024:          /// </summary>
3025:          public static string ConvertNumberListToHyphenAndCommaSeperatedNumberString(List<int> numberList)
3026:          {
3027:              return NumberListToPossiblyDegenerateRanges(numberList).Select(r => PrettyRange(r)).Intersperse(",");
3028:          }
3029:   
3030:          private static IEnumerable<Tuple<int, int>> NumberListToPossiblyDegenerateRanges(IEnumerable<int> numList)
3031:          {
3032:              Tuple<int, int> currentRange = null;
3033:   
3034:              foreach (var num in numList)
3035:              {
3036:                  if (currentRange == null)
3037:                  {
3038:                      currentRange = Tuple.Create(num, num);
3039:                  }
3040:                  else if (currentRange.Item2 == num - 1)
3041:                  {
3042:                      currentRange = Tuple.Create(currentRange.Item1, num);
3043:                  }
3044:                  else
3045:                  {
3046:                      yield return currentRange;
3047:                      currentRange = Tuple.Create(num, num);
3048:                  }
3049:              }
3050:              if (currentRange != null)
3051:              {
3052:                  yield return currentRange;
3053:              }
3054:          }
3055:   
3056:          private static string PrettyRange(Tuple<int, int> range)
3057:          {
3058:              if (range.Item1 == range.Item2)
3059:              {
3060:                  return range.Item1.ToString();
3061:              }
3062:              return string.Format("{0}-{1}", range.Item1, range.Item2);
3063:          }
3064:   
3065:          private static string Intersperse(this IEnumerable<string> items, string interspersand)
3066:          {
3067:              var currentInterspersand = "";
3068:              var result = new StringBuilder();
3069:   
3070:              foreach (var item in items)
3071:              {
3072:                  result.Append(currentInterspersand);
3073:                  result.Append(item);
3074:                  currentInterspersand = interspersand;
3075:              }
3076:   
3077:              return result.ToString();
3078:          }
3079:   
3080:          ////////////////////////////////////////////////////////////////////////////
3081:          ////////////////////////////////////////////////////////////////////////////
3082:   
3083:          /// <summary>
3084:          ///
3085:          /// </summary>
3086:          public static string NumberListToCommaSeperatedNumberString(List<int> numberList)
3087:          {
3088:              string s;
3089:   
3090:              if (numberList != null && numberList.Count > 0)
3091:              {
3092:                  s = string.Join(",", numberList.Select(n => n.ToString()).ToArray());
3093:              }
3094:              else s = null;
3095:   
3096:              return s;
3097:          }
3098:   
3099:          ////////////////////////////////////////////////////////////////////////////
3100:   
3101:          /// <summary>
3102:          ///
3103:          /// </summary>
3104:          public static List<int> CommaSeperatedNumberStringToNumberList(string numberListString)
3105:          {
3106:              List<int> numberList;
3107:   
3108:              if (!string.IsNullOrEmpty(numberListString))
3109:              {
3110:                  numberList = (numberListString != string.Empty) ? numberListString.Split(',').Select(Int32.Parse).ToList() : null;
3111:                  numberList.Sort();
3112:              }
3113:              else numberList = null;
3114:   
3115:              return numberList;
3116:          }
3117:   
3118:          /*
3119:          ////////////////////////////////////////////////////////////////////////////
3120:  
3121:          /// <summary>
3122:          /// Generate HTML table from list of generic class with specified properties
3123:          /// <see cref="http://stackoverflow.com/questions/11126137/generate-html-table-from-list-of-generic-class-with-specified-properties"/>
3124:          /// </summary>
3125:          public static string GenerateHtmlTableFromListOfGenericClass<T>(IEnumerable<T> list, List<string> columnNameList, params Func<T, object>[] fxns)
3126:          {
3127:              StringBuilder sb;
3128:  
3129:              sb = new StringBuilder();
3130:  
3131:              sb.Append("<table>\n");
3132:  
3133:              // column names
3134:              if (columnNameList.Count > 0)
3135:              {
3136:                  sb.Append("<tr>");
3137:  
3138:                  foreach (string column in columnNameList)
3139:                  {
3140:                      sb.Append("<td>");
3141:                      sb.Append(column);
3142:                      sb.Append("</td>");
3143:                  }
3144:  
3145:                  sb.Append("</tr>\n");
3146:              }
3147:  
3148:              foreach (var item in list)
3149:              {
3150:                  sb.Append("<tr>");
3151:  
3152:                  foreach (var fxn in fxns)
3153:                  {
3154:                      sb.Append("<td>");
3155:                      sb.Append(fxn(item));
3156:                      sb.Append("</td>");
3157:                  }
3158:  
3159:                  sb.Append("</tr>\n");
3160:              }
3161:  
3162:              sb.Append("</table>");
3163:  
3164:              return sb.ToString();
3165:          }
3166:           */
3167:   
3168:          ////////////////////////////////////////////////////////////////////////////
3169:   
3170:          /// <summary>
3171:          /// 
3172:          /// <see cref="http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable"/>
3173:          /// </summary>
3174:          public static DataTable GenerateDataTableFromGenericClassList<T>(this IList<T> data)
3175:          {
3176:              DataTable dataTable;
3177:              PropertyDescriptor propertyDescriptor;
3178:              PropertyDescriptorCollection propertyDescriptorCollection;
3179:   
3180:              dataTable = new DataTable();
3181:   
3182:              dataTable.TableName = TypeDescriptor.GetClassName(typeof(T));
3183:              propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));
3184:              object[] values = new object[propertyDescriptorCollection.Count];
3185:   
3186:              for (int i = 0; i < propertyDescriptorCollection.Count; i++)
3187:              {
3188:                  propertyDescriptor = propertyDescriptorCollection[i];
3189:   
3190:                  dataTable.Columns.Add(propertyDescriptor.Name, propertyDescriptor.PropertyType);
3191:              }
3192:   
3193:              foreach (T item in data)
3194:              {
3195:                  for (int i = 0; i < values.Length; i++) values[i] = propertyDescriptorCollection[i].GetValue(item);
3196:   
3197:                  dataTable.Rows.Add(values);
3198:              }
3199:   
3200:              return dataTable;
3201:          }
3202:   
3203:          ////////////////////////////////////////////////////////////////////////////
3204:   
3205:          /// <summary>
3206:          /// 
3207:          /// <see cref="http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable"/>
3208:          /// </summary>
3209:          public static DataTable GenerateDataTableFromGenericClassList<T>(this IList<T> data, string dataTableName)
3210:          {
3211:              // I need to pass the dataTableName here to make the code consitant
3212:              DataTable dataTable;
3213:              PropertyDescriptor propertyDescriptor;
3214:              PropertyDescriptorCollection propertyDescriptorCollection;
3215:              Type type;
3216:              PropertyInfo propertyInfo;
3217:              object value;
3218:              List<int> itemToBeRemoved;
3219:   
3220:              dataTable = new DataTable();
3221:              itemToBeRemoved = new List<int>();
3222:   
3223:              dataTable.TableName = dataTableName; //TypeDescriptor.GetClassName(typeof(T));
3224:   
3225:              propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));
3226:              List<object> valueList = new List<object>(propertyDescriptorCollection.Count);
3227:   
3228:              for (int i = 0; i < propertyDescriptorCollection.Count; i++)
3229:              {
3230:                  propertyDescriptor = propertyDescriptorCollection[i];
3231:   
3232:                  // Important: to handle complicated EF variables that represent foreign keys. I will check the property's full name, if it starts with "Ia."
3233:                  // then this is a complicated foreign key variables that most likely points to an Id in another table, and I will attach a "_Id" suffix to the name and pass it into the DataTable.
3234:                  // Also we will get the property type of this "Id" by checking the 0 index property of the parent property (since Id is almost always the first element)
3235:   
3236:                  if (propertyDescriptor.PropertyType.FullName.StartsWith("Ia."))
3237:                  {
3238:                      dataTable.Columns.Add(propertyDescriptor.Name + "_Id", TypeDescriptor.GetProperties(propertyDescriptor.PropertyType)[0].PropertyType);
3239:                  }
3240:                  else if (propertyDescriptor.PropertyType.FullName.StartsWith("System.Collections.Generic.ICollection"))
3241:                  {
3242:                      // this is a virtual property to to be converted to anything in table
3243:                      itemToBeRemoved.Add(i);
3244:                  }
3245:                  else dataTable.Columns.Add(propertyDescriptor.Name, propertyDescriptor.PropertyType);
3246:              }
3247:   
3248:              foreach (T d in data)
3249:              {
3250:                  valueList.Clear();
3251:   
3252:                  for (int i = 0; i < propertyDescriptorCollection.Count; i++)
3253:                  {
3254:                      if (!itemToBeRemoved.Contains(i))
3255:                      {
3256:                          propertyDescriptor = propertyDescriptorCollection[i];
3257:   
3258:                          // below: same as above we will check to see if property full name starts with "Ia." and assign the appropriate value accordingly
3259:   
3260:                          if (propertyDescriptor.PropertyType.FullName.StartsWith("Ia."))
3261:                          {
3262:                              type = d.GetType();
3263:   
3264:                              propertyInfo = type.GetProperty("Designation");
3265:   
3266:                              if (propertyInfo != null)
3267:                              {
3268:                                  value = propertyInfo.GetValue(d);
3269:   
3270:                                  valueList.Add(value.GetType().GetProperty("Id").GetValue(value));
3271:                              }
3272:                              else
3273:                              {
3274:                                  valueList.Add(null);
3275:                              }
3276:                          }
3277:                          else valueList.Add(propertyDescriptor.GetValue(d));
3278:                      }
3279:                  }
3280:   
3281:                  dataTable.Rows.Add(valueList.ToArray());
3282:              }
3283:   
3284:              return dataTable;
3285:          }
3286:   
3287:          ////////////////////////////////////////////////////////////////////////////
3288:   
3289:          /// <summary>
3290:          /// 
3291:          /// <see cref="http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable"/>
3292:          /// </summary>
3293:          public static string GenerateTextFromListOfGenericClass<T>(this IList<T> data, string propertyName)
3294:          {
3295:              StringBuilder sb;
3296:              PropertyDescriptor prop;
3297:              PropertyDescriptorCollection props;
3298:   
3299:              sb = new StringBuilder();
3300:              props = TypeDescriptor.GetProperties(typeof(T));
3301:   
3302:              object value;
3303:   
3304:              value = new object();
3305:   
3306:              foreach (T item in data)
3307:              {
3308:                  for (int i = 0; i < props.Count; i++)
3309:                  {
3310:                      prop = props[i];
3311:   
3312:                      if (propertyName == prop.Name) value = props[i].GetValue(item);
3313:                  }
3314:   
3315:                  sb.AppendLine(value.ToString());
3316:              }
3317:   
3318:              return sb.ToString();
3319:          }
3320:   
3321:          ////////////////////////////////////////////////////////////////////////////
3322:   
3323:          /// <summary>
3324:          /// 
3325:          /// <see cref="http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable"/>
3326:          /// </summary>
3327:          public static DataTable GenerateDataTableFromListOfGenericClass<T>(this IList<T> data, params string[] propertyNameList)
3328:          {
3329:              int j;
3330:              DataTable table;
3331:              PropertyDescriptor prop;
3332:              PropertyDescriptorCollection props;
3333:   
3334:              table = new DataTable();
3335:              props = TypeDescriptor.GetProperties(typeof(T));
3336:   
3337:              for (int i = 0; i < props.Count; i++)
3338:              {
3339:                  prop = props[i];
3340:   
3341:                  if (propertyNameList.Contains(prop.Name))
3342:                  {
3343:                      table.Columns.Add(prop.Name, prop.PropertyType);
3344:                  }
3345:              }
3346:   
3347:              object[] values = new object[propertyNameList.Length];
3348:   
3349:              foreach (T item in data)
3350:              {
3351:                  j = 0;
3352:   
3353:                  for (int i = 0; i < props.Count; i++)
3354:                  {
3355:                      prop = props[i];
3356:   
3357:                      if (propertyNameList.Contains(prop.Name))
3358:                      {
3359:                          values[j++] = props[i].GetValue(item);
3360:                      }
3361:                  }
3362:   
3363:                  table.Rows.Add(values);
3364:              }
3365:   
3366:              return table;
3367:          }
3368:   
3369:          ////////////////////////////////////////////////////////////////////////////
3370:   
3371:          /// <summary>
3372:          /// Generate HTML table from DataTable
3373:          /// <see cref="http://stackoverflow.com/questions/19682996/datatable-to-html-table"/>
3374:          /// </summary>
3375:          public static string GenerateHtmlTableFromDataTable(DataTable dataTable)
3376:          {
3377:              StringBuilder sb;
3378:   
3379:              sb = new StringBuilder();
3380:   
3381:              sb.Append("<table>\n");
3382:   
3383:              // header
3384:              sb.Append("<tr>");
3385:   
3386:              for (int i = 0; i < dataTable.Columns.Count; i++) sb.Append("<td>" + dataTable.Columns[i].ColumnName + "</td>");
3387:   
3388:              sb.Append("</tr>");
3389:   
3390:              // row
3391:              for (int i = 0; i < dataTable.Rows.Count; i++)
3392:              {
3393:                  sb.Append("<tr>");
3394:   
3395:                  for (int j = 0; j < dataTable.Columns.Count; j++) sb.Append("<td>" + dataTable.Rows[i][j].ToString() + "</td>");
3396:   
3397:                  sb.Append("</tr>");
3398:              }
3399:   
3400:              sb.Append("</table>");
3401:   
3402:              return sb.ToString();
3403:          }
3404:   
3405:          ////////////////////////////////////////////////////////////////////////////
3406:   
3407:          /// <summary>
3408:          /// Generate tab separated text format from DataTable
3409:          /// </summary>
3410:          public static string GenerateTabSeparatedTextFromDataTable(DataTable dataTable)
3411:          {
3412:              StringBuilder sb;
3413:   
3414:              sb = new StringBuilder();
3415:   
3416:              for (int i = 0; i < dataTable.Columns.Count; i++) sb.Append(dataTable.Columns[i].ColumnName + "\t");
3417:   
3418:              sb.Append("\r\n");
3419:   
3420:              // row
3421:              for (int i = 0; i < dataTable.Rows.Count; i++)
3422:              {
3423:                  for (int j = 0; j < dataTable.Columns.Count; j++) sb.Append(dataTable.Rows[i][j].ToString() + "\t");
3424:   
3425:                  sb.Append("\r\n");
3426:              }
3427:   
3428:              return sb.ToString();
3429:          }
3430:   
3431:          ////////////////////////////////////////////////////////////////////////////
3432:   
3433:          /// <summary>
3434:          /// Generate DataTable from delimited text
3435:          /// </summary>
3436:          public static DataTable GenerateDataTableFromTabDelimitedText(string text, out Result result)
3437:          {
3438:              // this will only read rows that have at least 5 distinct columns
3439:              bool first;
3440:              string line;
3441:              string[] columnList, lineSplit;
3442:              DataTable dataTable;
3443:   
3444:              first = true;
3445:              dataTable = new DataTable();
3446:              result = new Result();
3447:   
3448:              using (StringReader reader = new StringReader(text))
3449:              {
3450:                  while ((line = reader.ReadLine()) != null)
3451:                  {
3452:                      // lineSplit = line.Split((string[])null, StringSplitOptions.None);
3453:                      lineSplit = Regex.Split(line, @"\t", RegexOptions.None);
3454:   
3455:                      if (IsTableHeaderText(line) && first)
3456:                      {
3457:                          columnList = lineSplit;
3458:   
3459:                          foreach (var column in columnList) dataTable.Columns.Add(column);
3460:   
3461:                          first = false;
3462:                      }
3463:                      else if (!first)
3464:                      {
3465:                          if (lineSplit.Length == dataTable.Columns.Count)
3466:                          {
3467:                              dataTable.Rows.Add(lineSplit);
3468:                          }
3469:                          else
3470:                          {
3471:                              result.AddWarning("lineSplit.Length != dataTable.Columns.Count for line: " + line);
3472:                          }
3473:                      }
3474:                      else
3475:                      {
3476:                      }
3477:                  }
3478:              }
3479:   
3480:              return dataTable;
3481:          }
3482:   
3483:          ////////////////////////////////////////////////////////////////////////////
3484:   
3485:          /// <summary>
3486:          /// Examine a string to see if it resembles a table header string
3487:          /// <see cref="https://stackoverflow.com/questions/17812566/count-words-and-spaces-in-string-c-sharp"/>
3488:          /// </summary>
3489:          private static bool IsTableHeaderText(string text)
3490:          {
3491:              bool isHeader;
3492:              int whitespaceCount, wordCount;
3493:              Regex regex = new Regex(@"^[a-zA-Z\s]+$");
3494:   
3495:              if (!string.IsNullOrEmpty(text))
3496:              {
3497:                  text = text.Replace("\t", "     "); // we will replace every tab with 5 spaces
3498:   
3499:                  whitespaceCount = text.Count(Char.IsWhiteSpace);
3500:                  wordCount = CountWordsInText(text);
3501:   
3502:                  // if the whitespace count is bigger than word count is probably a header text string
3503:                  if (whitespaceCount > 2 * wordCount)
3504:                  {
3505:                      if (regex.IsMatch(text)) isHeader = true;
3506:                      else isHeader = false;
3507:                  }
3508:                  else isHeader = false;
3509:              }
3510:              else
3511:              {
3512:                  isHeader = false;
3513:              }
3514:   
3515:              return isHeader;
3516:          }
3517:   
3518:          ////////////////////////////////////////////////////////////////////////////
3519:   
3520:          /// <summary>
3521:          ///
3522:          /// </summary>
3523:          private static int CountWordsInText(string text)
3524:          {
3525:              int wordCount = 0, index = 0;
3526:   
3527:              while (index < text.Length)
3528:              {
3529:                  // check if current char is part of a word
3530:                  while (index < text.Length && !char.IsWhiteSpace(text[index])) index++;
3531:   
3532:                  wordCount++;
3533:   
3534:                  // skip whitespace until next word
3535:                  while (index < text.Length && char.IsWhiteSpace(text[index])) index++;
3536:              }
3537:   
3538:              return wordCount;
3539:          }
3540:   
3541:          ////////////////////////////////////////////////////////////////////////////
3542:   
3543:          /// <summary>
3544:          /// Generate tab separated text format from Dictionary
3545:          /// </summary>
3546:          public static string GenerateTabSeparatedTextFromDictionary(Dictionary<string, int> dictionary)
3547:          {
3548:              StringBuilder sb;
3549:   
3550:              sb = new StringBuilder();
3551:   
3552:              foreach (KeyValuePair<string, int> kvp in dictionary)
3553:              {
3554:                  sb.AppendLine(kvp.Key + "\t" + kvp.Value);
3555:              }
3556:   
3557:              return sb.ToString();
3558:          }
3559:   
3560:          ////////////////////////////////////////////////////////////////////////////
3561:   
3562:          /// <summary>
3563:          /// Generate tab separated text format from SortedDictionary
3564:          /// </summary>
3565:          public static string GenerateTabSeparatedTextFromDictionary(SortedDictionary<string, int> sortedDictionary)
3566:          {
3567:              StringBuilder sb;
3568:   
3569:              sb = new StringBuilder();
3570:   
3571:              foreach (KeyValuePair<string, int> kvp in sortedDictionary)
3572:              {
3573:                  sb.AppendLine(kvp.Key + "\t" + kvp.Value);
3574:              }
3575:   
3576:              return sb.ToString();
3577:          }
3578:   
3579:          ////////////////////////////////////////////////////////////////////////////
3580:   
3581:          /// <summary>
3582:          /// Generate simple two column name value table from DataTable
3583:          /// </summary>
3584:          public static string GenerateTwoColumnNameValueTextFromDataTable(DataTable dataTable)
3585:          {
3586:              StringBuilder sb;
3587:   
3588:              sb = new StringBuilder();
3589:   
3590:              for (int i = 0; i < dataTable.Rows.Count; i++)
3591:              {
3592:                  for (int j = 0; j < dataTable.Columns.Count; j++)
3593:                  {
3594:                      sb.Append(dataTable.Columns[j].ColumnName + ":\t" + dataTable.Rows[i][j].ToString() + "\r\n");
3595:                  }
3596:   
3597:                  sb.Append("\r\n");
3598:              }
3599:   
3600:              return sb.ToString().Trim();
3601:          }
3602:   
3603:          ////////////////////////////////////////////////////////////////////////////
3604:   
3605:          /// <summary>
3606:          /// Remove non-numeric characters
3607:          /// http://stackoverflow.com/questions/3977497/stripping-out-non-numeric-characters-in-string
3608:          /// </summary>
3609:          public static string RemoveNonNumericCharacters(string line)
3610:          {
3611:              string s;
3612:   
3613:              if (line != null && line.Length != 0)
3614:              {
3615:                  s = new string(line.Where(c => char.IsDigit(c)).ToArray());
3616:                  //s = Regex.Replace(line, "[^0-9]", "");
3617:              }
3618:              else s = line;
3619:   
3620:              return s;
3621:          }
3622:   
3623:          ////////////////////////////////////////////////////////////////////////////
3624:   
3625:          /// <summary>
3626:          /// 
3627:          /// <remarks>http://stackoverflow.com/questions/2475795/check-for-missing-number-in-sequence</remarks>
3628:          /// </summary>
3629:          public static List<int> ExcludedNumberListFromNumberListWithinRange(List<int> list, int listSize)
3630:          {
3631:              // Check for missing number in sequence
3632:              List<int> exclusionList;
3633:   
3634:              exclusionList = Enumerable.Range(1, listSize).Except(list).ToList();
3635:   
3636:              return exclusionList;
3637:          }
3638:   
3639:          ////////////////////////////////////////////////////////////////////////////
3640:   
3641:          /// <summary>
3642:          /// 
3643:          /// </summary>
3644:          public static string AutoGeneratedCodeStartCommentString
3645:          {
3646:              get
3647:              {
3648:                  string s;
3649:   
3650:                  s = @"<!-- auto-generated: start -->
3651:  <!-- This section was generated by code. Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. -->
3652:  ";
3653:   
3654:                  return s;
3655:              }
3656:          }
3657:   
3658:          ////////////////////////////////////////////////////////////////////////////
3659:   
3660:          /// <summary>
3661:          /// 
3662:          /// </summary>
3663:          public static string AutoGeneratedCodeEndCommentString
3664:          {
3665:              get
3666:              {
3667:                  string s;
3668:   
3669:                  s = @"<!-- auto-generated: end -->";
3670:   
3671:                  return s;
3672:              }
3673:          }
3674:   
3675:          ////////////////////////////////////////////////////////////////////////////
3676:          ////////////////////////////////////////////////////////////////////////////
3677:      }
3678:   
3679:  #if WINDOWS_FORM
3680:      ////////////////////////////////////////////////////////////////////////////
3681:   
3682:      /// <summary>
3683:      ///
3684:      /// </summary>
3685:      public class ListItem
3686:      {
3687:          // I created this because Windows Forms does not have the equivalent like System.Web ListItem
3688:   
3689:          private string name;
3690:          private string value;
3691:   
3692:          ////////////////////////////////////////////////////////////////////////////
3693:   
3694:          /// <summary>
3695:          ///
3696:          /// </summary>
3697:          public ListItem(string _name, string _value)
3698:          {
3699:              this.name = _name;
3700:              this.value = _value;
3701:          }
3702:   
3703:          ////////////////////////////////////////////////////////////////////////////
3704:   
3705:          /// <summary>
3706:          ///
3707:          /// </summary>
3708:          public string Name
3709:          {
3710:              get
3711:              {
3712:                  return name;
3713:              }
3714:          }
3715:   
3716:          ////////////////////////////////////////////////////////////////////////////
3717:   
3718:          /// <summary>
3719:          ///
3720:          /// </summary>
3721:          public string Value
3722:          {
3723:   
3724:              get
3725:              {
3726:                  return value;
3727:              }
3728:          }
3729:      }
3730:  #else
3731:  #endif
3732:   
3733:      ////////////////////////////////////////////////////////////////////////////
3734:      ////////////////////////////////////////////////////////////////////////////
3735:  }