public static bool GetOrSetThenGet(this ViewDataDictionary v, string key, bool?newVal = null, bool force = false) { if (newVal.HasValue && !v.ContainsKey(key)) { if (force || !v.ContainsKey(key)) { v[key] = newVal.Value; } } return(v.Get <bool>(key)); }
public static void WriteLog(ControllerContext controllerContext, ViewDataDictionary viewData) { var cc = controllerContext.Controller.ControllerContext; var category = GetCategory(controllerContext); var title = GetTitle(controllerContext); var log = new ActionLog { Controller = cc.RouteData.GetRequiredString("controller"), Action = cc.RouteData.GetRequiredString("action"), Url = controllerContext.HttpContext.Request.Path, CreatedAt = DateTime.Now, CreatedBy = "SYSTEM", Address = controllerContext.HttpContext.Request.UserHostAddress, Actor = TryGetUserName(controllerContext), Method = controllerContext.HttpContext.Request.HttpMethod, Category = GetCategory(controllerContext), Title = title.Equals(category) ? "查询" : title, Result = TryGetResult(controllerContext), ModelId = cc.RouteData.Values.ContainsKey("id") ? cc.RouteData.GetRequiredString("id") : null, Description = viewData.ContainsKey(Const.ToLogMessage) ? viewData[Const.ToLogMessage].ToString() : null }; if (log.Description == null && viewData.ContainsKey(Const.ToLogModel)) { // 取得描述 var model = viewData.ContainsKey(Const.ToLogModel) ? viewData[Const.ToLogModel] : viewData.Model; if (model != null) { if (!model.GetType().IsGenericType) { log.Description = model.Print(); } else { var objs = (IEnumerable<object>)model; log.Description = string.Join(";" + Environment.NewLine, objs.Select(m => m.Print())); } } } using (var ds = new SessionFactory().OpenSession()) { if (!ds.Create(log)) { Log.Error("记录日志失败:{0}", log.ToString()); } } }
/// <summary> /// Check the ViewData for a Webpack bundle name. /// </summary> /// <param name="viewData">The view data.</param> /// <returns>The name of the Webpack bundle.</returns> public static string?GetBundleName(this ViewDataDictionary viewData) { if (viewData == null) { throw new ArgumentNullException(nameof(viewData)); } if (!viewData.ContainsKey("Bundle") || !(viewData["Bundle"] is string)) { return(null); } var bundle = (string)viewData["Bundle"]; if (!bundle.StartsWith('/')) { return(bundle); } // Use Razor Page logic to resolve bundle. E.g. /Some/Bundle = Some_Bundle var viewPaths = bundle .Split('/') .ToList(); viewPaths.Remove(string.Empty); return(string.Join("_", viewPaths)); }
/// <summary> /// Returns true if ViewData has object by <typeparamref name="T"/> type name /// </summary> /// <typeparam name="T">Resolve type name</typeparam> /// <param name="viewData">ViewData</param> /// <param name="fullName">Use or not full qualifier type name</param> /// <returns>Returns ViewData.ContainsKey of <typeparamref name="T"/> type name</returns> public static bool Has <T>(this ViewDataDictionary viewData, bool fullName) where T : class { var type = typeof(T); return(viewData.ContainsKey(fullName ? type.FullName : type.Name)); }
private void Import(IDictionary <string, object> tempData, ViewDataDictionary currentViewData) { var importingViewData = tempData[Key] as ViewDataDictionary; if (importingViewData == null) { return; } foreach (var pair in importingViewData.Where(pair => ReplaceExisting || !currentViewData.ContainsKey(pair.Key))) { currentViewData[pair.Key] = pair.Value; } if ((ReplaceExisting || (currentViewData.Model == null)) && (importingViewData.Model != null)) { currentViewData.Model = importingViewData.Model; } var currentModelState = currentViewData.ModelState; foreach (var pair in importingViewData.ModelState.Where(pair => ReplaceExisting || !currentModelState.ContainsKey(pair.Key))) { currentModelState[pair.Key] = pair.Value; } }
public static void SetIfMissing(this ViewDataDictionary v, string key, object val) { if (!v.ContainsKey(key)) { v[key] = val; } }
public static ViewDataDictionary Merge(this ViewDataDictionary source, ViewDataDictionary dic1) { if (dic1 != null) { foreach (KeyValuePair <string, object> pair in dic1) { if (!source.ContainsKey(pair.Key)) { source.Add(pair.Key, pair.Value); } } foreach (KeyValuePair <string, ModelState> pair2 in dic1.ModelState) { if (!source.ModelState.ContainsKey(pair2.Key)) { source.ModelState.Add(pair2.Key, pair2.Value); } } if (source.Model == null) { source.Model = dic1.Model; } if (source.TemplateInfo == null) { source.TemplateInfo = dic1.TemplateInfo; } if (source.ModelMetadata == null) { source.ModelMetadata = dic1.ModelMetadata; } } return(source); }
public static MetaModel MetaModel(this ViewDataDictionary viewData) { if (viewData.ContainsKey(VIEWDATA_MetaModel)) { return((MetaModel)viewData[VIEWDATA_MetaModel]); } return(System.Web.DynamicData.MetaModel.Default); }
/// <summary> /// Loads the supplied object to the view data dictionary for use by other partials /// </summary> public static void RenderPartialWithData(this HtmlHelper htmlHelper, string partialName, string key, object objectToLoad, ViewDataDictionary viewDataDictionary) { if (!viewDataDictionary.ContainsKey(key)) { viewDataDictionary.Add(key, objectToLoad); } htmlHelper.RenderPartial(partialName); }
public static IDictionary <string, object> GetViewState(this ViewDataDictionary dict) { if (!dict.ContainsKey("__viewState")) { dict.Add("__viewState", new Dictionary <string, object>()); } return((IDictionary <string, object>)dict["__viewState"]); }
public static LinkTagDictionary LinkTags(this ViewDataDictionary viewData) { if (!viewData.ContainsKey(LinkTagsKey)) { viewData[LinkTagsKey] = new LinkTagDictionary(); } return(viewData[LinkTagsKey] as LinkTagDictionary); }
public static void CarregarDadosUsuario(ViewDataDictionary viewData, bool logado, string tipoUsuario, string erroLogin) { if (viewData.ContainsKey("logado")) viewData["logado"] = viewData["logado"]; else viewData.Add("logado", logado); if (viewData.ContainsKey("tipoUsuario")) viewData["tipoUsuario"] = viewData["tipoUsuario"]; else viewData.Add("tipoUsuario", tipoUsuario); if (viewData.ContainsKey("erroLogin")) viewData["erroLogin"] = viewData["erroLogin"]; else viewData.Add("erroLogin", erroLogin); }
public static string GetBundleName(this ViewDataDictionary viewData) { if (viewData.ContainsKey("Bundle")) { return((string)viewData["Bundle"]); } return(null); }
public static string _getTitle(this ViewDataDictionary <dynamic> viewData) { if (viewData.ContainsKey(PageKeyVal.PageTitleKey)) { return((string)viewData[PageKeyVal.PageTitleKey]); } return("Game"); }
public static string _getMetaDescription(this ViewDataDictionary <dynamic> viewData) { if (viewData.ContainsKey(PageKeyVal.PageMetaDescriptionKey)) { return((string)viewData[PageKeyVal.PageMetaDescriptionKey]); } return("4X stratege Game"); }
public static void CarregarDadosUsuario(ViewDataDictionary viewData) { if (viewData.ContainsKey("logado")) viewData["logado"] = viewData["logado"]; else viewData.Add("logado", false); if (viewData.ContainsKey("tipoUsuario")) viewData["tipoUsuario"] = viewData["tipoUsuario"]; else viewData.Add("tipoUsuario", ""); if (viewData.ContainsKey("erroLogin")) viewData["erroLogin"] = viewData["erroLogin"]; else viewData.Add("erroLogin", ""); }
public static T GetOrDefault <T>(this ViewDataDictionary bag, string key, T defaultValue) { if (bag.ContainsKey(key)) { return((T)bag[key]); } return(defaultValue); }
public static T GetData <T>(this ViewDataDictionary viewData) where T : IComparable { if (viewData.ContainsKey(typeof(T).ToString())) { return((T)Convert.ChangeType(viewData[typeof(T).ToString()], typeof(T))); } return(default(T)); }
public static List <Alert> GetJsonAlerts(this ViewDataDictionary viewData) { if (!viewData.ContainsKey(AppConstants.JSON_ALERT_KEY)) { viewData[AppConstants.JSON_ALERT_KEY] = new List <Alert>(); } return((List <Alert>)viewData[AppConstants.JSON_ALERT_KEY]); }
public static IList <ModelError> ModelErrors(this ViewDataDictionary viewData) { if (!viewData.ContainsKey(VIEWDATA_MODELERRORS)) { viewData[VIEWDATA_MODELERRORS] = new List <ModelError>(); } return((IList <ModelError>)viewData[VIEWDATA_MODELERRORS]); }
/// <summary> /// Get a date value from the ViewData. /// </summary> /// <param name="viewData"></param> /// <param name="key"></param> /// <returns></returns> public static DateTime?GetDateValueOrNull(this ViewDataDictionary viewData, string key) { if (viewData.ContainsKey(key) && DateTime.TryParse(viewData[key]?.ToString() ?? string.Empty, out DateTime parsedDate)) { return(parsedDate); } return(null); }
public static ModelStateList ModelState(this ViewDataDictionary viewData) { if (!viewData.ContainsKey(VIEWDATA_MODELSTATE)) { viewData[VIEWDATA_MODELSTATE] = new ModelStateList(); } return((ModelStateList)viewData[VIEWDATA_MODELSTATE]); }
public static bool IsLoggedIn(this ViewDataDictionary ViewData) { if (ViewData.ContainsKey(IS_LOGGED_IN)) { return((bool)ViewData[IS_LOGGED_IN]); } return(false); }
public ViewDataDictionary GetSections() { ViewDataDictionary vd = new ViewDataDictionary(); using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString)) { string SQL = "SELECT s.PageSectionID, s.PageSectionName " + " FROM cms_Page p JOIN cms_PageSection s ON p.PageTypeID = s.PageTypeID "+ " WHERE p.PageID = @PageID"+ " ORDER BY s.PageSectionName"; using (SqlCommand cmd = new SqlCommand(SQL, cn)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("PageID", SqlDbType.UniqueIdentifier).Value = _PageID; cmd.Connection.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string sectionContents = GetSection(dr.GetGuid(0)); if (!string.IsNullOrEmpty(sectionContents)) { vd.Add(dr[1].ToString(), sectionContents); } string footerSectionContents = GetFooterSection(dr.GetGuid(0)); if (!string.IsNullOrEmpty(footerSectionContents)) { if (vd.ContainsKey("FooterCode")) { string toAdd = vd["FooterCode"].ToString() + footerSectionContents; vd["FooterCode"] = toAdd; } else { vd.Add("FooterCode", footerSectionContents); } } } cmd.Connection.Close(); //Get shared components that are part of the "Shared" pseudo-page cmd.CommandText = "SELECT s.PageSectionID, s.PageSectionName, p.PageID FROM cms_Page p JOIN cms_PageSection s ON p.PageTypeID = s.PageTypeID WHERE p.VirtualPath = 'Shared' ORDER BY s.PageSectionName"; cmd.Parameters.Clear(); cmd.Connection.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { string sectionContents = GetSection(dr.GetGuid(2), dr.GetGuid(0)); if (!string.IsNullOrEmpty(sectionContents)) { vd.Add(dr[1].ToString(), sectionContents); } } cmd.Connection.Close(); } } return(vd); }
void Dispose(ViewDataDictionary viewData) { IDisposable elapsed = viewData.ContainsKey(Key) ? (IDisposable)viewData[Key] : null; if (elapsed != null) { elapsed.Dispose(); viewData.Remove(Key); } }
public static object Get(this ViewDataDictionary bag, Type type) { if (!bag.ContainsKey(getKey(type))) { string message = string.Format("No object exists that is of type '{0}'.", type); throw new ArgumentException(message); } return(bag[getKey(type)]); }
public static string GetMessage(this ViewDataDictionary dict) { if (dict.ContainsKey("message")) { var s = (string)dict["message"]; dict.Remove("message"); return(s); } return(""); }
public static MvcHtmlString GetHtmlAttributes <T>(this ViewDataDictionary <T> dict, string attributes) { string html = attributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(a => a.Trim() == "class" ? "cssClass" : a.Trim()) .Where(a => dict.ContainsKey(a)) .Select(a => (a == "cssClass" ? "class" : a) + "='" + HttpUtility.HtmlAttributeEncode(dict[a].ToString()) + "'") .Join(" "); return(MvcHtmlString.Create(html)); }
//showHeader public static bool _showHeader(this ViewDataDictionary viewData) { var showHeader = true; if (viewData.ContainsKey(PageKeyVal.NotShowHeaderKey)) { showHeader = !(bool)viewData[PageKeyVal.NotShowHeaderKey]; } return(showHeader); }
public static T Get <T>(this ViewDataDictionary bag, string key) { if (!bag.ContainsKey(key)) { string message = string.Format("No object exists with key '{0}'.", key); throw new ArgumentException(message); } return((T)bag[key]); }
public static string _getPageCssClass(this ViewDataDictionary viewData) { var pageCssClass = "default-page"; if (viewData.ContainsKey(PageKeyVal.BodyCssKey)) { pageCssClass = viewData[PageKeyVal.BodyCssKey].ToString(); } return(pageCssClass); }
public static string GetCobrowsingSnippetKey(this ViewDataDictionary viewData) { if (viewData.ContainsKey(ViewDataKeys.ZenDeskConfiguration)) { var zenDeskConfig = viewData[ViewDataKeys.ZenDeskConfiguration] as ZenDeskConfiguration; return(zenDeskConfig?.CobrowsingSnippetKey); } return(null); }
public static string IsActiveCategory <T>(this ViewDataDictionary viewData, T category) { if (!viewData.ContainsKey(ACTIVE_CATEGORY_KEY)) { return(null); } var activeCategory = (T)viewData[ACTIVE_CATEGORY_KEY]; return(category.Equals(activeCategory) ? "active" : null); }
public static string GetZenDeskSectionId(this ViewDataDictionary viewData) { if (viewData.ContainsKey(ViewDataKeys.ZenDeskConfiguration)) { var zenDeskConfig = viewData[ViewDataKeys.ZenDeskConfiguration] as ZenDeskConfiguration; return(zenDeskConfig?.SectionId); } return(null); }
protected virtual string GetMatch(Match m, ViewDataDictionary viewDataDictionary) { if (m.Success) { string key = m.Result("$1"); if (viewDataDictionary.ContainsKey(key)) { return viewDataDictionary[key].ToString(); } } return string.Empty; }
public void Merge(ViewDataDictionary source, ViewDataDictionary destiny) { Check.Arguments.ThrowIfNull(source, "source"); Check.Arguments.ThrowIfNull(destiny, "destiny"); foreach (var entry in destiny) if (!source.ContainsKey(entry.Key)) source.Add(entry.Key, entry.Value); if (destiny.Model != null) source.Model = destiny.Model; }
protected virtual string GetMatch(Match m, ViewDataDictionary viewData) { if (m.Success) { // 获取匹配后的结果,即 ViewData 中的 key 值,并根据这个 key 值返回 ViewData 中对应的 value string key = m.Result("$1"); if (viewData.ContainsKey(key)) { return viewData[key].ToString(); } } return string.Empty; }
public ContentAreaItemContext(ViewDataDictionary viewData, ContentAreaItem contentAreaItem) { _viewData = viewData; var displayOption = contentAreaItem.LoadDisplayOption() ?? new DisplayOption { Id = Guid.NewGuid().ToString(), Name = "Unknown" }; if (!_viewData.ContainsKey(Constants.CurrentDisplayOptionKey)) { _viewData.Add(Constants.CurrentDisplayOptionKey, displayOption); } else { _viewData[Constants.CurrentDisplayOptionKey] = displayOption; } }
private object GetFieldValueFromViewData(ViewDataDictionary viewData, string fieldName) { object value = null; string viewDataKey = null; fieldName = ParseFieldName(fieldName, out viewDataKey); if (string.IsNullOrEmpty(viewDataKey)) { if (viewData.ContainsKey(fieldName)) { value = viewData[fieldName]; } if (value == null && viewData.Model != null) { value = GetFieldValueFromObject(viewData.Model, fieldName); } if (value == null) { foreach (var item in viewData.Values) { value = GetFieldValueFromObject(item, fieldName); if (value != null) { break; } } } } else { if (viewData.ContainsKey(viewDataKey)) { value = GetFieldValueFromObject(viewData[viewDataKey], fieldName); } } return value; }
/// <summary> /// Renders a single pattern page /// </summary> /// <param name="id">The dash delimited path of the pattern (e.g. atoms-colors)</param> /// <param name="masterName">The optional master view to use when rendering</param> /// <param name="parse">Whether or not to parse the template and replace Mustache tags with data</param> /// <param name="enableCss">Generate CSS for each pattern. Currently unsupported</param> /// <param name="noCache">Set the cacheBuster value to 0</param> /// <returns>A pattern page</returns> public ActionResult ViewSingle(string id, string masterName, bool? parse, bool? enableCss, bool? noCache) { // Get data from provider and set additional variables var model = new ViewDataDictionary(Provider.Data()) { {"cssEnabled", (enableCss.HasValue && enableCss.Value).ToString().ToLower()}, {"cacheBuster", noCache.HasValue && noCache.Value ? "0" : Provider.CacheBuster()} }; // Find pattern from dash delimited path var pattern = Provider.Patterns() .FirstOrDefault(p => p.PathDash.Equals(id, StringComparison.InvariantCultureIgnoreCase)); if (pattern == null) return null; var childLineages = new List<object>(); var parentLineages = new List<object>(); // Gather a list of child patterns that the current pattern's template references foreach (var childPattern in pattern.Lineages.Select(partial => Provider.Patterns().FirstOrDefault( p => p.Partial.Equals(partial, StringComparison.InvariantCultureIgnoreCase))) .Where(childPattern => childPattern != null)) { childLineages.Add(new { lineagePath = string.Format("../../{0}/{1}", PatternProvider.FolderNamePattern.TrimStart(PatternProvider.IdentifierHidden), childPattern.HtmlUrl), lineagePattern = childPattern.Partial, lineageState = PatternProvider.GetState(childPattern) }); } // Gather a list of parent patterns whose templates references the current pattern var parentPatterns = Provider.Patterns().Where(p => p.Lineages.Contains(pattern.Partial)); foreach (var parentPattern in parentPatterns) { parentLineages.Add(new { lineagePath = string.Format("../../{0}/{1}", PatternProvider.FolderNamePattern.TrimStart(PatternProvider.IdentifierHidden), parentPattern.HtmlUrl), lineagePattern = parentPattern.Partial, lineageState = PatternProvider.GetState(parentPattern) }); } var serializer = new JavaScriptSerializer(); // Add pattern specific data to the data collection model.Add("viewSingle", true); model.Add("patternPartial", pattern.Partial); model.Add("lineage", serializer.Serialize(childLineages)); model.Add("lineageR", serializer.Serialize(parentLineages)); model.Add("patternState", PatternProvider.GetState(pattern)); // For all values in the pattern data collection update the main data collection foreach (var data in pattern.Data) { if (model.ContainsKey(data.Key)) { model[data.Key] = data.Value; } else { model.Add(data.Key, data.Value); } } if (!string.IsNullOrEmpty(masterName)) { // If a master has been specified, render 'pattern.html' using master view return View(pattern.ViewUrl, masterName, model); } var html = pattern.Html; if (parse.HasValue && parse.Value) { // If not parsing, render 'pattern.mustache' html = Render.StringToString(html, model, new MustacheTemplateLocator().GetTemplate); } // Else, render 'pattern.escaped.html' return Content(Server.HtmlEncode(html)); }
private void Import(IDictionary<string, object> tempData, ViewDataDictionary currentViewData) { ViewDataDictionary importingViewData = tempData[Key] as ViewDataDictionary; if (importingViewData == null) { return; } foreach (KeyValuePair<string, object> pair in importingViewData.Where(pair => ReplaceExisting || !currentViewData.ContainsKey(pair.Key))) { currentViewData[pair.Key] = pair.Value; } if ((ReplaceExisting || (currentViewData.Model == null)) && (importingViewData.Model != null)) { currentViewData.Model = importingViewData.Model; } ModelStateDictionary currentModelState = currentViewData.ModelState; foreach (KeyValuePair<string, ModelState> pair in importingViewData.ModelState.Where(pair => ReplaceExisting || !currentModelState.ContainsKey(pair.Key))) { currentModelState[pair.Key] = pair.Value; } }
public static void ValidateViewData(ViewDataDictionary expected, ViewDataDictionary actual) { if (expected == null) { return; } ValidateCount(expected.Count, actual.Count, "ViewData"); foreach(KeyValuePair<string, object> p in expected) { Validate(true, actual.ContainsKey(p.Key), string.Format("ContainsKey <{0}>",p.Key)); Validate(p.Value.ToString(), actual[p.Key].ToString(), "Value"); } Console.WriteLine("==========================="); }
/// <summary> /// Combines two data collections /// </summary> /// <param name="original">The original data collection</param> /// <param name="additional">The additional data</param> /// <returns>The combined data collection</returns> public static ViewDataDictionary AppendData(ViewDataDictionary original, Dictionary<string, object> additional) { foreach (var item in additional) { if (original.ContainsKey(item.Key)) { // Replace existing items (e.g. pattern specific data overrides provider-level data) original[item.Key] = item.Value; } else { // Add new items original.Add(item.Key, item.Value); } } return original; }