Archive | Javascript RSS for this section

Management studio for Mongodb, -Mongodb Part 3

I like command prompts, and CLI’s at times, perhaps you too like them. But most of the time I love to visualize stuff. For example, how does mongodb databases, collections and documents look visually? What if we can have a quicker simple way to visually work and manage our mongodb.

MSSQl is to Sql Server Management studio as MySQL is to phpmyadmin (if I am not wrong :)), what about about mongodb..?

Welcome Robomongo, which is a shell-centric cross-platform MongoDB management tool. You can download and install Robomongo from there website here, select your platform, download and basically go through the installation steps easily.

Some of the features highlighted from the websites includes:

1. Robomongo embeds or rather uses same javascript engine that powers mongodb’s v2.2 shell, hence you can reuse your existing skills.

2. You can open as many shells as you need pointing to a single mongoDB database or many shells for many different databases.

3. Your code is executed statement by statement way.

4. You get autocompletion for all objects including functions well known by javascript runtime, including autocompletion for databases, collections and even your document.

Once you are finished installing, ensure your mongodb instance is running. Follow the steps the here to start mongod shell, once you are done take not of the port (default is 27017).

Then double robomongo to open it, and you will see the following screen:

robo_mongo_1

From the screen you can see there is not connection, and so click on “create” link on the small child windows, and this present you with the following screen.

robo_mongo_2

Provide a preffered name for you connection, in my case I gave it ‘Connection One’. Ensure that the address points to the server where you mongod instance is running and also the port is correct. In my case I am using local instance running on port 27017.

You can test the connection by clicking the ‘Test’ button, which should tell you if the connection succeeded or not. In my case I got a success like below.

robo_mongo_3

For now I don’t have authorization to my mongodb, just click ‘close’, and then “save”, make sure your screen at this point is similar to this one:

robo_mongo_4

You can see our connection is listed. At this point select “Connection One” and click on the “Connect” button. If you have done everything right then your screen should look like:

robo_mongo_5

 

Voila! Here is you visual representation of you mongod instance, databases, collections, functions, documents etc. In my case I expanded to see how documents are represented as belowrobo_mongo_6

So now you know! If you want to explore robomongo, just right click on any level node on the tree, and see what you can achieve. But I can assure you can create, update, list and delete documents. You can also createa database here, add table functions which are just but javascript functions. There will be more advanced posts to come and so keep watch!!

Again happy coding nerdizzles 😀 !!

 

Backbone.js demisfied

This is the first post in backbone.js series which aims at looking at the overview of what is backbone. In this series we will look at various backbone aspects like the Models, Views, Collections, Eventing system, Event aggregator and its uses. And I do promises that by the end of the series you will be able to make decision of when to use backbone.js.

What is backbone.js?

From backbone.js home page, it is described as giving structure to web applications by providing models with key-value binding and custom events, collections with rich API of enumerable functions, Views with declaritive event handling and connects it all to you existing API over a RESTful json interface.

I would also take backbone.js being more of a javascript library providing basic and helpful types for building and organizing rich javascript interfaces, qualifying it not to be more of a framework.

The big and best differences between a library and a framework a  library is something you call from your program. A framework is something that calls into your program, or better frameworks sort of control how you design your code or applications. They specify what you can do with them and how to do it. On the other hand libraries provide with some useful features and then you can move on and implement or even extend them to build your application. Frameworks contain key distinguishing features that separate them from normal libraries like inversion of control. In a framework, unlike in libraries or normal user applications, the overall program’s flow of control is not dictated by the caller, but by the framework.

There has been conflicting opinion of whether backbone is MVC or not, a library or a framework etc. But I would like to take sometime to simply look at what MVC is.

What is MVC?

In short MVC stands for Model-View-Controller.

Model– represent  application data perhaps for a specific domain that an application is dealing with. So in short Models are at the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. This how backbone takes a model to be.

View -visual representation of the model. The view is dependent on the model and in case the model changes then the view should update accordingly. The user usually interacts with the view setting and changing the view thence the model. In most cases or ideal scenario it not the work of the view to update the model but the controller. e.g when a click occurs the information should be taken to the controllers to update the model accordingly.

Controller-controls the co-rodination of the views and the model. They are the mediators between the models and the views. They update the views when the model changes and update the models when any changes occurs on the view.

It is in the controllers where most javascripts frameworks and libraries brings issues as the developers of the framework tend to try to map one to one with the server side MVC frameworks, hence contradicting C on the client frameworks. This issue however is subjective and brings issues with understanding classical MVC patterns and the role of controllers in modern frameworks.

And therefore in respect to backbone, truly and distinctly it has model and views, but does not have true controllers since its views and routers sort of act similar to controller but neither of them can act as a controller on its own. And this on my own opinion does not qualify backbone a mvc framework and I consider it a member of MV* family with its own implementation.

Backbone had its own Backbone.Controller which was not making sense in the context in which it was used and therefore it was renamed to Backbone.Router. And therefore backbone shares the responsibility of a controllers with the view and the router.Router handle little more of the controller work  as you can bind the events and the models and any other customizations you may like regarding the same.

Some few points to note regarding backbone for this post is:

  •  Backbone core components are Model, View, Collection and Router. Therefore I would not be wrong saying it has borrowed from MVC from framework.
  • You have more control of what is happening.Backbone has one of the best eventing system which  is great between the views and models. You can even attach an event to any attribute in a model and you will be notified when the property changes.
  • Supports data bindings through manual events
  • Great support for RESTful interfaces and so models can easily be tied to the backend API’s like ASP NET WEB API.
  • It uses underscore.js templating engine which is great.
  • Clear and flexible conventions for structuring applications. Its not opinionated, and so does not force you to use all of its components and can only work with only those needed.
  • Initially you might have to write more javascript code but its very easy to implement complex user interactions.

