Wednesday 21 May 2014

Common split function with delimeter using Asp.net MVC

Common split function with delimeter using Asp.net MVC


- Serena Williams beats Angelique Kerber 7-5, 6-3

- It's a 22nd Grand Slam title to match Steffi Graf's record

- Serena: "Victory sweeter knowing how hard I had to work for it"

- Herbert & Mahut triumphant in Men's Doubles Final

- Serena adds Ladies' Doubles crown alongside sister Venus

- Jiske Griffioen is Ladies' Wheelchair Singles Champion

- Hewett & Reid win Wheelchair Doubles; Potapova is Girls' Singles champion




Strip Html Editor value to simple text using Regex

Strip Html Editor value to simple text using Regex


Introduction

Here we will strip value of html editor to simple text using Regex.

Description

We used asp.net MVC application to strip value of Html Editor to simple text.

Solution

Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Now add below code to your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text.RegularExpressions;


/// <summary>
/// Strip HTML
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Strip(string text)
{
            if (string.IsNullOrWhiteSpace(text))
                return string.Empty;

            text = HttpUtility.HtmlDecode(text);

            //replace html tags            
            text = Regex.Replace(text, @"<(.|\n)*?>", " ");

            //replace &nbsp;
            text = Regex.Replace(text, @"&nbsp;", " ");

            //replace spaces
            return Regex.Replace(text.Trim(), @"\s+", " ");
}

Step 3 :  Now access this function from your code and pass the html tags string and get the simple string value.

string result =  ClassName.Strip(htmlString);

How to check Is web link is available or not

Check Is Web link is Available or not


Introduction

Here we find is given web link is valid or active link or fake link.

Description

Here we find is given web link is valid or active link or fake link.This we will done using Asp.net MVC

Solution

Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Now add below code to your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;


/// <summary>
/// Check is website available
/// </summary>
/// <param name="Url"></param>
/// <returns></returns>
 public static bool IsWebSiteAvailable(string Url)
        {
            string Message = string.Empty;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);

            // Set the credentials to the current user account
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            request.Method = "GET";

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // Do nothing; we're only testing to see if we can get the response
                }
            }
            catch (WebException ex)
            {
                Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
            }

            return (Message.Length == 0);
}

Step 3 :  Now access this function from your code and pass the url value of website link.

bool isWebLinkExists = ClassName.IsWebSiteAvailable("http://www.google.com");

bool isWebLinkExists = ClassName.IsWebSiteAvailable("http://www.tesingwebsite.com");



Remove white space from string using Regex Asp.net MVC

Remove white space from string using Regex Asp.net MVC


Introduction

Here we learn how remove white space from string object using Regex.

Description

Regex in .net is used to do transaction on RegularExpressions .We can compare RegularExpressions also we can format string by using regex RegularExpressions. 

Solution

Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Now access your regex RegularExpressions in any method.

string result = System.Text.RegularExpressions.Regex.Replace("string value", @"\s", " ");



Encoding and Decoding base64 string using Asp.net MVC application

Encoding and Decoding base64 string using Asp.net MVC application


Introduction

Here we learn how to encode string value to base64 string and decode base64 to simple string.

Description

Here we learn how to encode string value to base64 string and decode base64 to simple string.
We use Asp.net mvc 4 application to do this transaction. Using  System.Text.Encoding methods.

Solution


Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Create one folder in your application called "Utilities" we will all customize .cs file in this folder. We called this type of transaction as utilities of application.

Step 3 :  Add one class file in to you application name as "Encryption.cs" or as per your acquirement.


Step 4 :  Now open that class file and make that class public and static for entire website after that there is no need to create object of that class file, we can directly access all function and property of this class.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace WebApplication1
{
    public static class Encryption
    {

    }

}

Step 5 :  Add below code to that file for Encryption of string.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WebApplication1
{
    public static class Encryption
    {        
        /// <summary>
        /// Encrypt the password in base64 string
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string EncryptToBase64(this string password)
        {
            byte[] encodedBytes = Encoding.UTF8.GetBytes(password);
            string base64EncodedText = Convert.ToBase64String(encodedBytes);
            return base64EncodedText;
        }

        /// <summary>
        /// Decrypt the password to base 64 string
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string DecryptToBase64(this string password)
        {
            byte[] encodedBytes = Convert.FromBase64String(password);
            string plainText = Encoding.UTF8.GetString(encodedBytes);
            return plainText;
        }
    }
}

Step 6 :  Now access Encryption method to encode and decode your simple string.

string encodeResult = Encryption.EncryptToBase64("Simple Text String");

