Hugoware

The product of a web developer with a little too much caffeine

Posts Tagged ‘Cobalt

Cobalt Progress

with 2 comments

CobaltMVC is coming along really well. I’ve been dog fooding it myself for the past few weeks in some projects and it fits nicely. I’ve discovered (and fixed) a lot of flaws and bugs along the way, so overall it has been a good experience.

I started a new site to be the dedicated home for CobaltMVC, which also happens to be on the same domain as my new website, at cobaltmvc.hugoware.com.

The site isn’t complete yet – I have a lot of documentation to write along with getting additional work done on my ‘personal’ part of the website, but overall it is a good example of what the finished site will look like.

Additionally, the site itself is powered by CobaltMVC… what a coincidence!

Written by hugoware

July 28, 2010 at 7:41 pm

CobaltMVC and Custom Selectors

leave a comment »

CobaltMVC is a server side templating framework that behaves just like jQuery for your Views. CobaltMVC also works in WebForms.

CobaltMVC supports a variety of CSS selectors including pseudo and attribute matching. To keep things flexible, I’ve made it so that you can create or overwrite anything built-in. This post we discuss how to create your own for your project.

Right now, if you wanted to select all of the even rows in a table then you could use the pseudo selector…

this.Find("table > :even");

Cool, but what if we wanted to create our own? Here is an example of a selector that finds ‘numeric’ HTML elements.


//called once to add it to the project
CobaltManagement.RegisterCustomPseudoSelector(
    "numeric", //the name of the selector :numeric
    (nodes, argument) => { //the comparison to use
        decimal container = 0;
        return nodes.Where(node => decimal.TryParse(node.InnerText.Trim(), out container));
    });

//then used from our pages like...
this.Find(":numeric");

You’ll notice there are two arguments for the method you provide – First is a list of the available nodes to compare against. The second is an optional ‘argument’ string. The method should return a list of nodes that should be kept in the selection.

And the argument? That is an optional value in case you want it included in your selector. A good example of using the argument is the nth pseudo selector which returns every x number item.

//Everything within the parens is included as part of the argument
this.Find(":nth(4)");

Note: The argument is passed as a string so you’ll need to perform any parsing before you begin using the value.

Attribute selectors match against the attributes of the HTML elements. CobaltMVC checks the values and makes sure that two string are passed (even if they are empty), but any additional parsing needs to be done as part of the method.

That said, the method you use to perform the comparison is slightly different.

CobaltManagement.RegisterCustomAttributeSelector(
    "%", //the prefix to use for the selector @attr%='value'
    (argument, value) => argument.Equals(value, StringComparison.Ordinal)); //the comparison

The special character is what you want to prefix the attribute selector with (if you plan to override the default = selector then you just pass in an empty string). This needs to be a special character so not to be confused with the name of the attribute.

The comparison method itself is just a pair of strings, the first being the argument provided by the user and the second being the value found on the attribute. If the element doesn’t have the matching attribute then it is skipped entirely.

So, we could use the method we created in the example above by using…

this.Find("[@title%='Hugoware']");

Pretty neat!

If you haven’t downloaded Cobalt then head out to GitHub and download the code!

Written by hugoware

June 6, 2010 at 11:08 pm

CobaltMVC – Custom Controls and Dynamic HTML

with one comment

CobaltMVC is a server side templating frameworks that works a lot like jQuery. You can use it with both ASP.NET MVC and WebForms – (Watch the introduction video)

So far all of the CobaltMVC examples that have been posted have involved selecting existing elements on the page and making changes to them. However, there are times you’d like to generate new elements or wrap the same markup in a reusable control and attach it to the page.

Controls in CobaltMVC are just CobaltElements with properties and methods that you can use to define the behavior of an element. Because of this, a control can be selected against and modified by external selectors. This means that any control can be adjusted and tweaked for your individual needs.

Want to learn more? Check out the screen cast below that explains some of the interesting things you can do with custom controls and dynamically generated HTML elements.

[Watch The Screencast!]

Written by hugoware

June 4, 2010 at 9:52 am

