Posted by
Al Nyveldt in
Development on Dec 06, 2009 |
1 responses
I had a nice time at the Central Penn .NET Code Camp this past Saturday. It was my first code camp in Harrisburg, PA and while not as large as the Philly Code Camp I’ve been to a few times, it was a good code camp just the same. There was a nice mix of sessions and I had a enjoyed getting to chat with fellow developers from the area (and a few from a bit further away.) I was also shocked to see the swag that was available at this code camp. It was incredible. Everyone who stayed the whole day left with at least a t-shirt and a technical book. My friend Mark scored a ReSharper license and some lucky fella went home with an XBox 360 (whatever that is.)
I gave a talk in the first time slot of the day on the Spark View Engine. I had not done a talk on Spark before and was very curious to see how it go over. I didn’t have a huge crowd for the talk but they were a great audience and had lots of good questions and insight. It was a pleasure to present to them.
In the presentation, I decided to go the route of showing Spark instead of teaching Spark. I showed a lot of different syntax, discussed spooling, partial files, and ended with an example of using iTextSharp and Spark to produce PDFs. Hopefully everyone there got a good taste of Spark and will take a moment to download it and give it a try soon.
I promised to put the demo code out on my blog so I’ll include it at the bottom of the post. It is far from perfect, but it will give you something to play around with.
Anyway, I hope to make it to future Code Camps in Harrisburg. It was a good time and something local developers should really try to make time for.
Download: CPCC2009-SparkDemo.zip
Posted by
Al Nyveldt in
Development on Nov 19, 2009 |
4 responses
If you are following along in this series, we have have already looked at getting Spark View Engine setup and some of the basics of markup and layouts. In this last section, we need to look at some of the pieces of Spark syntax that really stand out.
Conditional Syntax
One of the things that makes a view look ugly in a hurry in the Web Forms world is conditional logic. If you have an else or an else if as part of the situation, you’ve got <% %> tags all over the place. Spark makes conditional syntax flow in your html markup. You can see a good sample of Web Forms vs. Spark at the beginning of the part 1 post on Exploring Spark.
The first way to handle conditionals is with the if and else tags:
1: <if condition="!Request.IsAuthenticated">
2: <p>Hey... Login already!</p>
3: </if>
4: <else if="Context.User.IsInRole('Administrators')">
5: <p>Hello - You are special.</p>
6: </else>
7: <else>
8: <p>Hello - I know you.</p>
9: </else>
There is also a test tag that is very similar and there are a few variations on the how you write the markup but that is the basic principle. (Note: the single quote is converted to a double quote by Spark.) Another very cool way to handle conditionals is to put the if as part of the html tag.
1: <p if="CartTotal < 75">
2: Get free shipping when you order more than $75 worth of our good stuff
3: </p>
This p tag will only show up if the condition is met. In addition, you can still use an else tag underneath the p tag with the if.
One other really neat trick is using conditional logic inside an attribute with a ?{ } syntax.
1: <li class="listItem inStock?{item.Quantity > 0}">
2: ${item.Name}
3: </li>
In the case above, the class attribute “inStock” will only appear when the Quantity is greater than zero.
Iteration Syntax
To be honest, the first thing I noticed when I looked at a Spark view was how iteration was handled. It just looked elegant to me. Like the Conditional Syntax, you can use separate tags for iteration or put the iteration right inside an existing tag.
1: <for each="var movie in Movies">
2: <p>${movie.Title}</p>
3: </for>
4:
5: <table>
6: <tr each="var movie in Movies">
7: <td>${movie.Title}</td>
8: <td>${movie.Rating}</td>
9: </tr>
10: </table>
ViewData
A lot of views will use ViewData of some type and while you can wrap your ViewData request in ${ } brackets, there is a better option. With the viewdata tag, you can strongly type your variables in your view.
1: <viewdata message="string" model="IEnumerable[[Movie]]" />
Note: Spark converts the [[ ]] to < >. These double square brackets and the single quotes are the only Spark conversions I’m aware of at this point.
Inline Code
One of the really great parts of Spark is that you can continue to use your <% %> syntax if you need to or want to. If you want to convert a page from aspx to spark. Rename the file, take out your header and replace your ContentPlaceHolders. The rest of your <% %> stuff should be fine.
In addition though, if you actually need some inline code, you can just proceed the line with a # character and it will be handled as inline code. Again, I think it gives the markup a cleaner feel.
Conclusion
There is a lot more interesting pieces to dive into with Spark, but this is just meant to get you started. If you are interested in more Spark syntax, configuration, or conventions you should check out the Spark documentation.
Posted by
Al Nyveldt in
Development on Nov 17, 2009 |
1 responses
In my last post, we took a very brief look at the syntax of Spark then dove right into getting setup to try it out. If you have not looked at the first part of the series, that would be the best place to start.
In this post, we’re going to continue to look at the default project that I converted to use the Spark View Engine (instead of the default Web Forms view engine) and take a look at the syntax and some of the conventions. (Download it here.) Let’s start with a side by side look of the both the original View folder and my Spark version’s View folder.
.jpg)
.jpg)
You'll notice that the files look pretty much similar to the default application except the extensions have been changed from aspx to spark. The exception of course is in the Shared folder, we no longer have a Site.Master file. In its place, we have an Application.spark file and a _global.spark file. I also added an underscore in front of the LogOnUserControl’s file name. These change will be discussed later in this article.
Basic Markup
If you take a look at a simple view, like the Home/Index.spark, you will notice a few difference from the Web Forms version. First, the Page header line is no longer needed with spark. In addition, the ContentPlaceHolders are gone. In addition, there is only one content tagged area instead of the two in the original.
Original Home/Index.aspx:
1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
2:
3: <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
4: Home Page
5: </asp:Content>
6:
7: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
8: <h2><%= Html.Encode(ViewData["Message"]) %></h2>
9: <p>
10: To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
11: </p>
12: </asp:Content>
My Spark Home/Index.spark:
1: <content name="title">
2: Home Page
3: </content>
4:
5: <h2>${ViewData["Message"]}</h2>
6: <p>
7: To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
8: </p>
The loss of a ContentPlaceHolder is interesting. Spark renders your view differently than Web Forms and one change is the the view will spool named content for placement and render any un-named content where the view is called in the master layout.
The spooling concept is very powerful and we will likely dig into this further in a future post. For now, I’ll mention you can put your named content areas anywhere inside your view. You may make multiple entries and they will be concatenated. You can also set up default values in your Master Layout in case there is no matching named content area in the view you are rendering.
The other important change in these files in the displaying of the ViewData[“Message”]. In the original, it is wrapped in the alligator tags and encoded with Html.Encode(). In the spark version, it is simply wrapped with ${ }. You might remember that I added some configuration that html encodes all output by default so that part is not needed. The simple ${ } syntax represents code instead of the <% %>. Any C# code can be put inside the brackets.
This should bring up the obvious question, what if I don’t want to encode the output? In that case, you use an ! instead of a $. When you want to have your output be html, like an Html.ActionLink function or an Html.TextBox function, you’ll need the !{ } syntax. I really like this syntax as it allows me to be deliberate over what is encoded or not encoded with a single character.
Master Layouts
Now would be a good time to look at the master layouts of the original app and my Spark’s Application.spark. This will let us see the rest of the Home page that gets rendered when we start up the application.
Original Shared/Site.Master:
1: <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4: <html xmlns="http://www.w3.org/1999/xhtml">
5: <head runat="server">
6: <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
7: <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
8: </head>
9:
10: <body>
11: <div class="page">
12:
13: <div id="header">
14: <div id="title">
15: <h1>My MVC Application</h1>
16: </div>
17:
18: <div id="logindisplay">
19: <% Html.RenderPartial("LogOnUserControl"); %>
20: </div>
21:
22: <div id="menucontainer">
23:
24: <ul id="menu">
25: <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
26: <li><%= Html.ActionLink("About", "About", "Home")%></li>
27: </ul>
28:
29: </div>
30: </div>
31:
32: <div id="main">
33: <asp:ContentPlaceHolder ID="MainContent" runat="server" />
34:
35: <div id="footer">
36: </div>
37: </div>
38: </div>
39: </body>
40: </html>
My Spark Shared/Application.spark:
1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2: <html xmlns="http://www.w3.org/1999/xhtml">
3: <head runat="server">
4: <title><use content="title">Default title</use></title>
5: <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
6: </head>
7:
8: <body>
9: <div class="page">
10:
11: <div id="header">
12: <div id="title">
13: <h1>My MVC Application</h1>
14: </div>
15:
16: <div id="logindisplay">
17: <LogOnUserControl />
18: </div>
19:
20: <div id="menucontainer">
21:
22: <ul id="menu">
23: <li>!{Html.ActionLink("Home", "Index", "Home")}</li>
24: <li>!{Html.ActionLink("About", "About", "Home")}</li>
25: </ul>
26:
27: </div>
28: </div>
29:
30: <div id="main">
31: <use content="view" />
32:
33: <div id="footer">
34: </div>
35: </div>
36: </div>
37: </body>
38: </html>
Comparing the two, we’ll notice that the header line is gone again. Next, you’ll notice the first ContentPlaceHolder has been replaced with a <use content="title">Default title</use> section. This is what looks for any spooled content named title. The place between the tags is where I set a default information in the case there is no content named “title”. If I didn’t want to add default information, I could have made my tag simply, <use content=”title” />. While I’m in the header, I will state that you will want to use application based paths instead of relative paths, so I made this change as well.
As you look further down the file, you will come to a crazy looking tag, <LogOnUserControl />. We’ll talk about this tag in a moment, but let’s continue to scan down the Application.spark first. After the LogOnUserControl, you notice the use of the !{ } syntax wrapping the ActionLink functions and the <use content=”view” />. This is where the named view is rendered with in the layout.
Partial Files
Now, let’s look again at that <LogOnUserControl /> tag. This is simply a fancy way of displaying a partial file/view. When you name a partial file so that it starts with an underscore, it can be used as its own tag. The other syntax, if you prefer, would be <use file="_LogOnUserControl" />. You need to use that syntax is the file does not start with an underscore.
The code for the partial file is exactly what you’d expect, just a snippet of html and code markup. No special headers are needed. The code for the LogOnUserControl was actually shown in part 1 of this series so I won’t go back to it now.
This would also be a good time to look at the last piece of the puzzle, the _global.spark file. It is simply another partial file, but it has a special function. _global.spark is automatically imported into every single view that is compiled from the location it exists in. Since I have placed this one in the Shared folder, it will effect every view compiled. (If you had some specific globals you’d want in just the Home Controller views for example, you could put a _global.spark in the Home view folder.
In my _global.spark, I simply am declaring some namespaces. By default, the HtmlHelpers, for example, are not available without their full namepace included. I included a bunch of namespaces that I may want someday, but really only needed System.Web.Mvc.Html. You declare namespaces in spark like so:
<use namespace="System.Web.Mvc.Html" />
In the next part of the series, we’ll look at more of the Spark syntax including conditionals and iteration.
Posted by
Al Nyveldt in
Development on Nov 15, 2009 |
3 responses
If you are working with ASP.NET MVC and you haven’t taken a look at the Spark View Engine, you owe it to yourself to spend a few minutes exploring Spark. While it might not be for everyone, Spark View Engine offers a different option to the standard Web Forms View Engine used in MVC and it has a lot going for it.
Over the next week, I plan is to write a few of posts exploring the basics of Spark. We’ll go into installation, configuration, syntax, layouts, and partial files. There would be a lot more to dig into but this is the stuff you’ll want to start with. In this post, we’ll focus on getting your project ready to use Spark and some basic configuration.
.jpg)
The first thing you notice about Spark is the integration of your html and code in a simply easy to read way without all the code blocks in the code. It is a cleaner look to be sure, but the features go far beyond the initial cleaner look. To give you a better idea of what Spark actually looks like, here is the LogOnUserControl that is part of the default MVC application. This is using the default view engine, Web Forms.

