How to Debug Pylons with PyCharm

So I really hate Eclipse. Something fierce. And I have to admit it’s not really fair since I come from Visual Studios/C# which together can cost upwards of 2k to buy so it better be a great product. And Eclipse is free so you know, yah. But since IronPython may be dead, and it was annoying to set up anyway, I’ve been stuck with Eclipse… Until today. Turns out those Resharper guys (Resharper being the best thing ever since the last best thing ever.) made a Python IDE: PyCharm. At first I was all like “Whooa” then I was all like “Whoooooa” then I read there was no support for Pylons… then I was like “Wha?”.

Although it looks like PyCharm doesn’t directly support debugging with Pylons, I took my limited knowledge from Eclipse and just hopefully bashed it into PyCharm…. and I made a screen shot:


It’s really simple.

Script is the Paster script that is normally used to start the serve.

Script Parameters is just the normal serve command used WITHOUT the –reload.

Make sure you grab the right python interpreter that has Pylons “installed” and away you go. Just have that one set as the current debug config and run it.

Once it’s up and running, just go to the page and set a breakpoint. Yay.

Python / Pylons: Unit Testing a Controller And Unit Testing a Json Response

Nice thing about Python and Pylons is the complete lack of finds on the google. Basically anything you search on gets you the same 5 links… helpful or not.

This is a quick one though, and by quick I mean quick for you after it took me a f— load of time to get the f—ing thing right. Forgive me for swearing… even though I do it all the time… but in this case I really wanted emphasize how f—ing annoying it was to get this right.

So here’s the thing, you want to unit test a controller. Great. Now the nice thing is it’s actually pretty easy with what’s built into the TestController which is found in the __init__.py file in yourProject/tests. Imported simply by :

from yourProject.tests import *

Provided you didn’t move the tests folder.

Take the start of this method:

   def test_loginUser_bad_input(self):
          #Here is the call to the controller and the return response
          response = self.app.post(url(controller='security', action='loginUser', email='null', password='null' ))

Now here’s the interesting thing, response is actually a response object. Can you belee dat? At first I thought it was just whatever the controller method would return if called by a method and not during some web request. Turns out that self.app.post actually acts like a real request. Go f—ing figure. I like. So simple yet so capable. It’s like a long lost brother of mine. You know, the long lost brother that is simple yet capable… and is a method. I’m not sure any of that makes sense.

Now the second part of this debacle is how to work with a json response. For this example I am using jsonpickle but in reality the only thing to take from this is WHERE the stupid json actually is:

    jsonResponse = jsonpickle.decode(str(response.body))

Yeah so at first I thought it would be just jsonpickle.decode(response) but kept getting all sort of unhappiness. Now like I noted up top, the response is an actually object return that holds all sorts of information. (including header information.. yay?) So the next guess was what you see right above. Go figure what I was looking for was in the .body attribute.

See, told you it was simple. Painful for me, but in the end you win. And I bet you like that. Sadist f—.

Pylons: Dynamic Templates with Mako Using Controllers and jQuery

So a friend of mine (Yes I do have friends and occasionally the ARE real) asked me if there was a way to have a partial control/template have dynamic content using a controller. At first I was like ‘f— no’ but that passed quickly as I realized I was actually answering myself on whether Species should have yet another sequel. As for his question, I gave it some thought and the easiest way I could think it jquery and using it’s ajax method to call a controller and use the response (json for this example) to create the content. Could it be done? You bet your Rolex knock off that you bought in New York from some guy named Loey that looked legit for a guy selling things out of a dumpster.

Turns out the solution is fairly simple. Use jquery to call a controller’s action on the template’s load. Even can pass in whatever you need from the parent container.

Here is the parent page:

<!--This is the partial template page -->
<%namespace name="getInfo" file="getInfo.html" />

