/// <summary> /// This is the very first point where Sprocket interrupts the ASP.Net HTTP pipeline /// and allows itself to start handling requests. Note that this is way before the /// standard ASP.Net page framework would kick in. At this point state information like /// cookies and sessions have not yet been loaded. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> internal void FireBeginRequest(object sender, EventArgs e) { HandleFlag handled = new HandleFlag(); if (OnBeginHttpRequest != null) { OnBeginHttpRequest((HttpApplication)sender, handled); } if (handled.Handled) { HttpContext.Current.Response.End(); return; } // The SprocketSettings module is one of the modules that handles the OnBeginHttpRequest // event. It lets each module check for any .config file errors (or other settings errors) // and report them back here. If we get to this point and at least one module has reported // a settings error, we show Sprocket's critical error page which has a nice list of // error messages that the user can try to rectify. if (((SprocketSettings)SystemCore.Instance["SprocketSettings"]).ErrorList.HasCriticalError) { ShowErrorPage(); return; } }
void Instance_OnLoadRequestedPath(HandleFlag handled) { if (handled.Handled) { return; } if (SprocketPath.Value == "$dbsetup") { Result result = DatabaseManager.DatabaseEngine.Initialise(); if (result.Succeeded) { HttpContext.Current.Response.Write("<p>Database setup completed.</p>"); if (Completed != null) { Completed(); } WebUtility.Redirect("admin"); } else { HttpContext.Current.Response.Write("<h2>Unable to Initialise Database</h2><p>" + result.Message + "</p>"); } handled.Set(); } }
/// <summary> /// This is the very first point where Sprocket interrupts the ASP.Net HTTP pipeline /// and allows itself to start handling requests. Note that this is way before the /// standard ASP.Net page framework would kick in. At this point state information like /// cookies and sessions have not yet been loaded. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> internal void FireBeginRequest(object sender, EventArgs e) { if (!AjaxRequestHandler.IsAjaxRequest) { // The SprocketPath refers to the bit after the application base path and before the // querystring, minus any leading and trailing forward-slashes. (/) For example if the // full URL is "http://www.sprocketcms.com/myapp/admin/users/?edit" and the subdirectory // "myapp" is a virtual directory (IIS application) then the SprocketPath would be // "admin/users". string sprocketPath = null; string appPath = HttpContext.Current.Request.Path.ToLower(); // check to see if there's a trailing slash and if there isn't, redirect to stick a trailing // slash onto the path. This is to keep pathing consistent because otherwise relative paths // (such as to images and css files) aren't pathed as expected. We DON'T do this if a form // has been posted however, because otherwise we lose the contents of the posted form. It is // assumed that if you forget to post to a path with a trailing slash, that once you finish // processing the form that you'll redirect off to a secondary page anyway, which means // sticking a slash on the end of this URL is unnecessary anyway. if (!appPath.EndsWith("/") && !appPath.Contains(".") && HttpContext.Current.Request.Form.Count == 0) { HttpContext.Current.Response.Redirect(appPath + "/"); HttpContext.Current.Response.End(); return; } // changes (e.g.) "http://www.sprocketcms.com/myapp/admin/users/?edit" into "admin/users" SprocketPath.Parse(HttpContext.Current.Request.Url); //sprocketPath = appPath.Remove(0, HttpContext.Current.Request.ApplicationPath.Length).Trim('/'); //SprocketPath.Value = sprocketPath; //SprocketPath.Sections = SprocketPath.Value.Split('/'); } HandleFlag handled = new HandleFlag(); if (OnBeginHttpRequest != null) { OnBeginHttpRequest(handled); } if (handled.Handled) { HttpContext.Current.Response.End(); return; } // The SprocketSettings module is one of the modules that handles the OnBeginHttpRequest // event. It lets each module check for any .config file errors (or other settings errors) // and report them back here. If we get to this point and at least one module has reported // a settings error, we show Sprocket's critical error page which has a nice list of // error messages that the user can try to rectify. if (SprocketSettings.Errors.HasCriticalError) { ShowErrorPage(); return; } }
void Instance_OnLoadRequestedPath(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) return; if (sprocketPath == "$dbsetup") { DatabaseManager.Instance.ExecuteAllDataScripts(Database.Main.DatabaseEngine); HttpContext.Current.Response.Write("<p>Database setup completed.</p>"); handled.Set(); } }
void WebEvents_OnBeforeLoadExistingFile(HandleFlag handled) { if (!SprocketPath.Value.EndsWith(".js")) { return; } FileInfo file = new FileInfo(SprocketPath.Physical); TimeSpan maxCacheAge = new TimeSpan(24, 0, 0); HttpContext.Current.Response.Cache.SetLastModified(file.LastWriteTime); HttpContext.Current.Response.Cache.SetMaxAge(maxCacheAge); if (!CompressJavaScript) { return; } bool rewrite = false; string cachedJS = ContentCache.RetrieveText(SprocketPath.Value); if (cachedJS == null) { rewrite = true; } else if (!compressedJSFiles.ContainsKey(file.FullName)) { rewrite = true; } else if (compressedJSFiles[file.FullName] != file.LastWriteTime) { rewrite = true; } HttpContext.Current.Response.ContentType = "text/javascript"; if (rewrite) { try { using (StreamReader reader = file.OpenText()) { string s = JavaScriptCondenser.Condense(reader.ReadToEnd()); HttpContext.Current.Response.Write(s); ContentCache.StoreText(SprocketPath.Value, maxCacheAge, true, s); reader.Close(); compressedJSFiles[file.FullName] = file.LastWriteTime; } } catch { return; // if an error occurs, let the system serve up the file normally } } else { HttpContext.Current.Response.Write(cachedJS); } handled.Set(); }
void OnBeginHttpRequest(HandleFlag handled) { if (handled.Handled) { return; } if (IsAjaxRequest) { handled.Set(); ProcessRequest(HttpContext.Current); } }
void Instance_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (sprocketPath == "scripttest") { string html = Sprocket.Utility.ResourceLoader.LoadTextResource("Sprocket.Web.CMS.SprocketScript.test.htm"); SprocketScript script = new SprocketScript(html); HttpContext.Current.Response.ContentType = "text/html"; script.Execute(HttpContext.Current.Response.OutputStream); //string test = script.Execute(); //HttpContext.Current.Response.Write(test); handled.Set(); } }
void OnBeginHttpRequest(HttpApplication app, HandleFlag handled) { if (handled.Handled) { return; } if (app.Context.Request.Path.EndsWith(".ajax")) { handled.Set(); ProcessRequest(HttpContext.Current); } }
void OnPathNotFound(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) return; if (!sprocketPath.Contains(".")) return; string urlpath; if (pathSections.Length == 1) urlpath = ""; else urlpath = sprocketPath.Substring(0, sprocketPath.Length - pathSections[pathSections.Length - 1].Length - 1); XmlElement node = (XmlElement)PagesXml.SelectSingleNode("//Page[@Path='" + urlpath + "']"); if (node == null) return; string newurl = "resources/content/" + node.GetAttribute("ContentFile"); newurl = WebUtility.BasePath + newurl.Substring(0, newurl.LastIndexOf('/') + 1) + pathSections[pathSections.Length - 1]; if (!File.Exists(HttpContext.Current.Server.MapPath(newurl))) return; string file = HttpContext.Current.Server.MapPath(newurl); switch (new FileInfo(file).Extension) { case ".jpg": HttpContext.Current.Response.ContentType = "image/jpg"; break; case ".gif": HttpContext.Current.Response.ContentType = "image/gif"; break; case ".png": HttpContext.Current.Response.ContentType = "image/png"; break; } HttpContext.Current.Response.TransmitFile(file); handled.Set(); }
void ContentCache_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) return; else if (sprocketPath == "$clear-cache") { if (OnCacheClearanceRequested != null) { Result r = new Result(); OnCacheClearanceRequested(r); if (!r.Succeeded) { HttpContext.Current.Response.Write(r.Message); handled.Set(); return; } } ClearCache(); HttpContext.Current.Response.Write("The cache has been cleared."); handled.Set(); } else if (sprocketPath == "datastore\\content-cache" || sprocketPath.StartsWith("datastore\\content-cache\\")) { handled.Set(); HttpContext.Current.Response.Write("Access denied."); } }
void OnBeginHttpRequest(HttpApplication appInst, HandleFlag handled) { HttpApplicationState app = HttpContext.Current.Application; app.Lock(); if (app["Sprocket_PGREQ_XmlCache_Count"] == null) app["Sprocket_PGREQ_XmlCache_Count"] = 1; else app["Sprocket_PGREQ_XmlCache_Count"] = (int)app["Sprocket_PGREQ_XmlCache_Count"] + 1; app.UnLock(); }
void OnLoadRequestedPath(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) return; if (!File.Exists(WebUtility.MapPath(PageRegistry.XmlFilePath))) return; switch (sprocketPath) { case "$reset": PageRegistry.UpdateValues(); TemplateRegistry.Reload(); ListRegistry.Reload(); OutputFormatRegistry.Reload(); GeneralRegistry.Reload(); ContentCache.ClearCache(); WebUtility.Redirect(""); break; default: PageRegistry.CheckDate(); PageEntry page = PageRegistry.Pages.FromPath(sprocketPath); if(page == null) return; if (OnBeforeRenderPage != null) OnBeforeRenderPage(page, sprocketPath, pathSections); string output = page.Render(); if (output == null) return; Response.Write(output); break; } handled.Set(); }
void ContentCache_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) { return; } else if (sprocketPath == "$clear-cache") { if (OnCacheClearanceRequested != null) { Result r = new Result(); OnCacheClearanceRequested(r); if (!r.Succeeded) { HttpContext.Current.Response.Write(r.Message); handled.Set(); return; } } ClearCache(); HttpContext.Current.Response.Write("The cache has been cleared."); handled.Set(); } else if (sprocketPath == "datastore\\content-cache" || sprocketPath.StartsWith("datastore\\content-cache\\")) { handled.Set(); HttpContext.Current.Response.Write("Access denied."); } }
/// <summary> /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> internal void FireAcquireRequestState(object sender, EventArgs e) { if (OnRequestStateLoaded != null) // as always, let the other modules know where we are... { OnRequestStateLoaded(); } if (HttpContext.Current.Request.Form != null) { if (HttpContext.Current.Request.Form.Count > 0) { foreach (FormPostAction action in formPostActions) { if (action.PostFromPath != null) { if (action.PostFromPath != SprocketPath.ExtractSprocketPath(HttpContext.Current.Request.UrlReferrer.ToString())) { continue; } } if (action.PostToPath != null) { if (action.PostToPath.ToLower() != SprocketPath.Value) { continue; } } if (action.FieldName != null) { string s = HttpContext.Current.Request.Form[action.FieldName]; if (s == null) { continue; } if (action.FieldValue != null) { if (s != action.FieldValue) { continue; } } } action.PostHandler(); } } } // this is our flag so that request event handlers can let us know if they handled this request. HandleFlag flag = new HandleFlag(); if (OnLoadRequestedPath != null) { OnLoadRequestedPath(flag); if (flag.Handled) { // stop the browser from caching the page // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); if (OnRequestedPathProcessed != null) { OnRequestedPathProcessed(); } // if one of the modules handled the request event, then we can stop // doing stuff now. The OnEndRequest event will still be called though. HttpContext.Current.Response.End(); return; } } // if we've reached this point and none of our modules have volunteered to handle // the request, we can check to see if the requested path actually exists (gasp!) // and if so, serve up that file! This is handy if we insist on using the Standard // ASP.Net Page framework (yuck) or want to serve up other things like plain html // files. if (!flag.Handled && File.Exists(HttpContext.Current.Request.PhysicalPath)) { // here we provide a last chance opportunity to alter the response before the // file is served. if (OnBeforeLoadExistingFile != null) { OnBeforeLoadExistingFile(flag); if (flag.Handled) { HttpContext.Current.Response.End(); return; } } HttpContext.Current.RewritePath(HttpContext.Current.Request.Path); return; } // at this point we know that no file matching the exists, so we can check to see // if a directory of the specified name exists. If it does, we can see if there are // any default pages inside the folder that should execute. This requires the a key // to be configured for appSettings in the Web.config file: // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" /> if (Directory.Exists(HttpContext.Current.Request.PhysicalPath)) { string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames"); if (dpgstr != null) { string[] pgarr = dpgstr.Split(','); foreach (string pgname in pgarr) { string pgpath = "/" + HttpContext.Current.Request.Path.Trim('/') + "/" + pgname; string physpath = HttpContext.Current.Request.PhysicalPath + "\\" + pgname; if (File.Exists(physpath)) { HttpContext.Current.Response.Redirect(pgpath); return; } } } } // if we've reached this point and still havent found anything that wants to handle // the current request, we offer up a final chance to respond to this fact... if (OnPathNotFound != null) { OnPathNotFound(flag); if (flag.Handled) { if (OnRequestedPathProcessed != null) { OnRequestedPathProcessed(); } HttpContext.Current.Response.End(); return; } } // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page. }
/// <summary> /// Sprocket calls this method in response to ASP.Net's AcquireRequestState event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> internal void FireAcquireRequestState(object sender, EventArgs e) { if (OnRequestStateLoaded != null) // as always, let the other modules know where we are... { OnRequestStateLoaded((HttpApplication)sender); } HttpContext pg = HttpContext.Current; // The SprocketPath refers to the bit after the application base path and before the // querystring, minus any leading and trailing forward-slashes. (/) For example if the // full URL is "http://www.sprocketcms.com/myapp/admin/users/?edit" and the subdirectory // "myapp" is a virtual directory (IIS application) then the SprocketPath would be // "admin/users". string sprocketPath = null; string appPath = pg.Request.Path.ToLower(); // check to see if there's a trailing slash and if there isn't, redirect to stick a trailing // slash onto the path. This is to keep pathing consistent because otherwise relative paths // (such as to images and css files) aren't pathed as expected. We DON'T do this if a form // has been posted however, because otherwise we lose the contents of the posted form. It is // assumed that if you forget to post to a path with a trailing slash, that once you finish // processing the form that you'll redirect off to a secondary page anyway, which means // sticking a slash on the end of this URL is unnecessary anyway. if (!appPath.EndsWith("/") && !appPath.Contains(".") && HttpContext.Current.Request.Form.Count == 0) { pg.Response.Redirect(appPath + "/"); pg.Response.End(); return; } // changes (e.g.) "http://www.sprocketcms.com/myapp/admin/users/?edit" into "admin/users" sprocketPath = appPath.Remove(0, pg.Request.ApplicationPath.Length).Trim('/'); // split up the path sections to make things even easier for request event handlers string[] pathSections = sprocketPath.Split('/'); // this is our flag so that request event handlers can let us know if they handled this request. HandleFlag flag = new HandleFlag(); if (OnLoadRequestedPath != null) { OnLoadRequestedPath((HttpApplication)sender, sprocketPath, pathSections, flag); if (flag.Handled) { // stop the browser from caching the page // HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); // if one of the modules handled the request event, then we can stop // doing stuff now. The OnEndRequest event will still be called though. pg.Response.End(); return; } } // if we've reached this point and none of our modules have volunteered to handle // the request, we can check to see if the requested path actually exists (gasp!) // and if so, serve up that file! This is handy if we insist on using the Standard // ASP.Net Page framework (yuck) or want to serve up other things like plain html // files. if (!flag.Handled && File.Exists(pg.Request.PhysicalPath)) { // here we provide a last chance opportunity to alter the response before the // file is served. if (OnBeforeLoadExistingFile != null) { OnBeforeLoadExistingFile((HttpApplication)sender, sprocketPath, pathSections, flag); if (flag.Handled) { pg.Response.End(); return; } } HttpContext.Current.RewritePath(pg.Request.Path); return; } // at this point we know that no file matching the exists, so we can check to see // if a directory of the specified name exists. If it does, we can see if there are // any default pages inside the folder that should execute. This requires the a key // to be configured for appSettings in the Web.config file: // <add key="DefaultPageFilenames" value="default.aspx,default.asp,default.htm,index.htm" /> if (Directory.Exists(pg.Request.PhysicalPath)) { string dpgstr = SprocketSettings.GetValue("DefaultPageFilenames"); if (dpgstr != null) { string[] pgarr = dpgstr.Split(','); foreach (string pgname in pgarr) { string pgpath = "/" + pg.Request.Path.Trim('/') + "/" + pgname; string physpath = pg.Request.PhysicalPath + "\\" + pgname; if (File.Exists(physpath)) { HttpContext.Current.Response.Redirect(pgpath); return; } } } } // if we've reached this point and still havent found anything that wants to handle // the current request, we offer up a final chance to respond to this fact... if (OnPathNotFound != null) { OnPathNotFound((HttpApplication)sender, sprocketPath, pathSections, flag); if (flag.Handled) { pg.Response.End(); return; } } // if we got this far, sorry folks, but you're about to get a boring ASP.Net 404 page. }
void OnLoadRequestedPath(HttpApplication app, string path, string[] pathSections, HandleFlag handled) { if (path != "test") { return; } handled.Set(); HttpContext c = HttpContext.Current; c.Response.Write("QS Keys:<br/>"); for (int i = 0; i < c.Request.QueryString.Count; i++) { HttpContext.Current.Response.Write(c.Request.QueryString.GetKey(i) + " = " + c.Request.QueryString[i] + "<br/>"); } c.Response.Write("QS Form:<br/>"); for (int i = 0; i < c.Request.QueryString.Count; i++) { HttpContext.Current.Response.Write(c.Request.Form.GetKey(i) + " = " + c.Request.Form[i] + "<br/>"); } string html = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + WebUtility.BasePath; HttpContext.Current.Response.Write(html); //string scripts = ((WebClientScripts)SystemCore.Instance["WebClientScripts"]).BuildScriptTags(); //HttpContext.Current.Response.Write(scripts + html.Replace(Environment.NewLine, "<br />")); }
void OnLoadRequestedPath(HttpApplication app, string path, string[] pathSections, HandleFlag handled) { if (path != "sysinfo") { return; } handled.Set(); string html = ResourceLoader.LoadTextResource("Sprocket.Web.html.sysinfo.htm"); HttpResponse Response = HttpContext.Current.Response; string modules = "<tr>" + "<th nowrap=\"true\">Assembly</th>" + "<th nowrap=\"true\">Module Code</th>" + "<th nowrap=\"true\">Module Name</th>" + "<th>Description</th>" + "<th>Optional</th>" + "<th>DataHandler</th>" + "</tr>"; bool alt = false; List <ISprocketModule> bydll = new List <ISprocketModule>(); foreach (ISprocketModule module in SystemCore.Instance.ModuleRegistry) { bydll.Add(module); } bydll.Sort(new ModuleDLLSortComparer()); string oldf = ""; bool altf = true; bool newdllrow = true; foreach (ISprocketModule module in bydll) { string newf = new FileInfo(module.GetType().Assembly.Location).Name; string filename; if (oldf != newf) { filename = newf; oldf = newf; altf = !altf; newdllrow = true; } else { filename = " "; newdllrow = false; } modules += string.Format( "<tr class=\"row-{0}{2}\">" + "<td valign=\"top\" class=\"assembly-{1}\">" + filename + "</td>" + "<td valign=\"top\" class=\"module-code-{0}\"><strong>" + module.RegistrationCode + "</strong></td>" + "<td valign=\"top\" nowrap=\"true\" class=\"module-title-{0}\">" + module.Title + "</td>" + "<td valign=\"top\">" + module.ShortDescription + "</td>" + "<td valign=\"top\">" + (module is IOptionalModule ? "x" : " ") + "</td>" + "<td valign=\"top\">" + (module is IDataHandlerModule ? "x" : " ") + "</td>" + "</tr>", alt ? "alt2" : "alt1", altf ? "alt2" : "alt1", newdllrow ? " newdllrow" : ""); alt = !alt; } html = html.Replace("{modules}", modules); Response.Write(html); }
void OnBeginHttpRequest(HttpApplication app, HandleFlag handled) { if (handled.Handled) { return; } if (app.Context.Request.Path.EndsWith("module-hierarchy-diagram.gif")) { handled.Set(); int levels = 0; // the depth of the dependency hierarchy int pos = 0; // the number of horizontal positions that this level contains for the bordered boxes int maxpos = 1; // the highest box position for the current row Dictionary <string, int> modulePositions = new Dictionary <string, int>(); // store which horizontal position each module should have its box drawn in Dictionary <int, int> levelCounts = new Dictionary <int, int>(); // specify how many box positions are on each depth level foreach (RegisteredModule m in SystemCore.Instance.ModuleRegistry) { if (m.Importance > levels) // if we've hit the next depth level in the heirarchy { levels++; // set the number of the level we're now working at pos = 1; // specify that we're at horizontal position #1 on the image } else { pos++; maxpos = maxpos < pos ? pos : maxpos; } modulePositions[m.Module.RegistrationCode] = pos; levelCounts[levels] = pos; } int rectWidth = 110; int rectHeight = 50; int heightGap = 25; int widthGap = 15; int lineGap = 10; int bmpWidth = maxpos * rectWidth + (maxpos - 1) * widthGap + 11; // bmpHeight = top/bottom margins + combined height of boxes + the gaps between the levels int bmpHeight = (heightGap * 2) + (rectHeight * (levels + 1)) + (levels * heightGap) + 1; Bitmap bmp = new Bitmap(bmpWidth, bmpHeight); Graphics gfx = Graphics.FromImage(bmp); Pen pen = new Pen(Color.Red, 1); Brush whiteBrush = new SolidBrush(Color.White); Brush greyBrush = new SolidBrush(Color.WhiteSmoke); Brush blackBrush = new SolidBrush(Color.Black); Brush redBrush = new SolidBrush(Color.Red); Font font = new Font("Verdana", 7, FontStyle.Bold); gfx.FillRectangle(whiteBrush, 0, 0, bmpWidth, bmpHeight); gfx.SmoothingMode = SmoothingMode.AntiAlias; // draw rectangles foreach (RegisteredModule m in SystemCore.Instance.ModuleRegistry) { Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Module.RegistrationCode], levels, levelCounts[m.Importance], bmpWidth); gfx.FillRectangle(greyBrush, rect); gfx.DrawRectangle(pen, rect); } // draw lines foreach (RegisteredModule m in SystemCore.Instance.ModuleRegistry) { Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Module.RegistrationCode], levels, levelCounts[m.Importance], bmpWidth); ModuleDependencyAttribute[] atts = (ModuleDependencyAttribute[])Attribute.GetCustomAttributes(m.GetType(), typeof(ModuleDependencyAttribute), true); int attnum = 0; foreach (ModuleDependencyAttribute att in atts) { attnum++; RegisteredModule dm = SystemCore.ModuleCore.ModuleRegistry[att.Value]; int xmodstart = (rectWidth / 2) - ((atts.Length - 1) * lineGap) / 2 + ((attnum - 1) * lineGap); int xmodend = Math.Max(bmpWidth / 2 - (levelCounts[dm.Importance] * rectWidth + (levelCounts[dm.Importance] - 1) * widthGap) / 2, 0); int level = dm.Importance + 1; int dmxpos = modulePositions[dm.Module.RegistrationCode]; Point start = new Point(rect.X + xmodstart, rect.Y); Point end = new Point(xmodend + (dmxpos - 1) * rectWidth + (dmxpos - 1) * widthGap + rectWidth / 2, heightGap + level * rectHeight + (level - 1) * heightGap); Color color; switch (attnum % 7) { case 0: color = Color.Red; break; case 1: color = Color.Green; break; case 2: color = Color.Blue; break; case 3: color = Color.Violet; break; case 4: color = Color.Orange; break; case 5: color = Color.DarkCyan; break; default: color = Color.DarkSeaGreen; break; } gfx.DrawLine(new Pen(color), start, end); gfx.FillEllipse(new SolidBrush(color), start.X - 2, start.Y - 2, 5, 5); gfx.FillEllipse(redBrush, end.X - 2, end.Y - 2, 5, 5); } } // write words foreach (RegisteredModule m in SystemCore.Instance.ModuleRegistry) { Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Module.RegistrationCode], levels, levelCounts[m.Importance], bmpWidth); gfx.DrawString(m.Module.RegistrationCode, font, blackBrush, new PointF(rect.X + 3, rect.Y + 3)); } bmp.Save(app.Context.Response.OutputStream, ImageFormat.Jpeg); app.Context.Response.ContentType = "image/jpg"; } }
void Instance_OnBeforeLoadExistingFile(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (sprocketPath.EndsWith(".js")) { if (SprocketSettings.GetBooleanValue("CompressJavaScript")) { HttpContext.Current.Response.Write(WebUtility.CacheTextFile(sprocketPath, true)); handled.Set(); } } }
void Instance_OnBeforeLoadExistingFile(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if(sprocketPath.EndsWith(".js")) if (SprocketSettings.GetBooleanValue("CompressJavaScript")) { HttpContext.Current.Response.Write(WebUtility.CacheTextFile(sprocketPath, true)); handled.Set(); } }
void OnLoadRequestedPath(HttpApplication app, string path, string[] pathSections, HandleFlag handled) { if (path != "sysinfo") { return; } handled.Set(); string html = ResourceLoader.LoadTextResource("Sprocket.Web.html.sysinfo.htm"); HttpResponse Response = HttpContext.Current.Response; string modules = "<tr>" + "<th nowrap=\"true\">Assembly</th>" + "<th nowrap=\"true\">Module Namespace</th>" + "<th nowrap=\"true\">Module Name</th>" + "<th>Description</th>" + "</tr>"; bool alt = false; List <ISprocketModule> bydll = new List <ISprocketModule>(); int colorNum = -1; foreach (RegisteredModule module in Core.Instance.ModuleRegistry) { string asmname = new FileInfo(module.Module.GetType().Assembly.Location).Name; if (!dllColors.ContainsKey(asmname)) { colorNum++; if (colorNum >= colors.Length) { colorNum = 0; } dllColors.Add(asmname, colors[colorNum]); } bydll.Add(module.Module); } bydll.Sort(delegate(ISprocketModule x, ISprocketModule y) { string ax = new FileInfo(x.GetType().Assembly.Location).Name; string ay = new FileInfo(y.GetType().Assembly.Location).Name; int z = string.Compare(ax, ay, true); if (z != 0) { return(z); } return(string.Compare(x.GetType().FullName, y.GetType().FullName, true)); }); string oldf = ""; bool altf = true; bool newdllrow = true; foreach (ISprocketModule module in bydll) { string newf = new FileInfo(module.GetType().Assembly.Location).Name; string filename; if (oldf != newf) { filename = newf; oldf = newf; altf = !altf; newdllrow = true; } else { filename = " "; newdllrow = false; } RegisteredModule m = Core.Instance[module]; modules += string.Format( "<tr class=\"row-{0}{2}\">" + "<td valign=\"top\" class=\"assembly-{1}\">" + filename + "</td>" + "<td valign=\"top\" class=\"module-code-{0}\"><strong>" + m.Namespace + "</strong></td>" + "<td valign=\"top\" nowrap=\"true\" class=\"module-title-{0}\">" + m.Title + "</td>" + "<td valign=\"top\">" + m.Description + "</td>" + "</tr>", alt ? "alt2" : "alt1", altf ? "alt2" : "alt1", newdllrow ? " newdllrow" : ""); alt = !alt; } html = html.Replace("{modules}", modules); Response.Write(html); }
void OnBeginHttpRequest(HttpApplication app, HandleFlag handled) { if (handled.Handled) { return; } if (app.Context.Request.Path.EndsWith("module-hierarchy-diagram.gif")) { handled.Set(); int levels = 0; // the depth of the dependency hierarchy int pos = 0; // the number of horizontal positions that this level contains for the bordered boxes int maxpos = 1; // the highest box position for the current row Dictionary <string, int> modulePositions = new Dictionary <string, int>(); // store which horizontal position each module should have its box drawn in Dictionary <int, int> levelCounts = new Dictionary <int, int>(); // specify how many box positions are on each depth level foreach (RegisteredModule m in Core.Instance.ModuleRegistry) { if (m.Importance > levels) // if we've hit the next depth level in the heirarchy { levels++; // set the number of the level we're now working at pos = 1; // specify that we're at horizontal position #1 on the image } else { pos++; maxpos = maxpos < pos ? pos : maxpos; } modulePositions[m.Namespace] = pos; levelCounts[levels] = pos; } int rectWidth = 110; int rectHeight = 50; int heightGap = 25; int widthGap = 15; int lineGap = 10; int bmpWidth = maxpos * rectWidth + (maxpos - 1) * widthGap + 11; // bmpHeight = top/bottom margins + combined height of boxes + the gaps between the levels int bmpHeight = (heightGap * 2) + (rectHeight * (levels + 1)) + (levels * heightGap) + 1; Bitmap bmp = new Bitmap(bmpWidth, bmpHeight); Graphics gfx = Graphics.FromImage(bmp); Pen pen = new Pen(Color.FromArgb(200, 200, 200), 1); Brush whiteBrush = new SolidBrush(Color.White); Brush greyBrush = new SolidBrush(Color.WhiteSmoke); Brush blackBrush = new SolidBrush(Color.Black); Brush redBrush = new SolidBrush(Color.Red); Font font = new Font("Verdana", 7, FontStyle.Bold); gfx.FillRectangle(whiteBrush, 0, 0, bmpWidth, bmpHeight); gfx.SmoothingMode = SmoothingMode.HighQuality; // draw rectangles foreach (RegisteredModule m in Core.Instance.ModuleRegistry) { Brush brush = new SolidBrush(dllColors[new FileInfo(m.Module.GetType().Assembly.Location).Name]); Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Namespace], levels, levelCounts[m.Importance], bmpWidth); gfx.FillRectangle(brush, rect); gfx.DrawRectangle(pen, rect); } // draw lines foreach (RegisteredModule m in Core.Instance.ModuleRegistry) { Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Namespace], levels, levelCounts[m.Importance], bmpWidth); ModuleDependencyAttribute[] atts = (ModuleDependencyAttribute[])Attribute.GetCustomAttributes(m.Module.GetType(), typeof(ModuleDependencyAttribute), true); int attnum = 0; foreach (ModuleDependencyAttribute att in atts) { attnum++; RegisteredModule dm = Core.Modules.ModuleRegistry[att.ModuleType.FullName]; int xmodstart = (rectWidth / 2) - ((atts.Length - 1) * lineGap) / 2 + ((attnum - 1) * lineGap); int xmodend = Math.Max(bmpWidth / 2 - (levelCounts[dm.Importance] * rectWidth + (levelCounts[dm.Importance] - 1) * widthGap) / 2, 0); int level = dm.Importance + 1; int dmxpos = modulePositions[dm.Namespace]; Point start = new Point(rect.X + xmodstart, rect.Y); Point end = new Point(xmodend + (dmxpos - 1) * rectWidth + (dmxpos - 1) * widthGap + rectWidth / 2, heightGap + level * rectHeight + (level - 1) * heightGap); Color color; switch (attnum % 7) { case 0: color = Color.Red; break; case 1: color = Color.Silver; break; case 2: color = Color.Blue; break; case 3: color = Color.Violet; break; case 4: color = Color.Orange; break; case 5: color = Color.DarkCyan; break; default: color = Color.SlateBlue; break; } gfx.DrawLine(new Pen(color), start, end); gfx.FillEllipse(new SolidBrush(color), start.X - 2, start.Y - 2, 5, 5); gfx.FillRectangle(new SolidBrush(Color.FromArgb(200, 200, 200)), end.X - 2, end.Y - 2, 5, 5); } } // write words StringFormat fmt = new StringFormat(); fmt.Alignment = StringAlignment.Center; fmt.LineAlignment = StringAlignment.Center; fmt.Trimming = StringTrimming.Character; foreach (RegisteredModule m in Core.Instance.ModuleRegistry) { Rectangle rect = GetModuleRect(m, rectWidth, rectHeight, widthGap, heightGap, modulePositions[m.Namespace], levels, levelCounts[m.Importance], bmpWidth); Rectangle wordsrect = new Rectangle(rect.X + 3, rect.Y + 3, rect.Width - 6, rect.Height - 6); Brush bgbrush = new SolidBrush(Color.FromArgb(200, dllColors[new FileInfo(m.Module.GetType().Assembly.Location).Name])); gfx.FillRectangle(bgbrush, wordsrect); gfx.DrawString(m.Title, font, blackBrush, wordsrect, fmt); } ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo encoder = null; for (int i = 0; i < encoders.Length; i++) { if (encoders[i].MimeType == "image/jpeg") { encoder = encoders[i]; break; } } if (encoder == null) { throw new SprocketException("Can't create a image because no JPEG encoder exists."); } EncoderParameters prms = new EncoderParameters(1); prms.Param[0] = new EncoderParameter(Encoder.Quality, 200L); bmp.Save(app.Context.Response.OutputStream, encoder, prms); app.Context.Response.ContentType = "image/jpg"; } }
void Instance_OnLoadRequestedPath(HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled) { if (handled.Handled) { return; } if (sprocketPath == "$dbsetup") { Result result = DatabaseManager.DatabaseEngine.Initialise(); if (result.Succeeded) { HttpContext.Current.Response.Write("<p>Database setup completed.</p>"); if (Completed != null) { Completed(); } } else { HttpContext.Current.Response.Write("<h2>Unable to Initialise Database</h2><p>" + result.Message + "</p>"); } handled.Set(); } }