Posts

Showing posts with the label MVC

Refactoring ASP.NET MVC Routes

Routing is vital to MVC. Routing defines mappings between URL and ActionMethod - that would handle request to that URL. For example, following route mapping defines that when a user hits "http://mysite/shopping/cart", call OrderController's ShowCart() method to handle this request. routes.MapRoute("cart", "shopping/cart", new { controller = "Order", action = "ShowCart" }); Placing Routes A common place to put route mappings is in  RegisterGlobalFilters method inside Global.asax: public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //Define Routes routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Login", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } } Often, you would us...

How to implement really small and fast ORM with PHP (Part 7: IDE)

Image
Queries are gaining more and more complexity, data is getting bigger and bigger. Most optimizations in database technology are done in the database server. This is an approach to optimize queries on the client side. With this ORM, queries ... don't select more data than needed contain less joins when data is expected to be consistent can be written manually in pure SQL are not written in a new query language We need a good API, so ... it should be easy to learn method names must be short and intuitive the goal is to map datasets and relations to objects the API should offer method chaining special features like auto-increments should be included the code should be small, no getters and setters the database schema is created before writing PHP code relationships should be defined in the database, not in the code we get low latencies combined with low memory usage To make things easier, we make some restrictions: only UTF-8 only MySQL/MariaDB (mysqli) only PHP 5.4.0+ only buffer...

Exporting events to google calendar Link HtmlHelper

