#WebEssentials & Zen Coding

One of the plug-ins that I use the most in Visual Studio is Web Essentials.  It has a large set of features designed to make life easier for developers to get their jobs done.   Today I read the article by Visual Studio Time Saver – Faster HTML Coding by Susan Ibach where she talks about the Zen Coding feature in Web Essentials.  For as many years I have used Web Essentials this is not a feature that I am familiar with.  It’s incredible!  Here is a list of links to different places to get additional information on Web Essentials and tips on how to use Zen Coding.

As a bonus check out vstips in Twitter.  There some great suggestions in there for making Visual Studio easier to use.

Here is a link to the video Susan referenced that shows how to use the Zen Coding functionality.

Book Review: #SoftSkills

A few weeks back I came across a book called Soft Skills.  I’m a sucker for these kinds of books and before I realized what I was doing I had splurged and purchased it.  It is a fantastic book by John Sonmez of Simple Programmer.  With these kinds of books I usually skip around reading what interests me that day.  I make a note on the chapter to indicate that I have already read it.  After a week when flipping through it to find an unread chapter I realized that I was already more than half done with it, which is impressive since it is a 500+ page book.  It is very refreshing to read a book like this that talks to me as an in-the-trenches software developer with no aspirations to become great.  So many of these books talk about how to become an expert in your career and take things to the next level.  This book has some of that but more of it is just tips and tricks on how I can refine what I am doing now to be just that little bit better than I was before.  It’s definitely worth picking up a copy.

MVC: Check if Is Dirty via #JavaScript

I had a need to do some fancy work on a MVC Razor page enabling and disabling buttons based on various criteria.  To do this I needed to check to see if the user had changed any data on the page I ended up using the following structure to do it.

First set up your page with a form and all your input fields.

@using(Html.BeginForm("actionname", "controllername", new { area = "areaname" }, 
       FormMethod.Post, new { id = "saveForm", @class = "disable-submit-form" }))
{
     /* lots of page code */
}

This method serializes the data into a Name, Value array of objects  and hashes it.

     // Grab all the data fields in the code and serialize them, then hash them
     // @Html.Checkbox and CheckBoxFor need to be handled as a separate case 
     function GetSerializedItems() {
        var serializedArray = $(".disable-submit-form").serializeArray()
                                 .filter(function (item) { 
                                           return item.name != 'CheckboxItem1' 
                                               && item.name != 'CheckboxItem2'; 
                                         });
        var serializedCheckboxItems = $('input:checkbox').map(
                                        function () { 
                                           return { name: this.name, 
                                                    value: this.checked ? this.value 
                                                                        : "false" }; 
                                        });
        for (var index = 0; index < serializedCheckboxItems.length; ++index) {
           serializedArray.push(serializedCheckboxItems[index]);
        }
        return convertSerializedArrayToHash(serializedArray);
      }

      $(document).ready(function () {
        // Get the initial state of the data on the page.
        var startItems = GetSerializedItems(); 
       
        // On each field change recheck the current button state
        $('.disable-submit-form').on('change', function () {
           showhidebuttons();
        });

      function showhidebuttons() {
        var $form = $(".disable-submit-form");
        var currentItems = GetSerializedItems();
        var dirty = hashDiff(startItems, currentItems);
        var isDirty = countProperties(dirty) > 0;
        var isValid = $form.valid();
        var isDraft = '@Model.IsDraft' === 'True';

        $form.find(".submitform").attr('disabled', 'disabled');

        if (isValid && isDirty) {
          $form.find(".submitform").removeAttr('disabled');
        } else if (isDraft && isValid) {
          $form.find("#PreviewId").removeAttr('disabled');
          $form.find("#PublishId").removeAttr('disabled');
        }
      }
     }
     
     //Call ShowHideButtons to set the default state
     showhidebuttons();

Here are the javascript helpers I used.

 function convertSerializedArrayToHash(a) {
 var r = {};
 for (var i = 0; i < a.length; i++) {
 r[a[i].name] = a[i].value;
 }
 return r;
 }

 function hashDiff(h1, h2) {
 var d = {};
 for (k in h2) {
 if (h1[k] !== h2[k]) d[k] = h2[k];
 }
 return d;
 }

 function countProperties(obj) {
 var count = 0;

 for (var prop in obj) {
 if (obj.hasOwnProperty(prop))
 ++count;
 }

 return count;
 }

Quote: The End of the Beginning

Quote This quote is from a book I read to my children the other night but feel it is just as relevant to this side of my world as that one.  Learning to be able to identify when to rush and get something out the door and when to slow down and take some extra time is difficult but necessary in the work we do.

~ Avi, The End of the Beginning: Being the Adventures of a Small Snail (and an Even Smaller Ant)

tinymce

#TinyMCE: Fixing Pageload Flickering

When my TinyMCE boxes load I find that there is brief moment when it flickers, the users don’t like that.   Looking closely I found that the flicker is a brief glimpse of the underlying HTML that is rendered before the TinyMCE box finishes loading and is displayed.  To fix it I do some fancy hide/show work.  Initially the page is loaded with the control hidden, then when it is done loading it shows it. Since I had the code already put together, I left in an example of a read-only version of the editor.

When the page is loading mark the textarea as hidden:

     <div class="form-group">
        @Html.Label("Content:") @Html.ValidationMessageFor(m => m.ContentHtml)
        @if (Model.IsReadOnly)
        {
          @Html.TextAreaFor(m => m.ContentHtml, 
                            new { @class = "tinymce-ro", @readonly = "readonly", 
                            @style = "height:300px; width:100%; display:none" })
        }
        else
        {
          @Html.TextAreaFor(m => m.ContentHtml, 
                            new { @class = "tinymce", maxlength = 5000, 
                            @style = "height:300px; width:100%; display:none" })
        }
      </div>

Then show it again once loading is complete:

    $('textarea.tinymce').tinymce({
      script_url: '/scripts/tinymce/4.0.25/tinymce.min.js',
      theme: "modern",
      toolbar: "bold italic ",
      paste_auto_cleanup_on_paste: true,
      init_instance_callback: function (editor) {
        $('.mce-tinymce').show('fast');
      }
    });

    $('textarea.tinymce-ro').tinymce({
      readonly: true,
      script_url: '/scripts/tinymce/4.0.25/tinymce.min.js',
      theme: "modern",
      toolbar: false,
      menubar: false,
      statusbar: false,
      init_instance_callback: function (editor) {
        if (document.getElementById(editor.id).style.display === 'none') {
          editor.getBody().style.backgroundColor = "#EBEBE4";
        }
        $('.mce-tinymce').show('fast');
      }
    });

javascript; Auto-highlight on focus

Sometimes I look online for code and when I find it I realize that I should have known how to do it. Then I feel silly. This is a time when that happened.

I needed to auto-highlight the contents of a read-only textbox or textarea when the user clicked on the input.  Easiest javascript I’ve implemented today!

StackOverflow answer…..

<input type="text" name="textbox" value="Test" onclick="this.select()" />