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

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

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

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