How to prevent static files opening without login in ASP.NET MVC

If you are working on mvc application, and uploading pdf, images in your application than you have to prevent those files to open without login the application.
for this you have to use HttpHandler in MVC.

First you have to enable debug mode for static files from WebConfig, because static files route does not go in application pipeline.

Step 1 Enable runAllManagedModulesForAllRequests in webconfig and put Custom httphandler in

 <modules runAllManagedModulesForAllRequests="true" />
      <add name="PDF" path="*.pdf" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="JPG" path="*.jpg" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="PNG" path="*.png" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />
      <add name="BMP" path="*.bmp" verb="GET" type="ApplicationNameSpace.FileProtectionHandler" resourceType="File" />

Step 2 : Create Custom HttpHandler in RouteConfig file, You can create a separate class instead in App_Start folder.
Here is Complete route.config

Here you have to implement 2 interfaces IHttpHandler and IRequiresSessionState.

namespace ApplicationNamespace
 public class RouteConfig
        public static void RegisterRoutes(RouteCollection routes)

                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }

    public class FileProtectionHandler : IHttpHandler, IRequiresSessionState
        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context)
            switch (context.Request.HttpMethod)
                case "GET":
                        if (SessionHelpers.Userid != 0) // if Application is Login
                            string requestedFile = context.Server.MapPath(context.Request.FilePath);

                            SendContentTypeAndFile(context, requestedFile);
                            if (context.Request.FilePath.Contains("LoginPageLogo")) //it used for login page logo
                                string requestedFile = context.Server.MapPath(context.Request.FilePath);
                                SendContentTypeAndFile(context, requestedFile);


        private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
            context.Response.ContentType = GetContentType(strFile);
            return context;
        private string GetContentType(string filename)
            // used to set the encoding for the reponse stream
            string res = null;
            FileInfo fileinfo = new FileInfo(filename);
            if (fileinfo.Exists)
                switch (fileinfo.Extension.Remove(0, 1).ToLower())
                    case "pdf":
                            res = "application/pdf";
                return res;
            return null;

Here we are handling appplication login trough Session, if there is session Userid that we saved on Login Time, if it is found than file will out through response.
You have to use those methods SendContentTypeAndFile and GetContentType for file out response.

US Mobile Number Format validate JQuery (123)456-7890

Validation Mobile Number Field in US Format Mobile Number with Regexp in javascript/JQuery



<input type="text" class="form-control" name="Phone" placeholder="(123)456-7890" id="MobileNumber" onblur="return validateUsNumber(this);" maxlength="14" />

