Friday 27 March 2015

Microsoft releases Node.js Tools 1.0 for Visual Studio


Microsoft has released version 1.0 of its Node.js Tools for Visual Studio (NTVS).
The open-source extension for Visual Studio 2012 and 2013 turns Microsoft’s development environment into a Node.js IDE. NTVS has been in development for more than a year. Sara Itani, Node.js Tools for Visual Studio software engineer, detailed the NTVS 1.0 features in a blog post, drawing particular attention to IntelliSense editing and code completions.
“Code completions? For a dynamically typed language? Yep, you heard us right,” wrote Itani. “NTVS will statically analyze your project to provide you with syntactically correct code completions for your Node.js code and packages.”
NTVS supports syntax highlighting and code folding, including brace-completion, automatic formatting and F12 Go To Definition. Other features in NTVS 1.0 include:
  • Interactive Window (REPL)
  • npm integration
  • Advanced debugging and profiling
  • Test explorer integration for unit testing
  • Full integration with other Visual Studio features, including TypeScript, Git/TFS and Azure
  • js, io.js, JavaScript, TypeScript, HTML, CSS and JSON support

Friday 13 March 2015

Spring MVC: Validator and @InitBinder

It’s hard to imagine a web-application which doesn’t has some validation logic for an user data. Almost all user’s data has some constraints, e.g. date of birth should consist of day, month, year etc. Spring MVC has its own solution for the data validation, and it’s become available with the help of Validator interface.



Usage of Spring MVC Validator

A validation make sense in time when you receive some kind of data from users. An obvious way to do this is to use web forms. The Validator interface it is a means to implement the validation logic of entire Spring MVC application. Sounds promising.
There are three things which you need to do in order to start using the Validator:
  • Create a validator class for some domain model and implment the Validator interface.
  • Overload supports(Class clazz) method.
  • Overload validate(Object target, Errors errors) method.
Now you know the basics of the Validator interface usage. Enough of theory let’s go ahead with practice.

Exapmle of Vlidator Spring MVC

