Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, December 24, 2018

Retrieve MimeType by its extension

In file IO, we need to set content/type while downloading it and this should be dynamically set by file's extension. Here is code we can use to do the same

Create static class to store all available mime-type, here am showing few only, we can add more.


public static class MimeTypesHelper
        {
            public const string
            Doc = "application/msword",
            Docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            Xls = "application/vnd.ms-excel",
            Xlt = "application/vnd.ms-excel",
            Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Ppt = "application/vnd.ms-powerpoint",
            Pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            Pdf = "application/pdf",
            Zip = "application/zip";


            //get matched mime type by extension, so property name should be equals to file extension
            public static string GetMimeTypeByExtension(string extension)
            {
                //remove period in extension
                extension = extension?.Replace(".", "");
                //match mimetype by property
                string matchedMimeType = typeof(MimeTypes).GetField(extension, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)?.GetValue(null)?.ToString();

                //if there is no match default to octet stream
                if (string.IsNullOrEmpty(matchedMimeType))
                {
                    matchedMimeType = "application/octet-stream";
                }

                return matchedMimeType;
            }
        }


Call this method to retrieve your file mimetype

 Response.ContentType = MimeTypesHelper.GetMimeTypeByExtension(".pdf");   //this will return "application/pdf"



Wednesday, June 13, 2018

OTP Mechanism in Asp.Net core

OTP mechanism can be done using different algorithms like TOTP or HOTP. To use it we have inbuilt plugins available,

I have used Otp.Net and TOTP algorithm for this purpose, we can refer it from https://github.com/kspearrin/Otp.NET

Step 1: Refer library from Nuget "Otp.Net" https://www.nuget.org/packages/Otp.NET

Step 2: Create TOTP Object


var emailToSend ="balajisrmv@gmail.com";
var secretKey = Encoding.ASCII.GetBytes(emailToSend);
var TotpObj = new Totp(secretKey, step: 60); //set step for 60 secs for OTP expiration
var otpString = TotpObj.ComputeTotp();

//Send to email, you can customize this to however needed.
emailService.SendEmail(toAddress: emailToSend, subject: "OTP Subject", body: "Your otp code is: " + otpString);


Step 3: Send this otpString to any channel like Email or SMS as your covenient

Step 4: Create seperate action method to validate input OTP code from user

public IActionResult OnPostVerifyAuthCodeAsync(string OtpCode)
        {
   var emailToSend ="balajisrmv@gmail.com";
   var secretKey = Encoding.ASCII.GetBytes(emailToSend);
   var TotpObj = new Totp(secretKey, step: 60); //set step for 60 secs for OTP expiration            
bool otpValid = TotpObj.VerifyTotp(OtpCode, out long timeStepMatched, new VerificationWindow(2, 2));

            if (otpValid)
            {
               
//OTP is valid proceed your business logic            

            }
            else
            {
               //OTP is invalid throw error
     }

            return Page();

        }

Thursday, December 14, 2017

C# - How to merge paths with slashes in all subsequent params

To combine file paths with slashes will take care by below code

public static string MergePath(params string[] stringPaths)
        {

            for (int i = 0; i < stringPaths.Length; i++)
            {
                //To skip trim on first path
                if (i != 0)
                    stringPaths[i] = stringPaths[i].Trim().TrimStart(Path.DirectorySeparatorChar).TrimEnd(Path.DirectorySeparatorChar);
            }

            return Path.Combine(stringPaths);

        }



