MVC: Disabling buttons on submit

Don’t want to lose this one.  Its some simple javascript that disables the submit buttons on form submission, from here.

$(document).on('invalid-form.validate', 'form', function () {
    var buttons = $('input[type="submit"]');
    setTimeout(function () {
        buttons.removeAttr('disabled');
    }, 1);
});
$(document).on('submit', 'form', function () {
    var buttons = $('input[type="submit"]');
    setTimeout(function () {
        buttons.attr('disabled', 'disabled');
    }, 0);
});

#TinyMCE: Plugin DDL with Popup

Recently I had a story asking for some advanced functionality for a new TinyMCE button. I broke down the requirements to the following.  I created a JSFiddle to show it working.

  • Custom TinyMCE drop down menu
  • When a menu item is selected it should insert the menu value into the editor at the cursor
  • Last item on the menu will show a popup
  • On the popup have a text box for entering custom text
  • When Insert is clicked insert the text into the editor at the cursor
Core plugin code – Javascript
$('#Insert').click(function () {
    var text = $('#added-token').val();
    tinyMCE.activeEditor.execCommand('mceInsertContent', false, "{Added Text:" + text + "}");
    $('#token-modal').modal('hide');
    return false;
});
tinymce.PluginManager.add('tokens', function (editor, url) {
    editor.addButton('inserttoken', {
        title: "Insert Token",
        type: 'menubutton',
        text: 'Tokens',
        icon: false,
        onselect: function (e) {
          if (e.control.settings.value != '{MenuItemPopup}') {
            editor.insertContent(e.control.settings.value);
          } else {
            $('#token-modal').modal({ show: true });
          }
        },
        menu: [
            { text: 'Menu Item 1', value: '{MenuItem1}' },
            { text: 'Menu Item 2', value: '{MenuItem2}' },
            { text: 'Menu Item 3', value: '{MenuItem3}' },
            { text: 'Menu Item 4', value: '{MenuItem4}' },                     
            { text: 'Menu Item with Popup', value: '{MenuItemPopup}' }                        
        ],
        onPostRender: function () {
            this.value('{MenuItem1}');
        }
    });    
});
tinymce.init({
    selector: "textarea",
	width:      '100%',
	height:     270,
    plugins:    [ "anchor link tokens" ],
    statusbar:  false,
	menubar:    false,
    toolbar:    "inserttoken anchor | alignleft aligncenter alignright alignjustify",
	rel_list:   [ { title: 'Lightbox', value: 'lightbox' } ]
});
Core plugin code – HTML
<div id="token-modal" class="modal hide fade" >
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <input type="text" name="group" id="added-token"  />
    </div>
    <div class="modal-footer">
        <button data-dismiss="modal">Close</button>
        <button id="Insert">Insert</button>
    </div>

#TinyMCE: Disable/Enable Brute Force Solution

tinymceI spent a good chunk of yesterday trying to figure out how to change the state of the TinyMCE textbox from readonly to edit mode.  Or to set the values to enable and disable the box properly.  After much trial, error, and research I found this post which links to this post that explains that it is just not possible to do it cleanly.  These posts are a few years old but in the rest of my research I couldn’t find anything that contradicted them.  I tried many different workarounds suggested by other people and each one had something that just didn’t work quite right.  Here is the brute force solution that I came up with:

I created two TinyMCE editors one that is readonly and one that is not.  Then I show and hide them via a button click.

Another problem that I came across is properly showing and hiding the editors.  When I tried to use the built in options they would not show properly when toggling. I had problems with the textareas being set to visible.   To solve this problem I wrapped the original textarea inside a div and I show and hide the divs instead of the actual text area.

I like so many things about the TinyMCE editor but these problems were very frustrating and took up far too much of my time.

C# Tips N Tricks: Saving Character Literals as String Characters

We have a requirement that when saving a specific type of string to the database it needs to save newline characters as a string (“\n”) not the character literal (‘\n’). It should have been straight forward but I found myself spinning in circles and decided to make a note on what the final code looked like.

CSHTML View:

	@Html.TextArea("Message", Model.Message, new { maxlength = 5000 })

Saving to DB:

      item.Message = model.Message.Replace("\r\n","\\n");

Pulling from DB:

      if (item != null)
      {
        Message = item.Message.ToStringOrEmpty().Replace("\\n", "\r\n");
      }
      if (Message.IsNullOrEmpty())
        Message = "Message goes here.\r\n\r\nSincerely,";

MVC Tips n Tricks: Using a button like an action link

I had the need to display a button that works like an action link to redirect the user to a page within an Area and didn’t want to wrap the whole thing in a form just to do the redirect.  Here is what I used.  It allows the same styling and behavior as a button but redirects directly like an action link.

<input type="Submit" 
       value="Add Persona" 
       class="btn btn-primary btn-lg" 
       onclick="location.href='@Url.Action("Detail", "Persona", new { area = "ProfileInfo" })'" />

RegEx: Validating Phone Numbers

I am horrible at writing regular expressions but, like any developer, when I need them I want a good one.  Today I needed one to validate North American phone numbers, that would allow for all different kinds of formatting by the users and also allow for extensions.