Cobalt Beta – jQuery Style MVC View Templating!

leave a comment »

In a recent blog post I shared a preview of the Cobalt project I’ve been working on. Today, the source code has been uploaded to git-hub and the first beta binaries are being released!

Not sure what Cobalt is? Watch a screencast showing how you can use Cobalt in your MVC projects.
Watch the video now!

If you’ve seen any of my previous blog posts then you realize I’m not much of a fan of the current way to populate templates in ASP.NET MVC. I’ve tried a handful of different ways to improve the experience but so far nothing really felt like an improvement.

Cobalt uses CSS selectors to find and update content, much like the way that jQuery works. Cobalt works *with* ASP.NET MVC (and WebForms) so you can include it in an already existing project and use it right away!

So what does Cobalt look like? Here is an example of an MVC View…

<%@ Page Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<ProductDetail>>" %>
<%  
    this.Ready(() => {

        //select by tag names
        this.Find("form")
            .Attribute(new {
                action = this.Url.Action("CheckOut")
            });
        
        //find and set values for elements
        string current = this.Find("h3").Text();
        this.Find("#title").Text(current.ToUpper());
        
        //select classes and certain pseudo selectors
        this.Find(".list :even").AddClass("alt-item");
        
        //create new elements on the fly
        var link = this.Create("<a/>")
            .Text("Read About Us")
            .Attribute("href", this.Url.Action("AboutUs"));
        this.Find("p").Append(link);
       
        //create custom elements (like CustomControls)
        Stylesheet sheet = new Stylesheet("~/site.css");
        sheet.AddToPage();
        
    });
    
%>

<html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <form method="post" >
            <h3>Temp Title</h3>
            <p>The description goes here</p>
            <ul class="list" >
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
                <li>Item 4</li>
                <li>Item 5</li>
            </ul>
        </form>
    </body>
</html>

You can see that much like jQuery we have to queue up the work we need to execute once the document is ready.

I have a lot of documentation to write and a lot of screencasts to record, but don’t forget about the preview video which should get you started. For now, here are a list of the more important details.

The Important Stuff!

  • You must call CobaltManagement.Initialize() in your Global.asax file in the Init method (just override it and call it).
    public override void Init() {
        base.Init();
        CobaltManagement.Initialize();
    }
    
  • Cobalt uses HtmlAgilityPack to handle parsing of html content. I’m not happy with the framework so it will be one of the first things to be phased out, but for now you need to make sure to download it if you get the source code instead of the binaries.
  • You must use this.Ready from your pages and controls to wrap your commands. Otherwise your commands will run before the document is ready and fail.
  • Cobalt is aware of context, so if you use this.Find within a UserControl then you’re only going to select elements within that control. If you need to access the Page level from a UserControl then you can call this.Page.Find to change the scope of the command.
  • Cobalt supports a decent amount of selectors. Below is a list of currently available options.
    • Combinators: ‘ ‘, >, +
    • Shortcut Attributes: #elementId, .cssClass, $elementName
    • Attribute Matching (ex. [@name=’value’]): equals (=), starts with (|=), ends with ($=), contains (~=)
    • Pseudo: first, last, even, odd, nth(#), lt(#), lte(#), gt(#), gte(#), text, password, button, checkbox, radio, submit, file

Keep in mind this is very much beta code – I was literally working on changes today :). If you’re feeling brave then download the source and dig right in!

Download Beta

Cobalt (Source Code)

Written by hugoware

May 31, 2010 at 11:38 pm

Cobalt MVC Preview!

with 3 comments

Lately, I’ve been working a lot on my project Cobalt which is, more or less, jQuery for server side ASP.NET MVC views. I’ve shown some code examples before but today I have a screen cast of some of the code in action.

Watch the video now!

Hopefully, I’ll have some code released in the next week or two, but for now feel free to give thoughts and feedback!

Written by hugoware

May 27, 2010 at 9:09 am

MVC Templating – jQuery Style!

with 3 comments

I’ve messed around with a variety of ways to make MVC templating better but I’ve never really been satisfied with any of my solutions until now.

