context: /* Author: David Carroll
   * Copyright (c) 2008, 2009 Bellevue Baptist Church
   * Licensed under the GNU General Public License (GPL v2)
   * you may not use this code except in compliance with the License.
   * You may obtain a copy of the License at http://bvcms.codeplex.com/license
   */
  
  using System;
  using System.Collections;
  using System.Collections.Generic;
  using System.Configuration;
  using System.Drawing;
  using System.Globalization;
  using System.IO;
  using System.Linq;
  using System.Linq.Expressions;
  using System.Text;
  using System.Text.RegularExpressions;
  using System.Web;
  using System.Web.Hosting;
  using System.Web.Mvc;
  using System.Web.Mvc.Html;
  using System.Web.Routing;
  using System.Web.Script.Serialization;
  using CmsData;
  using CmsWeb.Areas.OnlineReg.Models;
  using CmsWeb.Code;
  using Elmah;
  using MarkdownDeep;
  using OfficeOpenXml;
  using OfficeOpenXml.Style;
  using UtilityExtensions;
  using System.ComponentModel;
  
  namespace CmsWeb
  {
      public enum ListType
      {
          Ordered,
          Unordered,
          TableCell
      }
  
      public static class ModelStateDictionaryExtensions
      {
          public static void SetModelValue(this ModelStateDictionary modelState, string key, object rawValue)
          {
              modelState.SetModelValue(key, new ValueProviderResult(rawValue, string.Empty, CultureInfo.InvariantCulture));
          }
      }
  
      public static class ViewExtensions2
      {
          public static string jqueryGlobalizeCulture
          {
              get
              {
                  //Determine culture - GUI culture for preference, user selected culture as fallback
                  var currentCulture = CultureInfo.CurrentCulture;
                  var filePattern = "/Content/touchpoint/lib/jquery-globalize/js/cultures/globalize.culture.{0}.js";
                  var regionalisedFileToUse = string.Format(filePattern, "en-US"); //Default localisation to use
  
                  //Try to pick a more appropriate regionalisation
                  if (File.Exists(HostingEnvironment.MapPath(string.Format(filePattern, currentCulture.Name)))) //First try for a globalize.culture.en-GB.js style file
                      regionalisedFileToUse = string.Format(filePattern, currentCulture.Name);
                  else if (File.Exists(HostingEnvironment.MapPath(string.Format(filePattern, currentCulture.TwoLetterISOLanguageName)))) //That failed; now try for a globalize.culture.en.js style file
                      regionalisedFileToUse = string.Format(filePattern, currentCulture.TwoLetterISOLanguageName);
  
                  return regionalisedFileToUse;
              }
          }
  
          public static string CmsHost => DbUtil.Db.CmsHost;
  
          public static string GridClass => "table table-condensed table-striped not-wide grid2";
  
          public static MvcHtmlString DivValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
          {
              try
              {
                  var msg = helper.ValidationMessageFor(expression);
                  if (msg == null)
                      return null;
                  var s = msg.ToString();
                  if (s.HasValue() && s.Contains("field-validation-valid"))
                      return null;
                  if (!s.HasValue())
                      return null;
                  var div = new TagBuilder("div");
                  div.AddCssClass("alert alert-danger");
                  div.InnerHtml = s;
                  return new MvcHtmlString(div.ToString());
              }
              catch (Exception ex)
              {
                  var errorLog = ErrorLog.GetDefault(null);
                  errorLog.Log(new Error(ex));
                  return null;
              }
          }
  
          public static MvcHtmlString DivValidationMessage(this HtmlHelper helper, string field, string @class = null)
          {
              try
              {
                  var msg = helper.ValidationMessage(field);
                  if (msg == null)
                      return null;
                  var s = msg.ToString();
                  if (s.HasValue() && s.Contains("field-validation-valid"))
                      return null;
                  if (!s.HasValue())
                      return null;
                  var div = new TagBuilder("div");
                  div.AddCssClass("alert alert-danger");
                  if (@class.HasValue())
                      div.AddCssClass(@class);
                  div.InnerHtml = s;
                  return new MvcHtmlString(div.ToString());
              }
              catch (Exception ex)
              {
                  var errorLog = ErrorLog.GetDefault(null);
                  errorLog.Log(new Error(ex));
                  return null;
              }
          }
  
          public static HtmlString DivAlertBox(this HtmlHelper helper, string msg, string alerttype = "alert-danger")
          {
              if (!msg.HasValue())
                  return null;
              var div = new TagBuilder("div");
              div.AddCssClass("alert");
              div.AddCssClass(alerttype);
              div.InnerHtml = msg;
              return new HtmlString(div.ToString());
          }
  
          public static MvcHtmlString PartialFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string partialViewName)
          {
              var name = ExpressionHelper.GetExpressionText(expression);
              var model = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
              var viewData = new ViewDataDictionary(helper.ViewData) {TemplateInfo = new TemplateInfo {HtmlFieldPrefix = name}};
              return helper.Partial(partialViewName, model, viewData);
          }
  
          public static string GetNameFor<M, P>(this M model, Expression<Func<M, P>> ex)
          {
              return ExpressionHelper.GetExpressionText(ex);
          }
  
          public static string GetIdFor<M, P>(this M model, Expression<Func<M, P>> ex)
          {
              return ExpressionHelper.GetExpressionText(ex).ToSuitableId();
          }
  
          public static string ToFormattedList(this IEnumerable list, ListType listType)
          {
              var outerListFormat = "";
              var listFormat = "";
  
              switch (listType)
              {
                  case ListType.Ordered:
                      outerListFormat = "<ol>{0}</ol>";
                      listFormat = "<li>{0}</li>";
                      break;
                  case ListType.Unordered:
                      outerListFormat = "<ul>{0}</ul>";
                      listFormat = "<li>{0}</li>";
                      break;
                  case ListType.TableCell:
                      outerListFormat = "{0}";
                      listFormat = "<td>{0}</td>";
                      break;
              }
              return string.Format(outerListFormat, ToFormattedList(list, listFormat));
          }
  
          public static string ToFormattedList(IEnumerable list, string format)
          {
              var sb = new StringBuilder();
              foreach (var item in list)
                  sb.AppendFormat(format, item);
              return sb.ToString();
          }
  
          public static string GetSiteUrl(this ViewPage pg)
          {
              var Port = pg.ViewContext.HttpContext.Request.ServerVariables["SERVER_PORT"];
              if (Port == null || Port == "80" || Port == "443")
                  Port = "";
              else
                  Port = ":" + Port;
  
              var Protocol = pg.ViewContext.HttpContext.Request.ServerVariables["SERVER_PORT_SECURE"];
              if (Protocol == null || Protocol == "0")
                  Protocol = "http://";
              else
                  Protocol = "http://";
  
              var appPath = pg.ViewContext.HttpContext.Request.ApplicationPath;
              if (appPath == "/")
                  appPath = "";
  
              var sOut = Protocol + pg.ViewContext.HttpContext.Request.ServerVariables["SERVER_NAME"] + Port + appPath;
              return sOut;
          }
  
          public static HtmlString PageSizesDropDown(this HtmlHelper helper, string id, string onchange)
          {
              var tb = new TagBuilder("select");
              tb.MergeAttribute("id", id);
              if (onchange.HasValue())
                  tb.MergeAttribute("onchange", onchange);
              var sb = new StringBuilder();
              foreach (var o in PageSizes(null))
              {
                  var ot = new TagBuilder("option");
                  ot.MergeAttribute("value", o.Value);
                  if (o.Selected)
                      ot.MergeAttribute("selected", "selected");
                  ot.SetInnerText(o.Text);
                  sb.Append(ot);
              }
              tb.InnerHtml = sb.ToString();
              return new HtmlString(tb.ToString());
          }
  
          public static IEnumerable<SelectListItem> PageSizes(this HtmlHelper helper)
          {
              var sizes = new[] {10, 25, 50, 75, 100, 200};
              var list = new List<SelectListItem>();
              foreach (var size in sizes)
                  list.Add(new SelectListItem {Text = size.ToString()});
              return list;
          }
  
          public static HtmlString SpanIf(this HtmlHelper helper, bool condition, string text, object htmlAttributes)
          {
              if (!condition)
                  return null;
              var tb = new TagBuilder("span");
              var attr = new RouteValueDictionary(htmlAttributes);
              tb.InnerHtml = text;
              tb.MergeAttributes(attr);
              return new HtmlString(tb.ToString());
          }
  
          public static HtmlString Span(this HtmlHelper helper, string text, object htmlAttributes)
          {
              var tb = new TagBuilder("span");
              var attr = new RouteValueDictionary(htmlAttributes);
              tb.InnerHtml = text;
              tb.MergeAttributes(attr);
              return new HtmlString(tb.ToString());
          }
  
          private static string TryGetModel(this HtmlHelper helper, string name)
          {
              ModelState val;
              helper.ViewData.ModelState.TryGetValue(name, out val);
              string s = null;
              if (val != null)
                  s = val.Value.AttemptedValue;
              return s;
          }
  
          public static HtmlString DropDownList2(this HtmlHelper helper, string name, IEnumerable<SelectListItem> list, bool visible)
          {
              var tb = new TagBuilder("select");
              tb.MergeAttribute("id", name);
              tb.MergeAttribute("name", name);
              if (!visible)
                  tb.MergeAttribute("style", "display: none");
              var s = helper.TryGetModel(name);
              var sb = new StringBuilder();
              foreach (var o in list)
              {
                  var ot = new TagBuilder("option");
                  ot.MergeAttribute("value", o.Value);
                  var selected = false;
                  if (s.HasValue())
                      selected = s == o.Value;
                  else if (o.Selected)
                      selected = true;
                  if (selected)
                      ot.MergeAttribute("selected", "selected");
                  ot.SetInnerText(o.Text);
                  sb.Append(ot);
              }
              tb.InnerHtml = sb.ToString();
              return new HtmlString(tb.ToString());
          }
  
          public static HtmlString DropDownList3(this HtmlHelper helper, string id, string name, IEnumerable<SelectListItem> list, string value)
          {
              var tb = new TagBuilder("select");
              if (id.HasValue())
                  tb.MergeAttribute("id", id);
              tb.MergeAttribute("name", name);
              var sb = new StringBuilder();
              foreach (var o in list)
              {
                  var ot = new TagBuilder("option");
                  ot.MergeAttribute("value", o.Value);
                  if (value == o.Value)
                      ot.MergeAttribute("selected", "selected");
                  ot.SetInnerText(o.Text);
                  sb.Append(ot);
              }
              tb.InnerHtml = sb.ToString();
  
gt:             return new HtmlString(tb.ToString());