Ehsan Ghanbari

Experience, DotNet, Solutions

Image browse plugin in CKEditor

I was recently integrating my blog with CKEditor Image Browser plugin and it was interesting to me, It was cool! in order to add Image Browser plugin to your CKEditor you should get the file from the mentioned link and put it in your plugins folder inside CKEditor. Then you should go to the config.js file of CKEditor and add the target plugin:

CKEDITOR.editorConfig = function( config ) {

// Define changes to default configuration here. For example:

// config.language = 'fr';

// config.uiColor = '#AADC6E';

    config.extraPlugins = 'imagebrowser';

    config.extraPlugins = 'prism';

    config.extraPlugins = 'codesnippet';

    config.extraPlugins = 'widget';

    config.extraPlugins = 'dialog';

};

Now before browsing, if you run your application, you would see the image properties with  Browse server button:

 

 

Now you should tell the plugin that where your images should be getting, imageBrowser_listUrl is the URL which should return a JSON file:

 <textarea id="my-textarea-id"></textarea>

 <script type="text/javascript">

    CKEDITOR.replace('js-my-textarea', {

        "extraPlugins": 'imagebrowser',

        "imageBrowser_listUrl": "/Administrator/File/BrowseImages"

    });

</script>

As I've written my blog with MVC4, I used HTML helper instead of <textarea> tag:

     @Html.TextAreaFor(blog => blog.Body, new { @id = "js-my-textarea", @class = "ckeditor" })

Image browser in CKEditor needs the JSON result in a format like this:

[

        {

                "image": "/image1.jpg",

                "thumb": "/image1_thumb.jpg"

        },

        {

                "image": "/image2_.jpg",

                "thumb": "/image2_thumb.jpg"                

        },

]

To create a JSON file like this in MVC, make JsonResult with the same output:

 public JsonResult BrowseImages()

        {

            var imageBrowser = new List<ImageBrowserViewModel>();

            var path="/Images/"

            var images = Directory.GetFiles(Server.MapPath(path)).OrderByDescending(d => new FileInfo(d).CreationTime);

            foreach (var image in images)

            {

                imageBrowser.Add(new ImageBrowserViewModel

                {

                    image = string.Format(finalPath + Path.GetFileName(image)),

                    thumb = string.Format(finalPath + "Thumb/" + Path.GetFileName(image)),

                });

            }

            return Json(imageBrowser, JsonRequestBehavior.AllowGet);

        }

And the ImageBrowserViewModel is just a ViewModel to initiate the output:

 public class ImageBrowserViewModel

    {

        public string image { get; set; }

 

        public string thumb { get; set; }

    }

As you can see in my code and also based on the required JSON output, I save the thumb of my images to show them in image browser to pick. Now you can see the output of your plugin in your editor:

  



Handling custom error in mvc

In asp.net MVC there is a custom error in web.config like below:

<customErrors mode="On">

<error statusCode="404" redirect="~/404.html"/>

</customErrors>

 

Sometimes you want to redirect the user to your own custom error controller and log the error message. You can handle it! Firstly create your own Error controller:

 

public class ErrorController : Controller

    {

        public ActionResult HttpError404()

        {

            return View("HttpError404");

        }



        public ActionResult HttpError500()

        {

            return View("HttpError500");

        }



        public ActionResult General()

        {

            return View("General");

        }

    }

 

Secondly, you need to handle this controller in a higher level in your application, refer to global.asax and create the Application_Error method with the following definition:

protected void Application_Error(object sender, EventArgs e)

        {

            Exception exception = Server.GetLastError();        

            Response.Clear();

            HttpException httpException = exception as HttpException;

            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");



            if (httpException != null)

            {

                switch (httpException.GetHttpCode())

                {

                    case 404:

                        routeData.Values.Add("action", "HttpError404");

                        break;

                    case 500:

                        routeData.Values.Add("action", "HttpError500");

                        break;

                    default:

                        routeData.Values.Add("action", "General");

                        break;

                }

            }



            routeData.Values.Add("error", exception);

            Server.ClearError();

            Response.TrySkipIisCustomErrors = true;

            IController errorController = new ErrorController();

            errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

        }

 

Done! Now you can create your own Views of ErrorController and have your handled ErrorController.



Redirect to an action from baseController in MVC

In Asp.net MVC, in order to redirect to an action you can call RedirectToAction(actionName, ControllerName) easily. But if you would have to do it in BaseController, it doesn't work! For example, if you want to check the nullability of the user session you should initialize the Result of filterContext like this:

protected override void OnActionExecuting(ActionExecutingContext filterContext)

{

if (CurrentUser == null)

        filterContext.Result = new RedirectResult(Url.Action("Login", "Account"));

base.OnActionExecuting();

}

Or maybe in OnException method on MVC:

     protected override void OnException(ExceptionContext filterContext)

        {

               filterContext.HttpContext.Response.Clear();

               filterContext.Result = new RedirectResult(Url.Action("Login", "Account"));

               requestContext.HttpContext.Response.End();

               base.OnException(filterContext);

        }

Cheers!



Multiple submit buttons in asp.net MVC

In asp.net MVC you can submit a form by @using(Html.BeginForm()). You can Post the model you have bound via this operation and command the beginning form to post to a Post action: 

@using(Html.BeginForm("Create","FooController")).

Now if you have more than one submit button to send the page content to different post action, there are few ways: one of them is to post the content to a specific action and then decide in it to redirect which action:

 Razor:

<input type="submit" value="Field1" name="submitButton"  />

<input type="submit" value="Field2" name="submitButton"  />

 

Controller:

         public ActionResult SpecificOne(DTO dTO, string submitButton)

         {

                switch (submitButton)

                {

                    case "Field1":

                            return RedirectToAction("FirstCreate")

                    case "Field2":

                              return RedirectToAction("SecondCreate")

                 }

          }

 

But the way that I like it more is to use the attribute in post actions, this attribute would be like this:

   [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class HttpParamActionAttribute : ActionNameSelectorAttribute

    {

        public string Name { get; set; }



        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)

        {

            return controllerContext.HttpContext.Request[Name] != null;

        }

    }

 

 

Now in your razor view, you should give a name to your buttons (names should be the same as your target actions) :

@model DTO 

@using(Html.beginForm(null, null))

{

   <button type="submit" name="FirstCreate" >First</button>

   <button type="submit" name="SecondCreate" >Second</button>        

}

And about the actions you should use the mentioned attribute and give the button name property:

        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult FirstCreate()

        {

            return View();

        }





        [HttpPost]

        [HttpParamAction(Name = "FirstCreate")]

        public ActionResult SecondCreate()

        {

            return View();

        }

 

Good luck!



How to turn off the caches in asp.net MVC

I've written about different kinds of caching in asp.net MVC here, I just wanted to turn off some specific caches in my project and found a way to do that, you can do that by overriding OnResultExecuting:

  1. public class TurnOffCache : ActionFilterAttribute
  2. {
  3.     public override void OnResultExecuting(ResultExecutingContext filterContext)
  4.     {
  5.         filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
  6.         filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
  7.         filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
  8.         filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
  9.         filterContext.HttpContext.Response.Cache.SetNoStore();
  10.     }
  11. }

and then simply register this page in global.asax like this:

  1.   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  2.     {
  3.         filters.Add(new TurnOffCache());
  4.     }

Notice that this will remove all of the caches in your application. but in some cases you just want to remove the cache of an action , in these cases you can simply make the NoStroe property as true in caching:

  1. [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
  2. public ActionResult AnAction()
  3. {
  4.     return View();
  5. }

this could be useful When you cache a controller and just want to disable the cache for an action, cheers!



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?