Now, here is the LogOnUserControl converted to Spark.
As you can see, it is a cleaner look with the alligator brackets <% %> removed. Also, there is no control header required. Using some simple convention, we are able to encode data and display html and we have conditional elements in use.
The easiest way to get a project started using spark is the following 3 steps. These instructions make the assumption that you have installed ASP.NET MVC and Spark View Engine.
- Create a new ASP.NET MVC Application in Visual Studio.
- Add a Reference to Spark.dll and Spark.Web.Mvc.dll (both found in the bin folder of your Spark install.)
- In your Global.asax, add the Spark View Engine to your View Engine collection by to the Application_Start. The code below also has a using Spark.Web.Mvc statement at the top of the file.
1: protected void Application_Start()
2: {
3: ViewEngines.Engines.Add(new SparkViewFactory());
4: RegisterRoutes(RouteTable.Routes);
5: }
That is it. You are ready to get started with Spark. I recommend adding some default configuration to your web.config, but it is not required. Integrating the code below in to the configuration section of your web.config will turn on debugging information for Spark syntax issues and default to automatically encode your data on your forms.
1: <configSections>
2: <section name="spark" type="Spark.Configuration.SparkSectionHandler, Spark"/>
3: </configSections>
4: <spark>
5: <compilation debug="true" />
6: <pages automaticEncoding="true" />
7: </spark>
Now that you have the quick and easy setup stuff done, you can go ahead and run your app and you’ll notice… nothing. If you’ve done everything correctly, it still works fine. When you set up your app to use Spark, it will still render Web Forms views (aspx & ascx) if they are available. This is important as you can add Spark to an existing application and create new views in Spark while not causing problems with your functionality. As you might expect, your controllers will look for a Web Form view in the View folder with the name of the controller and then is the Shared folder. If it doesn’t find a match, it will look for the spark versions in the same 2 places.
In addition to allowing you to use either type of view, Spark views will handle the Web Form syntax well, which makes converting views from Web Forms to Spark an easy process that doesn’t need to happen all at once. (We’ll look at this further in a future post.)
I’ve gone ahead and created an ASP.NET MVC application, followed the steps above and then converted all the views to spark views. Download it and take a look around. We’ll look into the syntax and some of the conventions in the next post using this project.
When I looked around at blog templates on different sites, I’m running across more and more templates that expect each post to have an image or two with it in the display template. I think it looks great, but I also think I would post even less if I had to have images in the certain sizes for each and ever post I wanted to make.
In thinking about it however, I decided it would work out pretty well for me if I picked out an image for each category and let my theme put the correct image into the template as needed. In my theme, I have only 2 image sizes and there are different enough that I decided to make images for both sizes, but if they were more similar, you might be able to get away with a single image and resizing it on the fly.
Since these images are part of how the post is displayed, the work for this is part of the PostView.ascx of your theme. I used the code behind file for this as well and added the following into my custom PostView class.
1: protected string CategoryImage;
2: protected string FeaturedImage;
3: protected void Page_Load(object sender, EventArgs e)
4: {
5: string imageRoot = Utils.AbsoluteWebRoot.ToString() +
6: "themes/myTheme/images/categories/";
7: string catImageName;
8: if (Post.Categories.Count > 0)
9: catImageName = Post.Categories[0].Title.Replace(".", "");
10: else
11: catImageName = "NoCategory";
12:
13: CategoryImage = imageRoot + catImageName + ".jpg";
14: FeaturedImage = imageRoot + catImageName + "Featured.jpg";
15:
16: base.Page_Load(sender, e);
17: }
Now I had a CategoryImage and FeaturedImage url string that I could use in my PostView.ascx to show the correct image for each post.
1: <img src="<%=CategoryImage %>" alt="<%=Server.HtmlEncode(Post.Title) %>" />
It is a relatively simple trick, but gives you some neat customization on your blog. This concept can be used to do countless customizations to the PostVIew, CommentView and even the Site.Master pages in your theme.