Wednesday, September 13, 2017

Get database size in MySQL

Another micropost. Use following query to get database size.


SELECT table_schema AS "Database", 
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" 
FROM information_schema.TABLES 
GROUP BY table_schema;

Use following query to get individual table sizes. Modify database_name parameter.


SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
ORDER BY (data_length + index_length) DESC;

Tuesday, November 22, 2016

Install mongodb server in ubuntu 16.04

Another micropost. Ubuntu also has a mongodb-server package which installs an older version. This post will guide you to install the official mongodb server. [docs]

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

If you are on a proxy, add --keyserver-options

sudo apt-key adv --keyserver-options http-proxy=PROXY_URL:PORT --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927

Then run,

echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

Finally,

sudo apt-get update
sudo apt-get install mongodb-org-server

Run mongo demon

mongod

That's all.

Tuesday, March 10, 2015

Different Versions of jQuery in the Same Page

Another MicroPost. Sometimes there will be requirements to use multiple jQuery versions in the same page. Scenarios like cross browser compatibility, support an old jQuery plugin etc. This can be accomplished by changing the global jQuery variable and using $.noConflict() method. Hope following snippet is self explaining.


<!-- load jQuery 1.11.2 -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
  var old$ = $.noConflict(true);
</script>

<!-- load jQuery 2.1.3 -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
  var new$ = $.noConflict(true);
</script>

<script type="text/javascript">
  // Using jQuery 1.11.2
  console.log(old$.fn.jquery);

  // Using jQuery 2.1.3
  console.log(new$.fn.jquery);
</script>

Use this Plunker to play with this.

Wednesday, February 25, 2015

Angular.js Visible Toggle Button

From this post onward I am planning to blog more frequently with solutions for random issues I face along the day. These MicroPosts may not include much content, but will be direct and simplely answered solutions for issues. Hope these might save someone's time.

Not like jQuery, which has many toggle functions, As per my knowledge, Angular do not have any straight forward way to toggle the DOM. Many examples and fiddles I went through suggest unwanted coding stuff. I am not going to write a controller for a simple thing like this. Finally found a solution which worth mentioning. Hope following snippet is self explaining.


<button ng-model="isVisible"
        ng-init="isVisible = false" 
        ng-click="isVisible = !isVisible">
        {{ isVisible ? "Hide Section" : "Show Section"}}
</button>

<div ng-show="isVisible">
  <!-- content -->
</div>    
    

Thursday, January 29, 2015

Simple Pure Node Server

I bet everyone who tried node, has written that famous sample server code which appears in nodejs.org homepage. Then without a blink most of us moved to express or some other node framework, with or without knowing what's happening under the hood. Well, for educational purposes I wrote a simple node server without using any npm module. For anyone who is interested in what's happening behind the scene, this would be a great starting point.

Following are the core modules used. "http" module for server creation, "fs" module for read static content from the disk and "path" module for work with file paths.

var http = require("http"),
    fs = require("fs"),
    path = require("path");

Static files are filtered using simple switch statement.

switch(extName) {
    case ".html": {
        contentType = "text/html";
        dirPath = "/public/views/";
    } break;
    case ".css": {
        contentType = "text/css";
        dirPath = "/public/css/";
    } break;      
    case ".js": {
        contentType = "text/javascript";
        dirPath = "/public/js/";
    } break;
}    
If requested file is available on the disk, read and send the response. If not redirect to the error page.

fs.exists(filePath, function(isExists) {
    if(isExists) {
        readAndSendFile(res, filePath, contentType,200);
    }
    else {
        redirect404();
    }
});    

Please find the complete code at github. Please note that there are many ways to improve this and I would recommend to checkout Danial Khosravi's blog on the same topic for improved version.

Friday, January 23, 2015

Useful Git Commands

When I'm working with git, once in a while I found myself searching through google for proper command syntax. For those who struggle like me and for myself, I decided to maintain a command list.

If you are using git for the first time you need to setup git with your email and name.

git config --global user.email "you@example.com"
git config --global user.name "john doe"

Create a new git repository in current directory

git init

Add created repository in github as "origin" using remote repository url.

git remote add origin https://github.com/someuser/anyrepo.git

Check current status of the repository.

git status

Add modified files to commit.

git add .
git add file.ext

Commit all modified files or commit file by file with a proper commit message.

git commit -m "commit message."
git commit file.ext -m "commit message."

Push committed files to the origin from master. usually goes like push to <remote> from <master>

git push origin master

Undo your last pushed commit

git push -f origin HEAD^:master

If you need to ignore certain files or folders you need to create a .gitignore file and the folder names as bellow.

#ignore all files in node_modules.
node_modules/

#ignore .ext files.
*.ext

#but track this file, even though all .ext files are ignored
!importantFile.ext

Thursday, January 15, 2015

Sorting Algorithms with Sound

Found this amazing video on youtube which shows sorting algorithms with sound. take a look.


Wednesday, December 31, 2014

CSS SPECIFICITY

In SharePoint when we write our own css classes sometimes we have to override some styles in corev4.css. Specificity is one of the techniques we use in style overriding. Also it would help to keep a clean stylesheet. Found some articles regarding specificity. One of them talks about calculating css selector value. Take a look.

references :
http://css-tricks.com/specifics-on-css-specificity
https://developer.mozilla.org/en-US/docs/CSS/Specificity

Friday, January 31, 2014

SharePoint 2013 Client Side Contact Form Using knockout.js and Twitter Bootstrap

Here I am going to implement a simple contact form which will add a contact details to a SharePoint list. I’m using knockout to get user input data and SharePoint 2013 REST service to insert contact details to the list as list item. For the fine UI purpose let’s use twitter bootstrap 3.0 to keep contact form’s user interface responsive and clean.

