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

Integrated Applications Programming Company

Skip Navigation LinksHome » Code Library » Default

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

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

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