JSON Based Document Storage Using Biggy In ASP.NET MVC

3. May 2014 13:51

API ASP.NET MVC C# Web  0 Comments

While working with a small web based project many developers will take advantage of web.config and XML files to read settings for the application. Using web.config is a good way but you cannot change the settings from within the application and when done manually it causes the website to restart. XML is good but many of us has a problem when it comes to update the details in XML. Biggy is an awesome library developed by Rob Conery to work with document storage. It does a lot well more than you can think of if you are not following the project closely on Github. For now I am just going to show you how you can use Biggy to save your application data in JSON based document storage. 

The library is not available on NuGet, so you have to download or fork the whole solution from Github and then build it. Create a new MVC application and add the reference of the Biggy assemblies you just build. 

Remove Newtonsoft.Json assembly that is added in your project by default when it is created by Visual Studio. The version of assembly seems to be incompatible with Biggy. Instead use the one which accompanies Biggy. 

Add a new model in your application and name it settings. The settings may depend on your application, as I am using it for my blog I have settings like blog name, blog description, posts per page and disable comments after 'x' days. 

public class Settings
{
    public string BlogName { get; set; }
    public string BlogDescription { get; set; }
    public string PostsPerPage { get; set; }
    public string CommentDays { get; set; }
}
I am manually building my view but you can use scaffolding if you wish to save your time. On submit of the form, the details will be sent to the server where my controller method will save the settings in the JSON file. Here is my view and controller code.
@model BiggyJSONDataStore.Models.Settings
@{
    ViewBag.Title = "Settings Page";
   }

<div class="row">
    @using (Html.BeginForm("Settings", "Home", FormMethod.Post))
    {
        <label>Blog Name</label>
        @Html.TextBoxFor(m => m.BlogName, new { @id = "blogname" })
        <br />
        <label>Blog Description</label>
        @Html.TextBoxFor(m => m.BlogDescription, new { @id = "blogdesc" })
        <br />
        <label>Posts per Page</label>
        @Html.TextBoxFor(m => m.PostsPerPage, new { @id = "postsperpage" })
        <br />
        <label>Disable comments after</label>
        @Html.TextBoxFor(m => m.CommentDays, new { @id = "commentdays" })
        <label>days</label><br />
        <input id="btnSave" type="submit" value="Save Settings" />
    }
</div>
When the first time the page is loaded I want to check if there are settings in the file or not. If settings are there then render my view with settings. So the default GET view will look like this.
IBiggyStore<Settings> settingStore = new JsonStore<Settings>(dbPath: HttpRuntime.AppDomainAppPath);
try
{
    var data = settingStore.Load().Single();
    return View(data);
}
catch { }

return View();
The settingStore object is being created and creates a new file in the Data folder in the application root. the dbPath parameter specifies where the file (JSON file in this case) is saved, which is the web root. The Load() method of the settingStore will load all the data in the JSOn file. In this case I have only single set of setting so I will use the Single() method to get the single setting record and not IEnumerable<Settings>.
IBiggyStore<Settings> settingStore = new JsonStore<Settings>(dbPath: HttpRuntime.AppDomainAppPath);

var store = new BiggyList<Settings>(settingStore);

var newSettings = new Settings();

newSettings.BlogName = setting.BlogName;
newSettings.BlogDescription = setting.BlogDescription;
newSettings.PostsPerPage = setting.PostsPerPage;
newSettings.CommentDays = setting.CommentDays;

store.Add(newSettings);
store.Update(setting);

return View();
The above code will add a new settings to the JSON file.
{"BlogName":"Midnight Programmer","BlogDescription":"Programming For Fun","PostsPerPage":"10","CommentDays":"90"}

At this point if you keep pressing save button by entering different values a new entry will be added to the JSON file. To avoid this you have to update the details instead of adding it over and over again in the JSON file.

IBiggyStore<Settings> settingStore = new JsonStore<Settings>(dbPath: HttpRuntime.AppDomainAppPath);

var store = new BiggyList<Settings>(settingStore);

var newSettings = new Settings();

Settings data = null;
try
{
    data = settingStore.Load().Single();
}
catch { }


if (data != null)
{
    data.BlogName = setting.BlogName;
    data.BlogDescription = setting.BlogDescription;
    data.PostsPerPage = setting.PostsPerPage;
    data.CommentDays = setting.CommentDays;
    store.Update(data);
}
else
{
    newSettings.BlogName = setting.BlogName;
    newSettings.BlogDescription = setting.BlogDescription;
    newSettings.PostsPerPage = setting.PostsPerPage;
    newSettings.CommentDays = setting.CommentDays;
    store.Add(newSettings);
    store.Update(setting);
}

return View();

As you can see that the store object Add method is not called but only the Update method is called in case if the data object is not null.  

If you plan to save multiple records in the file, then make sure you use identifier in order to get the required details.

References:

Biggy - Github

Currently rated 5.0 by 1 person

New Blogging Engine!

3. April 2014 15:10

Musings  2 Comments

I like Wordpress but not as much as I like BlogEngine.NET. I have to move to Wordpress because of a very serious issue in BlogEngine.NET. I am on a shared hosting and they are very peculiar about the memory/CPU usage of a site. So, The problem I faced was that if I use SQL Server CE as your data store than it will increase the disk usage time which in turn shuts down my site application pool and cause 503 service unavailable error. This was very annoying and to keep up my blog up and running I have to suddenly switch to Wordpress before I can figure out the exact cause of this problem.

I still have no issue with Wordpress, but I can't enhance it the way I can do it with BlogEngine.NET because it's in PHP. I decided to switch to BlogEngine once but then I thought it would be good to write a simple blog engine from scratch. So I fired up Visual Studio and start a new MVC web project. I worked on previous versions of MVC and I was aware of things which can be done more quickly than the traditional way. Writing a blog engine from scratch was a great way of learning a new technology. I am very much familiar with MVC so I opted to try some new stuff this time.

There is a lot of work pending but user facing part of my blog is completely ready by the end of this week or may be earlier than that. I want to thank K. Scott Allen for his valuable tips for creating a custom blog engine.

 No Rating

Desktop Notifications In HTML5

17. November 2013 22:41

HTML5 Web  1 Comment

If you are using Google chat on your browser you can see a notification pop-up when a new chat message arrives. I don’t use Google chat or GTalk a lot for communication so I am not very well versed about its over all functionality and coolness. But one thing that always got my attention in the past was the notification that I get on my desktop from Google. This is a very cool feature and my colleagues find it a very important feature of chat as it get their attention immediately.

HTML5 now gives us the ability to the developers to show Google like desktop notifications with a very little effort. Here is how you can accomplish this for one of your web applications. I am going to use Notifications API to show desktop notifications.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>HTML5 Notifications</title>
</head>
<body>
    <input type="text" id="txt" />
    <input type="button"  value="Show as Notification"/>
    <input type="button" value="Show Random Notification"/>
    <input type="button" value="Show Random Notification (with icons)"/>
</body>
</html>

This is the plain HTML with controls in place. I have a text box and three buttons which will call a JavaScript function to show the notification on the desktop. The first button will show the text entered by the user as a notification. The second button will show a random message as a notification and a third button will show the same random message but this time with an icon. To see it in action lets add the JavaScript code.

<script>
function ShowTextAsNotification() {
    ShowNotification("Custom Notification", document.getElementById("txt").value);
}
 
function GetRandomText(ico) {
    var Quotes = ["Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
                  "Copy and paste is a design error.",
                  "I had a life once. Now I have a computer.",
                  "Before software can be reusable it first has to be usable.",
                  "Software sucks because users demand it to."];
 
    if (ico == false) {
        ShowNotification("Famous Quotes", Quotes[Math.floor(Math.random() * (1 - 5 + 1) + 5)]);
    }
    else {
        ShowNotificationsWithIcons("Famous Quotes", Quotes[Math.floor(Math.random() * (1 - 5 + 1) + 5)]);
    }
}
function ShowNotification(title, body) {
    Notification.requestPermission(function (perm) {
        if (perm == "granted") {
            var notification = new Notification(title, { body: body });
            //Un-comment the below line if you want to close the notification after a certain period
            //It not working on Chrome...I don't know why!!
            //notification.onshow = function () {
            //    setTimeout(notification.close, 5000)
            //}
        }
    });
}
function ShowNotificationsWithIcons(title, body) {
    Notification.requestPermission(function (perm) {
        if (perm == "granted") {
            var notification = new Notification(title, { icon: "Bomber.ico", body: body });
        }
    });
}
</script>

The is pretty self-explanatory. The Notification API uses the Notification.requestPermission function to get the user consent before showing the notification on the desktop. The API documentation states that there are 3 permissions:

  • default: This is equivalent to denied, but the user has made no explicit choice thus far.
  • denied: This means user does not want notifications.
  • granted: This means notifications can be displayed.

On line 22 in the above code, you can see that the API checks for the request permission from the user. When it does that the user is prompted to either allow or deny the access of the API. You will be only asked once for this permission.

The perm object is then checked for the permission, if “granted” then show the desktop notification to the user else there will be no notifications for the user. After the permission is granted from the user, initializes an instance of a Notification with title and body. You can say that title is the heading of the desktop notification and body is the text of the notification. You can also have an icon for the notification by setting the icon property.

Run the sample and enter a text in the text box and click on the button labeled “Show as Notification”. As soon as you click the button, if you are running it for the very first time then you will be prompted by the browser to allow or deny the access or it will show the notification at the bottom right corner of your desktop.

In the above notification, Custom Notification is the title and “This is a desktop notification“ is the body.

Click the second button labeled “Show Random Notification”. Clicking this button will generate the same desktop notification but every time you click it it will generate a random message from an array and show it as a notification.

If you click the second button multiple times you will 3 notification at a time. The new notifications will be shown at the top of the current notification like this.

In case you click the button more than 3 times, you still be able to see these notifications until you close the one which are already visible. Once you close any of the notification the one in the queue will become visible.

The icon can be displayed in the left portion of these notifications. Click the third button to see it in action. It will display the same random quotes but this time with an icon.

The only problem I am facing implementing the Notifications API is that I cannot close these notifications automatically after the set time. You can try using it on your browser by un-commenting the lines in the ShowNotification() function.

Related Links:

 No Rating

Dev Buzz #2 - Bookmarks - 1 JUL 2013

1. July 2013 21:11

Devbuzz  0 Comments

 

Awesome Stuff

Web Development

JQuery

Open Source

  • Attribute Routing – Attribute based routing library for MVC and Web APIs
  • LessCSS – The dynamic stylesheet language
 No Rating

MSDN Style Syntax Highlighting In ASP.NET

30. June 2013 01:03

ASP.NET  0 Comments

There are many syntax highlighting plugins available on the web right now. Majority of the sites are using javascript based Syntax Highlighter from Alex Gorbatchev. I am using it for my current blog and BlogEngine.NET has it as a default syntax highlighter. It is good because it has a lot of themes to offer and you can also customize according to the look and feel of your blog or site. Moreover it has support for multiple languages which makes it acceptable among most of the bloggers and developers.

I also like the way MSDN and Codeplex style their code. Although it has some flaws like moving the code to the next line if it exceeds the length of the pre or div tags. The library MSDN and Codeplex are using for syntax highlighting is ColorCode. ColorCode is open-source and supports every language specific to Microsoft. The way ColorCode works is totally different than that of any other syntax highlighting library. Javascript based syntax highlighter use CSS for different styles whereas ColorCode uses in-line CSS to  set styling for the code.

To install ColorCode you can use NuGet command or add ColorCode reference as a library downloadable from Codeplex. NuGet command:

PM> Install-Package ColorCode

Only Microsoft stack languages are supported by ColorCode. Here is the complete list:

  • XML
  • Java
  • JavaScript
  • SQL
  • C#
  • VB.NET
  • ASPX (C#)
  • ASPX (VB.NET)
  • C++
  • PHP
  • PowerShell
  • Typescript
  • FSharp

As I mentioned earlier that this library uses in-line CSS and therefore you cannot use it in the windows forms application. You can use the webbrowser control in windows forms application if you want code to render correctly.

This is a sample basic usage of ColorCode.

string code = File.ReadAllText(Server.MapPath("~/Test.txt"));
string finalCode = new CodeColorizer().Colorize(code, Languages.CSharp);
codediv.InnerHtml = finalCode;

First line of the code will read all the text from a file. The second line will initialize a new CodeColorizer class Colorize method which will take 2 parameters, first is the code for which we want the syntax highlighting for and the second parameter is language. I now have the finalCode string which has the code with syntax highlighting. This is the output I have in my browser window.

It looks pretty good from the front but behind the scenes it’s not that pretty.

ColorCode is an open-source library and is hosted on Codeplex.

Reference:

 No Rating

Visit blogadda.com to discover Indian blogs Computers Blogs