How To Create a Vertical Separator with WPF

Insert HTML at Cursor/Caret within a Content Editable Div

27. July 2014 03:29 by Scott in javascript, jquery, C#, Development  //  Tags:   //   Comments (0)

First we need to capture the cursor position within the Div it self.

$scope.editorSelection;

    $scope.SetupEditor = function () {
        var editable = document.getElementById('editor'),
selection, range;
        var captureSelection = function (e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }
            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
            $scope.editorSelection = range;
        };
        editable.onkeyup = captureSelection;
    }

 

From here, we need to be able to insert HTML at the selection when we choose to.

    function insertHtmlAfterSelection(html) {
        var range, expandedSelRange, node;
        if ($scope.editorSelection) {
            range = $scope.editorSelection;
            expandedSelRange = range.cloneRange();
            range.collapse(false);
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    }

 

That will be it.

TinyMCE writer Image Upload for C# MVC

23. November 2013 21:12 by Scott in C#, javascript, tinymce, jquery  //  Tags:   //   Comments (0)

Just a quick code sample on how to plug an Image Upload into C# and MVC.  Since I searched all around the internet with no real easy example.

Put this somewhere on the page. This will be where the person adds the image.  As you can see, we will be posting the image to the “data-action” attribute.

  @Html.TextArea("Message", string.Empty, new
                           {
                               id = "wmd-input"
                           })
                            <div id="insertImageDialog" title="Insert Image">
                                <input type="file" name="file" id="file" data-action="/forum/postimageupload" />
                            </div>

Here is the Javascript. 

  1. Below, you can see in the first block, I create another button for TinyMCE panel.  I call it the imageUpload.
  2. I then add it to the Plugin Manager.
  3. I then enable it in the plugins: options called imageUpload.
  4. I create a Modal Dialog as I am using Jquery and the Jquery.UI library within my project.
  5. Below that is the hook up for the Image Upload Modal.  As you can see I use the AjaxFileUpload by jquery.
$(function () {
        tinymce.create('tinymce.plugins.imageUpload', {
            createControl: function (n, cm) {
                switch (n) {
                    case 'imageupload':
                        var c = cm.createButton('mysplitbutton', {
                            title: 'Upload Image',
                            image: '@Url.Content("~/content/images/icons/imageUpload.png")',
                            onclick: function () {
                                $dialog.dialog('open');
                            }
                        });
                        return c;
                }
                return null;
            }
        });
        tinymce.PluginManager.add('imageIupload', tinymce.plugins.imageUpload);
        tinymce.init({
            mode: "textareas",
            elements: "elm2",
            theme: "advanced",
            skin: "o2k7",
            skin_variant: "silver",
            plugins: "imageIupload,safari,style,layer,table,advhr,advimage,advlink,inlinepopups,preview,media,contextmenu,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,formatselect,fontsizeselect",
            theme_advanced_buttons2: "link,unlink,anchor,image,imageupload,cleanup,code,|,preview,|,forecolor,backcolor,|tablecontrols,|,hr,removeformat,visualaid,|,iespell,media,|,ltr,rtl",
            theme_advanced_buttons3: "",
            theme_advanced_buttons4: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,
            language: "en",
            relative_urls: false
        });
        var $dialog = $('#insertImageDialog').dialog({
            autoOpen: true,
            closeOnEscape: false,
            modal: false,
            open: function (event, ui) {
                $(this).parent().css('position', 'fixed');
                $(".ui-dialog-titlebar-close").hide();
            }
        });
        var $loader = $('span.loading-small', $dialog);
        var $url = $('input[type=text]', $dialog);
        var $file = $('input[type=file]', $dialog);
        var dialogInsertClick = function () {
            dialogClose();
        };
        var dialogCancelClick = function () {
            dialogClose();
        };
        var dialogClose = function () {
            $url.val('');
            $file.val('');
            $dialog.dialog('close');
        };
        $dialog.dialog('option', 'buttons', {
            'Insert': dialogInsertClick,
            'Cancel': dialogCancelClick
        });
        var uploadStart = function () {
            $loader.show();
        };
        var uploadComplete = function (response) {
            $loader.hide();
            if (response.success) {
                tinyMCE.execCommand("mceInsertContent", false, "<img src='" + response.imagePath + "'/>");
                dialogClose();
            } else {
                alert(response.message);
                $file.val('');
            }
        };
        $file.unbind('change').ajaxfileupload({
            action: $file.attr('data-action'),
            onStart: uploadStart,
            onComplete: uploadComplete,
            'params': {
                'Id': '@Model.Id',
                'TopicId': '@Model.Id'
            },
        });
        $dialog.dialog('close');
    });
 


Here is the MVC Model Method.

As you can see from above, within the AjaxFileUpload, I am posting a C# Model.  Its called NewPost.  Below is the Model I am passing in.

    [HttpPost]
        public ActionResult PostImageUpload(NewPost model)
        {
            string result;
            var serializer = new JavaScriptSerializer();
            try
            {
                // upload the file
                if (model.File != null && model.File.ContentLength > 0)
                {
                   
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            result = serializer.Serialize(
                        new { success = false, message = "Invalid image file" });
            return Content(result);
        }

Last but not least, I am posting a file within the Model.  Rather than it be apart of the request object, its within the model.

public HttpPostedFileBase File { get; set; }

 

Hope this little write up helps someone.