I want to demonstrate the Validator interface in action on one of my previous tutorials where a validation will not be redundant. I mean the sample application with Spring Data. First you need to update the pom.xml file, add the following dependency:
01...
02        <dependency>
03            <groupid>javax.validation</groupid>
04            <artifactid>validation-api</artifactid>
05            <version>1.0.0.GA</version>
06        </dependency>
07        <dependency>
08            <groupid>org.hibernate</groupid>
09            <artifactid>hibernate-validator</artifactid>
10            <version>4.3.0.Final</version>
11        </dependency>
12...
In the project I have the one POJO:
01@Entity 
02    @Table(name = "shops"
03    public class Shop { 
04 
05        @Id 
06        @GeneratedValue 
07        private Integer id; 
08 
09        private String name; 
10 
11        @Column(name = "employees_number"
12        private Integer emplNumber; 
13 
14        public Integer getId() { 
15            return id; 
16        
17 
18        public void setId(Integer id) { 
19            this.id = id; 
20        
21 
22        public String getName() { 
23            return name; 
24        
25 
26        public void setName(String name) { 
27            this.name = name; 
28        
29 
30        public Integer getEmplNumber() { 
31            return emplNumber; 
32        
33 
34        public void setEmplNumber(Integer emplNumber) { 
35            this.emplNumber = emplNumber; 
36        
37    }
So let’s create the validation rules for it:
  • The “name” can’t be empty.
  • The “emplNumber” can’t be empty.
  • The “emplNumber” can’t be less then 1.
The validation class for these purposes will look like:
01import org.springframework.stereotype.Component;
02import org.springframework.validation.Errors;
03import org.springframework.validation.ValidationUtils;
04import org.springframework.validation.Validator;
05 
06import com.spr.model.Shop;
07 
08@Component
09public class ShopValidator implements Validator {
10 
11    private final static String EMPLOYEES_NUMBER = "emplNumber";
12 
13    @Override
14    public boolean supports(Class clazz) {
15        return Shop.class.isAssignableFrom(clazz);
16    }
17 
18    @Override
19    public void validate(Object target, Errors errors) {
20        Shop shop = (Shop) target;
21 
22        Integer emplNumber = shop.getEmplNumber();
23 
24        ValidationUtils.rejectIfEmpty(errors, "name", "shop.name.empty");
25        ValidationUtils.rejectIfEmpty(errors, EMPLOYEES_NUMBER, "shop.emplNumber.empty");
26 
27        if (emplNumber != null && emplNumber < 1)
28            errors.rejectValue(EMPLOYEES_NUMBER, "shop.emplNumber.lessThenOne");
29 
30    }
31 
32}
Notice that I applied @Component annotation to the class because I’m planning to inject it later into the ShopController. Here are an explanation of the Validator’s methods:
supports(Class) – Can this Validator validate instances of the supplied Class? validate(Object, org.springframework.validation.Errors) – validates the given object and in case of validation errors, registers those with the given Errors object. For the additional information look at the javadoc of ValidationUtils class. The messages which will be shown during validation should be placed in the “messages.properties” file:
1shop.name.empty = The "Shop name" field can't be empty.
2shop.emplNumber.empty = The "Employees number" field can't be empty.
3shop.emplNumber.lessThenOne = The number of employees can't be less then 1.
Let’s move to the controller’s code:
01...
02    @Autowired
03    private ShopValidator shopValidator;
04 
05    @InitBinder
06    private void initBinder(WebDataBinder binder) {
07        binder.setValidator(shopValidator);
08    }
09...
10    @RequestMapping(value="/create", method=RequestMethod.POST)
11    public ModelAndView createNewShop(@ModelAttribute @Valid Shop shop,
12            BindingResult result,
13            final RedirectAttributes redirectAttributes) {
14 
15        if (result.hasErrors())
16            return new ModelAndView("shop-new");
17 
18        ModelAndView mav = new ModelAndView();
19        String message = "New shop "+shop.getName()+" was successfully created.";
20 
21        shopService.create(shop);
22        mav.setViewName("redirect:/index.html");
23 
24        redirectAttributes.addFlashAttribute("message", message);  
25        return mav;    
26    }
27...
The code snippet above demonstrates the main things which you need to perform in a controller layer in order to implement the validation:
  • Autowiring of the validator.
  • Adding of the validator to the InitBinder.
  • Apply @Valid annotation to the model in the concrete controller.
And finally let’s look at the JSP:
01<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
02...
03<h1>New Shop page</h1>
04<form:form method="POST" commandname="shop" action="${pageContext.request.contextPath}/shop/create.html">
05<table>
06<tbody>
07<tr>
08<td>Shop name:</td>
09<td><form:input path="name"></form:input></td>
10<td><form:errors path="name" cssstyle="color: red;"></form:errors></td>
11</tr>
12<tr>
13<td>Employees number:</td>
14<td><form:input path="emplNumber"></form:input></td>
15<td><form:errors path="emplNumber" cssstyle="color: red;"></form:errors></td>
16</tr>
17<tr>
18<td><input value="Create" type="submit"></td>
19<td></td>
20<td></td>
21</tr>
22</tbody>
23</table>
24</form:form>
25...
Pay your attention on the form:errors tags, they are responsible for the displaying of the error messages.
Spring-MVC-Validator

Summary

The Validator interface allows creation of the flexible validation layer for each domain model object in your application. It’s a good alternative for the standard JSR-303 validation annotations such as @Min, @Max, @NotNull, @Size etc.

Wednesday 4 March 2015

div vs span (HTML) - What's the difference?


Often confuse <div> with <span>?
Beginners learning the HTML and web designing / development often ask the difference between these two HTML tags, especially if they are learning by looking at the HTML code, as they both seem to do the same job of defining a section of HTML code as a class or an ID, which can later be styled using CSS (Hint: CSS is used for the presentation of HTML code).

Here, in this tutrorial, I will tell you the differences between them and which is appropriate for different cases.

div - Document Division Element

<div> tag is used for defining a division or a section in an HTML page as a classor an ID, which then can be formatted / styled with CSS. It divides the page into a section! Consider the following example:
<style>
.green-section {
    color:green;
}
</style>

<div class="green-section">
    <p>This is the text written in green color</p>
</div>

Here, we have defined a class "green-section" with <div> tag. The defined class "green-section" was earlier styled within <style> tag to change the text color to green. Thus, you can see that we used <div> tag to define a paragraph as the one with green text.

Through it, we can separate different sections of a website. For instance, you can define left / right widgets section in your blog with <div>, change the size of widgets, etc. It is generally used with block-level content.

Note that <div> creates a line around the section, so you don't need to use <p>for the text. Following is its default CSS value:
div {
    display: block;
}

 

span - Inline Element

It is used for defining an inline element within a section (i.e., <div> enclosed text, etc.) as a class or an ID. It is used for spanning the element!

Continuing from the previous example, we will now add a <span> tag to define a new element within the <div> defined section to change our text color to blue:
<style>
.green-section {
    color:green;
}

.blue-text {
    color:blue;
}
</style>

<div class="green-section">
    <p>This is the <span class="blue-text">blue text</span> in the green-section</p>
</div>

Here you can see that I've added a <span> tag to define a new class "blue-text" for changing the text color to blue through CSS. <span> doesn't create a line around the element, so it is suitable for defining a sub-section of a section. It is normally used to change the property of some text in a paragraph to make it prominent. Infolinks script changes the contextual text to ads through span element.

Note that both <div> and <span> should be used in the places where normal tags (<em><strong>, etc.) are not enough. Overusing them can result in an ugly and hard-to-manage code.

Following is the stand-alone example of HTML which you can copy / paste into your text editor, save it to index.html and then open the file in your browser to see its usage:

<!DOCTYPE html>
<html>
<head>
    <title>
        div vs span
    </title>
</head>
 
<style>
.green-section {
    color:green;
}
.blue-text {
    color:blue;
}
</style>
 
<div class="green-section">
    <p>This is the text written in green color</p>
</div>
 
<div class="green-section">
    <p>This is the <span class="blue-text">blue text</span> in the green-section div</p>
</div>
</html>