On the following blog post, by Chris Nanney, I finally found the perfect one: 

/\D*\(?(\d{3})?\)?\D*(\d{3})\D*(\d{4})\D*(\d{1,8})?/

I also found this site that I used to validate that it worked as I expected: http://regex101.com/

I’ve been in the position of having to take an unnormalized database that had virtually no data validation or standardization in place, and migrating it to a normalized schema. I used regex to help me through the process.

This post will deal specifically with phone numbers. The data I was importing had many problems: First, there was no standard formatting—some numbers were stored (xxx) xxx-xxxx, some xxx-xxx-xxxx, some xxx.xxx.xxxx, etc. Second, there wasn’t a separate field for extensions—they were just tacked on the end by either ext., EXT, x, Ex, or some variation. If there were only 20 numbers or so you could just fix them by hand, but you need an automated process to deal with say, 15,000.
via Cleaning Phone Numbers with Regular Expressions : Code : Chris Nanney.

C# Tips n Tricks: Simple IsHoliday Class

Today I had a need to check if the current date was a holiday. I wrote up this quick class to do the calculations. This may be a good class to add as an extension to the DateTime class as well. It is one of those nice simple classes that is always useful.

    public class Holiday
    {
        public static bool IsHoliday(DateTime date)
        {
            return
                Holiday.IsNewYearsDay(date)
             || Holiday.IsNewYearsEve(date)
             || Holiday.IsThanksgivingDay(date)
             || Holiday.IsDayAfterThanksgiving(date)
             || Holiday.IsChristmasEve(date)
             || Holiday.IsChristmasDay(date)
             || Holiday.IsFourthOfJuly(date)
             || Holiday.IsLaborDay(date)
             || Holiday.IsMemorialDay(date);
        }
        public static bool IsNewYearsDay(DateTime date)
        {
            return date.DayOfYear == AdjustForWeekendHoliday(new DateTime(date.Year, 1, 1)).DayOfYear;
        }
        public static bool IsNewYearsEve(DateTime date)
        {
            return date.DayOfYear == AdjustForWeekendHoliday(new DateTime(date.Year, 12, 31)).DayOfYear;
        }
        public static bool IsChristmasEve(DateTime date)
        {
            return date.DayOfYear == AdjustForWeekendHoliday(new DateTime(date.Year, 12, 24)).DayOfYear;
        }
        public static bool IsChristmasDay(DateTime date)
        {
            return date.DayOfYear == AdjustForWeekendHoliday(new DateTime(date.Year, 12, 25)).DayOfYear;
        }
        public static bool IsFourthOfJuly(DateTime date)
        {
            return date.DayOfYear == AdjustForWeekendHoliday(new DateTime(date.Year, 7, 4)).DayOfYear;
        }
        public static bool IsLaborDay(DateTime date)
        { // First Monday in September
            DateTime laborDay = new DateTime(date.Year, 9, 1);
            DayOfWeek dayOfWeek = laborDay.DayOfWeek;
            while (dayOfWeek != DayOfWeek.Monday)
            {
                laborDay = laborDay.AddDays(1);
                dayOfWeek = laborDay.DayOfWeek;
            }
            return date.DayOfYear == laborDay.DayOfYear;
        }
        public static bool IsMemorialDay(DateTime date)
        { //Last Monday in May
            DateTime memorialDay = new DateTime(date.Year, 5, 31);
            DayOfWeek dayOfWeek = memorialDay.DayOfWeek;
            while (dayOfWeek != DayOfWeek.Monday)
            {
                memorialDay = memorialDay.AddDays(-1);
                dayOfWeek = memorialDay.DayOfWeek;
            }
            return date.DayOfYear == memorialDay.DayOfYear;
        }
        public static bool IsThanksgivingDay(DateTime date)
        {//4th Thursday in November
            var thanksgiving = (from day in Enumerable.Range(1, 30)
                                where new DateTime(date.Year, 11, day).DayOfWeek == DayOfWeek.Thursday
                                select day).ElementAt(3);
            DateTime thanksgivingDay = new DateTime(date.Year, 11, thanksgiving);
            return date.DayOfYear == thanksgivingDay.DayOfYear;
        }
        public static bool IsDayAfterThanksgiving(DateTime date)
        {//Day after Thanksgiving
            var thanksgiving = (from day in Enumerable.Range(1, 30)
                                where new DateTime(date.Year, 11, day).DayOfWeek == DayOfWeek.Thursday
                                select day).ElementAt(3);
            DateTime thanksgivingDay = new DateTime(date.Year, 11, thanksgiving + 1);
            return date.DayOfYear == thanksgivingDay.DayOfYear;
        }

        private static DateTime AdjustForWeekendHoliday(DateTime holiday)
        {
            if (holiday.DayOfWeek == DayOfWeek.Saturday)
            {
                return holiday.AddDays(-1);
            }
            else if (holiday.DayOfWeek == DayOfWeek.Sunday)
            {
                return holiday.AddDays(1);
            }
            else
            {
                return holiday;
            }
        }
    }