Localizing Default Error Messages in MVC

Recently in a (non-english) project i’m working on, I was surprised with the following message “The value ‘150000.00’ is not valid for Preço.”.  I thought that my project was already localized to Portuguese, but apparently no.

mvc

The problem is related with some messages that can’t be localized using validation attributes Like the RequiredAttribute found in System.ComponentModel.DataAnnotations namespace.

Ex:

[Required(ErrorMessageResourceName = "ValidacaoObrigatoria", ErrorMessageResourceType = typeof(MyProject.Properties.Resources))]
public int Prop1 { get; set; }

Messages like “The value ‘{0}’ is not valid for {1}” need a different approach.
For localize default error messages in MVC we will need to add the following code to the Global.asax Application_Start method.

DefaultModelBinder.ResourceClassKey = "ValidationResources";
ClientDataTypeModelValidatorProvider.ResourceClassKey = "ValidationResources";

Where “ValidationResources” is the the name of the resource file (class key) that contains localized string values.
Next create a resource file name ValidationResources.resx or ValidationResources.fr.resx or whatever culture you need to support, mark it embeded inside App and add the following:

FieldMustBeDate The field {0} must be a date.
FieldMustBeNumeric The field {0} must be a number.
PropertyValueInvalid The value ‘{0}’ is not valid for {1}.
PropertyValueRequired A value is required.

My translation to Portuguese will be something like this:

PropertyValueInvalid O valor ‘{0}’ não é válido para o campo ‘{1}’.
FieldMustBeDate O campo ‘{0}’ deve ser uma data válida.
FieldMustBeNumeric O campo ‘{0}’ deve ser um número válido.
PropertyValueRequired O preenchimento deste campo é obrigatório.

Note:
The resource file should be added to the App_GlobalResources folder.

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

MVC 5 Signout Fails

Recently I came across with a problem in the LogOff method that is generated with a new MVC 5 solution.

mvc

The problem was:

  • User1  logged in  and Login method is called in the Account controller.
  • User1 logs off and the LogOff method is called in the Account controller and the following code is executed:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        AuthenticationManager.SignOut();
        return RedirectToAction("Login", "Account");
    }
    
  • User2 logged in  and Login method is called in the Account controller. After this the User1 is logged in instead of User2.

It seems this is a known issue where the explicit sign-in is preferred over a generic sign-out with no params. The solution is change the  call to SignOut and pass the AuthenticationType of the cookie, and this will override the explicit sign-in.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);
    return RedirectToAction("Login", "Account");
}
Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Antimalware Service Executable high CPU

Today I noticed that my computer fan was running more than normal, Windows Explorer become unresponsive and basically the computer wasn’t normal. I took a look at Task Manager and Process Explorer and I noticed that Antimalware Service Executable wasn’t normal and was using about 30% CPU.

antimalware

I found that strange and first I tried to kill the process, but unfortunately  I can’t kill it. Then I tried stop Windows Defender Service, but I can’t stop this service. Then I reboot the computer and the problem was the same…

After a while I did a google search to see if someone else had the same problem. I’ve found that this is a common problem with lots of possible solutions.

The solution that worked for me was:

1º  Open Windows Defender

2º Go to settings\Administrator and uncheck “Turn on this app” and then save settings

windows-defender

3º Now you will have warning messages in Windows TaskBar.

4º Open Action Center

action-center5º Click on button “Turn on now” to turn on Windows Defender.

And after this steps for some reason my computer CPU is again normal.

 

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Open Media Vault – WebGui disappeared

In one of the latest updates of Open Media Vault my webgui disappeared (don’t know why), the problem is reported here and the  first aid command (omv-firstaid) didn’t help. Solution that worked for me was:

  1. Start SSH session
  2. Login
  3. Write in the prompt

service apache2 stop
update-rc.d -f apache2 remove
service nginx restart

And the webgui was running again.

Open Media Server

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Open Media Vault

A few years ago many users, like my self, bought Windows home server but as you might know windows home server is dead.
So few years ago I tested a few NAS solutions like FreeNAS, Ubuntu Server + Webmin, etc.. but in the end I choose Open Media Vault.

OpenMediaServer
Why?

  1. I needed a very simple web interface to configure the server and FreeNAS and Open Media Vault has it.
  2. it has to be light not a resource hog.
  3. Support for samba, users, ftp, ssh, backups and other things I might need.
  4. Support for extensions/plugins.

Both FreeNAS and Open Media Vault have it but I sick with Open Media Vault mainly because it’s based on Debian and I’m more familiar with Debian than with FreeBSD.

I will post here a few links that worth check out so you can learn more about Open Media Vault.

Home
Live Demo
Features
Download
Virtual machine to test

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Make games with Construct2

Recently I was looking for HTML5 game frameworks because in the future I want to develop what I think would be a very cool game.
And while I was looking I found this application Construct2.

Construct2

This an application that allows users to make games just by drag and drop objects around, add behaviors to them, and make everything come alive with events!

Simple right.

If you want to learn more about Construct2 I really recommend that you see this video because it teach very quickly how to create simple games like Flappy Birds:

Now what is motivating me to test this application is the export options:
Construct2-export

Not only it exports to HTML5 but also to mobile devices and much much more.

I think this deserves test.

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

MVC bundle EnableOptimizations

Bundling and minification are two techniques you can use to improve request load time.

Bundling is a ASP.NET 4.5 feature to combine multiples files into a single file. This is used in CSS and JavaScript files.
Minification performs code optimizations (ex: remove comments) to CSS and JavaScript files to reduce size.

Bundling and minification are enabled or disabled by default by setting to true or false the Compilation element.

mvc

To change this behavior use the BundleTable.EnableOptimizations property and set to true to enable bundling and minification.

Many times in a production environment you need something else to control the bundling and minification especially when you need to diagnose a problem in your JavaScript.

You can use any logic you want or, for a simple scenario, use a app settings key.

ex:

BundleTable.EnableOptimizations = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["EnableOptimizations"]);

Place this code in your BundleConfig class inside method RegisterBundles.

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Windows 8.1 Tip to disable and re-enable hibernate

Many users like me need hibernate and found that wasn’t enabled by default.

windows81

After goggling I’ve found a command line command that does the enable and disable of hibernate.

First open the command line with administrative privileges then execute the following command:

To turn off hibernate type in the command line powercfg.exe /hibernate off
To turn on hibernate type in the command line powercfg.exe /hibernate on

Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter

Drop all tables, stored procedures, views, functions

Recently I had a need to drop all tables, stored procedures, views, functions in a Sql Server database.

In Stackoverflow I’ve found the solution :)

And here it is:

/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
Digg thisBuffer this pageShare on FacebookShare on Google+Share on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrTweet about this on Twitter