string recodeResult = Encryption.DecryptToBase64("Base64 String");


Cache working using Asp.net MVC 4 application

Cache working using Asp.net MVC 4 application


Introduction

Here we learn how to use Cache to manage asp.net mvc application to reduce the database call.

Description

Here we learn how to use Cache to manage asp.net mvc application to reduce the database call. We used asp.net mvc 4 application to implement this cache management. 

Solution


Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Create one folder in your application called "Utilities" we will all customize .cs file in this folder. We called this management as Utilities of application.

Step 3 :  Add one class file in to you application name as "CacheManager.cs" or as per your acquirement.


Step 4 :  Now open that class file and make that class public and static for entire website after that there is no need to create object of that class file, we can directly access all function and property of this class.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;

namespace WebApplication1
{
    public static class CacheManager
    {
             
    }

}

Step 5 :  Add below code to that file for accessing Cache.

private static List<CountryList> _countryList;
        public static List<CountryList> CountryList
        {
            get
            {
                if (HttpContext.Current.Cache.Get("CacheManager.CountryList") == null)
                {
                    _countryList = null;
                }
                else
                {
                    _countryList = (List<CountryList>)HttpContext.Current.Cache.Get("CacheManager.CountryList");
                }

                return _countryList;
            }
            set
            {
                _countryList = value;
                HttpContext.Current.Cache.Remove("CacheManager.CountryList");
                HttpContext.Current.Cache.Add("CacheManager.CountryList", _countryList, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), CacheItemPriority.Normal, null);
            }
        }

Step 6 :  Now access this cache object in your application for storing data and accessing data.

 public List<CountryList> GetCountries()
        {
            List<CountryList> countries = new List<CountryList>();
            if (CacheManager.CountryList == null)
            {
                CacheManager.CountryList = Query to get All country;
            }
            else
            {
                countries = CacheManager.CountryList;
            }
            return countries;
}

Dynamic html control creation using mvc 4 HtmlHelper

Dynamic html control creation using MVC 4 using HtmlHelper


Introduction

Here we learn how to create dynamic or custom html control using asp.net mvc 4 using HtmlHelper.

Description

In this blog we learn how to create custom html control using htmlHelper in  Asp.net mvc application. We create Script tag , Text box , button control . You can also customize other html control using htmlHelper like Radio Button ,CheckBox ,Image and many more.

Solution


Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Create one folder in your application called "Helper" we will all customize .cs file in this folder. We called this custom changes as helper of application.

Step 3 :  Add one class file in to you application name as "ContentFactory.cs" or as per your acquirement.


Step 4 :  Now open that class file and make that class public and static for entire website after that there is no need to create object of that class file, we can directly access all function and property of this class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1
{
    public static class ContentFactory
    {
        
    }
}

