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

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