Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

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

Monday, 14 October 2013

How to use resource sing in MVC 4 application.



How to use resource sing in MVC 4 application.



Step 1 : First create your MVC 4 Web application using Visual Studio 2010 | 2012

Step 2 : Right click on project node and Select Add  --> New Item -->  select "Resource File"
              and give file name and click on "Add Button".

Step 3 : Resource file will added to your project open that file and create labels 
             Like   Name = "lblProjectTitle"  value ="Demo"

Step 4 : To access resource file in your project please select access modifier as "Public"















Step 5 : Add resource parameter on your web page this way.

            @ResourceName.lblProjectTitle

Step 6 :  This way you can create your resource file and access in MVC.






 


Monday, 3 June 2013

Create Simple Application in MVC 3

How to create simple application in MVC 3 Using EntityFramework.


Click Below link to download project

http://www.mediafire.com/?f5ay24cq5nm1t36

Step 1 : Software requirement

  •  The ASP.NET MVC 3 run-time components require the following software:
  •  NET Framework version 4. 
  • Visual Studio 2010 or Visual Web Developer 2010 Express. 
  • ASP.NET MVC 3 Visual Studio 2010 tools require the following software.

Step 2 :

    Click on Microsoft Visual Studio 2010

  1. Click on File menu select new project 
  2. Select  

3.   Enter your project name and location where you want to save this project
4.   Click on ok button for next step and get this screen



5. Select project template
          Empty ,internet Application ,Internet Application
         I go with Internet Application
6.   Select View Engine
       Aspx view  :- View which is we used in all last .net application   Extension is .aspx
       Razor view :- Is good as compare to aspx view rendering is fast . Extension is   .cshtml
7.   Keep "Create a unit test project"  box UN-check we will learn later on about this.
8.   Check us HTML5 semantic markup
9.   Click on ok button
10. View solution explorer all the file and folder is created for your project..




    Adding Entity Framework in MVC3 Application

    How to add Entity Frame work in MVC 3 Application


    Step 1 :   First you have to know how to create MVC3  application so view my post about 

             http://mvc3withanuj.blogspot.in/2013/01/create-simple-application-in-mvc-3.html

    Step 2 :  Right click on Model folder in solution bar

    Step 3 : Select ADD option and then select ADD NEW one windows is open


    Step 4 : Click in Data option in Left menu

    Step 5 : Select ADO.NET Entity Data Model  give the name of the model  Like StudentModel and click on Add button.

    Step 6 : One new windows open click on Generate from database option and click on next

    Step 7 : Add New Database connection and Select the database you want to add in your project..

    • Click on New Connection .
    • Select Microsoft SQL server click on continue .
    •  Select server name or enter .   (dot)  .
    • Fill authentication details you have to access to database .
    • Select database you want to use in this application.
    • Once test the connection if they return Test Connection is Succeeded.
    • Click on OK button  


    Step 8 : Enter your entity name you like or keep it same..

    Step 9 : Click on NEXT button and Choose your Database objects..

    Step 10 : Select your Tables and Store Procedures you want to add in your application..



    Step 11 : And keep all check box selected ..

    Step 12 : Click on FINISH Button to create the entity model..

    Step 13 :This way you can add entity model in your Application


    Thank You

    Send Push Notification to android mobile using MVC,Asp.net

    Send Push Notification to android mobile using MVC  Code C#


    Step 1 : First create your [MVC ,Asp.net Application] .

    Step 2 : Paste the below code in your application.

    public void NotifyTest(string regId)
            {
                var applicationID = "xxxxxxxxxxxxxxxxxxxx";

                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";
                httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"registration_ids\":[\"" + regId + "\"]," +
                                "\"data\": {\"title\": \"This is testing.\"}}";
                    Console.WriteLine(json);
                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        Console.WriteLine(result);
                    }
                }
            }

    Step 3  : Call the function  NotifyTest(regID) with one Register ID of mobile  parameter.

    Step 4 : This way you can send push notification.