jump to navigation

jsRazor – New Way of Rendering Json That Is Pure Genius May 9, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Ajax, jQuery, JSON.Net, KnockoutJS, Open Source, Problem Solving.
Tags: , , , , ,
add a comment

DClick this link immediately, and you’ll see wonderful things! Sensei has said many times that simple is better, and rgubarenko of MakeItSoft has a brand spanking new template engine that is so simple it makes you speechless.  His premise:  every possible rendering task can be accomplished as a random combination of two functional primitives:

repeat – repeats fragment of HTML code for each object in array
toggle – shows or hides fragment of HTML depending on boolean flag

Here is an example taken from the github site.  To get the output display below:

jsRazor Example Output

from a Json data set that looks like this:

var data_Themes = [ { name: "Dreaming Theme", colors: ["#2A1910", "#9E7064", "#B0967C", "#E7435E", "#6D4F3F"] },

{ name: "Moth Theme", colors: ["#30382D", "#565539", "#78765F", "#403F2B"] },

{ name: "5 Dark Theme", colors: ["#000000", "#280705", "#2E0500", "#3B0000", "#3C1100"] },

{ name: "Blue Volcano Theme", colors: ["#5077FF", "#8A84FF", "#81C1FF"] } ];

You will have a template that looks like this:

<pre><div id="example">
  <ul>
    <!--repeatfrom:themes-->
    <li> 
      <div class="name">{name} ({CountColors} colors)</div>
      <!--repeatfrom:colors-->
      <div class="wrap">
        <div class="color" style="background-color:{item};">
          <!--showfrom:dark-->
          <span style="color:white">{item}</span>
          <!--showstop:dark-->
          <!--showfrom:light-->
          <span style="color:black">{item}</span>
          <!--showstop:light-->
        </div>
        <div class="rgb">({R},{G},{B})</div>
      </div>
      <!--repeatstop:colors-->
    </li>  
    <!--repeatstop:themes-->
  </ul>
</div></pre>

The controller that creates the final result is as follows:

<pre>// get initial template
var tmp = document.getElementById("example").innerHTML; 
// repeat theme objects (pass array of themes to repeat functional)
tmp = $.jsrazor.repeat(tmp, "themes", data_Themes, function (tmp, idx, item)
{
  // repeat inner color objects (pass array of colors of the current theme item)
  tmp = $.jsrazor.repeat(tmp, "colors", item.colors, function (tmp, idx, item)
  {
    // use toggle to show dark or light color text (to be contrast with background)
    tmp = $.jsrazor.toggle(tmp, "dark", hex2rgb(item).mid <= 128);
    tmp = $.jsrazor.toggle(tmp, "light", hex2rgb(item).mid > 128);
    // output RGB representation of the color as custom value
    tmp = tmp
      .replace("{R}", hex2rgb(item).r)  // red
      .replace("{G}", hex2rgb(item).g)  // green
      .replace("{B}", hex2rgb(item).b); // blue
    // return processed template for current INNER item
    return tmp;
  });
  // color counter is not a part of JSON, so we output it as custom value
  tmp = tmp.replace("{CountColors}", item.colors.length);
  // return processed template for current item
  return tmp;
});
// put processed output back
document.getElementById("example").innerHTML = tmp;</pre>

This looks very promising.  In fact, this could be a very cool way of writing reports in jQuery!  Think about it – with a tool like jLinq for filtering data sets and jsRazor, you could replace SQL Server Reports.

About these ads

Develop A Theme For Your Project – Spock Can Help April 28, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Mythology, New Techniques, Personal Development, Problem Solving, software economics.
Tags: , , , , , , ,
add a comment

Evil_SpockMany times Sensei has said you have to have a theme song for your projects. You may have certainly noticed that Sensei is old school, prog-rock and somewhat metal oriented. Spock’s Beard is a recent discovery and the group has direct roots with Transatlantic.

This latest album is a great source of inspiration, so if you have a ten minute walk ahead of, fire it up and it will get your head straight for serious productivity, creativity, or pure coding marathons.

Simplify Your Thoughts For Uninterrupted Flow April 24, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Agile, Coaching, New Techniques, Open Source, Personal Development, Problem Solving.
Tags: , , , ,
add a comment