Following list shows js/css references we need to add.

  • sp.runtime.debug.js and sp.debug.js : for SharePoint 2013 REST service
  • knockout-3.0.0.js : for Knockout
  • jquery-1.10.2.min.js, bootstrap.min.js and bootstrap.min.css : for Twitter Bootstrap

I have created a SharePoint 2013 Custom list named “Contact Us” with following columns.

  • FirstName – Single Line of Text
  • LastName – Single Line of Text
  • Email – Single Line of Text
  • Districts – Choice (CheckBoxes)
  • Message – Multiple Line of Text

Following js snippet shows the structure of viewModel object.


var viewModel = function() {

    // These properties hold TextBoxes content.
    this.firstName = ko.observable("");
    this.lastName = ko.observable("");
    this.email = ko.observable("");
    this.message = ko.observable("");

    // We need an array to map with districts column
    // since it's a choice type.
    this.districts = ko.observableArray();

    // This function will call on submit button click.
    this.submitValues = function() {};
};

Let me roughly explain how this works. On document ready I am getting the Contact Us list object. When user updates the Contact form, those changes get reflected to the viewModel. When user click the submit button, I am creating a list item and assign viewModel properties value to the relevant list column. Finally I am adding the list item to the list and update the list.

Piece of cake right ?

Now let me show how knockout helps us here.

  • to keep a centralized object with fresh form data.
  • to validate the form easily with the help of knockout observables.
  • to keep checkboxes values in an array.

Bellow you can find self-explanatory code with form validations and bootstrap applied.


<div id="contact-form">
    <div class="form-horizontal" role="form">
        <div class="form-group">
            <div class="col-sm-3"></div>
            <div class="col-sm-6">
                <h3 class="text-center">Provide your feedback</h3>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label">First Name</label>
            <div class="col-sm-4">
                <input data-bind="value:firstName,valueUpdate:'afterkeydown'" type="text" class="form-control" />
                <span data-bind="visible:isFirstNameEmpty" style="color:red">*</span>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label">Last Name</label>
            <div class="col-sm-4">
                <input data-bind="value:lastName,valueUpdate:'afterkeydown'" type="text" class="form-control" />
                <span data-bind="visible:isLastNameEmpty" style="color:red">*</span>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label">Email</label>
            <div class="col-sm-4">
                <input data-bind="value:email,valueUpdate:'afterkeydown'" type="text" class="form-control" />
                <span data-bind="visible:isEmailEmpty" style="color:red">*</span>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label">Districts</label>
            <div class="col-sm-4">
                <div class="checkbox"><label><input type="checkbox" data-bind="checked:districts" value="Colombo" />Colombo</label></div>
                <div class="checkbox"><label><input type="checkbox" data-bind="checked:districts" value="Galle" />Galle</label></div>
                <div class="checkbox"><label><input type="checkbox" data-bind="checked:districts" value="Kandy" />Kandy</label></div>
                <div class="checkbox"><label><input type="checkbox"data-bind="checked:districts" value="Jaffna" />Jaffna</label></div>
                <div class="checkbox"><label><input type="checkbox"data-bind="checked:districts" value="Other" />Other</label></div>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label">Message</label>
            <div class="col-sm-4">
                <textarea data-bind="value:message,valueUpdate:'afterkeydown'" class="form-control" form-groups="4"></textarea>
                <span data-bind="visible:isMessageEmpty" style="color:red">*</span>
            </div>
            <div class="col-sm-3"></div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-4">
                <input data-bind="click:submitValues" type="button" class="btn btn-default" value="Submit" />
            </div>
            <div class="col-sm-3"></div>
        </div>
    </div>
</div>  
  

var context,
    web,
    list,
    emailRegex = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/,
    thankyouMsg = "Your feedback was successfully submitted.",
    errorMsg = "Something went wrong. Please try again";

$(document).ready(function() {
    context = SP.ClientContext.get_current();
    web = context.get_web();
    list = web.get_lists().getByTitle("Contact Us");
});

var viewModel = function() {
    var self = this;
    self.firstName = ko.observable("");
    self.lastName = ko.observable("");
    self.email = ko.observable("");
    self.districts = ko.observableArray();
    self.message = ko.observable("");

    self.isFirstNameEmpty = ko.computed(function() {
        if ($.trim(self.firstName()).length > 0) return false;
        return true;
    }, self);

    self.isLastNameEmpty = ko.computed(function() {
        if ($.trim(self.lastName()).length > 0) return false;
        return true;
    }, self);

    self.isEmailEmpty = ko.computed(function() {
        if ($.trim(self.email()).length > 0 && emailRegex.test(self.email())) return false;
        return true;
    }, self);

    self.isMessageEmpty = ko.computed(function() {
        if ($.trim(self.message()).length > 0) return false;
        return true;
    }, self);

    self.submitValues = function() {

        if (self.isFirstNameEmpty() || self.isLastNameEmpty() || self.isEmailEmpty() || self.isMessageEmpty()) {
            alert('Please fill mandatory fields');
            return false;
        }

        try {
            var ici = new SP.ListItemCreationInformation();
            var item = list.addItem(ici);
            item.set_item("FirstName", self.firstName());
            item.set_item("LastName", self.lastName());
            item.set_item("Email", self.email());
            item.set_item("District", self.districts());
            item.set_item("Message", self.message());
            item.update();

            context.executeQueryAsync(function() {
                self.firstName("");
                self.lastName("");
                self.email("");
                self.districts([]);
                self.message("");
                alert(thankyouMsg);
            }, function() {
                alert(errorMsg);
            });

        } catch (e) {
            alert('Something went wrong. Please try again\n');
        }

    }; //End of submit values.
};

ko.applyBindings(new viewModel());