Hugoware

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

Posts Tagged ‘Web Development

jsshell 3.0

with one comment

This weekend I finished up an upgrade for jsshell to version 3.0. I also put together a new jsshell landing page to help users get started.

New Stuff In 3.0

  1. jQuery and jLinq Upgrade: Both libraries have been upgraded to their newest versions. jQuery 1.4.4 and jQuery UI 1.8.7. jLinq has been upgraded to 3.0.2.
  2. Auto Complete: Previously, jsshell would show css classes, IDs and tags that were on the page as a ‘auto-suggest” popup but you couldn’t select anything on the list. Now, jsshell allows you use TAB to select the currently highlighted item. You can use up and down to change the highlighted item.
  3. More Auto Complete Sources: jsshell now shows suggestions for jQuery and jLinq commands, current IDs, tag names and css classes on the page and now some Javascript keywords and common CSS properties.
  4. Remember Last Command: jsshell now remembers the last successfully executed command. If you browse to a new page or refresh the view, the last command you ran will still be waiting for you.
  5. Access ‘file:///’ URL: Previously, Google denied the app from being released because it had access to the file URL. It seems they have changed the way this rule is handled so this version now includes the local file url.
  6. A ‘Run’ Button – Finally…: The only way to run commands before was to press CTRL+Enter. Now there is a button that does the same thing.

Special thanks to @stevehebert for his great suggestions on improvements for jsshell.

Please feel free to let me know if anything isn’t behaving as expected.

Written by hugoware

December 20, 2010 at 1:01 am

Waiter, There Is Some jQuery In My jLinq…

leave a comment »

jLinq occasionally gets confused as a plug-in for jQuery. Unfortunately, jLinq doesn’t do much to help performing queries in jLinq. I’ve written some extension methods before to help link the two together but they were packaged with other projects (and not really ever released)

So this weekend I put together a few helpful extension methods and released them on GitHub.

Naturally, you’ll need the core jLinq library and the jLinq.jQuery library along with jQuery. Since a lot of jQuery uses chained methods you’ll need to use the special invoke syntax for jLinq queries (just an array).

Here are some of the commands you can use.

  • jlinq.$([selector]) : Starts a new query from document.body with the starting selector (if any).
  • $(selector).query([selector]) : Starts a new query from the current jQuery object. Allows an optional selector.
  • .include(selector, [jQuery Object]) : Includes the matches of the provided selector into the current query. You can use a different jQuery object as the source (otherwise it defaults to the object that started the query).
  • .get([selector]) : Converts the current matches in the query to a jQuery object. Allows an optional selector to further filter the results.

Just as a reminder, in order to invoke methods within a query you need to use an array where the first value is the name of the method and following values are the arguments. These arguments are all where the field name would normally be. Here are a few examples in case you need them.


//Example 1: Non-method query
jlinq.from(data).contains(
    "fieldName", //the field to pull the value from
    "check for this" //the argument for contains
    );

// Example 2 : No arguments
// function test() { ... }
jlinq.from(data).contains(
    ["test"], //no arguments, but still an invoke
    "check for this" //the argument for contains
    );

// Example 3 : With arguments
// function test(arg1, arg2) { ... }
jlinq.from(data).contains(
    ["test", 33, false], //the method with arguments
    "check for this" //the argument for contains
    );

So what do these new methods look like? Well here are a few examples to get you started!


//finds all .result elements containing red or green
//and is also case-insensitive
jlinq.$("div.results")
    .contains(["text"], "red")
    .or("green")
    .get()
    .appendTo(document.body);

//finds all links pointing to MP3 files then sorts and styles them
var mp3Links = jlinq.$("a")
    .endsWith(["attr","href"], ".mp3")
    .sort(["text"])
    .get()
    .css({
        color:"#f00",
        fontWeight:"bold"
    });

//highlights all of the matching markup with 'Joe Smith'
$("div.result").query()
    .contains(["html"], "Joe Smith")
    .each(function(rec) { 
        var markup = rec.html()
            .replace(/Joe Smith/g, 
                "<span class='highlight'>Joe Smith</span>");
        rec.html(markup); 
        });