Sensei recently gave up FogBugz. This was not because of FogBuz, as it is a great product. But Sensei realized that it was not meeting his needs. It was too much. When on the hunt, you can’t be slowed down, and sometimes you have to jettison the extra weight. To be fair, the context here is a prototyping project, where errors / foibles / new features need to be captured. FogBugz is great a teams, but it does require, well, too many clicks. You should always ask yourself this question: which James Bond do I want to be?

doctor-no1_lg bond_large_verge_medium_landscape

 

 

Which Bond gets the babe? Pretty easy choice. The unfettered thinker makes them swoon. The guy with the helmet …not so much.

Keeping It Real By Keeping It Simple

Yep – Sensei sounds like a whiny Apple-simplify-your-life-and-wear-a-black-turtle-neck Zen iPad fan boy. Well, that’s not right either. There’s just the right tools for the the right job. So when in the fight with the development environment, brain firing on all cylinders, Seseni uses Workflowy. You can quickly categorize your lists / sentences / thoughts as you go. Just typing, no modal dialog boxes, no creating an item, waiting for it to save, clicking, scrolling, more dialog boxes.

Before you attack, Sensei is not saying this will work for teams, for bug resolution, and other endeavors that FogBugz does very well. But it’s all about eliminating the tactics that get in the way of you achieving your goals. This is critical. And when prototyping you need as much room in your head as possible so you solve the bugs, but not spend more time tracking the bugs. Below is a sample. Issues and features, pretty easy. Click it to see the details.

Workflowy

So What? Well, How About Taking It a Step Further

Sensei hopes that the enterprising readers out there can take this idea and run with it: Why not create system that parses the format shown above? When you edit, each line gets a Guid. Then, start at the top level. Each item at that level is story or a deliverable, maybe broken down by screen or function. A child of each story will have an Issues or Features item, and the child items of Issues naturally belongs to Issues. All else would be ignored when converting to a database record, yet retained in your notes.

bond_01_slide-9f8039ebe14dba26b56314bd850026a107423d9c-s6-c10 - CopyThis would be your starting pointing. Because each of these items has an identifier, later you could parse them into a database format, assign people, etc. The point is that the starting point is easier, is more productive because you just type. That way your work gets done, and you feel more like him.

The Speed of Thought, Part Duh!!! (Or Driving Stick Shift with Javascript) April 18, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Coaching, Humor, jQuery, KnockoutJS, Mythology, Problem Solving, Scripting.
Tags: , , , , ,
add a comment

scream_baron_blood_01Sensei is a libertarian – so you can interpret that to mean few rules, respect others freedom, government and busy bodies “leave me the hell alone”, stay-outta-my-way-attitude-person is his motto.  That means the only way to drive is with the stick.  Automatic is for the soccer moms.  Javascript is like driving manual transmission – sometimes you grind the gears.

You’re hero just spent a half hour pouring over some Knockout.js code, wondering why his observableArray went MIA on each push.  Can you see why?

var Question = function (id, question, sortOrder) {
this.Id = id;
this.Question = ko.observable(question);
this.SortOrder = ko.observable(sortOrder);
};

It’s not Javascript’s fault, it’s Sensei’s fault. Now you can see why he writes in the third person, ’cause it’s easier to remove yourself from these type of dumb mistakes when you can treat your persona as separate person!! If you see the issue, leave a comment before I post the resolution.

Learning Techniques: What the Research Says April 18, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Mythology, New Techniques, Personal Development, Problem Solving.
add a comment

A great study in learning techniques how effective they are.

Learning Techniques: What the Research Says.

The Speed of Thought April 17, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Approvaflow, Business Processes, Coaching, Fluent, Mythology, Personal Development, Problem Solving.
Tags: , , , , , , , ,
add a comment

faradaypennytwinsOf late, Sensei needs to keep a clear head.  That has meant learning to segment ideas and really, really, really focus on streamlined features.  This is hard.  Not because Sensei has a plethora of great ideas.  That would be a nice problem to have.  Many times in software development you end up this guy:

