PageRenderTime 131ms CodeModel.GetById 20ms app.highlight 96ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/PigeonCms.Core/Helpers/Utility.cs

http://pigeoncms.googlecode.com/
C# | 1647 lines | 1335 code | 118 blank | 194 comment | 162 complexity | ec1373aa34e3576925b0b0aa82e4116e MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1using System;
   2using System.Collections.Generic;
   3using System.Configuration;
   4using System.Data;
   5using System.Text;
   6using System.Web;
   7using System.Web.Security;
   8using System.Web.UI;
   9using System.Web.UI.HtmlControls;
  10using System.Web.UI.WebControls;
  11using System.Web.UI.WebControls.WebParts;
  12using System.IO;
  13using System.Web.Routing;
  14using System.Threading;
  15using System.Text.RegularExpressions;
  16using System.Collections.Specialized;
  17using System.Collections;
  18using System.Security.Cryptography;
  19
  20namespace PigeonCms
  21{
  22    /// <summary>
  23    /// Useful static functions
  24    /// </summary>
  25    public static class Utility
  26    {
  27        /// <summary>
  28        /// useful methods to manage to work with html
  29        /// </summary>
  30        public class Html
  31        {
  32            /// <summary>
  33            /// parse textToParse filling existing [[placeholders]] e {{session_vars}}
  34            /// </summary>
  35            /// <param name="textToParse">text to parse</param>
  36            /// <returns>text parsed</returns>
  37            public static string FillPlaceholders(string textToParse)
  38            {
  39                string key = "";
  40                string value = "";
  41
  42                if (!string.IsNullOrEmpty(textToParse))
  43                {
  44                    //fill placeholders
  45                    //ex: [[yourname]] --> nicola
  46                    Regex regPlace = new Regex("(\\[\\[[a-zA-Z_][a-zA-Z0-9_]+\\]\\])");
  47                    string[] placeholderTags;
  48                    placeholderTags = regPlace.Split(textToParse);
  49
  50                    for (int i = 0; i < placeholderTags.Length; i++)
  51                    {
  52                        key = placeholderTags[i];
  53                        if (key.StartsWith("[[") && key.EndsWith("]]"))
  54                        {
  55                            key = key.Remove(0, 2);
  56                            key = key.Remove(key.Length - 2);
  57                            value = "";
  58                            Placeholder ph1 = new PlaceholdersManager().GetByName(key);
  59                            if (ph1.Visible)
  60                            {
  61                                value = ph1.Content;
  62                            }
  63
  64                            Regex r1 = new Regex("(\\[\\[" + key + "\\]\\])");
  65                            textToParse = r1.Replace(textToParse, value);
  66                        }
  67                    }
  68
  69                    //fill session vars
  70                    //ex: {{yourname}} --> session["yourname"] --> nicola
  71                    Regex regSessions = new Regex("(\\{\\{[a-zA-Z_][a-zA-Z0-9_]+\\}\\})");
  72                    string[] sessionTags;
  73                    sessionTags = regSessions.Split(textToParse);
  74
  75                    for (int i = 0; i < sessionTags.Length; i++)
  76                    {
  77                        key = sessionTags[i];
  78                        if (key.StartsWith("{{") && key.EndsWith("}}"))
  79                        {
  80                            key = key.Remove(0, 2);
  81                            key = key.Remove(key.Length - 2);
  82                            value = "";
  83                            if (HttpContext.Current.Session[key] != null)
  84                                value = HttpContext.Current.Session[key].ToString();
  85
  86                            Regex r1 = new Regex("(\\{\\{" + key + "\\}\\})");
  87                            textToParse = r1.Replace(textToParse, value);
  88                        }
  89                    }
  90
  91                    //parse special chars
  92                    //ex: \[\]\{\} --> []{}
  93                    textToParse = textToParse.Replace("\\[", "[");
  94                    textToParse = textToParse.Replace("\\]", "]");
  95                    textToParse = textToParse.Replace("\\{", "{");
  96                    textToParse = textToParse.Replace("\\}", "}");
  97                }
  98                return textToParse;
  99            }
 100
 101            /// <summary>
 102            /// create a text preview
 103            /// </summary>
 104            /// <param name="theText">the text to preview</param>
 105            /// <param name="charNo">num of chars in result string. 
 106            /// 0: no preview
 107            /// -1: empty result
 108            /// >0: return the text preview</param>
 109            /// <param name="textEtcetera">default: ...</param>
 110            /// <param name="removeTags">chenage theText in plain text, removing all html tags</param>
 111            /// <returns>the preview text</returns>
 112            public static string GetTextPreview(string theText, int charNo, string textEtcetera, bool removeTags)
 113            {
 114                const int MAX_EXTRALEN = 5;
 115                string res = "";
 116                if (textEtcetera == "")
 117                    textEtcetera = "...";
 118
 119                if (!string.IsNullOrEmpty(theText))
 120                    res = theText;
 121
 122                if (charNo > 0)
 123                {
 124                    if (removeTags)
 125                        res = Html.StripTagsCharArray(res);
 126
 127                    int i = charNo;
 128                    char c = ' ';
 129                    while (i < res.Length)
 130                    {
 131                        c = res[i];
 132                        if (res[i] == ' ' || i == charNo + MAX_EXTRALEN)
 133                        {
 134                            res = res.Substring(0, i) + textEtcetera;
 135                            break;
 136                        }
 137                        i++;
 138                    }
 139                }
 140                else if (charNo == -1)
 141                {
 142                    res = "";
 143                }
 144                else if (charNo == 0)
 145                { }
 146                return res;
 147            }
 148
 149            public static string GetTextPreview(string theText, int charNo, string textEtcetera)
 150            {
 151                return GetTextPreview(theText, charNo, textEtcetera, true);
 152            }
 153
 154            /// <summary>
 155            /// returns the text until readmore system tag
 156            /// if tag does not exist returns empty text
 157            /// </summary>
 158            /// <param name="theText">the text to parse</param>
 159            /// <returns></returns>
 160            public static string GetTextIntro(string theText)
 161            {
 162                string res = "";
 163                int readMoreIndex = theText.LastIndexOf(ContentEditorProvider.SystemReadMoreTag);
 164                if (readMoreIndex > 0)
 165                    res = theText.Substring(0, readMoreIndex);
 166                return res;
 167                //TODO: close not closed tags if any, 
 168                //see http://www.kad1r.com/article.aspx?articleId=190&Category=ASP.Net&title=Read-more-or-continue-reading-function-in-Asp.net
 169            }
 170
 171            /// <summary>
 172            /// rempove the system tags before render the text on browser
 173            /// </summary>
 174            /// <param name="theText"></param>
 175            /// <returns>the clean text</returns>
 176            public static string RemoveSystemTags(string theText)
 177            {
 178                string res = theText;
 179                if (!string.IsNullOrEmpty(res))
 180                {
 181                    res = res.Replace(ContentEditorProvider.SystemReadMoreTag, "");
 182                    res = res.Replace(ContentEditorProvider.SystemPagebreakTag, "");
 183                }
 184                return res;
 185            }
 186
 187            /// <summary>
 188            /// Remove HTML from string with Regex.
 189            /// speed: 1(slow)
 190            /// see url: http://dotnetperls.com/remove-html-tags
 191            /// see url: http://dotnetperls.com/xhtml-validator
 192            /// </summary>
 193            public static string StripTagsRegex(string source)
 194            {
 195                return Regex.Replace(source, "<.*?>", string.Empty);
 196            }
 197
 198            /// <summary>
 199            /// Compiled regular expression for performance.
 200            /// </summary>
 201            static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
 202
 203            /// <summary>
 204            /// Remove HTML from string with compiled Regex.
 205            /// speed: 2(medium)
 206            /// see url: http://dotnetperls.com/remove-html-tags
 207            /// see url: http://dotnetperls.com/xhtml-validator
 208            /// </summary>
 209            public static string StripTagsRegexCompiled(string source)
 210            {
 211                return _htmlRegex.Replace(source, string.Empty);
 212            }
 213
 214            /// <summary>
 215            /// Remove HTML tags from string using char array.
 216            /// speed: 3(fast)
 217            /// see url: http://dotnetperls.com/remove-html-tags
 218            /// see url: http://dotnetperls.com/xhtml-validator
 219            /// </summary>
 220            public static string StripTagsCharArray(string source)
 221            {
 222                char[] array = new char[source.Length];
 223                int arrayIndex = 0;
 224                bool inside = false;
 225
 226                for (int i = 0; i < source.Length; i++)
 227                {
 228                    char let = source[i];
 229                    if (let == '<')
 230                    {
 231                        inside = true;
 232                        continue;
 233                    }
 234                    if (let == '>')
 235                    {
 236                        inside = false;
 237                        continue;
 238                    }
 239                    if (!inside)
 240                    {
 241                        array[arrayIndex] = let;
 242                        arrayIndex++;
 243                    }
 244                }
 245                return new string(array, 0, arrayIndex);
 246            }
 247
 248            /// <summary>
 249            /// Whether the HTML is likely valid. Error parameter will be empty
 250            /// if no errors were found.
 251            /// </summary>
 252            static public void CheckHtml(string html, out string error)
 253            {
 254                // Store our tags in a stack
 255                Stack<string> tags = new Stack<string>();
 256
 257                // Initialize out parameter to empty
 258                error = string.Empty;
 259
 260                // Count of parenthesis
 261                int parenthesisR = 0;
 262                int parenthesisL = 0;
 263
 264                // Traverse entire HTML
 265                for (int i = 0; i < html.Length; i++)
 266                {
 267                    char c = html[i];
 268                    if (c == '<')
 269                    {
 270                        bool isClose;
 271                        bool isSolo;
 272
 273                        // Look ahead at this tag
 274                        string tag = lookAhead(html, i, out isClose, out isSolo);
 275
 276                        // Make sure tag is lowercase
 277                        if (tag.ToLower() != tag)
 278                        {
 279                            error = "upper: " + tag;
 280                            return;
 281                        }
 282
 283                        // Make sure solo tags are parsed as solo tags
 284                        if (_soloTags.ContainsKey(tag))
 285                        {
 286                            if (!isSolo)
 287                            {
 288                                error = "!solo: " + tag;
 289                                return;
 290                            }
 291                        }
 292                        else
 293                        {
 294                            // We are on a regular end or start tag
 295                            if (isClose)
 296                            {
 297                                // We can't close a tag that isn't on the stack
 298                                if (tags.Count == 0)
 299                                {
 300                                    error = "closing: " + tag;
 301                                    return;
 302                                }
 303
 304                                // Tag on stack must be equal to this closing tag
 305                                if (tags.Peek() == tag)
 306                                {
 307                                    // Remove the start tag from the stack
 308                                    tags.Pop();
 309                                }
 310                                else
 311                                {
 312                                    // Mismatched closing tag
 313                                    error = "!match: " + tag;
 314                                    return;
 315                                }
 316                            }
 317                            else
 318                            {
 319                                // Add tag to stack
 320                                tags.Push(tag);
 321                            }
 322                        }
 323                        i += tag.Length;
 324                    }
 325                    else if (c == '&')
 326                    {
 327                        // & must never be followed by space or other &
 328                        if ((i + 1) < html.Length)
 329                        {
 330                            char next = html[i + 1];
 331
 332                            if (char.IsWhiteSpace(next) ||
 333                                next == '&')
 334                            {
 335                                error = "ampersand";
 336                                return;
 337                            }
 338                        }
 339                    }
 340                    else if (c == '\t')
 341                    {
 342                        error = "tab";
 343                        return;
 344                    }
 345                    else if (c == '(')
 346                    {
 347                        parenthesisL++;
 348                    }
 349                    else if (c == ')')
 350                    {
 351                        parenthesisR++;
 352                    }
 353                }
 354
 355                // If we have tags in the stack, write them to error
 356                foreach (string tagName in tags)
 357                {
 358                    error += "extra:" + tagName + " ";
 359                }
 360
 361                // Require even number of parenthesis
 362                if (parenthesisL != parenthesisR)
 363                {
 364                    error = "!even ";
 365                }
 366            }
 367
 368            /// <summary>
 369            /// Called at the start of an html tag. We look forward and record information
 370            /// about our tag. Handles start tags, close tags, and solo tags. 'Collects'
 371            /// an entire tag.
 372            /// </summary>
 373            /// <returns>Tag name.</returns>
 374            static private string lookAhead(string html, int start, out bool isClose,
 375                out bool isSolo)
 376            {
 377                isClose = false;
 378                isSolo = false;
 379
 380                StringBuilder tagName = new StringBuilder();
 381                int slashPos = -1;      // Stores the position of the final slash
 382                bool space = false;     // Whether we have encountered a space
 383                bool quote = false;     // Whether we are in a quote
 384
 385                // Begin scanning the tag
 386                int i;
 387                for (i = 0; ; i++)
 388                {
 389                    // Get the position in main html
 390                    int pos = start + i;
 391
 392                    // Don't go outside the html
 393                    if (pos >= html.Length)
 394                    {
 395                        return "x";
 396                    }
 397
 398                    // The character we are looking at
 399                    char c = html[pos];
 400
 401                    // See if a space has been encountered
 402                    if (char.IsWhiteSpace(c))
 403                    {
 404                        space = true;
 405                    }
 406
 407                    // Add to our tag name if none of these are present
 408                    if (space == false &&
 409                        c != '<' &&
 410                        c != '>' &&
 411                        c != '/')
 412                    {
 413                        tagName.Append(c);
 414                    }
 415
 416                    // Record position of slash if not inside a quoted area
 417                    if (c == '/' &&
 418                        quote == false)
 419                    {
 420                        slashPos = i;
 421                    }
 422
 423                    // End at the > bracket
 424                    if (c == '>')
 425                    {
 426                        break;
 427                    }
 428
 429                    // Record whether we are in a quoted area
 430                    if (c == '\"')
 431                    {
 432                        quote = !quote;
 433                    }
 434                }
 435
 436                // Determine if this is a solo or closing tag
 437                if (slashPos != -1)
 438                {
 439                    // If slash is at the end so this is solo
 440                    if (slashPos + 1 == i)
 441                    {
 442                        isSolo = true;
 443                    }
 444                    else
 445                    {
 446                        isClose = true;
 447                    }
 448                }
 449
 450                // Return the name of the tag collected
 451                string name = tagName.ToString();
 452                if (name.Length == 0)
 453                {
 454                    return "empty";
 455                }
 456                else
 457                {
 458                    return name;
 459                }
 460            }
 461
 462            /// <summary>
 463            /// Tags that must be closed in the start
 464            /// </summary>
 465            static Dictionary<string, bool> _soloTags = new Dictionary<string, bool>() 
 466            { 
 467                {"img", true},{"br", true} 
 468            };
 469        }
 470
 471        /// <summary>
 472        /// useful methods for mobile devices
 473        /// </summary>
 474        public class Mobile
 475        {
 476            public enum DeviceTypeEnum
 477            {
 478                Android,
 479                Iphone,
 480                Ipad,
 481                Kindle,
 482                Blackbarry,
 483                Unknown
 484            }
 485
 486            public static bool IsMobileDevice(HttpContext ctx)
 487            {
 488                string userAgent = ctx.Request.UserAgent.ToLower();
 489
 490                if (userAgent.Contains("blackberry")
 491                      || userAgent.Contains("iphone")
 492                      || userAgent.Contains("ipad")
 493                      || userAgent.Contains("kindle")
 494                      || userAgent.Contains("android"))
 495                    return true;
 496
 497                return ctx.Request.Browser.IsMobileDevice;
 498            }
 499
 500            public static DeviceTypeEnum DeviceType(HttpContext ctx)
 501            {
 502                DeviceTypeEnum res = DeviceTypeEnum.Unknown;
 503                string userAgent = ctx.Request.UserAgent.ToLower();
 504                switch (userAgent)
 505                {
 506                    case "android":
 507                        res = DeviceTypeEnum.Android;
 508                        break;
 509                    case "blackberry":
 510                        res = DeviceTypeEnum.Blackbarry;
 511                        break;
 512                    case "iphone":
 513                        res = DeviceTypeEnum.Iphone;
 514                        break;
 515                    case "ipad":
 516                        res = DeviceTypeEnum.Ipad;
 517                        break;
 518                    case "kindle":
 519                        res = DeviceTypeEnum.Kindle;
 520                        break;
 521                }
 522                return res;
 523            }
 524        }
 525
 526        /// <summary>
 527        /// useful methods to manage js scripts
 528        /// </summary>
 529        public class Script
 530        {
 531            public static void RegisterClientScriptBlock(Control control, string key, string script)
 532            {
 533                RegisterClientScriptBlock(control, key, script, true);
 534            }
 535
 536            public static void RegisterClientScriptBlock(Control control, string key, string script, bool addScriptTags)
 537            {
 538                ScriptManager.RegisterClientScriptBlock(control, typeof(bool)/*GetType()*/, key, script, addScriptTags);
 539            }
 540
 541            public static void RegisterClientScriptInclude(Control control, string key, string url)
 542            {
 543                ScriptManager.RegisterClientScriptInclude(control, typeof(bool)/*GetType()*/, key, url);
 544            }
 545
 546            public static void RegisterClientScriptInclude(Page page, string key, string url)
 547            {
 548                ScriptManager.RegisterClientScriptInclude(page, typeof(bool)/*GetType()*/, key, url);
 549            }
 550
 551            public static void RegisterStartupScript(Control control, string key, string script)
 552            {
 553                RegisterStartupScript(control, key, script, true);
 554            }
 555
 556            public static void RegisterStartupScript(Control control, string key, string script, bool addScriptTags)
 557            {
 558                ScriptManager.RegisterStartupScript(control, typeof(bool), key, script, addScriptTags);
 559            }
 560
 561            /// <summary>
 562            /// Encodes a string to be represented as a string literal. The format
 563            /// is essentially a JSON string.
 564            /// The string returned includes outer quotes 
 565            /// Example Output: "Hello \"Rick\"!\r\nRock on"
 566            /// </summary>
 567            /// <param name="s"></param>
 568            /// <returns></returns>
 569            public static string EncodeJsString(string s)
 570            {
 571                StringBuilder sb = new StringBuilder();
 572                //sb.Append("\"");
 573
 574                if (!string.IsNullOrEmpty(s))
 575                {
 576                    foreach (char c in s)
 577                    {
 578                        switch (c)
 579                        {
 580                            case '\"':
 581                                sb.Append("\\\"");
 582                                break;
 583                            case '\'':
 584                                sb.Append("\\\'");
 585                                break;
 586                            case '\\':
 587                                sb.Append("\\\\");
 588                                break;
 589                            case '\b':
 590                                sb.Append("\\b");
 591                                break;
 592                            case '\f':
 593                                sb.Append("\\f");
 594                                break;
 595                            case '\n':
 596                                sb.Append("\\n");
 597                                break;
 598                            case '\r':
 599                                sb.Append("\\r");
 600                                break;
 601                            case '\t':
 602                                sb.Append("\\t");
 603                                break;
 604                            default:
 605                                int i = (int)c;
 606                                if (i < 32 || i > 127)
 607                                {
 608                                    sb.AppendFormat("\\u{0:X04}", i);
 609                                }
 610                                else
 611                                {
 612                                    sb.Append(c);
 613                                }
 614                                break;
 615                        }
 616                    }
 617                }
 618                //sb.Append("\"");
 619
 620                return sb.ToString();
 621            }
 622        }
 623
 624        /// <summary>
 625        /// useful crypt decript methods
 626        /// </summary>
 627        public class Encryption
 628        {
 629            public static string Decrypt(string textToDecrypt, string key)
 630            {
 631                RijndaelManaged rijndaelCipher = new RijndaelManaged(); //AES
 632                rijndaelCipher.Mode = CipherMode.CBC;
 633                rijndaelCipher.Padding = PaddingMode.PKCS7;
 634
 635                rijndaelCipher.KeySize = 0x80;
 636                rijndaelCipher.BlockSize = 0x80;
 637                byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
 638                byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
 639                byte[] keyBytes = new byte[0x10];
 640                int len = pwdBytes.Length;
 641                if (len > keyBytes.Length)
 642                {
 643                    len = keyBytes.Length;
 644                }
 645                Array.Copy(pwdBytes, keyBytes, len);
 646                rijndaelCipher.Key = keyBytes;
 647                rijndaelCipher.IV = keyBytes;
 648                byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
 649                return Encoding.UTF8.GetString(plainText);
 650            }
 651
 652            public static string Encrypt(string textToEncrypt, string key)
 653            {
 654                RijndaelManaged rijndaelCipher = new RijndaelManaged();
 655                rijndaelCipher.Mode = CipherMode.CBC;
 656                rijndaelCipher.Padding = PaddingMode.PKCS7;
 657
 658                rijndaelCipher.KeySize = 0x80;
 659                rijndaelCipher.BlockSize = 0x80;
 660                byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
 661                byte[] keyBytes = new byte[0x10];
 662                int len = pwdBytes.Length;
 663                if (len > keyBytes.Length)
 664                {
 665                    len = keyBytes.Length;
 666                }
 667                Array.Copy(pwdBytes, keyBytes, len);
 668                rijndaelCipher.Key = keyBytes;
 669                rijndaelCipher.IV = keyBytes;
 670                ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
 671                byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
 672                return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
 673            }
 674        }
 675
 676        public class StaticData
 677        {
 678            public static Dictionary<string, string> Nations
 679            {
 680                get
 681                {
 682                    var list = new Dictionary<string, string>();
 683                    list.Add("IT", "Italy");
 684                    list.Add("AF", "Afghanistan");
 685                    list.Add("AL", "Albania");
 686                    list.Add("DZ", "Algeria");
 687                    list.Add("AS", "American Samoa");
 688                    list.Add("AD", "Andorra");
 689                    list.Add("AO", "Angola");
 690                    list.Add("AI", "Anguilla");
 691                    list.Add("AQ", "Antarctica");
 692                    list.Add("AG", "Antigua And Barbuda");
 693                    list.Add("AR", "Argentina");
 694                    list.Add("AM", "Armenia");
 695                    list.Add("AW", "Aruba");
 696                    list.Add("AU", "Australia");
 697                    list.Add("AT", "Austria");
 698                    list.Add("AZ", "Azerbaijan");
 699                    list.Add("BS", "Bahamas");
 700                    list.Add("BH", "Bahrain");
 701                    list.Add("BD", "Bangladesh");
 702                    list.Add("BB", "Barbados");
 703                    list.Add("BY", "Belarus");
 704                    list.Add("BE", "Belgium");
 705                    list.Add("BZ", "Belize");
 706                    list.Add("BJ", "Benin");
 707                    list.Add("BM", "Bermuda");
 708                    list.Add("BT", "Bhutan");
 709                    list.Add("BO", "Bolivia, Plurinational State Of");
 710                    list.Add("BA", "Bosnia And Herzegovina");
 711                    list.Add("BW", "Botswana");
 712                    list.Add("BV", "Bouvet Island");
 713                    list.Add("BR", "Brazil");
 714                    list.Add("IO", "British Indian Ocean Territory");
 715                    list.Add("BN", "Brunei Darussalam");
 716                    list.Add("BG", "Bulgaria");
 717                    list.Add("BF", "Burkina Faso");
 718                    list.Add("BI", "Burundi");
 719                    list.Add("KH", "Cambodia");
 720                    list.Add("CM", "Cameroon");
 721                    list.Add("CA", "Canada");
 722                    list.Add("CV", "Cape Verde");
 723                    list.Add("KY", "Cayman Islands");
 724                    list.Add("CF", "Central African Republic");
 725                    list.Add("TD", "Chad");
 726                    list.Add("CL", "Chile");
 727                    list.Add("CN", "China");
 728                    list.Add("CX", "Christmas Island");
 729                    list.Add("CC", "Cocos (Keeling) Islands");
 730                    list.Add("CO", "Colombia");
 731                    list.Add("KM", "Comoros");
 732                    list.Add("CG", "Congo");
 733                    list.Add("CD", "Congo, The Democratic Republic Of The");
 734                    list.Add("CK", "Cook Islands");
 735                    list.Add("CR", "Costa Rica");
 736                    list.Add("CI", "Côte D'Ivoire");
 737                    list.Add("HR", "Croatia");
 738                    list.Add("CU", "Cuba");
 739                    list.Add("CY", "Cyprus");
 740                    list.Add("CZ", "Czech Republic");
 741                    list.Add("DK", "Denmark");
 742                    list.Add("DJ", "Djibouti");
 743                    list.Add("DM", "Dominica");
 744                    list.Add("DO", "Dominican Republic");
 745                    list.Add("EC", "Ecuador");
 746                    list.Add("EG", "Egypt");
 747                    list.Add("SV", "El Salvador");
 748                    list.Add("GQ", "Equatorial Guinea");
 749                    list.Add("ER", "Eritrea");
 750                    list.Add("EE", "Estonia");
 751                    list.Add("ET", "Ethiopia");
 752                    list.Add("FK", "Falkland Islands (Malvinas)");
 753                    list.Add("FO", "Faroe Islands");
 754                    list.Add("FJ", "Fiji");
 755                    list.Add("FI", "Finland");
 756                    list.Add("FR", "France");
 757                    list.Add("GF", "French Guiana");
 758                    list.Add("PF", "French Polynesia");
 759                    list.Add("TF", "French Southern Territories");
 760                    list.Add("GA", "Gabon");
 761                    list.Add("GM", "Gambia");
 762                    list.Add("GE", "Georgia");
 763                    list.Add("DE", "Germany");
 764                    list.Add("GH", "Ghana");
 765                    list.Add("GI", "Gibraltar");
 766                    list.Add("GR", "Greece");
 767                    list.Add("GL", "Greenland");
 768                    list.Add("GD", "Grenada");
 769                    list.Add("GP", "Guadeloupe");
 770                    list.Add("GU", "Guam");
 771                    list.Add("GT", "Guatemala");
 772                    list.Add("GG", "Guernsey");
 773                    list.Add("GN", "Guinea");
 774                    list.Add("GW", "Guinea-Bissau");
 775                    list.Add("GY", "Guyana");
 776                    list.Add("HT", "Haiti");
 777                    list.Add("HM", "Heard Island And Mcdonald Islands");
 778                    list.Add("HN", "Honduras");
 779                    list.Add("HK", "Hong Kong");
 780                    list.Add("HU", "Hungary");
 781                    list.Add("IS", "Iceland");
 782                    list.Add("IN", "India");
 783                    list.Add("ID", "Indonesia");
 784                    list.Add("IR", "Iran, Islamic Republic Of");
 785                    list.Add("IQ", "Iraq");
 786                    list.Add("IE", "Ireland");
 787                    list.Add("IM", "Isle Of Man");
 788                    list.Add("IL", "Israel");
 789                    list.Add("JM", "Jamaica");
 790                    list.Add("JP", "Japan");
 791                    list.Add("JE", "Jersey");
 792                    list.Add("JO", "Jordan");
 793                    list.Add("KZ", "Kazakhstan");
 794                    list.Add("KE", "Kenya");
 795                    list.Add("KI", "Kiribati");
 796                    list.Add("KP", "Korea, Democratic People's Republic Of");
 797                    list.Add("KR", "Korea, Republic Of");
 798                    list.Add("KW", "Kuwait");
 799                    list.Add("KG", "Kyrgyzstan");
 800                    list.Add("LA", "Lao People's Democratic Republic");
 801                    list.Add("LV", "Latvia");
 802                    list.Add("LB", "Lebanon");
 803                    list.Add("LS", "Lesotho");
 804                    list.Add("LR", "Liberia");
 805                    list.Add("LY", "Libyan Arab Jamahiriya");
 806                    list.Add("LI", "Liechtenstein");
 807                    list.Add("LT", "Lithuania");
 808                    list.Add("LU", "Luxembourg");
 809                    list.Add("MO", "Macao");
 810                    list.Add("MK", "Macedonia, The Former Yugoslav Republic Of");
 811                    list.Add("MG", "Madagascar");
 812                    list.Add("MW", "Malawi");
 813                    list.Add("MY", "Malaysia");
 814                    list.Add("MV", "Maldives");
 815                    list.Add("ML", "Mali");
 816                    list.Add("MT", "Malta");
 817                    list.Add("MH", "Marshall Islands");
 818                    list.Add("MQ", "Martinique");
 819                    list.Add("MR", "Mauritania");
 820                    list.Add("MU", "Mauritius");
 821                    list.Add("YT", "Mayotte");
 822                    list.Add("MX", "Mexico");
 823                    list.Add("FM", "Micronesia, Federated States Of");
 824                    list.Add("MD", "Moldova, Republic Of");
 825                    list.Add("MC", "Monaco");
 826                    list.Add("MN", "Mongolia");
 827                    list.Add("ME", "Montenegro");
 828                    list.Add("MS", "Montserrat");
 829                    list.Add("MA", "Morocco");
 830                    list.Add("MZ", "Mozambique");
 831                    list.Add("MM", "Myanmar");
 832                    list.Add("NA", "Namibia");
 833                    list.Add("NR", "Nauru");
 834                    list.Add("NP", "Nepal");
 835                    list.Add("NL", "Netherlands");
 836                    list.Add("AN", "Netherlands Antilles");
 837                    list.Add("NC", "New Caledonia");
 838                    list.Add("NZ", "New Zealand");
 839                    list.Add("NI", "Nicaragua");
 840                    list.Add("NE", "Niger");
 841                    list.Add("NG", "Nigeria");
 842                    list.Add("NU", "Niue");
 843                    list.Add("NF", "Norfolk Island");
 844                    list.Add("MP", "Northern Mariana Islands");
 845                    list.Add("NO", "Norway");
 846                    list.Add("OM", "Oman");
 847                    list.Add("PK", "Pakistan");
 848                    list.Add("PW", "Palau");
 849                    list.Add("PS", "Palestinian Territory, Occupied");
 850                    list.Add("PA", "Panama");
 851                    list.Add("PG", "Papua New Guinea");
 852                    list.Add("PY", "Paraguay");
 853                    list.Add("PE", "Peru");
 854                    list.Add("PH", "Philippines");
 855                    list.Add("PN", "Pitcairn");
 856                    list.Add("PL", "Poland");
 857                    list.Add("PT", "Portugal");
 858                    list.Add("PR", "Puerto Rico");
 859                    list.Add("QA", "Qatar");
 860                    list.Add("RE", "Réunion");
 861                    list.Add("RO", "Romania");
 862                    list.Add("RU", "Russian Federation");
 863                    list.Add("RW", "Rwanda");
 864                    list.Add("BL", "Saint Barthélemy");
 865                    list.Add("SH", "Saint Helena, Ascension And Tristan Da Cunha");
 866                    list.Add("KN", "Saint Kitts And Nevis");
 867                    list.Add("LC", "Saint Lucia");
 868                    list.Add("MF", "Saint Martin");
 869                    list.Add("PM", "Saint Pierre And Miquelon");
 870                    list.Add("VC", "Saint Vincent And The Grenadines");
 871                    list.Add("WS", "Samoa");
 872                    list.Add("SM", "San Marino");
 873                    list.Add("ST", "Sao Tome And Principe");
 874                    list.Add("SA", "Saudi Arabia");
 875                    list.Add("SN", "Senegal");
 876                    list.Add("RS", "Serbia");
 877                    list.Add("SC", "Seychelles");
 878                    list.Add("SL", "Sierra Leone");
 879                    list.Add("SG", "Singapore");
 880                    list.Add("SK", "Slovakia");
 881                    list.Add("SI", "Slovenia");
 882                    list.Add("SB", "Solomon Islands");
 883                    list.Add("SO", "Somalia");
 884                    list.Add("ZA", "South Africa");
 885                    list.Add("GS", "South Georgia And The South Sandwich Islands");
 886                    list.Add("ES", "Spain");
 887                    list.Add("LK", "Sri Lanka");
 888                    list.Add("SD", "Sudan");
 889                    list.Add("SR", "Suriname");
 890                    list.Add("SJ", "Svalbard And Jan Mayen");
 891                    list.Add("SZ", "Swaziland");
 892                    list.Add("SE", "Sweden");
 893                    list.Add("CH", "Switzerland");
 894                    list.Add("SY", "Syrian Arab Republic");
 895                    list.Add("TW", "Taiwan, Province Of China");
 896                    list.Add("TJ", "Tajikistan");
 897                    list.Add("TZ", "Tanzania, United Republic Of");
 898                    list.Add("TH", "Thailand");
 899                    list.Add("TL", "Timor-Leste");
 900                    list.Add("TG", "Togo");
 901                    list.Add("TK", "Tokelau");
 902                    list.Add("TO", "Tonga");
 903                    list.Add("TT", "Trinidad And Tobago");
 904                    list.Add("TN", "Tunisia");
 905                    list.Add("TR", "Turkey");
 906                    list.Add("TM", "Turkmenistan");
 907                    list.Add("TC", "Turks And Caicos Islands");
 908                    list.Add("TV", "Tuvalu");
 909                    list.Add("UG", "Uganda");
 910                    list.Add("UA", "Ukraine");
 911                    list.Add("AE", "United Arab Emirates");
 912                    list.Add("GB", "United Kingdom");
 913                    list.Add("US", "United States");
 914                    list.Add("UM", "United States Minor Outlying Islands");
 915                    list.Add("UY", "Uruguay");
 916                    list.Add("UZ", "Uzbekistan");
 917                    list.Add("VU", "Vanuatu");
 918                    list.Add("VA", "Vatican City State");
 919                    list.Add("VE", "Venezuela, Bolivarian Republic Of");
 920                    list.Add("VN", "Viet Nam");
 921                    list.Add("VG", "Virgin Islands, British");
 922                    list.Add("VI", "Virgin Islands, U.S.");
 923                    list.Add("WF", "Wallis And Futuna");
 924                    list.Add("EH", "Western Sahara");
 925                    list.Add("YE", "Yemen");
 926                    list.Add("ZM", "Zambia");
 927                    list.Add("ZW ", "Zimbabwe");
 928                    list.Add("AX", "?land Islands");
 929
 930                    return list;
 931                }
 932            }
 933        }
 934
 935        /// <summary>
 936        /// Gets the first day of a week where day (parameter) belongs. weekStart (parameter) specifies the starting day of week.
 937        /// </summary>
 938        /// <returns></returns> 
 939        public static DateTime FirstDayOfWeek(DateTime day, DayOfWeek weekStarts)
 940        {
 941            DateTime d = day;
 942            while (d.DayOfWeek != weekStarts)
 943            {
 944                d = d.AddDays(-1);
 945            }
 946            return d;
 947        }
 948
 949        /// <summary>
 950        /// Add a glyph to the ordered column in a gridview
 951        /// </summary>
 952        /// <example>
 953        ///protected void GridViewProducts_RowCreated(object sender, GridViewRowEventArgs e)
 954        ///{
 955        ///    if (e.Row.RowType == DataControlRowType.Header)
 956        ///        AddGlyph(GridViewProducts, e.Row);
 957        ///}
 958        /// </example>
 959        /// <param name="grid">the GridView</param>
 960        /// <param name="item">the Row</param>
 961        public static void AddGlyph(GridView grid, GridViewRow item)
 962        {
 963            //Label glyph = new Label();
 964            //glyph.EnableTheming = false;
 965            //glyph.Font.Name = "Webdings";
 966            //glyph.Font.Size = FontUnit.XSmall;
 967            //glyph.Font.Bold = true;
 968            //glyph.ForeColor = System.Drawing.Color.DarkGray;
 969            //glyph.Text = (grid.SortDirection == SortDirection.Ascending ? "?" : "?");
 970
 971            Label space = new Label();
 972            space.Text = " ";
 973
 974            Image imgSort = new Image();
 975            imgSort.SkinID = (grid.SortDirection == SortDirection.Ascending ? "ImgSortAsc" : "ImgSortDesc");
 976
 977            for (int i = 0; i < grid.Columns.Count; i++)
 978            {
 979                string colExpr = grid.Columns[i].SortExpression;
 980                if (colExpr != "" && colExpr == grid.SortExpression)
 981                    //item.Cells[i].Controls.Add(space);
 982                    item.Cells[i].Controls.Add(imgSort);
 983            }
 984        }
 985
 986        /// <summary>
 987        /// add onclick script to allow static file tracking
 988        /// </summary>
 989        /// <param name="trackParam">the param in for the script</param>
 990        /// <param name="addScript">false:do nothing</param>
 991        /// <returns></returns>
 992        public static string AddTracking(string trackParam, bool addScript)
 993        {
 994            string res = "";
 995            string currUrl = HttpContext.Current.Request.FilePath + "#";
 996            if (addScript && !string.IsNullOrEmpty(trackParam))
 997                res = " onclick=\"pageTracker._trackPageview('"+ currUrl + trackParam + "');\" ";
 998            return res;
 999        }
1000
1001        /// <summary>
1002        /// add onclick script to allow static file tracking
1003        /// </summary>
1004        /// <param name="trakParams">list of params used to build the param path</param>
1005        /// <param name="addScript">false:do nothing</param>
1006        /// <returns></returns>
1007        public static string AddTracking(string[]trakParams, bool addScript)
1008        {
1009            string res = "";
1010            if (trakParams != null)
1011            {
1012                string path = "";
1013                foreach (string param in trakParams)
1014                {
1015                    if (!string.IsNullOrEmpty(param))
1016                        path += "/" + param;
1017                }
1018                res = AddTracking(path, addScript);
1019            }
1020            return res;
1021        }
1022
1023        /// <summary>
1024        /// transform an url in a valid alias
1025        /// </summary>
1026        /// <param name="url">url or string to sanitize</param>
1027        /// <returns>a valid url</returns>
1028        public static string GetUrlAlias(string url)
1029        {
1030            string res = url.ToLower();
1031            res = res.Replace(" ","-");
1032            res = HttpUtility.UrlEncode(res);
1033            return res;
1034        }
1035
1036        public static string GetCurrCultureName()
1037        {
1038            return Thread.CurrentThread.CurrentCulture.Name;
1039        }
1040
1041        /// <summary>
1042        /// 
1043        /// </summary>
1044        /// <param name="month">the month</param>
1045        /// <returns>month name in current culture</returns>
1046        public static string GetMonthName(int month)
1047        {
1048            string res = "";
1049            string label = "month";
1050            if (month >= 1 && month <= 12)
1051            {
1052                label += month.ToString();
1053                res = GetLabel(label);
1054            }
1055            return res;
1056        }
1057
1058        public static string GetAbsoluteUrl()
1059        {
1060            return GetAbsoluteUrl("");
1061        }
1062
1063        public static string GetAbsoluteUrl(string url)
1064        {
1065            string res = "http://" +
1066                HttpContext.Current.Request.Url.Authority +
1067                HttpContext.Current.Request.ApplicationPath;
1068            if (!res.EndsWith("/")) res += "/";
1069            if (url.StartsWith("/"))
1070                url = url.Substring(1);
1071            res += url;
1072            return res;
1073        }
1074
1075        public static string GetRoutedUrl(Menu menuEntry)
1076        {
1077            return GetRoutedUrl(menuEntry, null, "", true);
1078        }
1079
1080        public static string GetRoutedUrl(Menu menuEntry, string queryString, bool addPagePostFix)
1081        {
1082            return GetRoutedUrl(menuEntry, null, queryString, addPagePostFix);
1083        }
1084
1085        public static string GetRoutedUrl(Menu menuEntry, 
1086            RouteValueDictionary routeValueDictionary, string queryString, bool addPagePostFix)
1087        {
1088            var res = new StringBuilder();
1089
1090            try
1091            {
1092                var defaults = new RouteValueDictionary { { "pagename", menuEntry.Alias.ToLower() } };
1093                if (routeValueDictionary != null)
1094                {
1095                    foreach (var item in routeValueDictionary)
1096                    {
1097                        if (defaults.ContainsKey(item.Key)) 
1098                            defaults.Remove(item.Key);
1099                        defaults.Add(item.Key, item.Value);
1100                    }
1101                }
1102                res = res.Append(
1103                    RouteTable.Routes.GetVirtualPath(
1104                    null, menuEntry.RouteName, defaults).VirtualPath
1105                );
1106                if (addPagePostFix)
1107                    res = res.Append(".aspx");
1108                if (!string.IsNullOrEmpty(queryString))
1109                {
1110                    res = res.Append("?");
1111                    res = res.Append(queryString);
1112                }
1113            }
1114            catch (Exception ex)
1115            {
1116                Tracer.Log("GetRoutedUrl, missing RouteValueDictionary: " + ex.ToString(), TracerItemType.Error);
1117                throw new ArgumentException("missing RouteValueDictionary", ex);
1118            }
1119            return res.ToString();
1120        }
1121
1122        public static string GetThemedImageSrc(string fileName)
1123        {
1124            return GetThemedImageSrc(fileName, "", "");
1125        }
1126
1127        public static string GetThemedImageSrc(string fileName, string pageTheme)
1128        {
1129            return GetThemedImageSrc(fileName, pageTheme, "");
1130        }
1131
1132        /// <summary>
1133        /// get image url for current page theme
1134        /// </summary>
1135        /// <param name="fileName">the image file name</param>
1136        /// <param name="pageTheme">name of theme; "" for current theme</param>
1137        /// <param name="defaultFileName">file to use if filename is not found; "" for no default file</param>
1138        /// <returns>absolute path of the image</returns>
1139        public static string GetThemedImageSrc(string fileName, string pageTheme, string defaultFileName)
1140        {
1141            string res = "";
1142            if (string.IsNullOrEmpty(pageTheme))
1143            {
1144                Page page = (Page)HttpContext.Current.CurrentHandler;
1145                pageTheme = page.Theme;
1146            }
1147            if (!string.IsNullOrEmpty(defaultFileName))
1148            {
1149                if (File.Exists(
1150                    HttpContext.Current.Server.MapPath(
1151                    "~/App_Themes/" + pageTheme + "/Images/" + fileName)))
1152                    res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + fileName;
1153                else
1154                    res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + defaultFileName;
1155            }
1156            else
1157                res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + fileName;
1158
1159            return res;
1160        }
1161
1162        /// <summary>
1163        /// get css url for current page theme
1164        /// </summary>
1165        /// <param name="fileName">the css file name</param>
1166        /// <returns></returns>
1167        public static string GetThemedCssSrc(string fileName)
1168        {
1169            Page page = (Page)HttpContext.Current.CurrentHandler;
1170            return GetThemedCssSrc(fileName, page.Theme);
1171        }
1172
1173        public static string GetThemedCssSrc(string fileName, string pageTheme)
1174        {
1175            string res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme /*Config.CurrentTheme*/ + "/" + fileName;
1176            return res;
1177        }
1178
1179        public static string GetLabel(string stringKey)
1180        {
1181            string res = "";
1182            if (HttpContext.GetGlobalResourceObject("PublicLabels", stringKey) != null)
1183                res = HttpContext.GetGlobalResourceObject("PublicLabels", stringKey).ToString();
1184            //if (Resources.AdminLabels.ResourceManager.GetString(stringKey) != null)
1185            //    res = Resources.AdminLabels.ResourceManager.GetString(stringKey);
1186            
1187            return res;
1188        }
1189
1190        public static string GetLabel(string stringKey, string defaultValue)
1191        {
1192            string res = GetLabel(stringKey);
1193            if (res == "")
1194                res = defaultValue;
1195            return res;
1196        }
1197
1198        public static string GetLabel(string stringKey, string defaultValue, Control targetControl)
1199        {
1200            return GetLabel(stringKey, defaultValue, targetControl, "");
1201        }
1202
1203        public static string GetLabel(string stringKey, string defaultValue, Control targetControl, string title)
1204        {
1205            if (!string.IsNullOrEmpty(title))
1206                title = "title='" + title + "'";
1207            string clientID = "";
1208            if (targetControl != null)
1209                clientID = targetControl.ClientID;
1210
1211            string res = GetLabel(stringKey, defaultValue);
1212            res = "<label for='" + clientID + "' " + title + ">" + res + "</label>";
1213       

Large files files are truncated, but you can click here to view the full file