)>}]
شركة التطبيقات المتكاملة لتصميم وبرمجة البرمجيات الخاصة ش.ش.و.
Integrated Applications Programming Company
Skip Navigation LinksHome » Code Library » Default

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

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

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