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

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

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

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