Step 5 :  Add below code to that file for customization of html tags.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1
{
    public static class ContentFactory
    {
        #region [Methods]

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static MvcHtmlString Script(this HtmlHelper htmlHelper, string filePath)
        {
            TagBuilder tagBuilder = new TagBuilder("script");
            tagBuilder.MergeAttribute("src", UrlHelper.GenerateContentUrl(filePath, htmlHelper.ViewContext.HttpContext));
            tagBuilder.MergeAttribute("type", "text/javascript");
            return new MvcHtmlString(tagBuilder.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper, string name, object value = null)
        {
            TagBuilder tagBuilder = new TagBuilder("input");
            tagBuilder.MergeAttribute("name", name);
            tagBuilder.MergeAttribute("id", name);
            tagBuilder.MergeAttribute("type", "text");
            tagBuilder.MergeAttribute("value", Convert.ToString(value));
            return new MvcHtmlString(tagBuilder.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="buttonType"></param>
        /// <returns></returns>
        public static MvcHtmlString CustomButton(this HtmlHelper htmlHelper, string name, string value, ButtonType buttonType = ButtonType.submit)
        {
            TagBuilder tagBuilder = new TagBuilder("input");
            tagBuilder.MergeAttribute("name", name);
            tagBuilder.MergeAttribute("id", name);
            tagBuilder.MergeAttribute("type", buttonType.ToString());
            tagBuilder.MergeAttribute("value", value);
            return new MvcHtmlString(tagBuilder.ToString());
        }

        #endregion
    }

    #region [Enum]

    public enum ButtonType
    {
        submit,
        button
    }

    #endregion
    
}

Step 6 :  Now access all custom control in you html page using @Html .


@Html.Script("~/Scripts/bootstrap.js")

@Html.CustomTextBox("txt1", "10")


@Html.CustomButton("btnClick", "Click here!", ButtonType.button)

Friday 18 April 2014

How to create Custom Data Annotations using MVC 4 application with client validation

How to create Custom Data Annotations using MVC 4 application with client validation



Step 1 : create mvc application .

Step 2 : Add one entity class "Employee"

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        public int Age { get; set; }

         public string Sem { get; set; }

        public string EmailAddress { get; set; }

        public int Year { get; set; }

    }

Step 3 : Create .cshtml file of Employee creation.

Step 4 : Add one class file of creation of CustomValidationAttribute

Step 5 : Paste below code in that file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace MVC_Custom_DataAnnotations
{
    public class CustomRangeAttribute : RangeAttribute, IClientValidatable
    {
        private double _Minimum;
        private double _Maximum;
        private string _message;
        public CustomRangeAttribute(double minimum, double maximum, string message)
            : base(minimum, maximum)
        {
            _Minimum = minimum;
            _Maximum = maximum;
            _message = message;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            double valueObject;
            Double.TryParse(Convert.ToString(value), out  valueObject);
            return _Minimum <= valueObject && valueObject <= _Maximum;
        }

        public override string FormatErrorMessage(string name)
        {
            return _message;
        }


        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("range", string.Format("{0}~{1}", Minimum, Maximum));
            rule.ValidationType = "customrange";
            yield return rule;
        }
    }

    public class CustomStringLengthAttribute : StringLengthAttribute, IClientValidatable
    {
        public int MaximumLength;
        public string message;
        public string KeyName;

        public CustomStringLengthAttribute(int maximumLength, string errormessage)
            : base(maximumLength)
        {
            MaximumLength = maximumLength;
            message = errormessage;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            int valueObject = Convert.ToString(value).Length;
            return valueObject <= MaximumLength;
        }
        public override string FormatErrorMessage(string name)
        {
            return message;
        }
       

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("maximumlength", MaximumLength);
            rule.ValidationType = "customstringlength";
            yield return rule;
        }
    }

    public class CustomRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        private string Pattern;
        private string message;

        public CustomRegularExpressionAttribute(string pattern, string errorMessage)
            : base(pattern)
        {
            Pattern = pattern;
            message = errorMessage;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }

            Match match = Regex.Match(Convert.ToString(value), Pattern, RegexOptions.IgnoreCase);

            return match.Success;
        }

        public override string FormatErrorMessage(string name)
        {
            return message;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationParameters.Add("pattern", Pattern);
            rule.ValidationType = "customregularexpression";
            yield return rule;
        }
    }
}

Step 6 : Now add attribute to Employee class object.

public class Employee
    {
        public int RollNumber { get; set; }

        public string StudentName { get; set; }

        [CustomRangeAttribute(1, 100, "Age between 1 to 100")]
        public int Age { get; set; }

        [CustomStringLengthAttribute(5, "Maximum char allowed in sem field is 5.")]
        [DataMember]
        public string Sem { get; set; }

        [CustomRegularExpressionAttribute("^[A-Za-z0-9_\\+-]+(\\.[A-Za-z0-9_\\+-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*\\.([A-Za-z]{2,4})$", "Please enter valid email address.")]
        public string EmailAddress { get; set; }

        [CustomRangeAttribute(1950, 2014, "Year between 1950 to 2014")]
        public int Year { get; set; }

    }

Step 8 : Add code for checking server side validation.

 [HttpPost]
        public ActionResult Create(Employee  emp)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View(emp);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

Step 9 : Run your application and try to produce the error using invalid value.

Step 10 : This way you can create custom validation for server side.

Watch video for visual explanation on this point.

https://www.youtube.com/watch?v=-t1EemDasMc&feature=youtu.be

Thursday 14 November 2013

Find any string match in store procedure.

Find any string match in store procedure.




SELECT DISTINCT OBJECT_NAME(OBJECT_ID)
     ,object_definition(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + '<<StringTextValue>>' + '%'

Find Store procedure, modified in specific range



Find Store procedure, modified in specific range


SELECT name as Store_Procedure_Name
FROM sys.Procedures
Where modify_Date >=  <<Datevalue>> AND modify_Date <=  <<Datevalue>>

Find column name match in tables


Find column name match in tables


SELECT sys.Tables.NAME AS TableName
     ,sys.columns.NAME AS ColumnName
FROM sys.columns
INNER JOIN sys.Tables ON sys.Tables.object_id = sys.columns.object_id
WHERE sys.columns.NAME LIKE '<<Column Name>>'