Now you can enjoy the awesomeness of jQuery along with the semi-usefulness of jLinq! You have access to ‘or’-ing, case insensitivity, sorting — It is all there!

This code is all brand new so I don’t recommend using it anywhere important just yet, but it is fun to see how jLinq can make queries a little bit easier.

Written by hugoware

September 26, 2010 at 10:18 pm

Using jLinq With JSON APIs

leave a comment »

I’ve had a few e-mails asking how to perform a query on JSON data from an external source, for example Flickr Services. This post we will go over accessing Flickr data but also performing a secondary query on the information returned.

You can download a .zip file at the end of the post with the files used in the examples.

Let’s take a look at what we’re going to create…

You can see we’ve included a search box along with a few additional check boxes with options we can use for the secondary query. These options aren’t available for the API call, but we can intercept the records and apply additional filters before we use them on the page.

To start, we need to create an extension method for downloading the data from the Flickr APIs. jLinq allows you to create extension methods and plug them directly into the framework.

//extend jLinq to search Flickr
jlinq.flickr = function(search, action) {
    search = escape(search);
    $.getJSON(
        "http"+"://api.flickr.com/services/feeds/photos_public.gne?"+
        "tagmode=any&format=json&jsoncallback=?&tags="+search, 
        function(data) {
            var query = jlinq.from(data.items);
            action(query);
        });
};

This example creates a method named flickr that resides with the rest of the jLinq library. The method accepts a keyword to search with and an anonymous function that will be used to work with the data. This is because we have to wait for the server to return a response.

This means you would use the function with a search phrase and a jLinq query to perform.

//start a new jLinq query
jlinq.flickr("cake", function(query) {

    //perform a normal query and use the data
    query.contains("title", "red")
        .sort("title");
});

At this point we need to wire up all of the UI elements on the page. I won’t go into detail on this part but you can always refer to the example for help if you get stuck.

So lets take a step back and take a look at how the filtering is done for the records. You’ll notice that we can selectively perform certain parts of the query depending on which check boxes are selected.

//sample.js - line 31     - - - - - -
//if excluding titles with digits
if (flickr.ui.filterNumbers.is(":checked")) {
    query.notMatch("title", /\d/g);
}

//if requiring a photo to have a title
if (flickr.ui.requireTitle.is(":checked")) { 
    query.notEmpty("title"); 
}

//if requiring sorting of titles
if (flickr.ui.sortTitle.is(":checked")) { 
    query.sort("title"); 
}

//snip...

You’ll notice that you don’t have to chain the entire query together. You can do sections at a time. This means you can decide when certain parts of the script run and when they are skipped.

Now, we can write queries against Flickr and also perform our own secondary queries using jLinq. In this case we are sorting data and filtering out records that wasn’t part of the query to the server.

Of course, this is a simple example but is does show some of the neat ways you can you can use jLinq to help you work with JSON data.

[Sample Files]
http://hugoware.com/examples/jlinq-flickr.zip

Written by hugoware

August 26, 2010 at 1:12 am

Installing CobaltMVC

with one comment

Got an interesting piece of anonymous feedback today reminding me of something rather obvious…

How exactly do you install CobaltMVC?

Oh yeah… That would be handy information… and it probably should have already been released. That said, lets get right to it.

Download CobaltMVC

The new CobaltMVC site is still in beta (like the rest of the framework) but you can still download the libraries you need to get started.

Add CobaltMVC To Your Project

Unpack the files to an easy to reach location and then add them as references to your project. You don’t need to add both, the Cobalt.dll is good enough.

‘Initialize’ CobaltMVC

Next, open up the Global.asax file and include the Cobalt.CobaltConfiguration.Initialize(); call to the Application_Start method. This makes sure that CobaltMVC is set up fully before it begins processing requests.

Update Web.config (sorta optional)

This step can be skipped but it will make coding your pages less convenient since you’ll have to add the namespaces all over the rest of your project. Add the Cobalt and the Cobalt.Web namespaces to your system.web/pages/namespaces section. This opens up the extension methods used to start Cobalt commands from your views.

You’re Done!

At this point we can test CobaltMVC to see if it is working. For example, here is a command you can run on the default MVC Index view.

And you’ll get the following results…

Not bad, huh?

It is worth mentioning that CobaltMVC might have unexpected results if you use .browser files with your project. Why?

Well, part of the Initialize() call actually creates a .browser file that is used to capture rendering for content on the page.

So, if you see this file floating around in your project, don’t delete it.

Who knows what happens when too many .browser files are fighting for the same thing but I doubt it will be a good thing.

Good luck!

Written by hugoware

August 20, 2010 at 12:09 am

3 Things To Know Before Using jLinq

leave a comment »

Since I released the beta code for the new jLinq I’ve had several of the same questions show up. Here are some answers to help you get started.

Where Is ‘Manual’, Query Commands Are ‘Auto-pilot’

I’ve had a few questions where people start trying to use the where command and find that it isn’t solving anything.

As far as I can tell, a lot of other LINQ style Javascript libraries use Where as their query command and have the developer manually provide the comparisons. Granted, I don’t know the other frameworks very well (hint, I wrote my own) but a lot of the code samples look something like this.

var results = lib.From(data)
    .Where(function(record) { return record.name.substr(0, 1) == "a"; })
    .OrderBy(function(record) { return record.name; })
    .Select();

I’m sure that these libraries are doing a lot of stuff for you in the background, but the where command in itself seems like placing too much work on the developer.

jLinq approaches this differently. Instead, you’ll find many common query methods included as part of the library. These methods also evaluate the data types to determine the best way to query the property.

Here is an example, consider you have some data that looks like this.

var data = [{
    name: "James",
    permissions: ["read", "write", "delete"]
},
/* snip... */];

Instead of checking these records manually, you can use the same command for both properties and they will handle the data differently for each.

//with string types
jlinq.from(data).contains("name", "e").select(); //matches the 4th 'e' in 'James'

//with array types
jlinq.from(data).contains("permissions", "write").select(); //matches the 2nd 'write'

This reduces the typing you do since you no longer have to perform manual comparisons.

Of course, jLinq does include a where command that uses the same syntax as the example above (anonymous function), but it is recommended to create extension methods instead of using the where command.

Operators Are Query Commands Too

Operators are an important part of jLinq. Sometimes you’d like to match on more than one condition or ignore records that do not meet a certain condition. You can use operators as individual commands in your queries.

//Examples only - Shorter syntax explained in Section 3

jlinq.from(data)
    .starts("first", "a")
    .or()
    .starts("first", "b");

jlinq.from(data)
    .not()
    .starts("first", "d")

jLinq takes operators a step further by creating operator aliases for all of the query commands in your library. This means that instead of only having the query command starts you actually have 6 – starts, orStarts, andStarts, notStarts, orNotStarts, andNotStarts. The queries above can be rewritten as.

//Examples only - Shorter syntax explained in Section 3

jlinq.from(data)
    .starts("first", "a")
    .orStarts("first", "b")
    .select()

jlinq.from(data)
    .notStarts("first", "d");

It is worth noting that and is the implied default unless you provide an or – the and versions of the query commands are for aethestetics only. 🙂

DRY — I Repeat, DRY!

If you aren’t familiar with the term DRY, it means “Don’t Repeat Yourself”. The previous samples reduced some of our typing, but jLinq can actually take it a step further.

jLinq uses field and command memorizing, meaning after you say it once it is implied until you say something different.

jlinq.from(data)
    .starts("first", "a")
    .or("b")
    .or("c");

jlinq.from(data)
    .starts("first", "a")
    .ends("b")
    .or("last", "a");

The first example memorizes the command being used is starts and the field being queried is first. After that, the remaining calls to ‘or’ will repeat the previous command and field unless something else is used.

The second example shows how you can mix up commands and field names without needing to repeat yourself. Basically, here is what the query is doing.

  1. Records with first names starting with ‘a’…
  2. then records with first names ending with ‘b’…
  3. then records with last names ending with ‘a’

You can see that jLinq makes it easy to avoid repeating the same commands and field names to reduce the typing.

This is just some of the first basics to understand about jLinq. I’ll be blogging more (and writing documentation) for the next few days. Feel free to contact me with questions.

Written by hugoware

August 11, 2010 at 9:54 pm

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