{ Dev Farm }

Web & Windows Development

10 Luglio 2013
di max
2 commenti

ASP.NET MVC CheckBox Validations (server and client side)

A very annoing lack in Asp.Net MVC is the checkbox validation.
I need to validate Privacy acceptation in many websites. The best way is to validate both server side and client side, in this way you can make your websites it more usable.

First: add a new validation attribute MustBeTrueAttribute. you can use it besides the other attributes in your Models

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeTrueAttribute : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if ((bool)value)
                return ValidationResult.Success;
            return new ValidationResult(String.Format(ErrorMessageString, validationContext.DisplayName));
        }

        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "checkrequired"
            };

            yield return rule;
        }
    }

Second: Extend jQuery validation to get client side check

    if (jQuery.validator) {
        // Checkbox Validation
        jQuery.validator.addMethod("checkrequired", function (value, element, params) {
            var checked = false;
            checked = $(element).is(':checked');
            return checked;
        }, '');
        if (jQuery.validator.unobtrusive) {
            jQuery.validator.unobtrusive.adapters.addBool("checkrequired");
        }
    }

With these two pieces you can now easily validate your checkbox with a simple attribute.
This is a sample how it’s used:

    public class FormContact
    {

        [Display(Name = "Name")]
        [Required]
        public string Name { get; set; }

        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        [Required]
        public string Email { get; set; }

        [Display(Name = "Privacy")]
        [MustBeTrueAttribute(ErrorMessage = "Please Accept Privacy Policy")]
        public bool Privacy { get; set; }

    }

19 Giugno 2013
di max
0 commenti

Correct Link SEO Migration from old Asp.Net WebForm to new Asp.Net Mvc Website

When you are designing a new website you have to think about old website links migration.

This is very important to avoid tons of 404 errors and losing massive traffic.

First of all you’ll have to find out all your old link. Such as

/news/Default.aspx
/news/Default.aspx?id=123
/news/Default.aspx?id=456
etc..

and map them to

/news/
/news/new-website
/news/dismiss-old-website
etc..

Fortunately ASP.NET MVC made this translation quite simple.

In your global.asax (or RegisterRutes function) add the code to handle the 301 redirect

    routes.MapRoute(
        name: "News Redirect",
        url: "news/Default.aspx",
        defaults: new { controller = "Redirect", action = "News" }
    );

Than, I suppose you have a Redirect Controller, just convert the old link in the new website url system.

    public class RedirectController : Controller
    {

        public ActionResult News(int? id)
        {
            if (id > 0)
            {
                // your code to find out your new permalink
                var permalink = "xxxxxxxxxxxxxxxxxxxx";
                // your code to find out your new permalink
                return RedirectPermanent("/News/" + permalink);
            }
            return RedirectPermanent("/News");
        }

    }

RedirectPermanent function will set301 as Response Status Code.
Http Status Code 301 means “Moved Permanently”, in this way the search engine will replace the old link with the new one without losing traffic and throwing annoying 404 errors.

Other Resources:

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

http://msdn.microsoft.com/it-it/library/system.web.httpresponse.redirectpermanent.aspx

30 Maggio 2013
di max
0 commenti

CSS Internet Explorer Flat Scrollbars – Win 8 style

Result screenshot:
 
win8-scrolls
 

Very simple css:

body {
scrollbar-3dlight-color: #eaeaea; /* LightGray */
scrollbar-arrow-color: #cfcfcf; /* Gray */
scrollbar-darkshadow-color: #eaeaea; /* LightGray */
scrollbar-face-color: #cfcfcf; /* Gray */
scrollbar-highlight-color: #cfcfcf; /* Gray */
scrollbar-shadow-color: #cfcfcf; /* Gray */
scrollbar-track-color: #eaeaea; /* LightGray */
}

3 Maggio 2013
di max
0 commenti

WPF – Running long tasks without freezing the UI

In orther to avoid freezed ui and annoing “Application is Not Responding” messages I made this very easy helper.
It simply set the cursor in Waiting mode and call your function on anoter task, without freezing your wpf app. When the function is done, cursor return to default.

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Windows.Controls;

public static class UIHelper
{

  public static void callAsync(UserControl el, Action<Object> action)
  {
    el.Cursor = Cursors.Wait;
    var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    Task.Factory.StartNew(action, TaskCreationOptions.LongRunning).ContinueWith(_ => el.Cursor = Cursors.Arrow, uiScheduler);
  }

}

You can call the function from your UserColtrols like this:


  UIHelper.callAsync(this, o => test("hello"));

Than, if you want to update your UI from the task, you have to ask the Dispatcher, here a sample:

  private void test(string msg)
  {
    // your code...
    // your code...
    // your code...

    this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
      yourTextBox1.Text = msg;
    }));
  }

9 Gennaio 2012
di max
1 commento

Ready to use 301 Redirect with Http Module

[wpdm_file id=2]

Just open the web.config and edit the appsetting newSite with your new site. That’s all!

All the requests will be forwarded with “301 Moved Permanently” status code.

Example: Your site is published at http://www.currentsite.com and you want to redirect at http://www.newsite.com

upload the files at http://www.currentsite.com and edit the web.config like:

www.newsite.com"/>

All request will be forwarded like:

http://www.currentsite.com
-> http://www.newsite.com

http://www.currentsite.com/helloworld
-> http://www.newsite.com/helloworld

 

 

The site is tested on iis7, framework 4 Integrated pipeline mode (standard configuration in most of cases).

Source Code:

——————————— Web.config


——————————— Module.cs

using System;
using System.Web;
using System.Configuration;

namespace Redirect
{
public class Module : IHttpModule
{

public void Dispose()
{
}

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
context.EndRequest += (new EventHandler(Application_EndRequest));
}

private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication hap = (HttpApplication)source;
HttpContext hc = (HttpContext)hap.Context;
string newSite = ConfigurationManager.AppSettings["newSite"];
string strUrl = newSite + hc.Request.Url.PathAndQuery;
hc.Response.Clear();
hc.Response.Status = "301 Moved Permanently";
hc.Response.Headers.Add("Location", strUrl);
}

private void Application_EndRequest(Object source, EventArgs e)
{

}

}
}