function validateUsNumber(e) {
        var value = $(e).val();
        if (value.trim() != '') {
            var pattern = new RegExp("^[\\(]{0,1}([0-9]){3}[\\)]{0,1}[ ]?([^0-1]){1}([0-9]){2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}$");
            if (!pattern.test(value)) {
                alert("Please enter mobile number in valid format ! (123)456-7890");
                return false;

Error log in catch block write Exception Detail in C#

This method helps you to trace or keeping log of your exception in a text file with a formatted manner. Just use as extension method and pass object of you Catch Exception obj.


public class ErrorLog
 public static void WriteError(Exception ex)
  string err = "";

   string path = System.AppDomain.CurrentDomain.BaseDirectory + "/ErrorLog/" + 
   DateTime.Today.ToString("dd-MM-yy") + ".txt";

   if (!File.Exists(path))
  using (StreamWriter w = File.AppendText(path))
    w.WriteLine("\r\nLog Entry : ");
    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
    err = "Error Log at : " + ex.ToString() + "___. Error Message:" + ex.StackTrace;
    catch (Exception ex1)

And you can use this extension method anywhere in catch block with class name.

  //your Code
catch(Exception ex)


Highlight the tab according to action and controller in MVC

In Menu bar, while navigating, “Active” class will add in menu item according to your controller and action, that is fixed by you in your html code.

Just use this extension method in your menu item class.


public static string IsActive(this HtmlHelper html,
                                      string control,
                                      string action)
            var routeData = html.ViewContext.RouteData;

            var routeAction = (string)routeData.Values["action"];
            var routeControl = (string)routeData.Values["controller"];

            // both must match
            var returnActive = control == routeControl &&
                               action == routeAction;

            return returnActive ? "active" : ""; //Here you can change class name according to your theme like "active" or anything

Now you have to use this method as HTML helper in your razor page.

<li class="@Html.IsActive("About","Index")">
 <a href="@Url.Action("Index","About")">About Us</a>

<li class="@Html.IsActive("Contact","Index")">
 <a href="@Url.Action("Index","Contact")">Contact Us</a>

Now if your controller and action will “About” and “Index” then “active” named class will add in you li class.

Multiple email validations in multiple text boxes with comma separate email ids in Javascript

Before Form submit, if you have multiple text boxes for emails like To Email and Cc Email, and both text boxes having multiple email ids with comma separate, then before form submit you can add validation through JQuery or java script.


<!DOCTYPE html>

To Email: <textarea name=”ToEmail” id=”ToEmail”></textarea><br>
CC Email: <textarea name=”CCEmail” id=”CCEmail”></textarea><br>
<input type=”submit” value=”Submit”>


$('form').submit(function () {
        var ToEmail = $('#ToEmail').val();
        var CCEmail = $('#CCEmail').val();
        var validArray = [];
        var emails = ToEmail.replace(/\s/g, '').split(",");
        Array.prototype.push.apply(emails, CCEmail.replace(/\s/g, '').split(","));
        var valid = true;
        var regex = /^(([^&amp;amp;lt;&amp;amp;gt;()[\]\\.,;:\s@\"]+(\.[^&amp;amp;lt;&amp;amp;gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        for (var i = 0; i &amp;amp;lt; emails.length; i++) {
            if (emails[i] == "" || !regex.test(emails[i])) {
                valid = false;
        var isFalse = validArray.includes(false);
        if (isFalse == true) {
alert("Please enter emails in proper format !");
            return false;
        else {
            return true;

Now Here an array will store comma separate email ids of first text box and then same array will append the more email ids from another text box, for this we have used :

Array.prototype.push.apply(emails, CCEmail.replace(/\s/g, '').split(","));

Above line of code will append second text box email ids into array, that already having values of first textbox.(email)

Note:- If you are working on ASP.NET MVC Razor then in Regex Expression you have to replace @ to @@, because @ will determine as razor syntex.

Editable Text Box In Jquery And Post Data to ASP.NET


Here i have a grid, and in grid i have a column with Quanity, so if i want to change this quantity with editable text box.

so Here will be Link tag and text box with some id and selectors.

And this will work if there will multiple editable textboxes are there in table grid.

Here First HTML Code

<a href="JavaScript:Void(0);" id="editqty">@item.Qty</a>
<input type="text" style="width:70px;display:none;" class="form-control" id="qtyValue" value="@item.Qty" data-value="@item.PKId" data-target="@item.Qty" />

So above is html code and only <a> tag will be shown on grid, and when you will click on Link then it will hide and text box will show.
In this jquery code all other text box in grid and all things will be same as previous.
Below is jquery code
$("a[id$='editqty']").each(function () {
$(this).on('click', function () {

$("input[type='text'][id$='qtyValue']").blur(function () {


var prevValue = $(this).attr('data-target');
var savedValue = $(this).val().trim();
var id = $(this).attr('data-value');

if (prevValue != savedValue)


cache: false,
type: "POST",
url: '@Url.Action("Index","Employee")',
data: { savedValue: savedValue, id: id },
success: function (data) {
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 401) {
window.location.href =  "Account/Login/";



Get Enum Description According to language culture or resource file in C#

if i have an enum and i want to show the description on view or in dropdown than, than we can change the description according to resource language file.

Full example below:

We have an Enum First

public enum MeetingType
            [Description("Booked Meeting")]
            APPOINTMENTBOOKED = 1,
            [Description("Prescription Bookings")]
            [Description("Prescription Renewal")]

And then we will add these description strings in our resource files.

After Adding strings or key in resource file we have created a extension method for further use.

First import

using System.Resources;

public static string GetDisplayName(this Enum e)
            var rm = new ResourceManager(typeof(DoctorPanel.Resources.Resource));
            var resourceDisplayName = rm.GetString(ExtensionMethod.EnumDescription(e).Replace(" ",string.Empty));

            return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;

And use this method where you want to get enum description according to resource or language wise.

var GetString=YourEnum.GetDisplayName();

we used white space remover because, Resource file keys accept without spaces or you can write your enum description without spaces.


Get disease ICD code in C# using ICD10 API

public string GetICDCode(string ICDCode)
            DiagnosisModel model = new DiagnosisModel();
            String postURL = string.Format("{0}&desc=short&r=json", ICDCode);
            WebRequest request = WebRequest.Create(postURL);
            request.Method = "GET";
            request.ContentType = "application/json; charset=utf-8";

            var response = (HttpWebResponse)request.GetResponse();
            string jsonText;
            using (var sr = new StreamReader(response.GetResponseStream()))
                jsonText = sr.ReadToEnd();
            return jsonText;


We created a method for getting icd code.

Create Model for icd code vlaues and data

public class ICDCode
            public string Name { get; set; }
            public string[] Inclusions { get; set; }
            public string[] ExcludesOne { get; set; }
            public string[] ExcludesTwo { get; set; }
            public string Description { get; set; }
            public string Valid { get; set; }
            public string Type { get; set; }
            public string Response { get; set; }

Just pass icd code in above method and it will give you result as json,

deserilize it with you model class and store in your model properties.

ICDCode model = new ICDCode();

var jsonResultICDCode = GetICDCode(yourICDcode);

model.ICDResponse = new JavaScriptSerializer().Deserialize<ICDCode>(jsonResultICDCode);

If your ICD code is valid than, it will return
model.ICDResponse.Valid=1 and model.ICDResponse.Response == “True”

Now you can get all information about icd code in your model properties.

How to get System IP address in ASP.NET MVC C#?

Getting client machine ip address in mvc.

you have to use System.Web.HttpContext context = System.Web.HttpContext.Current;
for current request.

public static string GetIPAddress()
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                    return addresses[0];

            return context.Request.ServerVariables["REMOTE_ADDR"];

Maximum request length exceeded

If you are using IIS for hosting your application, then the default upload file size if 4MB. To increase it, please use this below section in your web.config –

        <httpRuntime maxRequestLength="1048576" />

For IIS7 and above, you also need to add the lines below:

         <requestLimits maxAllowedContentLength="1073741824" />


  • maxRequestLength is measured in kilobytes
  • maxAllowedContentLength is measured in bytes

which is why the values differ in this config example. (Both are equivalent to 1 GB)