This is the state where you have things you want to accomplish, yet even when you pair things down to the “essential”, other essential, critical factors must be taken into consideration before you create a mess.  This is life calling, and that string which suspends that giant sword that you noticed hovering over your head is about to snap.  There is a good chance that you need more discipline, better execution tactics, far better honed chops, you name the metaphor.  Sensei has been at this game for over 22 years, and still the speed that thought takes to become reality is way too slow.

With great sarcasm you can remind your self that some of the best work lays ahead, but the reality is that you still need to fight to be fluent, you have to claw your way to a Zen state of mind / no-mind.  So chose, the art of bushido or the art of BS.  Or maybe work smarter and enjoy life.

Before Sensei leaves you, ponder this:  does “being done” mean that you’ve dropped off a product but have to get on the phone in order to make changes, and maybe now that you are struggling why couldn’t you figure out to take time when it was more critical to be fluent with your productivity?

 

A Life Time In a Day April 5, 2013

Posted by ActiveEngine Sensei in ActiveEngine, Coaching, Mythology, Problem Solving.
Tags: ,
3 comments

If you are lucky, you can experience a life through the course of a day. Consider it the antithesis of ground hogs day. Instantaneous history, melancholy,!and certainty all at once. You are here, where do you go?

20130405-174801.jpg

NuGet Causes Needless Headaches With RavenDB, RestSharp and Json.Net September 25, 2012

Posted by ActiveEngine Sensei in .Net, ActiveEngine, Mythology, Open Source, Problem Solving.
Tags: , , ,
add a comment

Just because something is shiny and promises riches doesn’t mean you should put it in your pocketses.  NuGet, while good for getting an assembly for quick and dirty research and development, is a tour to the valley of frustration when you need to focus and deploy a solution with many dependencies.

NuGet has a pretty dialog box so you think you can just “wire up” and go, but this is an illusion my precious.  Sometimes it doesn’t update the Hint path.  Sometimes it forces you to install packages in certain order, as with SignalR, RestSharp and RavenDB.

Think about it – NuGet pulls down files, creates directories and then references to all the paths that were just created.  We can’t do that ourselves by pulling a directory, the adding the reference to old fashioned way, meaning the way that leaves you feeling more in control, not requiring you to spend hours hunting references in package.config files in different folders?  The main premise is to eliminate this practice, right?  What is going to happen when you introduce AppHarbor into the mix where you won’t be able to look and the production server to divine what assemblies are indeed deployed!

What Works Versus What Makes You Feel Cool

Sensei wants to direct you to a solution where a developer needed to use two versions of Json.Net with RavenDB.  His solution:  add dependentAssembly tag to the web.config, upload the file to a sub directory of the bin folder, and move on.

Ok, so it’s not cool, but the job is done.  And that should be the whole point.  Why use tools that put us in this mess in the first place?  Unfortunately NuGet is becoming the primary way to get assemblies.  The road may go ever on but projects have a deadline!!  Poor Smeagul.

A Great Post on Managing Branches in Git September 20, 2012

Posted by ActiveEngine Sensei in AppHarbor, Open Source, Problem Solving.
Tags: , , ,
add a comment

Vincent Driessen has written an amazing post on managing branches in Git, and how to effectively avoid the fire drill that we’ve been through when we have to push a hot-fix into production while preserving new development.  It is titled A Successful Git Branching Model.

This can be very critical if you are using AppHarbor, a .Net cloud platform where you push your source code from Github to AppHarbor and the AppHarbor elves build it and push to a production server if the app passes its unit tests.  AppHarbor maintains a history of builds so that you can -ahem – roll back on the very occasion that you have made a mistake.  But this only speaks to Vincent’s point that if you configure Git with the appropriate branches to handle development, production and hot-fixes you should use the rollback feature less.

Sensei has been spending a lot time working with Git and AppHarbor and one of the next milestone on his journey will be to learn how to disable auto push for the development branch of his project while maintaining the synchronization with the master branch.  This should be the subject of up-coming, shouldn’t it?  Or maybe one of you, the dear readers of this blog has answer they’d like to share?

ApprovaFlow: Create A Plugin System And Reduce Deployment Headaches June 29, 2011

Posted by ActiveEngine Sensei in .Net, ActiveEngine, Approvaflow, ASP.Net, Problem Solving, Workflow.
Tags: , , , ,
2 comments

