Ehsan Ghanbari

Experience, DotNet, Solutions

Disable directory browsing in asp.net core

In asp.net applications, directory browsing has enabled some versions and you let the users see all of the content and structure of your application like the picture below:

To the best of my knowledge, in order to disable the directory browsing, there are two ways: by web.config and IIS. In web.config file you just need to add the following piece of code:

 

    <system.webServer>
      <directoryBrowse enabled="false" />
    </system.webServer>

 

and In IIS, you have to disable the configuration manually:

 

 

Actually, both of them are the same. But in asp.net core, as the structure has been changed, you can handle the mentioned feature by code. In web asp.net core, static files are located in a folder named wwwroot. In the configure method of Startup class you can call the UseFileServer() and set the enableDirectoryBrowsing as false:

 

      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc();
            app.UseFileServer(enableDirectoryBrowsing: false);
        }



Patterns, Principles, and practices of Domain-Driven Design

I don't know why I'm writing this blog post right now! I was supposed to write it when I was honored to receive this topless book as a gift by Scott Millett about 4 years ago! Now It's my send time that I'm reading this book and it's literally phenomenal one. I've read all the books written by Mr. Millett and I adore all of them. You will learn more than DDD and patterns by reading this book, and, I do believe that every single paragraph of this book deserves to be focused for several times.

 

If you are interested in software architecture and design patterns, firstly, read this book! I think you should have some architectural backgrounds in your mind, despite, everything has been covered in detail and approximately from scratch in this book.  For more information about the book you can see the table of content here and for purchasing the book you can refer to Amazon.



Basic producer and consumer by RabitMQ in .Net

RabitMQ is one of the most popular queue messages in the development world. In the basic form, for producing or so-called sending a message or an object into the queue you can use BasicPublish of the channel you have connected. As you can see in the following picture after sending the message to the queue, you can consume or so-called retrieve the message.

 

After installing erlang and rabitMQ in your machine, create a console application and copy and paste the following code!

 class Program
    {
        static void Main(string[] args)
        {
            Producer();
            Consumer();
        }

        public static void Producer()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                string message = "Thid first element of the channel!";
                var body = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
                Console.WriteLine(" [x] Sent {0}", message);
            }
        }

        public static void Consumer()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);

                Console.WriteLine(" [*] Waiting for messages.");

                var consumer = new EventingBasicConsumer(channel);

                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(" [x] Received {0} successfully", message);
                };

                channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);

                Console.WriteLine(" Press enter to exit.");
                Console.ReadLine();
            }
        }
    }

Rather than BasicPublish, there is also a BasicConsume to get the message from queue! This was just a simple usage of RabitMQ. I will post some advanced usages of RabitMQ in the future.

 



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:

  



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?