<html>
  <head>
   <script type="text/javascript" src="${h.url('/scripts/jquery-1.4.2.min.js')}"></script>
  </head>
  <body>
    This is just plain text that is pre method call.  Textbox will be fill post method call.
    <!--This is the method set up on the partial template -->
    ${getInfo.getInfo(1) }
  </body>
</html>

Here is the partial template file:

<%def name="getInfo(id)">
  <script type="text/javascript">
    //This is the method to be called to get whatever it is you need from the controller action
    function getInfo(id){
      jQuery.ajax({
        type:'POST',
        url: '${h.url(controller='getInfo', action='index')}',
        dataType:'json',
        data:{ id:id },
        success: function(result){
          onSuccess(result);
        },
        error:function (xhr, ajaxOptions, thrownError){
          alert(xhr.status);
        }
      });
    }

    function onSuccess(result){
      jQuery('#testLabel').val(result.returnValue);
    }
    <!-- This will force the getInfo method to be called when this page loads. -->
    getInfo(${id});
  </script>

  <!-- This is the content to be updated -->
  <input type="text" id="testLabel" name="testLabel" />
</%def>

And really that’s it. Very simple. Have the parent page call the partial template method and have the partial template method use whatever value being passed in to send it on to the right controller/action. Once the response is there, update the content.  In this case, result.returnValue that is just a simple string.  Or maybe a puppy.  Could be both.

A more complicated example could use javascript to construct html based on the return but not real important here.  That’s for smart people, read not me, to figure out.

As a bonus, I will actually post the code. NOVEL IDEA!111

What? Why did I choose purple for the color of Mako markup?  Don’t… just don’t.  You have no right to judge.

Python… DOUBLE TEE EFF Exclamation mark one one

Fair Warning: This is all conjecture and idiocy… possible more the latter than the former. With that in mind, this is more of a flow of thought than any kind of organized scientific paper… thing.

NOTE: When I use the word “attribute” I really mean things like properties, fields, methods, ect on a class. Since I am guessing most people reading this come from a C# or Java background, the word “attribute” might be confused with something else. So remember attribute = property/method/field/anything that defines an object.

So as I delve farther and farther into the insanity that is Python, I can feel my mind screaming. Not like “Oh f— I’m being eaten alive” kind of screaming, more like “Don’t open that door! You know the guy with the axe is behind it!” Of course, like any good horror movie character I’m too dumb to know better. So delve I do.

Now I’m what you could consider a classically trained programmer and by that I mean I never programmed before college so I didn’t do much exploration. You know, a Microsoft programmer. With that, I’ve had the ideas of interfaces and class hierarchies complete hammered into my head, so it shouldn’t be any surprise that I’ve tried my best to make Python into c#. After all, that’s what I should be doing. I don’t know any better. DONT JUDGE ME!
It wasn’t until the other day when it just hit me. And I don’t mean slight hit, I mean like I just told Miguel Cabrera I’ve seen better players in Little League. It occurred to me that it’s possible, just possible I might have to change my way of thinking because of one major design difference: dynamic attributes… actually f— it, dynamic everything, but let’s just stick with something simple. In Python something like this:

  someObject = dynamicObject()
  someObject.propertyImJustAddingForTheHellOfIt = 1

Where dynamicObject is nothing but a cheesy class that inherits Object but has nothing on it. (Turns out that if I did someObject = Object() I couldn’t do this since Object by default doesn’t contain the ability to add things dynamically… and this was by design.) So what does this mean? Well it means that anything at anytime could have any attribute. You might be asking why this is such a big deal. Annnnnnd that’s why I’m typing this out so stop asking questions until the end, k?

If any object can have anything on it at anytime, it could be said that types and classes kind of go out the window. Why? Because when it all gets washed away, what really does the work in a program? Methods. Now with C# there is a much stronger enforcement of typing so a method KNOWS that whatever coming in has to be a certain type. This is where object inheritance and interface implementation come in. Because there is such a prerequisite for typing in C#, you have to develop around the object itself and have the methods conform to them. In Python, I question whether this approach is really warranted since with dynamic attributes what really matters is what the method needs. It could be argued in the world of dynamic, the methods actually dictate everything. Since types are basically thrown out the window, what’s the point? Why not just shift all development around methods and their results? It’s kind of an inverse way of looking at things when used to the C# way of doing them.