One of the things that I really like about jQuery is that it allows for better separation of markup from code since you can use CSS selectors to find and change elements on the page. ASP.NET MVC requires server side blocks of code to be mixed into the markup to display content.

The other day I started working on a new project I’ve named Cobalt – A jQuery style, context aware templating framework for ASP.NET MVC. I’m not quite ready to release the code but I wanted to share the idea in advance.

Note: When I say “jQuery Style”, I mean method chaining with css selectors – You can’t use $()… sorry 🙂

Let’s pretend we have the following markup

[Index.aspx (Markup)]

<%@ Page ... %>
<html>
    <head>
        <title>Untitled</title>
    </head>
    <body>
        <h1>Title</h1>
        <div class="content">
            <p></p>
            <ul></ul>
        </div>
        <a id="back" >Previous</a> | <a id="next" >Next</a>
    </body>
</html>

Using Cobalt, we can use jQuery style code to select the correct elements and update content in server side code at the top of the view.

[Index.aspx (Server Code)]


//select tags by their names
this.Find("h1")
    .Text("My Page");

//select tags by name
this.Find("a")
    .Attr("href", this.Url.Action(link.Text())
    .Css(new { color = "#f00" });

//find by ID
this.Find("#back")
    .Remove();

//use other selectors
this.Find(".content > p")
    .Html(this.Model.PostContent);

//select classses and children
this.Find(".content > ul")
    .Remove();

//or perform sub queries
this.Find(".content", content =>
    content.Find("strong")
        .Text(bold.Text().ToUpper())
            .AppendTo(content)
            );

Keep in mind, this code is part of the view and not in a code behind file.

Of course, this view could probably be just as easily updated using a Model and assigning values using server side blocks of code, but consider some of the advantages of keeping our code separated.

  1. Markup stays free of server side code blocks so it is easier to pull the content from external resources (for example a database)
  2. If the markup is constantly being changed by another team member (for example a designer) we can avoid tinkering with the new HTML and instead make changes to our selectors (if even needed).
  3. Many web developers are familiar with CSS selectors – The template could be understood by other team members and developers regardless of programming language choice.

Being Context Aware

The context of a selector is another important part of Cobalt. If you’re working in a UserControl you might changes to stay within the context of the control. At the same time, you might want some of your commands to change other parts of the page.

[SomeControl.ascx]

<@ Control ... %>

<h3>Latest Tweets</h3>
<ul class="tweet-list" ></ul>
<a href="http://www.twitter.com/hugoware" >Follow Me!</a>
<% =this.Html.ActionLink("Rendered Link", "Index") %>

When you use the this.Find(...) command, the actions are queued up and executed only for the calling control. That said, you can use the this.Page or the this.Parent properties to change the context (and scope) of a command.

[SomeControl.ascx (Server Code)]


//context stays inside of the UserControl
this.Find("ul.tweet-list")
    .Html(this.Model.Tweets);

//context stays inside of the UserControl
this.Find("h3")
    .Text("Follow Me!");

//finds both links (static and rendered)
this.Find("a")
    .Attr("href", this.Url.Action("Home"))
    .Text("changed!");

//context changes to the page level
this.Page.Find("head")
    .Append(this.Model.Stylesheet);

//updates the title in the page
this.Page.Find("title")
    .Text("Changed the title!!");

//never finds the title (context is in the control)
this.Find("title")
    .Text("Title not changed!");

Again, this might be a little extra code in some cases, but we are also able to access elements all over the page without needing to apply special WebControls or wire up to the Page life cycle.

It is worth pointing out that both links will be discovered by the a selector since the actions aren’t actually invoked until after the page is rendered. This means you can use MVC like you normally would and still use Cobalt to find and change elements. In fact, as far as I can tell this should work with WebForms as well as MVC, but I’d have to test it before I could say how well it works.

Work In Progress

This project is only a few days old right now but is already coming along very well. I’ll be posting some code soon but till then feel free to share any ideas you have.

Written by hugoware

May 17, 2010 at 11:56 pm