Ehsan Ghanbari

Experience, DotNet, Solutions

Syntaxhighlighter plugin in CKEditor

 There are lots of plugins for CKEditor and one of the most used plugin for the developers is SyntaxHighlighter. In order to get and install this nice one with a sexy them like the following picture:

Get the latest version from the website and copy the content of the plugin into the plugin folder. Note that you should get the requirement plugin of every plugin in CKEditor of course, you will see the following popup modal after clicking the download button:

And the Dialog plugin needs Dialog User Interface as well. So after getting all three plugins and putting in the plugin folder. You just need to define the plugin like below:


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

<script type="text/javascript">

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

        "extraPlugins": 'syntaxhighlight'

    }); 

</script>


 

If you run your application you will see the plugin, you just need to copy and paste your code and select the language. That's all!

 

 

But you don't have that sexy highlighter yet! You need to add some CSS and JS code wherever your final body would be rendered. You have to get those extra files from highlighter web site. Get the latest version, after extracting you will see Scripts and Styles folder:

 

 

Some files are needed to be referenced like XRegExp.js, shCore.js, shCore.css, shThemeDefault.css :

 

    <script src="~/Content/syntaxhighlighter/scripts/XRegExp.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shCore.js"></script>

    <script src="~/Content/syntaxhighlighter/scripts/shBrushCSharp.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushCss.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushJava.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushJScript.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushPython.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushRuby.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushSql.js"></script>
    <script src="~/Content/syntaxhighlighter/scripts/shBrushXml.js"></script>

    <link href="~/Content/syntaxhighlighter/styles/shCore.css" rel="stylesheet" />
    <link href="~/Content/syntaxhighlighter/styles/shThemeDefault.css" rel="stylesheet" />
    <script type="text/javascript">SyntaxHighlighter.all();</script>
 

Then you can reference all the language you want to highlight. By the way, you can find some other template rather than the default (shThemeDefault.css) in the same folder. 



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:

  



Redis as a cache server

Although Redis is much more than a cache, But it's possible to use as cache server especially in distributed applications. Redis lets you operate on the values and it's just a key-value pair in-memory database.

To getting started, get the latest version of Redis from here and install in your windows machine (Server) by instruction and run it in your services. Redis runs in your server machine (you can have Redis server and client in one machine which could be your client development machine) and you call it from a client by a library. Now to work with Redis in a server you need to get stack exchange via Nuget and implement your methods provided by it.

Note: You can read all descriptions and instructions of stack exchange Redis in Github.

public class RedisCacheManager

    {

        private readonly ConnectionMultiplexer _connectionMultiplexer;

        private readonly IDatabase _dataBase;

        private IServer _server;



        private static Lazy<ConfigurationOptions> configurations = new Lazy<ConfigurationOptions>(() =>

        {

            var configuration = new ConfigurationOptions();

            configuration.EndPoints.Add("192.168.110.149:6421");

            configuration.ConnectTimeout = 100000;

            configuration.SyncTimeout = 100000;

            configuration.AllowAdmin = true;

            configuration.Password = "skdfenr4";

            return configuration;

        });



        public RedisCacheManager()

        {

            _connectionMultiplexer = ConnectionMultiplexer.Connect(configurations.Value);

            _dataBase = _connectionMultiplexer.GetDatabase();

            var endpoints = _connectionMultiplexer.GetEndPoints();

            _server = _connectionMultiplexer.GetServer(endpoints.First());

        }



        public object Retrieve(string key)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return rValue;

            return JsonHelper.Deserialize<object>(rValue);

        }



        public T Retrieve<T>(string key)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return JsonHelper.Deserialize<T>(null);

            return JsonHelper.Deserialize<T>(rValue);

        }



        public T Retrieve<T>(string key, int pageIndex)

        {

            var rValue = _dataBase.StringGet(key);

            if (!rValue.HasValue)

                return JsonHelper.Deserialize<T>(null);

            return JsonHelper.Deserialize<T>(rValue);

        }



        public bool Contain(string key)

        {

            return _dataBase.KeyExists(key);

        }



        public void Store(string key, object value)

        {

            if (value == null)

                return;



            var entryBytes = JsonHelper.Serialize(value);

            _dataBase.StringSet(key, entryBytes);

        }



        public void Store(string key, object value, int cacheTime)

        {

            if (value == null)

                return;



            var entryBytes = JsonHelper.Serialize(value);

            var expiresIn = TimeSpan.FromMinutes(cacheTime);



            _dataBase.StringSet(key, entryBytes, expiresIn);

        }



        public void Remove(string key)

        {

            _dataBase.KeyDelete(key);

        }



        public void Clear()

        {

            var endpoints = _connectionMultiplexer.GetEndPoints(true);

            foreach (var endpoint in endpoints)

            {

                var server = _connectionMultiplexer.GetServer(endpoint);

                server.FlushAllDatabases();

            }

        }



        private static byte[] Serialize(object item)

        {

            var jsonString = JsonConvert.SerializeObject(item);

            return Encoding.UTF8.GetBytes(jsonString);

        }



        private static T Deserialize<T>(byte[] serializedObjectValue)

        {

            if (serializedObjectValue == null)

                return default(T);



            var jsonString = Encoding.UTF8.GetString(serializedObjectValue);

            return JsonConvert.DeserializeObject<T>(jsonString);

        }

    }

 

I Just implemented the most used methods in a caching system, you can implement your own based on your needs. As you see I created configurations with some initializing. for example EndPoints(you can get it from the server that Redis is running on) and password (for making the connection between client and server secure).  In the constructor of the class, you need to connect to Redis server via ConnectionMultiplexer and get the database to work with.



Multithreading in java

I'm not a java developer and I've never worked with java in real products. Sometimes I read and concepts and compare with C#, Java is cool as well! By using multithread you can perform many operations together and the system doesn't block the user until completing the operations. There are two ways for multithreading in java: inhering from a class named Thread and implementing an interface named Runnable. I like Runnable because you have another chance to inherit the class from another class if you would need!

 

public class Multithread implements Runnable  {

    public void run() {

        System.out.println("Thread: " + Thread.currentThread().getId() + " is running");

    }

}

 

class MainClass

{

    public static void main(String[] args)

    {

        int n = 5;

        for (int i=0; i<5; i++)

        {

            Thread object = new Thread(new Multithread());

            object.start();

        }

    }

}

 

If you run this code, the following output will appear:

 

Thread: 8 is running
Thread: 9 is running
Thread: 10 is running
Thread: 11 is running
Thread: 12 is running



Using Generic type for type casting in F#

In order to validate some input of type object into numeric types, you can use System.Convert in F#. We have them in F# as well! Look at the following function:

 

open System

let validate<'a, 'b> (cast: 'a -> 'b) (x: 'a) =
    try
        cast x |> Some
    with _ -> None

let a = validate int "3423"
let d = validate<obj, decimal> Convert.ToDecimal (null :> obj)
let e = validate<string, DateTime> Convert.ToDateTime "2017-10-10"

 

Validate has been used to convert obj to decimal and even to DateTime. In order to see the result of the following piece of code, you can use it in F#.Net Core console application: 

 

[<EntryPoint>]

let main argv =

    printfn "%A" e // or d and a that has calculated by Validate<,>

    0

 



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'm spending a lot of my time on software architecture. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
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?