Checking if an object is empty in EcmaScript5 / Javascript

Web programming
I was getting a JSON response from a server request that can contain just an empty value (this is, nothing, nothing de nothing that we Spaniards say). On checking if the object had anything within I did this which seemed to work... for a while: [sourcecode language="js" wraplines="false"] var d = response.data; var person = new Person(d); /**************/ // inside Person constructor: if (d) { this.Id = d.Id; this.Name = d.Name; ... } ... [/sourcecode] And that worked quite fine, as sometimes I want to instantiate a Person object without giving it any data, that's a null or "undefined" and checking if (d) exists just works. But what if d does exist but it's empty? Coming from the response I have "something", an empty something, it has no properties, no…
Read More

C#.Net DAO Access class template

Web programming
Something I had around there: [sourcecode language="csharp" wraplines="false"] using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace Blabla.Data { public interface IDataAccess { SqlDataReader GetReader(string sql, List<SqlParameter> pl = null); object GetScalar(string sql, List<SqlParameter> pl = null); DataSet GetDataset(string sql, List<SqlParameter> paramsList = null); int ExecuteNonQuery(string query, List<SqlParameter> paramsList = null, CommandType commandType = CommandType.Text, bool avoidTransaction = true); } public class DaoTemplate : IDataAccess { public const string DefaultConnectionString = "DefaultConn"; private SqlConnection GetConnection() { return new SqlConnection(ConfigurationManager.ConnectionStrings[DefaultConnectionString].ConnectionString); } public SqlDataReader GetReader(string sql, List<SqlParameter> paramsList = null) { SqlConnection conex = GetConnection(); try { conex.Open(); SqlCommand cmd = conex.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.StoredProcedure; if (paramsList != null) { cmd.Parameters.AddRange(paramsList.ToArray()); } return cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (InvalidCastException e) { throw (e); } } public object GetScalar(string sql,…
Read More

Using Unicode characters to improve your website!

Web programming, Web standards
Using HTML unicode characters can help you reducing the amount of images on your site, just using the right HTML code and you can get this: ✔ or this ★ Doing that is as simple as adding its unicode code like this: [sourcecode language="html" wraplines="false"] tick: <span style="color:green">✔</span> star: <span style="color:red">★</span> [/sourcecode] To get an idea of which unicode characters you can use just check this W3C list. Though probably what you really want is to have a look at the symbols, the geometric shapes, the arrows or the dingbats. Unicode format Have always in mind that there are more unicode character sets than the standard (UTF-8), like UTF-16. You can make use of other standards by setting it on a meta or on your XHTML declaration tag: [sourcecode language="csharp"…
Read More

Adding Google Maps to angular using RequireJS

Web programming
New method Since I wrote this post many things changed on the plugin and what this post explains isn't valid anymore unless you are still using the old plugin. I wrote another article about how to include Google Maps in your AngularJS App using the new plugin. Navigate to the new method. WARNING: This method is deprecated I was trying to use Google Maps in an Angular application and load all its modules, directives, etc. using RequireJS. This gave me some headache due to this: Google Maps API prefers to be written into the page on document load, so it can use the document.write. But as we are loading it asynchronously, it will require the DOM to be ready to be added. Angular Google Maps plugin requires Google Maps API…
Read More

Creational Patterns

Software Architecture
Singleton This pattern consists on making sure that there is only one instance of an object and provide a global access to such instance (this would be an static object in C#). Prototype Creates a duplicate of an existing instance (clone) so you end up with two instances with the same state at the moment of creating it. Useful if you want to keep a copy of the original. This can be done by having a method like ".Clone()" or by using an injection on the constructor: "Person copy = new Person(personToCopy);". Factory method Allows you to determine the type of the instance on run-time by calling a method that has some internal logic to determine which instance you get. While this was planned as a "parent-child" to determine which…
Read More

Avoid event propagation in Angular

Web programming
I had a button inside a box that had an "onclick" feature, which means that both the button and the box had an "onclick" listener. On clicking the box everything worked fine, but on clicking the button the box's listener also fired its event. To avoid this, it seems someone developed an "stopPropagation" in jQuery that you can also use in Angular: [sourcecode language="js" wraplines="false"] app.directive('dontPropagate', function () { /* This directive allows to stop the propagation of an event, so that if DOM element B is inside DOM element A, on clicking B the event is not propagated to A (the parent). You have to add the property "dont-propagate='click'" to B, where "click" is the event you don't want to be propagated. */ return { restrict: 'A', link: function…
Read More

Adding video src with Angular

Web programming
Well, well, well... if you try to add a video to your page and use Angular to set its URL... you may discover that Angular doesn't allow you to do that. This is because Angular blocks some possible hacking attempts like setting manual html to the page or so with a service called $sanitizer, interestingly, Angular allows you to set an image "src" or the href of a link without issues, but blocks you if you try to add the "src" of an HTML5 video element. To be able to add the video URL this way you need to tell Angular that this is a safe operation using Angular's Strict Contextual Escaping Service. There are different ways in which you can make use of such service to solve this: Solution…
Read More

Creating directives with Angular

Web programming
One of the main points of angular consists on adding functionalities to your html elements, so that instead of setting the effects the jQuery way: selecting the element and making that happen or adding a listener, you create an "effect", "functionality" or "behaviour" and give it a name, and then assign it to an element by just writing it on the View. No need to access the view from the controller, only to set the directive. Let's see a quick example: [sourcecode language="js" wraplines="false"] var app = angular.module('myApp', []); app.directive('helloWorld', function ($compile) { return { restrict: 'AE', replace: 'true', template: "<h1>Hello World!</h1>" } }); [/sourcecode] Now just add this HTML: [sourcecode language="html" wraplines="false"] <html ng-app> <body> <hello-world></hello-world> </body> </html> [/sourcecode] That example creates a directive named "helloWorld", and we are…
Read More

Loading scripts using RequireJS

Web programming
With all the front-ending needing so many script libraries, plugins or even frameworks like Angular, the amount of scripts to load and, even more, the order in which they need to be loaded has increased its complexity highly in the last years. To help with this one very useful solution is called RequireJS. So what does RequireJS do? RequireJS will take control of the scripts load order and improve page load, configure their dependencies, etc. To do that, we have three methods: require(), define() and config(). Require() will immediately load the files set, while define() will just "configure" a module that can be called (using require()) and loaded. config() will help on setting some values to make all this easier. (more…)
Read More

Quick Introduction to LESS

Web programming
These are some of the features LESS is offering you: Creating variables You can save a value on a variable and use it later, quite useful to set colors: [sourcecode language="css" wraplines="false"] @myCustomColor: #567; @primaryColor: blue; @secondaryColor: darkblue; .myCustomStyle{ background: @myCustomColor; } .anotherStyle{ color: 'myCustomColor'; } [/sourcecode] Notice you can add the variable by setting it directly or by setting its name. (more…)
Read More

MVC5 with Bootstrap 3.1.1 LESS files

Web programming
MVC5 already comes with Bootstrap and LESS by default, but unfortunately it doesn't come with Bootstrap LESS files to custom them in case you want to do that. Luckily Osowicki created this template that you can install in your Visual Studio and use to have all of it already prepared on a clean project. Just open Visual Studio > New Project > Online (it's at the very bottom) > Templates. You should find it here with the name "ASP.Net MVC5 with Bootstrap 3.1.1 LESS" and an "ok" icon showing you already installed it. Now select it and click Ok to create your new MVC5 project with Bootstrap LESS files ready to go :)
Read More

Getting into Bootstrap!

Web programming
Bootstrap is another javascript library to help us making our websites better and simpler. It's main core is to be a handful set of CSS styles to make your website automatically responsive, this is, the stlysheet has already covered the media queries required to make the styles responsive so that on using those styles all your website will. Let's see it in action: [sourcecode language="html" wraplines="false"] <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap 101 Template</title> <!-- Bootstrap --> <link href="../../Content/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <h1>Hello,…
Read More

First steps with Knockout

Web programming
As Knockout seems to be there by default with MVC4 and MVC5 and its creator is now working with Microsoft it seems wise to have a look at it and check how good it can be to go the MVVM way. Installation If you are using MVC.Net 4 or 5 it just comes by default so there isn't anything else to do, else, you only need the library knockout.js and a call to it on your pages. Look for it on NuGet as it's probably there. Hello World This is a simple example of how it works: [sourcecode language="html" wraplines="false"] <body> <h1>Knockout</h1> <p>Your name: <input data-bind="value: firstName, valueUpdate: 'afterkeydown'" /></p> <h2>Hello, <span data-bind="text: firstName"> </span>!</h2> <script src="~/Scripts/knockout-2.2.0.js"></script> <script> var HelloWorldViewModel = function (name) { this.firstName = ko.observable(name); }; ko.applyBindings(new HelloWorldViewModel("World"));…
Read More

Displaying multiple pages with Angular

Web programming
Ok, so after checking how the basics of Angular work on a single page and the different ways to create a controller in Angular it's time to do what angular is meant to do: create a client's side application that will consume server's data and templates (views) to behave like a desktop application in a browser: Routing First thing to do is learning about routing, which is the place were we will configure our Angular module (aka application here). The routing is what allows us to establish which View a Controller will use, binding them and avoiding the Controllers to know anything about the View. This is how it works: [sourcecode language="js" wraplines="false"] var app = angular.module('BasicApp', ['ngRoute']); app.config(function($routeProvider) { $routeProvider .when('/', { controller: 'UsersController', templateUrl: '../../ViewsAngular/MiniAppIndex.html' }).when('/profile/:userId', { controller:…
Read More

3 ways to create a Controller in Angular

Web programming
Creating the controller when adding it to the module [sourcecode language="js" wraplines="false"] var app = angular.module('BasicApp', []); app.controller('UsersController', function ($scope) { $scope.userProfiles = [ { "id": 1, "Name": "Peter", "Age": 21 }, { "id": 2, "Name": "Alex", "Age": 22 }, { "id": 4, "Name": "Andrew", "Age": 53 } ]; }); [/sourcecode] When we add a Controller to the module we set a name for the Controller and the controller, we can just define the Controller at that point, giving the full object as an input. Creating the controller at a place and assigning it to the module later [sourcecode language="js" wraplines="false"] var app = angular.module('BasicApp', []); app.controller('UsersController', UsersController); function UsersController($scope) { $scope.userProfiles = [ { "id": 1, "Name": "Peter", "Age": 21 }, { "id": 2, "Name": "Alex", "Age": 22 },…
Read More
Close Bitnami banner
Bitnami