Method Oriented Programming?

This is something I’m kicking around a bit, but why not base the architecture around methods rather than classes? It would give a much truer sense to the word “Factory”. Instead of worrying about having a class hierarchy, have methods responsible for creating objects on the fly, piecing them together with other methods and such. I would think this could give a program a massive ability to adapt quickly to any given situation if you can add and subtract from objects on the fly since you are not longer concerned with types, just attributes. Does the thing coming in have X attribute? Yes? Great do something. No? Fine don’t do something. (Python has a built in way to check if an object has a certain property) Does it need it to continue? Well call a method to add it to the object. Has the use for it expired? Well just remove it. Taken to an extreme, I could see this being used to construct more self sustainable programs, ones that can makes choices on their own to produce novel outcomes. (Sadly, used like viruses and hacking security systems come to mind, but there has to be more noble uses for this) Sounds like a lot of freedom.

Now I’m not saying you can completely get away from class structure… at least I haven’t gone far enough into this concept to see if it’s possible. However, it should be obvious that it at least allows for a completely different way of thinking that may help solve problems that were seemingly impossible to solve using more rigid languages like C#. Of course, it also lends itself to shooting yourself in the foot. Most likely, this approach would need more overall care since you don’t have things like type safety to cover your a–.
Anyways, this is just preliminary rambling of a child (programmatically speaking… and maturity wise) who is just kicking around ideas that weren’t really there before.

An odd side note, python gives a new… or maybe the correct… meaning to the word “constructor” since because of that highly dynamic nature it’s not unlikely to see something like this:

  __int__(self):
    self.someNewField = "This property now exists"
    self.someNewMethod = someFile.someMethod

Which is actually more like a factory then how say c# uses constructors, which more the most part is like a initialization. The other interesting thing to note is how python treats files and methods. If you declare a method on a file, you can actually import that method as if it were an object itself. This makes the above code even easier to accomplish since you can have a file of just methods that you can “import” and add to an object.

What happened to Lan Parties?

As I was making my third attempt to reassemble a horribly aged futon (that had been passed around to so many people there’s no doubt its seen more action than Tom Selleck in his Magnum PI days), wondering if it was some kind of early attempt of Ikea’s to blend furniture with some kind of social experiment to see how much a person can take before starting a three figure body count, and swearing enough to make Bog Saget blush, I decided that the best course of action to keep me from going hulk on it was to think of better place.

Lan Parties - Panel One

That didn’t feed into my almost Gibson-esque epic instability.

Lan Parties - Panel Two

I then started thinking of my friend (no not that way) and how he (still not that way) was having a lan party this weekend and how he had invited me to it. Now I probably would have gone if it weren’t for the fact he lives 10 hours away, I’ve never actually met him in person, and I’m pretty sure he’s actually just inviting me over because he needs a new host body as his is falling apart.

You remember those days. 10 high school (maybe college) dudes all smashed into a basement with 10 computers going full blast, cases and cases of mountain dew, all completely focused on one and one thing only: gaming. Those 48 hour gaming benders fueled by so much caffeine that by the morning of the second days everyone had that weird anxious/excited/electrified feeling that somehow mixes the feeling you get right before you start opening birthday presents and the feeling you get right before vomiting:

Lan Parties - Panel Three

You know, the same feeling we would feel again 10 years later right before having sex for the first time:

Lan Parties - Panel Four

Well this led to me asking my self, “Self, why don’t I go to lan parties anymore?” For the most part, I think part of getting older is realizing that the copious amounts of caffeine taken in at 16 would no doubt kill me or more than likely be replaced with alcohol and no doubt would end with some kind of machine being forced down my throat in a last ditch effort to keep me alive so that I could enjoy the week long hangover to follow.

