Friday 26 April 2013

Javascript/Jquery tricks

Apply below tricks in your code and see the results.  

1. Calling  server side function from javascript


        function CallServerSideFuncFromJavascript(name, sender) {
        var url = "/testfolder/myfunc";

        var data = "value=" + name;
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            success: function (value) {
                if (value != "Null") {
                    sender.SetText(value);
                }
            }
        });
    }


2. Validating SSN through javascript


    function ValidateSSN(s, e) {
        var value = s.GetValue();

        if (value != null && value.trim().length > 0) {
            len = 10 - value.trim().length;

            value = len > 0 ? new Array(len).join('0') + value : value

            s.SetValue(value.toUpperCase());
        }

    }


3. Restrict user entering specific values:

<input type="text" onkeypress="return  ValidateText(event);" />

    function ValidateText(evt)
{
var value = String.fromCharCode(evt.which ? evt.which : evt.keyCode);
if(value=="^" || value=="<" || value=="*")
{
return false;
}
return true;
}

4. Enable/ Disable button through jquery


To disable a button:

$("input[type=submit]").attr("disabled", "disabled");
or
$("#btnSubmit").attr("disabled", "disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").attr("disabled", "disabled");
});


To enable a button:

$("input[type=submit]").removeAttr("disabled");
or
$("#btnSubmit").removeAttr("disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").removeAttr("disabled");
});

We can use it with any html control. functionality will be same.


5. Check if text in  textbox is selected or not.

 function CheckTextSelectionInTextBox(ctrl) {
        if (document.selection != undefined) {
            var sel = document.selection.createRange();
            selectedText = sel.text;
            if (selectedText != "") {
                return true;
            }
        }
        // Mozilla version
        else if (ctrl.selectionStart != undefined) {
            if (ctrl.selectionStart != ctrl.selectionEnd) {
                return true;
            }
        }
        return false;
    }

<input type="text" onkeypress="return CheckTextSelectionInTextBox(this); " />




I will get back soon with more solutions and tricks.

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();
        }