شركة التطبيقات المتكاملة لتصميم النظم البرمجية الخاصة ش.ش.و.

Integrated Applications Programming Company

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