I think also in my oldness, I’ve lost the ability to play games for any extended period of time. Seems as if that part of my brain has been removed or possibly atrophied due to suffering from depression brought on by lack of use. Either way, I now have a greater capacity to code for extended periods of time instead… Wait. I’m feeling something… I think it’s an idea which would explain why its a feeling I don’t recognize.

What if the gaming lan party were to evolve? What if all that caffeine drinking, sardine can sized room of guys, (I’d say gals too since I realize there are women coders but really, what woman wants to take the chance of being locked in a small room chock full of essentially coked up geeks?), table to table, computer to computer, energy filled mayhem could be used to code? Think about it:

What if you were to take some idea like say a program that compares the hotness factor of supermodels (YEAH SUPERMODELS MAN, CAUSE THAT’S WHAT MANLY MEN DO, YEAH!) or the best picks for fantasy football (more in line with reality) and just go at it for 48 hours straight? I think this could actually work. After all, you have the combination of a ton of minds and no external interruptions to really just hammer something out. I realize there could be some issues inherent with super-fast coding:

Lan Parties - Panel Five

But couldn’t this work? You get lots of up-side on this one. Comradery, energy, excitement, a semi-working program, and quite possibly good, old-fashioned physical nerd fights (hey, that’s what Youtube was invented for) caused by late nights, caffeine psychosis, and uncomfortably close proximity to other people for more than 10 minutes. How could this be a bad idea? So I say, have at it. Prove me wrong about this one. And make sure you take video proof of how wrong I was. You know, some kind of video diary of you attempting to flee the country after they find the 9 bodies you somehow managed rage into the trunk of your car. (Again, that’s what Youtube was invented for).

Lan Parties - Panel Six

Quick Example of Inheritance in Templates with Mako: Using Next

So as I further my side journey into Python, or Pylons to be more exact, one of the decent things I’ve run into is that Mako templating system. What is that? It’s what runs along side of Pylons (Or at least one of many) for displaying the View side of the whole MVC thing. Now if you’re here, chances are you just searched on this so I wouldn’t go into a huge thing about Pylons or Mako. I’ll just get to the damn point.

This is just an example of a three layer template I use to help with pumping out pages with out repeating a lot of code. The nice thing about Mako is how simple it is to have multiple layers of templates to make up a single page. This is basically done with using the next keyword.

What is next?
Mako has a system that works something like an abstract class. A page template can define a certain area in a method like way and like an abstract method, there is no method body. Any page template that “inherits” the base has to fill in the body or create an abstract method itself to call the original method.

Now with that being said, there are two key words for doing this and the default keyword is self. Problem with self is that it looks at the top most template only. So if you have say 3 layers:

BasePage -> SecondLayer -> ThirdLayer

self will always look to the third layer:

BasePage -> ThirdLayer

While second layer is all like, “Yeah whateve”. Overall, this isn’t very helpful if you want a sort of chain like effect. Its basically like a base class not giving a flying… not caring about what any child classes do except the top most child class. What if you have a div that holds content on the base, and the second layer has its own content area to hold the third layer. This would be useless if you used self since that second layer would just be ignored. Sad day. This is where next comes in. Next, like an abstract method, basically just sets a place holder for the next template to “inherit” the said template. Now the danger of next is that just like an abstract method, the system will be all “Waaaaaah, you didn’t override the method. Waaaaaah.” if you forget to define the method in the next layer. The huge advantage is you can create a nice consistent design in which you can just bang out child templates since you know exactly what the baser (Yeah I wrote baser.) page will have.

On to the example. And this is an example of what a template structure could look like.

The base page:

  <html>
    <head>
       //next.title will allow all children to add on to the title
       <title>First Level - ${next.title()} </title>

        //next.styleSheetIncludes will allow all children to add any included css files if needed.
        <link rel="Stylesheet" href="${h.url('/css/base.css')}" />
        ${next.styleSheetIncludes()} 

        //next.javascriptIncludes will allow all children to add any included javascript files if needed.
        <script type="text/javascript" src="${h.url('/scripts/base.js')}"></script>
        ${next.javascriptIncludes()} 

        //next.styleSheet allow all children to add any page specific css that wasn't included in files.  Why
        //  have the style tags instead of just having the  ${next.styleSheet()}.  Well you could but then you would
        //  end up with more than one style tag when the page is built.
        <style type="text/css">
          ${next.styleSheet()}
        </style>

        //next.javascript allows all children to add any page specific javascript that wasn't included in files. This
        //  follow the same idea as the next.styleSheet above.  Why have a possible 3...4...5... script tag when
        //  the child templates can just add to this one?
        <script type="text/javascript">

          function firstLevel(){
          }

          ${next.javascript()} 

          //next.javascript allows all children to add any page jquery document.ready javascript that is specific to the
          //  given child.  Once again this is an example of add to instead of repeating a section
          jQuery(document).ready(
            function () {
              jQuery('button').button();

              ${next.documentReady()} 

            }
          );
        </script>
    </head>
    <body>
      <div class="header">
      </div>
        <div class="bodyContainer">
          //This will be where the child html will fall.
          ${next.body()}
        </div>
      </div>
   </body>
  </html>

The second layer:

  <%inherit file="base.html" />

  <%def name="title()">
    - Second Level
  </%def>

  <%def name="styleSheetIncludes()">
    <link rel="Stylesheet" href="${h.url('/css/secondLevel.css')}" />
    ${next.styleSheetIncludes}
  </%def>

  <%def name="styleSheet()">
    ${next.styleSheet()}
  </%def>

  <%def name="javascriptIncludes()">
    <script type="text/javascript" src="${h.url('/scripts/secondLevel.js')}"></script>

    ${next.javascriptIncludes()}
  </%def>

  <%def name="javascript()">
    function secondLevel(){
      //Method in second level
    }
    ${next.javascript()}
  </%def>

  <%def name="documentReady()">
    //nothing here on second level
    ${next.documentReady()}
  </%def>

  <%def name="body()">
    <div class="leftMenu">
      <a href="something.html">something</a>
      <a href="somethingElse.html">something else</a>
    </div>
    <div class="rightArea">
      ${next.body()}
    </div>
  </%def>

As you can see, all the abstract areas defined in the base are being used by this layer and then this layer is in turn adding its own abstract methods that share the same name as the base template’s method. The nice this is you can do this using the next keyword as the current template will only respond to the template immediately inheriting it. You don’t get any kind of method name clash.

And the final layer:

  <%inherit file="secondLevel.html" />

  <%def name="title()">
     - Third Level
  </%def>

  <%def name="styleSheetIncludes()">
    <link rel="Stylesheet" href="${h.url('/css/thirdLevel.css')}" />
  </%def>

  <%def name="styleSheet()">
    .thirdLevel
    {
    }
  </%def>

  <%def name="javascriptIncludes()">
    <script type="text/javascript" src="${h.url('/scripts/thirdLevel.js')}"></script>
  </%def>

  <%def name="javascript()">
    function thirdLevel(){
      //Method in second level
    }
  </%def>

  <%def name="documentReady()">
    //nothing here on third level
  </%def>

  <%def name="body()">
    <div> Hi from third level</div>
  </%def>

The third layer now closes off the chain by no longer adding any abstract methods of its own. Now if I knew there could be yet another layer, all I would have to do is use the same naming convention and add the needed next.methods.