Following is a ASP.NET MVC HtmlHelper to generate an anchor link for exporting an event to Google Calendar. public static MvcHtmlString ExportEventToGoogleLink(this HtmlHelper htmlHelper, string title, DateTime startDateTime, DateTime endDateTime, string description, string location, string linkText, IDictionary<string, object> htmlAttributes = null) { const string dateFormat = "yyyyMMddTHHmmssZ"; Uri url = System.Web.HttpContext.Current.Request.Url; StringBuilder sb = new StringBuilder(); sb.Append("http://www.google.com/calendar/event?action=TEMPLATE"); sb.Append("&text=" + title); sb.Append("&dates=" + startDateTime.ToUniversalTime().ToString(dateFormat)); sb.Append("/"); sb.Append(endDateTime.ToUniversalTime().ToString(dateFormat)); sb.Append("&details=" + description); sb.Appe...

Conditionally render MVC layout section

Error: The following sections have been defined but have not been rendered for the layout page "~/_SiteLayout.cshtml" Reason: Let's say there is a Layout as following: <html> <head> </head> <body> @RenderBody() @RenderSection("footer") </body> </html> And a view as following: <H1>Hello World</H1> @section footer{ Copyright 2012 } When rendered, <h1>Hello World</h1> will be rendered by RenderBody() while Copyright 2012 will be rendered by RenderSection(). But, what if for some reason you want to display footer conditionally on Layout? So for that, if you do something like following, you will encounter an error: <body> @RenderBody() if(condition){ @RenderSection("footer") } </body> Reason is that MVC needs to flush out section declared in your view. Else it displays error as on top of article. To resolve this, there is a quick trick: <body> @RenderBody() if(condition...

How to write a really small and fast controller with PHP (update: benchmark Slim, Silex, Zend Framework, Symfony2)

To handle a lot of traffic, we need a fast controller with very little memory overhead. First, we implement a dynamic controller . The design is based on the micro frameworks Slim and Silex . The first example maps the URL "http://server/index.php/blog/2012/03/02" to a function with the parameters $year, $month and $day: // index.php, handle /blog/2012/03/02 $app = new App(); $app->get('/blog/:year/:month/:day', function($year, $month, $day) { printf('%d-%02d-%02d', $year, $month, $day); }); Our controller is a class named App and uses the get() function to map a GET request. Parameters mapped to the function are marked with a colon. Optional parameters are written inside brackets. Here is an example: // handle /blog, /blog/2012, /blog/2012/03 and /blog/2012/03/02 $app = new App(); $app->get('/blog(/:year(/:month(/:day)))', function($year=2012, $month=1, $day=1) { printf('%d-%02d-%02d', $year, $month, $day); }); Instead of ...

Managing raw HTML and Razor code in project

Image
Intent of this post ================= This article is about approach for structuring MVC application so as to manage front end  raw HTML design code along with developer's corresponding dynamic razor code Background ================== In general,  following is a flow of an idea to a live page (from design perspective): Now here comes a question:  "How should static HTML code and dynamic Razor code be managed in a solution?" Answer...Depends.......! Case-1 : When developer is the same person who does both front end design and server code, there is no special arrangement required and one physical .cshtml file is enough.  Case-2 : When designers are smart enough to sneak into developer's razor code and implement any UI requirement, again a single file is sufficient. Case-3 : In bigger projects, where exists separate team for Design+HTML code and Razor+Backend code which is bridged by a Manager, there, it is really a good idea to have design HTML exists physically separa...

Replace Smarty with PHP templates

In many performance guides, Smarty is considered to be removed to speed up things. But oftentimes it's not Smarty causing performance problems, but rather big modifier chains not being cached. To point this out, we need to profile our template which is quite difficult when Smarty compiles in into something unreadable. So we need a quick and easy way to replace the Smarty template engine with pure PHP code. Since Smarty can't do more than PHP, let's replace Smarty with simple PHP templates. So I'm providing here a small guide to replace Smarty with simple PHP based templates. These can be also cached by APC without any compiler. First thing: Smarty configuration files e.g. core.conf foo = bar [core] logo = public/img/logo.png link = http://www.simple-groupware.de notice = Photo from xy bg_grey = #F5F5F5 Now let's convert it to PHP: core_conf.php <?php $config = array( "logo" => "public/img/logo.png", "bg_grey" => ...

Solving Potentially dangerous Request.Form with custom attribute in MVC3

Image
If you punch in “<” character while filling a MVC web form (or even ASP.NET) and press submit, you’ll encounter a System.Web.HttpRequestValidationException exception. I.e., results in: Upon search, you’ll find few common options to resolve this. I've tried to consolidate them and also have added an interesting approach at end which I find very useful for handling this issue: Option-1: Disabling RequestValidation through Web.Config Adding following tag in Web.Config: Pros : Easiest to do!! Cons : Skips validation throughout application. As a good rule, Validation should be explicitly bypassed but by setting this option, we are implicitly bypassing validation which is not good. Option-2: ValidateInput attribute Another option that resolves this problem is using ValidationInput = false attribute on Controller. For example: [ValidateInput(false)] [HttpPost] public ActionResult Index(MyViewModel vModel) { return View(); } Pros: Easy to use and can be applied only on s...

Replacing OuterHTML with AJAXHelper.ActionLink

There are various wayswhich provides unobtrusive way of updating UI with response from server via AJAX. One such option provided by MVC framework is Ajax.ActionLink. For example, @Ajax.ActionLink ( "TextOfLink", "ActionName", "ControllerName", new AjaxOptions() { UpdateTargetId = "DivToBeReplaced"} ) Above code generates a link which when clicked, calls an action called “ActionName” of the controller “ControllerName” and what ever is returned from this action, is displayed in a div with id “DivToBeReplaced”. That’s so easy!But there is a minor caveat in using UpdateTargetID . By default, it replaces the contents of div and not the div itself. Which means in following Razor code, <div id="mydiv"> Some Text @Ajax.ActionLink( "Refresh", "Index", new AjaxOptions(){UpdateTargetId = "myDiv"} <div> Clicking on generated action link would r...

Understanding MVC Razor layouts

Image
Q) What are ASP.NET MVC3 Razor Layouts? You want a disclaimer, header and a menu on left to appear on all pages to bring in consistency to your web application. If you're from webforms background, you'd be quick enough to think of using a Master Page. Similar to Masterpage, MVC 3 introduces concepts of layout . Similar to selecting master page in ASPX pages in page directive, in MVC you can specify layout at global or specific view level. Q) When and how are they created? When you add a new MVC3 application (either blank or internet or intranet), Visual Studio automatically adds a default layout file called “ _layout.cshtml ” , placed in shared folder of view. Note: There is no special extension for layout file. This layout is  automatically wired in another auto generated file called “ _viewStart.cshtml ” which contains following code: @{     Layout = "~/Views/Shared/CustomLayout.cshtml"; } Of course, you can replace CustomLayout.cshtml with your custom ht...