public ExportHelper(bool isexport, int? pageSize, string filename, JContext jc) { this.isexport = isexport; if (!filename.EndsWith(".xls") || !filename.EndsWith(".xlsx")) this.filename = filename + ".xls"; else this.filename = filename; this.jc = jc; QC = new WebQuery(); QC.LoadCondidtion(); if (this.isexport) { if (jc.QueryString["export"] == "all") { QC.NoPaging(); } else if (pageSize != null) { QC.PageSize = pageSize.Value; } } else { QC.PageSize = pageSize.Value; } }
public static ArrayList GetDataSource(QueryCondition qc, int numDisplay, int numEdge, bool AlwaysShowPrev, bool AlwaysShowNext) { JContext jc = JContext.Current; ArrayList datasource = new ArrayList(); StringBuilder txt = new StringBuilder(); int[] interval = getInterval(qc, numDisplay); var np = get_numPages(qc); if (np < 2) { return(datasource); } if (qc.PageIndex > 0 || AlwaysShowPrev) { datasource.Add(new { pageindex = qc.PageIndex - 1, type = "prev", href = FormatUrl(qc.PageIndex - 1, null, jc.IsAjaxRequest) }); } if (interval[0] > 0 && numEdge > 0) { var end = Math.Min(numEdge, interval[0]); for (int i = 0; i < end; i++) { datasource.Add(new { pageindex = i, type = "item", href = FormatUrl(i, null, jc.IsAjaxRequest) }); } if (numEdge < interval[0]) { datasource.Add(new { pageindex = -1, type = "ellipsis" }); } } for (int i = interval[0]; i < interval[1]; i++) { datasource.Add(new { pageindex = i, type = "item", href = FormatUrl(i, null, jc.IsAjaxRequest) }); } if (interval[1] < np && numEdge > 0) { if (np - numEdge > interval[1]) { datasource.Add(new { pageindex = -1, type = "ellipsis" }); } var begin = Math.Max(np - numEdge, interval[1]); for (int i = begin; i < np; i++) { datasource.Add(new { pageindex = i, type = "item", href = FormatUrl(i, null, jc.IsAjaxRequest) }); } } if (qc.PageIndex < np - 1 || AlwaysShowNext) { datasource.Add(new { pageindex = qc.PageIndex + 1, type = "next", href = FormatUrl(qc.PageIndex + 1, null, jc.IsAjaxRequest) }); } return(datasource); }
public override void ExecuteResult(JContext jc) { if (jc == null) { throw new ArgumentNullException("jc"); } HttpResponse response = jc.Context.Response; response.ContentType = ContentType; response.ContentEncoding = Encoding.UTF8; if (!String.IsNullOrEmpty(FileDownloadName)) { // From RFC 2183, Sec. 2.3: // The sender may want to suggest a filename to be used if the entity is // detached and stored in a separate file. If the receiving MUA writes // the entity to a file, the suggested filename should be used as a // basis for the actual filename, where possible. string headerValue = GetHeaderValue(FileDownloadName); response.AddHeader("Content-Disposition", headerValue); } WriteFile(response); response.End(); }
private void WidgetController_BeforeActionExecute(object sender, BeforeActionExecuteEventArgs e) { JContext jc = e.JContext; if (jc == null) { //服务器错误 ResponseUtil.OutputJson(httpContext.Response, new { code = 500, msg = "不合法请求" }); e.PreventDefault = true; return; } if (!jc.IsAuth) { //权限验证失败 ResponseUtil.OutputJson(httpContext.Response, new { code = 403, msg = "没有权限访问" }); e.PreventDefault = true; return; } #region 校验站点信息 if (string.IsNullOrEmpty(jc.Params["siteId"])) { ResponseUtil.OutputJson(httpContext.Response, new { code = 200, msg = "参数列表不正确,缺少SiteId参数" }); e.PreventDefault = true; return; } var site = Site.Get(jc.Params["siteId"]); if (site == null) { ResponseUtil.OutputJson(httpContext.Response, new { code = 200, msg = "指定的站点不存在" }); e.PreventDefault = true; return; } #endregion #region 校验用户对站点的权限 var relation = (from q in SiteUsers.CreateContext() where q.UserId == jc.UserName && q.SiteId == site.Id select q).FirstOrDefault(); //只有管理人员才可以对站点的挂件进行编辑 if (relation == null || relation.PermissionLevel != PermissionLevel.ADMIN) { ResponseUtil.OutputJson(httpContext.Response, new { code = 403, msg = "没有权限访问" }); e.PreventDefault = true; return; } #endregion jc["site"] = site; }
public override void ExecuteResult(JContext jc) { if (jc == null) { throw new ArgumentNullException("jc"); } jc.Context.Response.Redirect(Url, true); }
internal static void SetViewData() { JContext jc = JContext.Current; jc.ViewData["jc"] = jc; foreach (string key in ContextData.Datas.Keys) { jc.ViewData[key] = ContextData.Datas[key]; } }
public override void ExecuteResult(JContext jc) { if (jc == null) { throw new ArgumentNullException("context"); } // 401 is the HTTP status code for unauthorized access - setting this // will cause the active authentication module to execute its default // unauthorized handler jc.Context.Response.StatusCode = 401; }
protected virtual void Invoke(object sender, EventArgs e) { if (EventBroker.IsStaticResource((sender as HttpApplication).Request)) { return; } JContext jc = JContext.Current; try { jc.Controller = ControllerResolver.Instance.CreateController(jc.Navigation.Id); if (jc.Controller == null) { if (jc.IsEmbed) { jc.RenderContent = false; ResponseUtil.OutputJson(jc.Context.Response, new TemplatedControl() { UsedInMvc = jc.Context.Request.Headers["usedinmvc"].ToBoolean(true), OverrideSkinName = true, Templated = true }.Execute()); } return; } object[] attrs = jc.Controller.GetType().GetCustomAttributes(typeof(CheckLicenceAttribute), true); if (attrs.Length == 1) { ILicenceProvider lp = ServiceLocator.Instance.SafeResolve <ILicenceProvider>(); if (lp != null && !lp.Check()) { if (!lp.OnLicenceInvalid()) { return; } } } jc.Controller.jc = jc; jc.ViewData["this"] = jc.Controller; invoker.InvokeAction(jc); } catch (ThreadAbortException) { }// ignore this exception }
public override void ExecuteResult(JContext jc) { jc.Items["__viewResult__"] = ViewName; jc.Items["__viewResult_IsFile__"] = IsFile; if (!jc.RenderContent) { jc.Context.Response.Write(new TemplatedControl() { SkinName = ViewName, UsedInMvc = !ViewName.StartsWith("/"), OverrideSkinName = true, Templated = true }.Execute()); } }
public override void ExecuteResult(JContext jc) { if (jc == null) { throw new ArgumentNullException("jc"); } HttpResponse response = jc.Context.Response; if (Script != null) { response.Write("<script type='text/javascript'>"); response.Write(Script); response.Write("</script>"); } }
private void CategoryController_BeforeActionExecute(object sender, BeforeActionExecuteEventArgs e) { JContext jc = e.JContext; if (jc == null) { //服务器错误 ResponseUtil.OutputJson(httpContext.Response, new { code = 500, msg = "不合法请求" }); e.PreventDefault = true; return; } if (!jc.IsAuth) { //权限验证失败 ResponseUtil.OutputJson(httpContext.Response, new { code = 403, msg = "没有权限访问" }); e.PreventDefault = true; return; } #region 校验站点信息 if (string.IsNullOrEmpty(jc.Params["siteId"])) { ResponseUtil.OutputJson(httpContext.Response, new { code = 200, msg = "参数列表不正确,缺少SiteId参数" }); e.PreventDefault = true; return; } var site = Site.Get(jc.Params["siteId"]); if (site == null) { ResponseUtil.OutputJson(httpContext.Response, new { code = 200, msg = "指定的站点不存在" }); e.PreventDefault = true; return; } #endregion jc["site"] = site; }
void send_action_execute_msg(JContext jc) { if (Connection != null && Connection.IsConnected) { ISubscriber sub = Connection.GetSubscriber(); //构造当前请求的数据 object interfaceInfo = new { ModuleName = jc.Area.AreaKey, ControllerId = jc.Navigation.Id, ActionName = jc.Navigation.Action, StartDate = jc.RequestStartTime, EndDate = DateTime.Now, uid = jc.UserName, }; sub.Publish("kiss.web.stat", new Kiss.Json.JavaScriptSerializer().Serialize(interfaceInfo)); } }
private static string FormatUrl(int page_id, string Url, bool isAjaxRequest) { JContext jc = JContext.Current; if (jc.IsEmbed) { Url url = new Url(jc.Context.Request.Url.PathAndQuery).SetQuery(StringUtil.ToQueryString(jc.QueryString)); url = url.UpdateQuery("page", page_id + 1); return(string.Format("#{0}", url.PathAndQuery)); } if (isAjaxRequest && StringUtil.IsNullOrEmpty(Url)) { return("#"); } HttpContext httpContext = HttpContext.Current; if (StringUtil.HasText(Url)) { if (Url.Contains("?")) { return(string.Format(Url, page_id + 1)); } return(string.Format(Url + httpContext.Request.Url.Query, page_id + 1)); } else { Url url = new Url(httpContext.Request.Url.PathAndQuery); int i = url.Path.LastIndexOf("/"); return(string.Format("{0}{1}{2}{3}", url.Path.Substring(0, i + 1), page_id + 1, url.Extension, string.IsNullOrEmpty(url.Query) ? string.Empty : "?" + url.Query )); } }
private void SiteController_BeforeActionExecute(object sender, BeforeActionExecuteEventArgs e) { JContext jc = e.JContext; if (jc == null) { //服务器错误 ResponseUtil.OutputJson(httpContext.Response, new { code = 500, msg = "不合法请求" }); e.PreventDefault = true; return; } //只有管理员角色才能访问该控制器下的接口 if (!jc.IsAuth || !jc.User.IsInRole("admin")) { //权限验证失败 ResponseUtil.OutputJson(httpContext.Response, new { code = 403, msg = "没有权限访问" }); e.PreventDefault = true; return; } }
private bool Match(HttpRequest request, string urlRequested, out string newPath, out NameValueCollection qs) { qs = new NameValueCollection(); JContext jc = JContext.Current; UrlMappingItem matched = null; foreach (UrlMappingItem item in _provider.UrlMappings ?? new UrlMappingItemCollection()) { Match match = item.UrlTarget.Match(urlRequested); if (match.Success) { // add querystring parameters for dynamic mappings for (int i = 1; i < match.Groups.Count; i++) { qs.Add(item.UrlTarget.GroupNameFromNumber(i), match.Groups[i].Value); } // temp use jc.QueryString.Add(qs); matched = item; break; } } if (matched != null) { if (jc.Navigation.Set(matched, urlRequested)) { OnUrlMatched(); newPath = matched.Redirection; return(true); } } newPath = string.Empty; return(false); }
protected virtual void RenderMetaTags(HtmlTextWriter writer) { NameValueCollection metaTags = Context.Items[metaKey] as NameValueCollection; if (metaTags == null) { metaTags = new NameValueCollection(); } JContext jc = JContext.Current; metaTags["keywords"] = jc.Navigation["keywords"]; metaTags["description"] = jc.Navigation["description"]; foreach (string key in metaTags.Keys) { if (StringUtil.HasText(metaTags[key])) { writer.WriteLine(metaFormat, key, metaTags[key]); } } }
protected override void CreateChildControls() { base.CreateChildControls(); JContext jc = JContext.Current; if (jc.User == null) { return; } isSiteAdmin = jc.User.HasPermission(string.Format("site.control_panel@{0}", jc.Area["support_multi_site"].ToBoolean() ? jc.SiteId : string.Empty)); jc.Context.Items["_has_controlpanel_permission_"] = isSiteAdmin; foreach (var cpItem in Plugin.Plugins.GetPlugins <ControlPanelItemAttribute>(JContext.Current.User)) { Object obj = Activator.CreateInstance(cpItem.Decorates); if (obj is Control) { Controls.Add(obj as Control); } renderers.Add(obj as IControlPanelItemRenderer); } if (renderers.Count == 0 || !isSiteAdmin) { return; } ClientScriptProxy proxy = ClientScriptProxy.Current; proxy.Require(jc.Area, "jquery.js,kiss.js,kiss.css"); proxy.RegisterCssResource(GetType(), "Kiss.Web.jQuery.cp.c.css"); }
private RequestArgs Reset() { isBusy = false; issended = false; Method = context.Request.HttpMethod.ToUpper(); var h = context.Request.Headers.ToString(); Params.Clear(); JContext.Reset(); JContext.ResetParameterSerialiers(); _bodyASJson = null; var rawurl = context.Request.RawUrl.Split('?'); var raw = rawurl[0].Split('/'); if (rawurl.Length > 1) { UpdateParams(rawurl[1]); } if (raw[1] == "_" || raw[1] == "Login") { Path = new string[raw.Length - 2]; Array.Copy(raw, 2, Path, 0, Path.Length); IsFile = false; if (Path.Length > 0) { Service = Server.GetService(Path[0]); } } else { IsFile = true; Path = null; Service = null; } _bodyASJson = null; _bytes = null; return(this); }
protected override void Render(HtmlTextWriter writer) { base.Render(writer); JContext jc = JContext.Current; if (!jc.IsAjaxRequest) { ClientScriptProxy.Current.RegisterJsResource( "Kiss.Web.jQuery.kiss.js"); } StringBuilder sb = new StringBuilder(); foreach (AjaxClass c in Find()) { if (c.Id == "gAjax") // make sure gAjax script render only once in one http request { if (!HttpContext.Current.Items.Contains(GAJAX)) { HttpContext.Current.Items[GAJAX] = true; AppendClassScript(c, ref sb); } } else { AppendClassScript(c, ref sb); } } ClientScriptProxy.Current.RegisterJsBlock(writer, Guid.NewGuid().ToString(), sb.ToString(), true, jc.IsAjaxRequest); }
public override void ExecuteResult(JContext jc) { }
private MethodInfo getActionMethod(JContext jc) { Type t = jc.Controller.GetType(); if (!_mis.ContainsKey(t)) { lock (_mis) { if (!_mis.ContainsKey(t)) { _mis[t] = new Dictionary<string, MethodInfo>(); } } } Dictionary<string, MethodInfo> mis = _mis[t]; string action = string.Format("{0}:{1}:{2}", jc.Navigation.Action, jc.IsPost, MobileDetect.Instance.IsMobile); if (!mis.ContainsKey(action)) { lock (mis) { if (!mis.ContainsKey(action)) { List<MethodInfo> methods = new List<MethodInfo>(t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); methods.Sort((x, y) => { bool hasPostAttr = x.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; bool hasPostAttr_2 = y.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; int v = hasPostAttr_2.CompareTo(hasPostAttr); if (v == 0) { ParameterInfo[] paras = x.GetParameters(); bool hasMobileParam1 = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); paras = y.GetParameters(); bool hasMobileParam2 = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); return hasMobileParam2.CompareTo(hasMobileParam1); } return v; }); mis[action] = null; foreach (MethodInfo m in methods) { bool hasPostAttr = m.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; bool hasGetAttr = m.GetCustomAttributes(typeof(HttpGetAttribute), false).Length == 1; bool hasAjaxAttr = m.GetCustomAttributes(typeof(Ajax.AjaxMethodAttribute), true).Length > 0; ParameterInfo[] paras = m.GetParameters(); bool hasMobileParam = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); if (!m.ContainsGenericParameters && m.Name.Equals(jc.Navigation.Action, StringComparison.InvariantCultureIgnoreCase) && !hasAjaxAttr && ((hasMobileParam && MobileDetect.Instance.IsMobile) || (!hasMobileParam)) && ((jc.IsPost && hasPostAttr) || (!jc.IsPost && hasGetAttr) || (!hasPostAttr && !hasGetAttr))) { mis[action] = m; break; } } } } } return mis[action]; }
private byte[] GetFileContent(HttpContext context, string virtualPath) { byte[] content = null; try { JContext jc = JContext.Current; IArea site = jc.Area; string path = virtualPath; if (path.IndexOf("_res.aspx") == -1) { // 不是样式也不是脚本文件,返回null if (!path.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase) && !path.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase)) { return(null); } int index = path.IndexOf(site.VirtualPath); if (index != -1) { path = path.Substring(index + site.VirtualPath.Length); } if (path.StartsWith("themes", StringComparison.InvariantCultureIgnoreCase)) { path = path.Substring(6); path = string.Concat(VirtualPathUtility.ToAbsolute(jc.url(site.ThemeRoot)), path); } else if (index != -1) { path = StringUtil.CombinUrl(site.VirtualPath, path); } virtualPath = StringUtil.CombinUrl("/", path); string physicalPath = context.Server.MapPath(virtualPath); content = File.ReadAllBytes(physicalPath); } else { NameValueCollection qs = new NameValueCollection(); foreach (var item in new Url(virtualPath).GetQueries()) { qs[item.Key] = item.Value; } content = ResourceController.GetResourceContent(qs); } } catch (Exception ex) { logger.Error("file: {0} is not found. {1}", virtualPath, ExceptionUtil.WriteException(ex)); } if (content == null) { logger.Error("file: {0} is null.", virtualPath); return(null); } // remove bom byte if (content.Length <= 3 || !(content[0] == 0xEF && content[1] == 0xBB && content[2] == 0xBF)) { return(content); } using (var ms = new MemoryStream()) { ms.Write(content, 3, content.Length - 3); return(ms.ToArray()); } }
public static List <NavigationItem> GetDataSource(IArea site, MenuType type, string key) { JContext jc = JContext.Current; List <NavigationItem> list = new List <NavigationItem>(); int index = jc.Navigation.Index; int subIndex = jc.Navigation.SubIndex; int subsubIndex = jc.Navigation.SubsubIndex; Dictionary <int, NavigationItem> Items = UrlMappingModule.Instance.Provider.GetMenuItemsBySite(site); string currentSiteKey = jc.Area.AreaKey; // set menu index of root site if (site.AreaKey != currentSiteKey) { foreach (var k in Items.Keys) { if (string.Equals(Items[k].Name, currentSiteKey, StringComparison.InvariantCultureIgnoreCase)) { index = k; } foreach (var k2 in Items[k].Children.Keys) { if (string.Equals(Items[k].Children[k2].Name, currentSiteKey, StringComparison.InvariantCultureIgnoreCase)) { index = k; subIndex = k2; } } } } List <int> keys; int key_index; switch (type) { case MenuType.TopLevel: keys = new List <int>(Items.Keys); foreach (int i in Items.Keys) { NavigationItem item = Items[i].Clone() as NavigationItem; item.Selected = index == i; item.Url = GetUrl(site, item.Url); key_index = keys.IndexOf(i); item.IsFirst = key_index == 0 || Items[keys[key_index - 1]].IsSeparator; item.IsLast = key_index == Items.Count - 1 || Items[keys[key_index + 1]].IsSeparator; list.Add(item); } break; case MenuType.SubLevel: if (Items.ContainsKey(index)) { Dictionary <int, NavigationItem> subItems = Items[index].Children; keys = new List <int>(subItems.Keys); foreach (int j in subItems.Keys) { NavigationItem subItem = subItems[j].Clone() as NavigationItem; subItem.Selected = subIndex == j; subItem.Url = GetUrl(site, subItem.Url); subItem.SubItems = new List <NavigationItem>(); key_index = keys.IndexOf(j); subItem.IsFirst = key_index == 0 || subItems[keys[key_index - 1]].IsSeparator; subItem.IsLast = key_index == subItems.Count - 1 || subItems[keys[key_index + 1]].IsSeparator; Dictionary <int, NavigationItem> subsub = Items[index].Children[j].Children; List <int> subsub_keys = new List <int>(subsub.Keys); foreach (int k in subsub.Keys) { NavigationItem subsubItem = subsub[k].Clone() as NavigationItem; subsubItem.Selected = subItem.Selected && subsubIndex == k; subsubItem.Url = GetUrl(site, subsubItem.Url); key_index = subsub_keys.IndexOf(k); subsubItem.IsFirst = key_index == 0 || subsub[subsub_keys[key_index - 1]].IsSeparator; subsubItem.IsLast = key_index == subsub.Count - 1 || subsub[subsub_keys[key_index + 1]].IsSeparator; subItem.SubItems.Add(subsubItem); } list.Add(subItem); } } break; case MenuType.SubsubLevel: if (Items.ContainsKey(index) && Items[index].Children.ContainsKey(subIndex)) { Dictionary <int, NavigationItem> subsub = Items[index].Children[subIndex].Children; List <int> subsub_keys = new List <int>(subsub.Keys); foreach (int k in subsub.Keys) { NavigationItem subsubItem = subsub[k].Clone() as NavigationItem; subsubItem.Selected = subsubIndex == k; subsubItem.Url = GetUrl(site, subsubItem.Url); key_index = subsub_keys.IndexOf(k); subsubItem.IsFirst = key_index == 0 || subsub[subsub_keys[key_index - 1]].IsSeparator; subsubItem.IsLast = key_index == subsub.Count - 1 || subsub[subsub_keys[key_index + 1]].IsSeparator; list.Add(subsubItem); } } break; case MenuType.Cascade: keys = new List <int>(Items.Keys); foreach (int i in keys) { NavigationItem item = Items[i].Clone() as NavigationItem; item.Selected = index == i; item.Url = GetUrl(site, item.Url); item.SubItems = new List <NavigationItem>(); key_index = keys.IndexOf(i); item.IsFirst = key_index == 0 || Items[keys[key_index - 1]].IsSeparator; item.IsLast = key_index == Items.Count - 1 || Items[keys[key_index + 1]].IsSeparator; Dictionary <int, NavigationItem> sub = Items[i].Children; List <int> sub_keys = new List <int>(sub.Keys); foreach (int j in sub.Keys) { NavigationItem subItem = sub[j].Clone() as NavigationItem; subItem.Selected = item.Selected && subIndex == j; subItem.Url = GetUrl(site, subItem.Url); subItem.SubItems = new List <NavigationItem>(); key_index = sub_keys.IndexOf(j); subItem.IsFirst = key_index == 0 || sub[sub_keys[key_index - 1]].IsSeparator; subItem.IsLast = key_index == sub.Count - 1 || sub[sub_keys[key_index + 1]].IsSeparator; Dictionary <int, NavigationItem> subsub = Items[i].Children[j].Children; List <int> subsub_keys = new List <int>(subsub.Keys); foreach (int k in subsub.Keys) { NavigationItem subsubItem = subsub[k].Clone() as NavigationItem; subsubItem.Selected = subItem.Selected && subsubIndex == k; subsubItem.Url = GetUrl(site, subsubItem.Url); key_index = subsub_keys.IndexOf(k); subsubItem.IsFirst = key_index == 0 || subsub[subsub_keys[key_index - 1]].IsSeparator; subsubItem.IsLast = key_index == subsub.Count - 1 || subsub[subsub_keys[key_index + 1]].IsSeparator; subItem.SubItems.Add(subsubItem); } item.SubItems.Add(subItem); } list.Add(item); } break; case MenuType.Self: List <UrlMappingItem> items = UrlMappingModule.Instance.Provider.UrlMappings.FindAll(delegate(UrlMappingItem item) { if (StringUtil.HasText(key)) { return(item.Index == index && item.SubIndex == subIndex && item["key"] == key); } else { return(item.Index == index && item.SubIndex == subIndex); } }); items.Sort(); foreach (UrlMappingItem i in items) { SerializerData sd = i.GetSerializerData(); NavigationItem nav = new NavigationItem() { Selected = (i.SelfIndex == JContext.Current.Navigation.Url.SelfIndex), Url = StringUtil.CombinUrl(site.VirtualPath, i.UrlTemplate.Replace("[page]", "1")), Title = i.Title }; nav.SetSerializerData(sd); list.Add(nav); } break; default: break; } FilterEventArgs e = new FilterEventArgs(); e.Type = type; e.Items = list; e.Site = site; OnBeforeFilter(e); return(e.Items); }
public bool InvokeAction(JContext jc) { MethodInfo mi = getActionMethod(jc); if (mi == null) { return(false); } object ret = null; try { if (jc.User != null) { object[] attrs = mi.GetCustomAttributes(typeof(PermissionAttribute), true); if (attrs.Length > 0) { PermissionAttribute attr = attrs[0] as PermissionAttribute; if (!string.IsNullOrEmpty(attr.Permission)) { if (jc.User.HasPermission(attr.Permission)) { goto execute; } else { jc.User.OnPermissionDenied(new PermissionDeniedEventArgs(attr.Permission)); } } } } else { goto execute; } execute: // before execute action Controller.BeforeActionExecuteEventArgs e = new Controller.BeforeActionExecuteEventArgs() { JContext = jc }; jc.Controller.OnBeforeActionExecute(e); Controller.AfterActionExecuteEventArgs e2 = new Controller.AfterActionExecuteEventArgs() { JContext = jc }; if (e.PreventDefault) { ret = e.ReturnValue; } bool support_embed = false; if (jc.IsPost) { jc.RenderContent = false; if (!e.PreventDefault) { NameValueCollection form = jc.Form; // 在post表单中加入key不存在的querystring值 foreach (string key in jc.QueryString.Keys) { if (form[key] == null) { form[key] = jc.QueryString[key]; } } ret = execute(jc.Controller, mi, form); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); } else if (!jc.RenderContent) { ResponseUtil.OutputJson(jc.Context.Response, ret); } } } else { if (!e.PreventDefault) { ret = execute(jc.Controller, mi, jc.QueryString); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); support_embed = ret is ViewResult; } else { jc.RenderContent = false; int cacheMinutes = 0; object[] attrs = mi.GetCustomAttributes(typeof(HttpGetAttribute), false); if (attrs.Length == 1) { cacheMinutes = (attrs[0] as HttpGetAttribute).CacheMinutes; } ResponseUtil.OutputJson(jc.Context.Response, ret, cacheMinutes); } } else { support_embed = true; } } if (support_embed && jc.IsEmbed) { jc.RenderContent = false; ResponseUtil.OutputJson(jc.Context.Response, new TemplatedControl() { UsedInMvc = jc.Context.Request.Headers["usedinmvc"].ToBoolean(true), OverrideSkinName = true, Templated = true }.Execute()); } // 发送控制器执行时间的消息 send_action_execute_msg(jc); } catch (ThreadAbortException) { }// ignore this exception catch (Exception ex) { jc.Controller.OnException(ex); } return(true); }
/// <summary> /// execute mvc action result /// </summary> public abstract void ExecuteResult(JContext jc);
private MethodInfo getActionMethod(JContext jc) { Type t = jc.Controller.GetType(); if (!_mis.ContainsKey(t)) { lock (_mis) { if (!_mis.ContainsKey(t)) { _mis[t] = new Dictionary <string, MethodInfo>(); } } } Dictionary <string, MethodInfo> mis = _mis[t]; string action = string.Format("{0}:{1}:{2}", jc.Navigation.Action, jc.IsPost, MobileDetect.Instance.IsMobile); if (!mis.ContainsKey(action)) { lock (mis) { if (!mis.ContainsKey(action)) { List <MethodInfo> methods = new List <MethodInfo>(t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)); methods.Sort((x, y) => { bool hasPostAttr = x.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; bool hasPostAttr_2 = y.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; int v = hasPostAttr_2.CompareTo(hasPostAttr); if (v == 0) { ParameterInfo[] paras = x.GetParameters(); bool hasMobileParam1 = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); paras = y.GetParameters(); bool hasMobileParam2 = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); return(hasMobileParam2.CompareTo(hasMobileParam1)); } return(v); }); mis[action] = null; foreach (MethodInfo m in methods) { bool hasPostAttr = m.GetCustomAttributes(typeof(HttpPostAttribute), false).Length == 1; bool hasGetAttr = m.GetCustomAttributes(typeof(HttpGetAttribute), false).Length == 1; bool hasAjaxAttr = m.GetCustomAttributes(typeof(Ajax.AjaxMethodAttribute), true).Length > 0; ParameterInfo[] paras = m.GetParameters(); bool hasMobileParam = paras.Length > 0 && paras[0].ParameterType == typeof(MobileDetect); if (!m.ContainsGenericParameters && m.Name.Equals(jc.Navigation.Action, StringComparison.InvariantCultureIgnoreCase) && !hasAjaxAttr && ((hasMobileParam && MobileDetect.Instance.IsMobile) || (!hasMobileParam)) && ((jc.IsPost && hasPostAttr) || (!jc.IsPost && hasGetAttr) || (!hasPostAttr && !hasGetAttr))) { mis[action] = m; break; } } } } } return(mis[action]); }
protected void RerouteRequest(HttpApplication app, string newPath, NameValueCollection qs, NameValueCollection incomingQS) { JContext jc = JContext.Current; // signal to the future page handler that we rerouted from a different URL HttpContext.Current.Items.Add(kCONTEXTITEMS_RAWURLKEY, HttpContext.Current.Request.RawUrl); HttpContext.Current.Items.Add(kCONTEXTITEMS_ADDEDQSKEY, qs); NameValueCollection urlQueryString = null; if (newPath.Contains("?")) { Url url = new Url(newPath); if (StringUtil.HasText(url.Query)) { urlQueryString = StringUtil.CommaDelimitedEquation2NVCollection(url.Query); urlQueryString.Remove("kissMasterFile"); } } // apply the querystring to the path newPath = ApplyQueryString(newPath, qs); jc.QueryString.Clear(); jc.QueryString.Add(qs); if (urlQueryString != null && urlQueryString.HasKeys()) { jc.QueryString.Add(urlQueryString); } // if configured, apply the incoming query string variables too if (_qsBehavior == IncomingQueryStringBehavior.PassThrough) { NameValueCollection _qs = new NameValueCollection(incomingQS); _qs.Remove("kissMasterFile"); _qs.Remove("__VIEWSTATE"); newPath = ApplyQueryString(newPath, _qs); foreach (string item in _qs.Keys) { jc.QueryString[item] = _qs[item]; } } // perform the redirection if (newPath.StartsWith("~/")) { HttpContext.Current.RewritePath(newPath, false); } else if (newPath.StartsWith("/")) { app.Response.Redirect(jc.url(newPath)); } else if (newPath.StartsWith("http:") || newPath.StartsWith("https:")) { app.Response.Status = "301 Moved Permanently"; app.Response.AddHeader("Location", newPath); app.Response.End(); } else { // otherwise, treat it as a local file and force the virtual path HttpContext.Current.RewritePath("~/" + newPath, false); } }
void proc() { JContext jc = JContext.Current; HttpContext context = jc.Context; // set a ajax request token jc.IsAjaxRequest = true; // get querystring string qs = context.Request.Params["querystring"]; if (StringUtil.HasText(qs)) { qs = qs.TrimStart('?'); jc.QueryString.Add(StringUtil.DelimitedEquation2NVCollection("&", qs)); } if (context.Request.UrlReferrer != null) { UrlMappingModule module = UrlMappingModule.Instance; if (module != null) { UrlMappingItem mapping = null; jc.QueryString.Add(module.GetMappedQueryString(context.Request.UrlReferrer.AbsolutePath, out mapping)); if (mapping != null) { NavigationInfo navi = new NavigationInfo(); navi.Set(mapping, UrlMappingModule.GetUrlRequested(context.Request.UrlReferrer.AbsolutePath)); jc.Navigation = navi; // fire url matched event module.OnUrlMatched(); } } } // set view data UrlMappingModule.SetViewData(); string classId = context.Request.Params[CLASS_ID_PARAM]; string methodName = context.Request.Params[METHOD_NAME_PARAM]; string methodJsonArgs = context.Request.Params[METHOD_ARGS_PARAM]; string jsonp = context.Request.Params[JSONP]; object result; int cacheMinutes = -1; if (string.IsNullOrEmpty(classId) || string.IsNullOrEmpty(methodName)) { result = "null"; } else { AjaxConfiguration config = AjaxConfiguration.GetConfig(); AjaxMethod m = null; try { string id = jc.Navigation.Id; if (id.Contains(":")) { id = id.Substring(id.IndexOf(":") + 1); } AjaxClass c = config.FindClass(classId, id); m = config.FindMethod(c, methodName); if (string.Equals("Post", m.AjaxType, StringComparison.InvariantCultureIgnoreCase)) { cacheMinutes = -1; } else if (StringUtil.HasText(m.CacheTest)) { cacheMinutes = methodJsonArgs.Equals(m.CacheTest) ? cacheMinutes : -1; } // before execute BeforeExecuteEventArgs e = new BeforeExecuteEventArgs() { JContext = jc, TypeName = c.Key, MethodName = m.MethodName }; OnBeforeExecute(e); if (e.PreventDefault) { result = e.ReturnValue; goto response; } if (c.Type != null) { result = m.Invoke(c.Type, methodJsonArgs); } else { result = m.Invoke(c.TypeString, methodJsonArgs); } } catch (Exception ex) { LogManager.GetLogger <AjaxController>().Error("ajax handler error." + ExceptionUtil.WriteException(ex)); AjaxServerException ajaxEx = null; if (m != null) { ajaxEx = m.Exception; } if (ajaxEx != null) { result = ajaxEx.ToJson(); } else { result = null; } } } goto response; response: OnAfterExecute(result); ResponseUtil.OutputJson(context.Response, result, cacheMinutes, jsonp); ContentType = context.Response.ContentType; }
/// <summary> /// execute mvc action result /// </summary> public abstract void ExecuteResult( JContext jc );
public bool InvokeAction(JContext jc) { MethodInfo mi = getActionMethod(jc); if (mi == null) return false; object ret = null; try { if (jc.User != null) { object[] attrs = mi.GetCustomAttributes(typeof(PermissionAttribute), true); if (attrs.Length > 0) { PermissionAttribute attr = attrs[0] as PermissionAttribute; if (!string.IsNullOrEmpty(attr.Permission)) { if (jc.User.HasPermission(attr.Permission)) goto execute; else jc.User.OnPermissionDenied(new PermissionDeniedEventArgs(attr.Permission)); } } } else { goto execute; } execute: // before execute action Controller.BeforeActionExecuteEventArgs e = new Controller.BeforeActionExecuteEventArgs() { JContext = jc }; jc.Controller.OnBeforeActionExecute(e); Controller.AfterActionExecuteEventArgs e2 = new Controller.AfterActionExecuteEventArgs() { JContext = jc }; if (e.PreventDefault) { ret = e.ReturnValue; } bool support_embed = false; if (jc.IsPost) { jc.RenderContent = false; if (!e.PreventDefault) { NameValueCollection form = jc.Form; // 在post表单中加入key不存在的querystring值 foreach (string key in jc.QueryString.Keys) { if (form[key] == null) form[key] = jc.QueryString[key]; } ret = execute(jc.Controller, mi, form); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); } else if (!jc.RenderContent) { ResponseUtil.OutputJson(jc.Context.Response, ret); } } } else { if (!e.PreventDefault) { ret = execute(jc.Controller, mi, jc.QueryString); } e2.Result = ret; jc.Controller.OnAfterActionExecute(e2); ret = e2.Result; if (ret != null) { if (ret is ActionResult) { ActionResult actionResult = ret as ActionResult; actionResult.ExecuteResult(jc); support_embed = ret is ViewResult; } else { jc.RenderContent = false; int cacheMinutes = 0; object[] attrs = mi.GetCustomAttributes(typeof(HttpGetAttribute), false); if (attrs.Length == 1) { cacheMinutes = (attrs[0] as HttpGetAttribute).CacheMinutes; } ResponseUtil.OutputJson(jc.Context.Response, ret, cacheMinutes); } } else { support_embed = true; } } if (support_embed && jc.IsEmbed) { jc.RenderContent = false; ResponseUtil.OutputJson(jc.Context.Response, new TemplatedControl() { UsedInMvc = jc.Context.Request.Headers["usedinmvc"].ToBoolean(true), OverrideSkinName = true, Templated = true }.Execute()); } } catch (ThreadAbortException) { }// ignore this exception catch (Exception ex) { if (ex is TargetInvocationException) ex = ex.InnerException; jc.Controller.OnException(ex); } return true; }
public ExportHelper(int? pageSize, string filename, JContext jc) : this(StringUtil.HasText(jc.QueryString["export"]), pageSize, filename, jc) { }
public ExportHelper(string filename, JContext jc) : this(10, filename, jc) { }
void QueryCondition_BeforeQuery(object sender, QueryCondition.BeforeQueryEventArgs e) { //leixu 2015年10月29日16:01:30 if (HttpContext.Current == null) { return; } QueryCondition q = sender as QueryCondition; JContext jc = JContext.Current; Qc qc = null; string qId = q.Id; string sitekey = jc.Area.AreaKey; if (qId == null) { qId = jc.Navigation.ToString(); } else { if (qId.Contains(":")) { string[] ar = StringUtil.Split(qId, ":", true, true); sitekey = ar[0]; qId = ar[1]; } } if (string.IsNullOrEmpty(qId)) { return; } qc = GetById(sitekey, string.Format("{0}.{1}.{2}", qId, e.Method, e.DbProviderName)); if (qc == null) { qc = GetById(sitekey, string.Format("{0}.{1}", qId, e.Method)); } if (qc == null) { qc = GetById(sitekey, string.Format("{0}.{1}", qId, e.DbProviderName)); } if (qc == null) { qc = GetById(sitekey, qId); } if (qc == null) { _logger.Warn("query:{0} not found!", q.Id); return; } if (qc.PageSize > -1 && q.PageSize == -1) { q.PageSize = qc.PageSize; } q.Parameters.Clear(); if ((string.IsNullOrEmpty(q.TableField) || q.TableField == "*" || q.EventFiredTimes > 1) && StringUtil.HasText(qc.Field)) { if (qc.Field.Contains("$")) { using (StringWriter writer = new StringWriter()) { Dictionary <string, object> di = new Dictionary <string, object>(jc.ViewData); di["this"] = sender; ServiceLocator.Instance.Resolve <ITemplateEngine>().Process(di, string.Empty, writer, qc.Field); q.TableField = writer.GetStringBuilder().ToString(); } } else { q.TableField = qc.Field; } } // 解析field里的@参数 Match m = Regex.Match(q.TableField, @"@\w+"); while (m.Success) { string param_name = m.Value.Substring(1).Trim(); if (q[param_name] != null) { q.Parameters[param_name] = q[param_name]; } m = m.NextMatch(); } if (StringUtil.HasText(qc.AllowedOrderbyColumns)) { q.AllowedOrderbyColumns.AddRange(StringUtil.CommaDelimitedListToStringArray(qc.AllowedOrderbyColumns)); } if (StringUtil.HasText(qc.Orderby)) { List <string> ls = new List <string>(StringUtil.CommaDelimitedListToStringArray(qc.Orderby)); if (q.IsAddOrderBy2First) { ls.Reverse(); foreach (string oderby in ls) { q.InsertOrderby(0, oderby.TrimStart('-'), !oderby.StartsWith("-")); } } else { foreach (string oderby in ls) { q.AddOrderby(oderby.TrimStart('-'), !oderby.StartsWith("-")); } } } foreach (string key in qc.Keys) { q[key] = qc[key]; } using (StringWriter writer = new StringWriter()) { Dictionary <string, object> di = new Dictionary <string, object>(jc.ViewData); di["this"] = sender; ServiceLocator.Instance.Resolve <ITemplateEngine>().Process(di, string.Empty, writer, qc.Where); string sql = Regex.Replace(writer.GetStringBuilder().ToString(), @"\s{1,}|\t|\r|\n", " "); // 解析where里的@参数 m = Regex.Match(sql, @"@\w+"); while (m.Success) { string param_name = m.Value.Substring(1).Trim(); if (q[param_name] != null) { q.Parameters[param_name] = q[param_name]; } m = m.NextMatch(); } if (StringUtil.HasText(sql)) { q.WhereClause = sql; } } }