This is the fourth in a series of posts for ApprovaFlow, an alternative to Windows Workflow written in C# and JSON.Net.  Source code for this post is here.

Last Time on ApprovaFlow

In the previous post we discussed how the Pipe and Filter pattern facilitated a robust mechanism for executing tasks prior and after a transition is completed by the workflow state machine.  This accomplished our third goal and to date we have completed:

Model a workflow in a clear format that is readable by both developer and business user. One set of verbiage for all parties.  Discussed in Simple Workflows With ApprovaFlow and Stateless.

•  Allow the state of a workflow to be peristed as an integer, string, etc.  Quickly fetch state of a workflow.  Discussed in Simple Workflows With ApprovaFlow and Stateless.

•  Create pre and post processing methods that can enforce enforce rules or carry out actions when completing a workflow task.  Discussed in ApprovaFlow:  Using the Pipe and Filter Pattern to Build a Workflow Processor

These goals remain:

• Introduce new functionality while isolating the impact of the new changes. New components should not break old ones

• Communicate to the client with a standard set of objects. In other words, your solution domain will not change how the user interface will gather data from the user.

• Use one. aspx page to processes user input for any type of workflow.

• Provide ability to roll your own customizations to the front end or backend of your application.

It’s the Small Changes After You Go Live That Upset You

The goal we’ll focus on next is Introduce new functionality while isolating the impact of the new changes. New components should not break old ones, as it’s the small upsetters that lurk around the corner that your users will think up that will keep you in the constant redeployment cycle. If we implement a plug-in system, then we can prevent the new features from breaking the current production system. Implementing these changes in isolation will lead to faster testing, validation and happier users.

We lucked out as our implementation of the Pipe And Filter pattern forced us to create objects with finite functionality.  If you recall each step in our workflow chain was implemented as a filter derived from FilterBase and this lends itself nicely to creating plug-ins.  The Pipe and Filter pattern forces us to have a filter for each unique action we wish to carry out.  To save data we have a SaveData filter, to validate that a user can supply a Trigger we have the ValidateUserTrigger, and so on.

“Great, Sensei, but aren’t we still constrained by the fact that we have to recompile and deploy any time we add new filters?  And, if I have to do that, why bother with the pattern in the first place?”

Well, we can easily reduce the need for re-deploying the application through the use of a plugin system where we read assemblies from a share and interrogate them by searching for a particular object type on application start up.  Each new feature will be a new filter.  This means you will be working with a small project that references ApprovaFlow to create new filters without disturbing the existing architecture.   We’ll also create a manifest of approved plug-ins so that we can control what is used and institute a little security since we wouldn’t want any plugin to be introduced surreptitiously.

Plug-in Implementation

The class FilterRegistry will perform the process of reading a share, fetching the object with type FilterBase, and register these components just like we do with our system components.  There are a few additions since the last version, as we now need to read and store the manifest for later comparison with the plug-ins.  The new method ReadManifest takes care of this new task:

private void ReadManifest()
{
  string manifestSource = ConfigurationManager.AppSettings["ManifestSource"].ToString();

  Enforce.That(string.IsNullOrEmpty(manifestSource) == false,
          "FilterRegistry.ReadManifest - ManifestSource can not be null");

  var fileInfo = new FileInfo(manifestSource);

  if (fileInfo.Exists == false)
  {
    throw new ApplicationException("RequestPromotion.Configure - File not found");
  }

  StreamReader sr = fileInfo.OpenText();
  string json = sr.ReadToEnd();
  sr.Close();

  this.approvedFilters = JsonConvert.DeserializeObject>>(json);
}

The manifest is merely a serialized list of FilterDefinitions. This is de-serialized into a list of approved filters.With the approved list the method LoadPlugin performs the action of reading the share and matching the FullName of the object type between the manifest entries and the methods in the assembly file:

