31 March 2013

MVC- Custom Data Annotations validation server and client side







           public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$",
                     ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage = 
                    "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                public DateTime PlanEndDate { get; set; }
                public string ExternalId { get; set; }
            }

           






       
        public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$", 
                ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage =
                "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                [GratherThen("PlanStratDate")]
                public DateTime PlanEndDate { get; set; }
                [ExternalIdPattern]
                public string ExternalId { get; set; }
            }

        






       public class ExternalIdPatternAttribute : ValidationAttribute , IClientValidatable
        {
            public ExternalIdPatternAttribute() : 
            base("External id should be match with system pattern") { }

            public override bool IsValid(object value)
            {
                const string matchingPattern = "code4help";
                return Convert.ToString(value).Contains(matchingPattern);
            }

            public IEnumerable[ModelClientValidationRule] GetClientValidationRules
            (ModelMetadata metadata, ControllerContext context)
                {
                   var errorMessage = ErrorMessageString;
                    var extidrule = new ModelClientValidationRule();
                    extidrule.ErrorMessage = errorMessage;
                    extidrule.ValidationType = "externalidpattern";
                    //extidrule.ValidationParameters.Add("otherpropertyname",
                         otherPropertyName);

                    yield return extidrule;
                }
         }


                
                


        public class GratherThenAttribute : ValidationAttribute , IClientValidatable
            {
                public string OtherProperty { get; set; }

                public GratherThenAttribute(string oprop)
                    : base("{0} should be grather then {1}")
                {
                    this.OtherProperty = oprop;
                }

                protected override ValidationResult IsValid(object value,
                 ValidationContext validationContext)
                {
                    var validationResult = ValidationResult.Success;
                    var otherPropertyval = 
                    validationContext.ObjectType.GetProperty(this.OtherProperty);
                    if (otherPropertyval.PropertyType == new DateTime().GetType())
                    {
                        var edate = (DateTime)value;
                        var sdate = 
                        (DateTime)otherPropertyval.GetValue(validationContext.ObjectInstance,
                         null);

                        if (edate.CompareTo(sdate) < 1)
                            validationResult = new ValidationResult(ErrorMessageString);
                    }
                    else
                        validationResult =
                            new ValidationResult(
                                "An error occurred while validating the property.
                                 OtherProperty is not of type DateTime");
                    return validationResult;
                }

                public IEnumerable[ModelClientValidationRule] 
                    GetClientValidationRules(ModelMetadata metadata, 
                    ControllerContext context)
                        {
                            var errorMessage = ErrorMessageString;

                            var extidrule = new ModelClientValidationRule();
                            extidrule.ErrorMessage = errorMessage;
                            extidrule.ValidationType = "gratherthen";
                            extidrule.ValidationParameters.Add("otherproperty", OtherProperty);

                            yield return extidrule;
                        }
                    }

            






            $.validator.addMethod("externalidpattern", function (value, element, params) {
            return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("externalidpattern", [], function (options) {
                options.rules["externalidpattern"] = "#" + options.params.otherpropertyname;
                options.messages["externalidpattern"] = options.message;
            });

            $.validator.addMethod("gratherthen", function (value, element, params) {
                return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("gratherthen", ["otherproperty"], function (options) {
                options.rules["gratherthen"] = "#" + options.params.otherpropertyname;
                options.messages["gratherthen"] = options.message;
            });

            




JSON and XML serialization





             public class TestModel
            {
                public int id { get; set; }
                public string Name { get; set; }
                public List[string] lstskill { get; set; }
                public DateTime Birthday { get; set; }
                public bool Active { get; set; }
                public List[personaldata] Datalst { get; set; }
                public personaldata data { get; set; }
            }
            public class personaldata
            {
                public string data1 { get; set; }
                public string data2 { get; set; }
            }

           




         NOTE: Please add reference of dll 
              [System.Runtime.Serialization.Json]
            
            

         public class JsonHelper
            {
                /// 
                /// JSON Serialization
                /// 
                public static string JsonSerializer[T](T t)
                {
                    DataContractJsonSerializer ser =
                     new DataContractJsonSerializer(typeof(T));
                    MemoryStream ms = new MemoryStream();
                    ser.WriteObject(ms, t);
                    string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();
                    return jsonString;
                }
                /// 
                /// JSON Deserialization
                /// 
                public static T JsonDeserialize[T](string jsonString)
                {
                    DataContractJsonSerializer ser =
                     new DataContractJsonSerializer(typeof(T));
                    MemoryStream ms =
                     new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                    T obj = (T)ser.ReadObject(ms);
                    return obj;
                }
            }

        






        public ActionResult Index()
           {
               var model = new Models.TestModel
               {
                   Active = true,
                   Birthday = DateTime.Now,
                   data = new Models.personaldata
                   {
                       data1 = "data1",
                       data2 = "data2",
                   },
                   Datalst = new List[Models.personaldata]
                   {
                       new Models.personaldata
                       {
                           data1 = "ldata1",
                           data2 = "ldata2",
                       },
                       new Models.personaldata
                       {
                           data1 = "ldata1",
                           data2 = "ldata2",
                       },
                   },
                   id = 3,
                   lstskill = new List[string]
                   {
                       "skill1",
                       "skill2",
                   },
                   Name = "name1"
               };

               var strjson = Helper.JsonHelper.
                       JsonSerializer[Models.TestModel](model);

               var strmodel = Helper.JsonHelper.
                           JsonDeserialize[Models.TestModel](strjson);


               return View();
           }

            






        public class XMLHelper
            {
                public static string XMLSerialize[T](T obj)
                {
                    XmlSerializer serializer = 
                    new XmlSerializer(obj.GetType());
                    using (StringWriter writer = new StringWriter())
                    {
                        serializer.Serialize(writer, obj);
                        return writer.ToString();
                    }
                }

                public static object XMLDeSerialize[T](string data)
                {
                    StringReader rdr = new StringReader(data);
                    XmlSerializer xmlSerializer =
                     new XmlSerializer(typeof(T));
                    var result = (T)xmlSerializer.Deserialize(rdr);
                    return result;
                }
            }

            




        public ActionResult Index1()
          {
              var model = new Models.TestModel1
              {
                  Active = true,
                  Birthday = DateTime.Now,
                  data = new Models.personaldata1
                  {
                      data1 = "data1",
                      data2 = "data2",
                  },
                  Datalst = new List[Models.personaldata1]
                  {
                      new Models.personaldata1
                      {
                          data1 = "ldata1",
                          data2 = "ldata2",
                      },
                      new Models.personaldata1
                      {
                          data1 = "ldata1",
                          data2 = "ldata2",
                      },
                  },
                  id = 3,
                  lstskill = new List[string]
                  {
                      "skill1",
                      "skill2",
                  },
                  Name = "name1"
              };

              var strXML = Helper.XMLHelper.XMLSerialize[Models.TestModel1](model);
              var strmodel = Helper.XMLHelper.XMLDeSerialize[Models.TestModel1](strXML);
              return View();
          }

            




        [XmlRoot("TestModel1")]
            public class TestModel1
            {
                public int id { get; set; }
                [XmlAttribute("Name")]
                public string Name { get; set; }
                [XmlElement(ElementName = "lstskill")]
                public List[string] lstskill { get; set; }
                [XmlAttribute("Birthday")]
                public DateTime Birthday { get; set; }
                public bool Active { get; set; }
                [XmlElement(ElementName = "Datalst")]
                public List[personaldata1] Datalst { get; set; }
                [XmlElement(ElementName = "data")]
                public personaldata1 data { get; set; }
            }
            public class personaldata1
            {
                [XmlAttribute("data1")]
                public string data1 { get; set; }
                [XmlAttribute("data2")]
                public string data2 { get; set; }
            }