And this is what the source should look like:

  <html>
    <head>
      <title>First Level - - Second Level - Third Level </title>

      <link rel="Stylesheet" href="${h.url('/css/base.css')}" />
      <link rel="Stylesheet" href="${h.url('/css/secondLevel.css')}" />
      <link rel="Stylesheet" href="${h.url('/css/thirdLevel.css')}" />

      <style type="text/css">

      .thirdLevel
      {
      }

      </style>

      <script type="text/javascript" src="${h.url('/scripts/base.js')}"></script>
      <script type="text/javascript" src="${h.url('/scripts/secondLevel.js')}"></script>
      <script type="text/javascript" src="${h.url('/scripts/thirdLevel.js')}"></script>

      <script type="text/javascript">

        function firstLevel(){
        }

        function secondLevel(){
          //Method in second level
        }

        function thirdLevel(){
          //Method in second level
        }

        jQuery(document).ready(
          function () {
            jQuery('button').button();
	      //nothing here on second level
              //nothing here on third level
          });
        </script>
    </head>
    <body>
      <div class="header">
      </div>
      <div class="bodyContainer">
        <div class="leftMenu">
          <a href="something.html">something</a>
          <a href="somethingElse.html">something else</a>
        </div>
        <div class="rightArea">
          <div> Hi from third level</div>
        </div>
      </div>
    </div>
   </body>
  </html>

As you can see, things like the ${next.documentReady()} really helped to keep the source code clean and avoid repeated code on the source side. Now go forth, all 2 of you… including me…, and use this knowledge to do something.

Pylons: ‘module’ object has no attribute ‘redirect_to’

Yeah I’m using python/pylons, don’t you worry about it.

So ran into this while looking over a pylons tutorial.  Turns out, that method was removed in Pylons 1.0 but the tutorial was a little bit old. So instead of:

  redirect_to(controller='hello', action='other_action', _code=303)

just use:

  from pylons import url
  from pylons.controllers.util import abort, redirect

  ...

  redirect(url(controller='hello', action='index', _code='303'))

Bad news is I didn’t get a chance to actually see the full behavior of the old redirect to, so I’m not sure the result:

  http://127.0.0.1:5000/?_code=303

Is the same. Still new to this thing called pylons. Just got annoyed trying to find an answer to this one so hopefully my title will speed up the search for future people.

WPF: Inherit Style From Style. BasedOn Is Your Friend

So another quick one.  Say you have a style for creating round buttons, but you don’t want to include a size, how a size be applied without touching the original style?  Well you could just adjust the properties right on the button, but what if you want something a little more reusable?  It’s actually pretty simple, just have one style “inherit” the other.  Well that’s where BasedOn comes in.

Say you have a style named RoundButton.

    <Style x:Key="GlassButton" TargetType="{x:Type Button}">
      ...
    </Style>

All you have to do is create a new style:

    <Style x:Key="HeaderButton" BasedOn="{StaticResource GlassButton}" TargetType="{x:Type Button}">
        <Setter Property="Height" Value="20" />
        <Setter Property="Width" Value="20" />
    </Style>

As you can see, it’s pretty simple using the BasedOn keyword. Now when the HeaderButton style is applied to the button, it will take on the properties of the RoundButton style and the HeaderButton one. Nice huh?

WPF: Hide Built in Header Bar For an Open Window

Ok so this one is a simple one.  Well at least once you see it in action.  Say you want to get rid of the built in windows header bar:


You know, that thing. Well it’s crazy simple. And I mean crazy as in mind boggling, not crazy like dress up your cat in clothes crazy.

All you have to do is set these two properties:

AllowsTransparency="True" WindowStyle="None"

In the window tag at the top of the page. For example:

<Window x:Class="DesCombine.WPF.FileUpload"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="File Upload" Height="350" Width="525" BorderThickness="0" ResizeMode="NoResize"
  WindowStartupLocation="CenterScreen" AllowsTransparency="True" WindowStyle="None">

Only catch is that you have to now supply any useful buttons like Minimize or Close by yourself. But I never said that you wouldn’t. You thought that. You.

Spark View Engine, ASP.Net MVC, and You

So one of the things I was forced to use, semi kicking and screaming, at one point in my illustrious career was the Spark View Engine for ASP.Net MVC. Actually that’s not totally true. I only kicked for a bit then skipped the screaming once I noticed what it did: It took all the ugly <% %> junk out of the html… my beautiful html… and made things like for loops much nicer. Mind you, this is mererly the tip of the ice pick… eh berg I meant berg… there’s a lot more to it. It handles things like Master Pages and Partial Controls pretty darn well as well as caching javascript files on the go. Sounds good? Well it should and if it doesn’t, I don’t think we can be friends.

First off, I just wanted to quickly write something up on how to get it all going and because I’m such a nice guy I even have a project that is ready to go for common use. The catch is that I made it in 2010 so if you don’t have that yet, you could be screwed. Then again I could type out a lot of the steps too. You just don’t know.

First off you can either get the assemblies from my hosted project, or you can go here and get it. Either way, I don’t care. No really, I don’t. Not just sayin’. The care cup had run dry.

The two assemblies you need to reference in your project are:

  spark.dll
  spark.mvc

Next add this line to the Application_Start method in the Global.asax.cs file:

  ViewEngines.Engines.Add(new SparkViewFactory());

After that, you’ll have to add a little somethin’ somethin’ to your web.config. I know, I know. This is all so very hard. Live strong like Lance.

  <configuration>
    ...
    <configSections>
      <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
    </configSections>
    ...
    <spark>
      <compilation debug="true" defaultLanguage="CSharp">
        <assemblies>
          <add assembly="PhotoShare.UI" /> //Whatever the actual UI project is
        </assemblies>
      </compilation>
      <pages automaticEncoding="false"> //If you want it to auto HTML encode post/get stuff
        <namespaces>
          <add namespace="System"/>
          <add namespace="System.Collections.Generic"/>
          <add namespace="System.Linq"/>
          <add namespace="System.Web.Mvc"/>
        </namespaces>
      </pages>
    </spark>

Ok so the web config is ready. Now what?

Well now you are going to create a master page. That’s right you are. Don’t fight me on this. I’m way cooler than you.

There is a little directory structure hard coding going on since by default you have to have things in certain places for Spark. Oh well. All Master Pages go in a directory named “Layouts” in the “Views” directory. So something like:

  Views/Layouts/Application.spark

D— it. Forgot about that little tid bit too. Spark files have to be named .spark. Well actually I think there’s a way to call them whatever you want, but lets just go with defaults for now smarty pants.

And for the hard part, the html for the master page.

  <html>
    <head>
    </head>
    <body>
      <div>
        <use content="Middle" />
          aasdfasdfa
      </div>
    </body>
  </html>

HOLY HECK THAT’S HARD! Now there needs to be a controller. So just create one in the controllers folder. In my project it’s called this:

  Controllers/SparkTestController.cs

And then go ahead and create a view for index. Once you’ve done that, rename the extension from aspx to spark. Now for the html:

  <use master="Application"/>

  <div>
    <content name="Middle">
        hi there
    </content>
  </div>

And that’s it really. As you can see, the placeholder on the master page (use content=”Middle”) is referred to on the child page.

To make testing this page easy, I would suggest changing the routing in the Global.asax.cs file to:

  routes.MapRoute(
          "Default",
          "{controller}/{action}",
          new { controller = "SparkTest", action = "Index"}

And you should see something like:

  hi there aasdfasdfa

Proving that both the master page and the child page are printing stuff out.

You might be wondering why you should do all of this? If you aren’t, you are one hell of a lemming. And not the cool kind like those little guys that blow themselves up for the betterment of the lemming collective.  You’re that stupid one the just sits there with its hand out shaking its head.

A quick example:

  <%
    if(something.IsTrue)
    {
  %>
       <div> hihihihih </div>
  <%
    }
  %>

Compared to:

  <div if="something.IsTrue"> hihihihih </div>

Small example, but I think its pretty obvious why the second is so much better. And this is just scratching the surface on what spark does really.  I’d suggest looking here for more. I’d also suggest a new hair cut because… just wow.