public void LoadPlugIn(string source)
{
  Enforce.That(string.IsNullOrEmpty(source) == false,
             "PlugInLoader.Load - source can not be null");

  AppDomain appDomain = AppDomain.CurrentDomain;
  var assembly = Assembly.LoadFrom(source);

  var types = assembly.GetTypes().ToList();

  types.ForEach(type =>
  {
    var registerFilterDef = new FilterDefinition();

    //  Is type from assembly registered?
    registerFilterDef = this.approvedFilters.Where(app => app.TypeFullName == type.FullName)
                                   .SingleOrDefault();

    if (registerFilterDef != null)
    {
      object obj = Activator.CreateInstance(type);
      var filterDef = new FilterDefinition();
      filterDef.Name = obj.ToString();
      filterDef.FilterCategory = registerFilterDef.FilterCategory;
      filterDef.FilterType = type;
      filterDef.TypeFullName = type.FullName;
      filterDef.Filter = AddCreateFilter(filterDef);

      this.systemFilters.Add(filterDef);
     }
  });
}

That’s it. We can now control what assemblies are included in our plug-in system.  Later we’ll create a tool that will help us create the manifest so we do not have to managed it by hand.

What We Can Do with this New Functionality

Let’s turn to our sample workflow to see what possibilities we can develop.  The test CanPromoteRedShirtOffLandingParty from the class WorkflowScenarios displays the capability of our workflow.  First lets review our workflow scenario.  We have created a workflow for the Starship Enterprise to allow members of a landing party to request to be left out of the mission.  Basically there is only one way to get out of landing party duty and that is if Kirk says it’s okay.  Here are the workflow’s State, Trigger and Target State combinations:

State Trigger Target State
RequestPromotionForm Complete FirstOfficerReview
FirstOfficerReview RequestInfo RequestPromotionForm
FirstOfficerReview Deny PromotionDenied
FirstOfficerReview Approve CaptainApproval
CaptainApproval OfficerJustify FirstOfficerReview
CaptainApproval Deny PromotionDenied
CaptainApproval Approve PromotedOffLandingParty

Recalling the plots from Star Trek, there were times that the medical officer could declare the commanding officer unfit for duty. Since the Enterprise was originally equipped with our workflow, we want to make just a small addition – not a modification – and give McCoy the ability to allow a red shirt to opt out of the landing party duty.

Here’s where our plugin system comes in handy.  Instead of adding more states and or branches to our workflow we’ll check for certain conditions when Kirk makes his decisions, and execute actions.  In order to help out McCoy the following filter is created in a separate project:

public class CaptainUnfitForCommandFilter : FilterBase
{
  protected override Step Process(Step input)
  {
    if(input.CanProcess & input.State == "CaptainApproval")
    {
      bool kirkInfected = (bool)input.Parameters["KirkInfected"];

      if(kirkInfected & input.Answer == "Deny")
      {
        input.Parameters.Add("MedicalOverride", true);
        input.Parameters.Add("StarfleetEmail", true);
        input.ErrorList.Add("Medical Override of Command");
        input.CanProcess = false;
      }
    }

    return input;
  }
}

This plug-in is simple: check that the state is CaptainApproval and when the answer was “Deny” and Kirk has been infected, set the MedicalOverride flag and send Starfleet an email.

The class WorkflowScenarioTest.cs has the method CanAllowMcCoyToIssueUnfitForDuty() that demonstrates how the workflow will execute. We simply add the name of the plug-in to our list of post transition filters:

string postFilterNames = "MorePlugins.TransporterRepairFilter;Plugins.CaptainUnfitForCommandFilter;SaveDataFilter;";

This portion of code uses the plug-in:

//  Captain Kirt denies request, but McCoy issues unfit for command
parameters.Add("KirkInfected", true);

step.Answer = "Deny";
step.AnsweredBy = "Kirk";
step.Participants = "Kirk";
step.State = newState;

processor = new WorkflowProcessor(step, filterRegistry, workflow);
newState = processor.ConfigurePipeline(preFilterNames, postFilterNames)
  .ConfigureStateMachine()
  .ProcessAnswer()
  .GetCurrentState();

//  Medical override issued and email to Starfleet generated
bool medicalOverride = (bool)parameters["MedicalOverride"];
bool emailSent = (bool)parameters["StarfleetEmail"];

Assert.IsTrue(medicalOverride);
Assert.IsTrue(emailSent);

Now you don’t have to hesitate with paranoia each time you need introduce a variation into your workflows. No more small upsetters lurking around the corner. Plus you can deliver these changes faster to your biggest fan, your customer. Source code is here.   Run through the tests and experiment for your self.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: