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

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