Example:
var stringtest = Extensions.MergePath(@"c:\path\", @"\dir\file.txt");
var stringtest2 = Extensions.MergePath(@"c:\path\",@"\test\adsf\", @"\dir\file.txt");
var stringtest3 = Extensions.MergePath(@"c:\path", @"test\adsf", @"dir\file.txt");

Output:
"c:\\path\\dir\\file.txt"
"c:\\path\\test\\adsf\\dir\\file.txt"
"c:\\path\\test\\adsf\\dir\\file.txt"

Thursday, October 27, 2016

C# - Passing Linq condition as parameter

We can pass LINQ conditions dynamically as parameter, Lets consider simple example to get Single property and multiple properties by condition. We can use this for Generic Repository Pattern also.

Implementation below,

      public Student GetSingleObjectByCondition(System.Func<Student, bool> predicate)
        {
                var result = default(Student);
            using (var efContext = new DbContext())
            {
                result = efContext.Students.FirstOrDefault(predicate);
            }
            return result;
 }    

     public List<Student> GetMultipleObjectsByCondition(Func<Student, bool> predicate)
        {
            var result = default(List<Student>);
            using (var efContext = new DbContext())
            {
                result = efContext.Students.Where(predicate).ToList<Student>();
            }
            return result;
  }          

    }



How to call the method,

   Func<Student, bool> selector = str => str.Name == "Balaji";

  var student = _studentRepository.GetSingleObjectByCondition(selector);



 Func<Studentbool> selector = str => str.Rank <= 5;


  var students = _studentRepository.GetMultipleObjectsByCondition(selector);


Monday, December 7, 2015

C# - How to send email without any plugins


Below code helps to send email without any third party email plugins, but it requires SMTPServer details to be specified in web.config AppSettings. That server needs to be configured as email server.

using System.Net.Mail;
public void SendEmail(string fromAddress, string[] toAddress, string subject, string bodyContent, string[] filenames)
        {
            MailMessage email = new MailMessage();

            email.From = new MailAddress(fromAddress);
            if (toAddress != null && toAddress.Length > 0)
            {
                foreach (var toAdd in toAddress)
                {
                    email.To.Add(new MailAddress(toAdd));
                }
            }

            email.Subject = subject;
            email.Body = bodyContent;

            if (filenames != null && filenames.Length > 0)
            {
                foreach (var file in filenames)
                {
                    Attachment attachment;
                    attachment = new Attachment(@file);
                    email.Attachments.Add(attachment);
                }
            }

            try
            {
                using (var client = new SmtpClient())
                {
                    client.Send(email);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                email.Dispose();
            };
        }

Friday, November 27, 2015

RavenDB Linq - How to use dynamic where clause

I faced scenario to add some specified where clause based some conditions, so that i have used following code. We can add any number of where conditions like below and execute query to RavenDB. 


public IEnumerable<Student> SearchStudents()
{
List<Expression<Func<Student, bool>>> whereConditionList = new List<Expression<Func<Student, bool>>>();

whereConditionList.Add(p => p.Name == "Balajiprasad");
whereConditionList.Add(p => p.Age > 16);
whereConditionList.Add(p => p.City == "Coimbatore");

var ravenQuery = ravenSession.Query<Student>();

foreach (var condition in whereConditionList)
  ravenQuery = ravenQuery.Where(condition);

return ravenQuery.ToList();
}       

Saturday, April 25, 2015

MVC & WebAPI - Model Binder

There are some specific cases in order to use model binder to MVC and WebAPI in same project.

Here i will explain step by step to implement MVC and WebAPI Model Binders

What is Model Binder?

In some cases, we should do common operations for all actions inside controller. So in that case we can add model binder and pass as parameter to actions. In below example UserModel class sent as Model Binder

public ActionResult Index([ModelBinder]UserModel model)

{
...
}

Implementing Model Binder for MVC

MVC uses different namespace such as System.Web.Mvc. So Model Binder class also should use the same.

Step 1:

Create UserModel class as required. Here we can add our required properties. In this example, i am going to display UserId and UserName

public class UserModel
    {
        public string UserId { get; set; }
        public string UserName { get; set; }

    }

Step 2:

Create custom ModelBinder class which can be implemented from System.Web.Mvc.IModelBinder as below. Here i created as partial for merging with WebAPI. If you dont need WebAPI then just have it as normal class


public partial class UserModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return null;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
/// Create your custom logics to fill the other required details. In this example i can fill username
            }
            return userModel;
        }
    }

Step 3:

Register this Custom ModelBinder class into Global.asax.cs file

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Model binder for MVC controller usermodel
            ModelBinders.Binders.Add(typeof(UserModel), new UserModelBinder());

        }

Step 4:

Use this custom model binder in action methods of MVC controller

public ActionResult Index([System.Web.Http.ModelBinding.ModelBinder]UserModel model)

{
...
 //Write your logic to do with UserModel class object
}


Thats all for MVC Model Binder.


Implementing Model Binder for WebAPI

WebAPI cannot be worked with MVC model binder. So we need to create differently. Step 1 to create UserModel is same. So i will go from Step 2

Step 2:

Create Custom Model Binder for WebAPI as follows. Here IModelBinder uses System.Web.Http.ModelBinding.

using Microsoft.AspNet.Identity;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;

public partial class UserModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return false;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
               //Your logic to fill usermodel class and assign to binding context’s model
                bindingContext.Model = userModel;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Error in model binding");
            return false;
        }

    }


Step 3:

Create ModelBinderProvider class as follows. It is going to be register with configuration. Here ModelBinderProvider uses namespace System.Web.Http.ModelBinding..

public class UserModelBinderProvider : ModelBinderProvider
    {
        private System.Type type;
        private UserModelBinder userModelBinder;

        public UserModelBinderProvider(System.Type type, UserModelBinder userModelBinder)
        {
            this.type = type;
            this.userModelBinder = userModelBinder;
        }

        public override IModelBinder GetBinder(HttpConfiguration configuration, System.Type modelType)
        {
            if (modelType == type)
            {
                return userModelBinder;
            }

            return null;
        }

    }


Step 4:

Register ModelBinderProvider in Global.asax.cs file under WebApiConfig register method

public static class WebApiConfig

    {
    public static void Register(HttpConfiguration config)
        {
         var provider = new UserModelBinderProvider(typeof(UserModel), new UserModelBinder());

         config.Services.Insert(typeof(ModelBinderProvider), 0, provider);


Step 5:

Use in APIController action methods as follows

[HttpGet]
        public string GetUserName([ModelBinder]UserModel model)
        {
              return model.UserName;
  }

Thats all for WebAPI Model Binder.