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

Hello,
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


<system.webServer>
....
 <modules runAllManagedModulesForAllRequests="true" />
    <handlers>
      <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" />
    </handlers>
....
</system.webServer>

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)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                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);
                        }
                        else
                        {
                            if (context.Request.FilePath.Contains("LoginPageLogo")) //it used for login page logo
                            {
                                string requestedFile = context.Server.MapPath(context.Request.FilePath);
                                SendContentTypeAndFile(context, requestedFile);
                            }
                            else
                            {
                                context.Response.Redirect("~/Account/Login");
                            }
                        }
                        break;
                    }
            }

        }

        private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
        {
            context.Response.ContentType = GetContentType(strFile);
            context.Response.TransmitFile(strFile);
            context.Response.End();
            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";
                            break;
                        }
                }
                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.

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 = "";
  try
  {

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

   if (!File.Exists(path))
   {
    File.Create(path).Close();
   }
  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;
    w.WriteLine(err);
    w.WriteLine("________________________________________________");
    w.Flush();
    w.Close();
  }
 }
    catch (Exception ex1)
    {
       return;
     }
  }
}


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


try
{
  //your Code
}
catch(Exception ex)
{
  ErrorLog.WriteError(ex);
}

 

Highlight the tab according to action and controller in asp.net 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>

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


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

Sending Mail To Admin On USB Insertion or Removal In C#

Here is the c# console code to create a event watcher to monitor, if any usb attached or detached from PC.

Simple just create a console application in visual studio and install a package from nuget to import namespace System.Management.

Install-Package System.Management -Version 4.5.0

And Code is Bellow :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;

namespace USB
{
    class Program
    {
        public enum EventType
        {
            Inserted = 2,
            Removed = 3
        }

        static void Main(string[] args)
        {
            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
            {
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
                Console.WriteLine("Mail Sending...to admin"); //You can write your email code here
            };

            watcher.Query = query;
            watcher.Start();

            Console.ReadKey();
        }
    }
}




you can write your email sending code after Console.WriteLine(“{0}: {1} {2}”, DateTime.Now, driveName, eventName);

How to Create a byte array from stream in C#?

Moslty we want to save images or any file in database as byte, so we can convert any stream in byte array in c#, here below a method to convert.

 public static byte[] StreamToBytes(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

Convert List or any type of object to XML string data in C#

Here is a method to conver any type of object to string xml, this method will take parameters of T type and will return XML string.

public static string ConvertToXML<T>(T obj)
        {
            try
            {

                using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
                {
                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(stringWriter, obj);
                    XDocument xDoc = XDocument.Parse(stringWriter.ToString());
                    xDoc.Declaration = null;
                    return xDoc.ToString();
                }

            }
            catch (Exception ex)
            {
                return ex;
            }
        }

How to use reserved keyword as variable name in c# ?

Here in c# you can use reserved keyword as variable name, here the sample

string @string = "";

you have to add only @ sign before the reserved keyword, than it will treat as a normal variable. as well as you can also use @ sign with unreserved keywords but its not a good practice, its only a trick.

Best way to convert array of object into array of string in C#

I have an array of object in c#

object arrayofobject = new object[] {"Name", "Password", "Address"}

now i want to convert this array of object into array of string so i’ll use Array.CovertAll() method as string array.

string[] arr = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

Full Code Here

object arrayofobject = new object[] {"Name", "Password", "Address"}
string[] arrayofstring = Array.ConvertAll((object[])arrayofobject, Convert.ToString);

now you can get arrayofstring.

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")]
            MEETINGWITHPRESCRIPTIONRENEWAL = 2,
            [Description("Prescription Renewal")]
            PRESCRIPTIONRENEWAL = 3
        }

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("http://icd10api.com/?code={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.