Feel free to engage me in discussion, questions, recommendations or even you input. There are more to come on specific backbone intrinsics.

Happy coding 🙂

Returning javascript from ASP NET MVC

I have seen developers wonder how to return javascript from the server and have executed on client in an ASP NET MVC application. Fortunately, we have JavascriptResult in the ASP NET MVC stack which is responsible for doing exactly this.  It will make your life easier, but I am not advocate for  this as there are better ways doing this using Javascript on the client.

Anyway, here is how you can go about this in a few short lines of code

View:

@Ajax.ActionLink("display", "Display", new AjaxOptions())

@Html.TextBox("name","Pius")

@Ajax.ActionLink("checks", "Sample", new AjaxOptions())

Controller:


public JavaScriptResult Display()

{

const string script = "$('#message').append('Display');";

return JavaScript(script);

}

public JavaScriptResult Sample()

{

string script = "var textboxvalue=$('#name').val();";

script += "$('#message').append(textboxvalue);";

return JavaScript(script);

}

Output:

1) Clicking on the first link will display Display in the message div.

2) Clicking on the second link will display mazhar in the message div.

Happy coding and see you here again 🙂

Comparing passwords using angularJS

While working on a single page application using AngularJs, I did come across a situation where I needed to compare and validate passwords. Using angular documentation site, I found that the answer to my problem was to use directives. With angularJs directive you have all the control about you HTML markup.  Directives are executed during DOM compilation allowing you to transform DOM or add new behaviours.

There are directives that are offered out of box, but that does not mean you can not implement yours.  Some of the points you should have when implementing your directives include:

-Directives have camel cased name e.g ngBind. The directives can then be invoked by translating the camel case name into a snake case with special characters like – or _. Optionally you can prefix the directive with x- or data- to make it HTML validator compliant. This is seen on the custom directive I have worked on here.

e.g


<input bs-password-validator="password" ></span>

-AngularJS have restrictions which are a subset of EACM which provides restriction to specific declarations style. Omitting means that the directive will be allowed on attributes only. They are as follows:

  1. E-Element name <my-directive></my-directive>
  2. A-attribute <div my-directive=”expression”></div>
  3. C-class <div class=”my-directive:expression;”></div>
  4. M-comment <!–directive: my-directive exp –>

Without further ado, lets dive to the main topic of the day.  I started by adding html markup  as shown below

<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;"><div></span></pre>
<div class="container" style="padding-top:100px">
 <div class="content">
 <div class="wrapper">
 <div class="proper-content">
 <form class="form-horizontal" name="registerForm" data-ng-controller="testCtrl" novalidate>

<div class="control-group">
 <label class="control-label" for="password">Password</label>
 <div class="controls">
 <input type="password" name="password" placeholder="password" id="password" data-ng-model="account.Password" required />
 <span class="text-error" data-ng-show="registerForm.password.$dirty && registerForm.password.$error.required">Password is required</span>

</div>
 </div>

<div class="control-group">
 <label class="control-label" for="repeatPassword">Confirm Password</label>
 <div class="controls">
 <input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" bs-password-validator="password" ng-model="account.ConfirmPassword" required>

<span class="text-error" ng-show="registerForm.repeatPassword.$dirty &amp;&amp; registerForm.repeatPassword.$error.required" style="display: none;">Repeat password</span>
 <span class="text-error" data-ng-show="registerForm.repeatPassword.$dirty && !registerForm.repeatPassword.$error.required && registerForm.repeatPassword.$error.repeat" style="display: none">Fields are not equal!
 </span>
 </div>
 </div>

 <div class="control-group">
 <div class="controls">
 <button class="btn btn-primary" data-ng-click="SaveUser()">Save</button>
 </div>
 </div>
 </form>
 </div></div></div></div></div>

My directive looks like this:

angular.module('test.directives',[]).directive('bsPasswordValidator', function () {</pre>
return {
 require: "ngModel",
 link: function (scope, elem, attrs, ctrl) {
 var otherInput = elem.inheritedData("$formController")[attrs.bsPasswordValidator];

ctrl.$parsers.push(function (value) {
 if (value === otherInput.$viewValue) {
 ctrl.$setValidity("repeat", true);
 return value;
 }
 ctrl.$setValidity("repeat", false);
 });

otherInput.$parsers.push(function (value) {
 ctrl.$setValidity("repeat", value === ctrl.$viewValue);
 return value;
 });
 }
 };
});

<span style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px;">

 

In angular a controller is a javascript type that is used to make instances of the Scope, and this excludes root scope (more about scope to come).  There are mainly two uses of controllers:

  1. Set up the initial state of a scope object
  2. Add behavior to the scope object

So here is the my test controller and application set up

angular.module('test',['test.directives']);</pre>
function testCtrl($scope) {
$scope.Password='';
$scope.ConfirmPassword='';
 $scope.SaveUser = function () {

 $scope.registerForm.repeatPassword.$dirty = true;
 $scope.registerForm.password.$dirty = true;

 if ($scope.registerForm.$valid && $scope.registerForm.repeatPassword.$valid) {
<!--call your services after here-->
 }
}
}
<pre>

If you have followed and done everything correctly you should be able to get the following screen if you type mismatched passwords.
password_comparer

And there you go.This code is just for demonstration, and so where I would prefer if you can separate directives into there own directory.

And your comments are highly appreciated, and its the only way to know you were here 😉

Happy coding and welcome back!! 🙂

Sample code can be found here 

%d bloggers like this: