Wednesday, 10 April 2013

Model validation in entity framework through Data Annotation

Here is the sample code to implement model validation through data annotation using entity framework.

Steps to follow:
  1. Create a file to store your information say MyDataAnnotations.
  2. Now create a metadata class(preferably put the class name as ClassNameMetaData for naming convention like if your class name is Account then it can be AccountMetaData. It will help you finding your metadata class in future). Assign validations to your model properties and it will reflect when using that model class in your UI.
  3.  Third and last step would be to assign your model class with MetaDataType attribute. For this simple put your attribute to the class like this [MetadataType(typeof(AccountMetaData))] and you are done.
Here in this example I have  taken my class name as SampleClass and metadta name as SampleClassMetaData. I have created a regular expression validation to the property Email which exists in my SampleClass. Next I assigned the MetaDataType attribute to my SampleClass and that's all. You can create your own custom validation attributes also and can use here. That I will explain in my upcoming posts. Use the code in your app and enjoy.

Sample Code:


 public partial class SampleClassMetaData
    {
        [RegularExpression(@"^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1}[\da-zA-Z-]{2,3}$", ErrorMessage = "Please enter valid email address")]
        public string Email { get; set; }
    }
    [MetadataType(typeof(SampleClassMetaData))]
    public partial class SampleClass
    {      
    }


Tuesday, 9 April 2013

Send email

 public void SendMail(string fromId, string to, string subject, string body,string fromName)
        {
            try
            {
                string host = ConfigurationManager.AppSettings["SMTPHost"].ToString();
                string userName = ConfigurationManager.AppSettings["SMTPUserName"].ToString();
                string pwd = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
                string ssl = ConfigurationManager.AppSettings["SSL"].ToString();
                int port = 25;
                int.TryParse(ConfigurationManager.AppSettings["SMTPPort"].ToString(), out port);

                MailMessage message = new MailMessage();
                SmtpClient Smtp = new SmtpClient();
               

                Smtp.Host = host;
                Smtp.Credentials = new System.Net.NetworkCredential(userName, pwd);
                Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                Smtp.Port = port;
                if (!string.IsNullOrEmpty(ssl) && ssl.ToLower().Equals("true"))
                {
                    Smtp.EnableSsl = true;
                }

                message.From = new MailAddress(fromId.Trim(),fromName);
                string[] toAddress = to.Split(',');
                foreach (object o in toAddress)
                {
                    message.To.Add(o.ToString().Trim());
                }
                message.Subject = subject;
                message.Body = body;

                message.IsBodyHtml = true;
                message.Priority = MailPriority.Normal;
                Smtp.Send(message);
            }
            catch
            {
                throw;
            }
        }

Thursday, 4 April 2013

Encryption methods


Hi Big,

Please check below the encryption method for SHA256 and TripleDES

using System.Security.Cryptography;

SHA256 Encryption:


        public static string SHA256Encryption(string valueToEncrypt)
        {
            var uEncode = new UnicodeEncoding();
            byte[] byteVal = uEncode.GetBytes(valueToEncrypt);
            SHA256 sha = SHA256.Create();
            byte[] hash = sha.ComputeHash(byteVal);

            return Convert.ToBase64String(hash);
        }




TripleDES Encryption:


        public static string TripleDESEncryption(string valueToEncrypt)
        {
            byte[] key = Encoding.ASCII.GetBytes("<TripleDESCryptoService>"); //24characters       
            byte[] byteValue = Encoding.ASCII.GetBytes(valueToEncrypt);
            TripleDES des = TripleDES.Create();
            des.Key = key;
            byte[] IV = new byte[des.IV.Length];
            Array.Copy(key, IV, des.IV.Length);
            des.IV = IV;
            //des.Mode = CipherMode.ECB;

            byte[] encryptedByte = des.CreateEncryptor(key, IV).TransformFinalBlock(byteValue, 0, byteValue.Length);

            return Convert.ToBase64String(encryptedByte);
        }
       
TripleDES Decryption:


        public static string TripleDESDecryption(string value)
        {
            byte[] key = Encoding.ASCII.GetBytes("<TripleDESCryptoService>"); //24characters       
            byte[] plainText = Convert.FromBase64String(value);
            TripleDES des = TripleDES.Create();

            des.Key = key;
            byte[] IV = new byte[des.IV.Length];
            Array.Copy(key, IV, des.IV.Length);
            des.IV = IV;
            byte[] enc = des.CreateDecryptor(key, IV).TransformFinalBlock(plainText, 0, plainText.Length);

            return Encoding.ASCII.GetString(enc);
        }

Calculate your age

Hi Big,

Many times I found myself to write code to  calculate age. So here it is:



  public static void CalculateYourAge(DateTime currentDate, DateTime? dob,out int year,out int month,out int day)
        {
            year = 0;
            month = 0;
            day = 0;
            if (dob != null)
            {
                DateTime dateOfBirth;
             
                DateTime.TryParse(dob.Value.ToShortDateString(), out dateOfBirth);
               

                TimeSpan difference = currentDate.Subtract(dateOfBirth);
                DateTime age = DateTime.MinValue + difference;
                 year = age.Year - 1;
                 month = age.Month - 1;
                 day = age.Day - 1;
            }
        }

Entity Framework generic save

Hi,

Do you know during saving entity you can loose some data if it is not available in object. To  avoid this you can perform generic save.

Please check below solution for entity generic save.

 public void UpdateRecord(EntityClass info)
        {
            using (EntitiesContext context = new (EntitiesContext())
            {
        context.EntityClasses.Find(info.ID);
                DbEntityEntry entry = context.ChangeTracker.Entries().FirstOrDefault();
                entry.CurrentValues.SetValues(info);
        GenericSave(context, entry);
            }
        }

 public static void GenericSave(EntitiesContext context, DbEntityEntry entry)
        {

            DbPropertyValues OriginalValues = entry.OriginalValues;
            DbPropertyValues CurrentValues = entry.CurrentValues;

            foreach (var orgProName in OriginalValues.PropertyNames)
            {
                foreach (var currentPropName in CurrentValues.PropertyNames)
                {
                    if (orgProName == currentPropName)
                    {
                        if (CurrentValues[currentPropName] == null && OriginalValues[orgProName] != null)
                        {
                            entry.CurrentValues[currentPropName] = OriginalValues[orgProName];
                        }
                        continue;
                    }
                }
            }
            context.SaveChanges();
        }

Tuesday, 25 December 2012

Getting Timezone ID through javascript

Introduction:

It happens to me most of the time that I need to find user local timezone id in my projects. So here is the solution. Use it in your app and enjoy.


CODE:

<script language="javascript">

function GetUserTimeZoneID(){
    var timezone=String(new Date());
     return timezone.substring(timezone.lastIndexOf('(')+1).replace(')','').trim();
     }


</script>

Wednesday, 15 February 2012

Getting value from HashTable

Hi Big,

I have faced this problem many times I junked into the logic. Getting Value/Key from the HashTable is needed every time we work with two values simultaneously. So I thought to write it here. There are two way to do this one is from DictionaryEntry collection and through IDictionaryEnumerator.


HashTable objHash=new HashTable();

objHash.Add(1,"AAA");
objHash.Add(2,"BBB");

1:Getting through DictionaryEntry:

foreach (DictionaryEntry entry in objHash)
            {
                Console.WriteLine(entry.Key.ToString()+","+entry.Value.ToString());
            }

 2:Getting through IDictionaryEnumerator:

            IDictionaryEnumerator objDictionary = objHash.GetEnumerator();

            while (objDictionary.MoveNext())
            {
                Console.WriteLine(objDictionary.Key.ToString()+","+objDictionary.Value.ToString());
            }