Thursday, March 21, 2019

C# - Read file and save bytes into Text file


Read file and save bytes into Text file

System.IO.FileStream stream = System.IO.File.OpenRead(@"FileFullPathRead.pdf");
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();

string base64 = Convert.ToBase64String(fileBytes);
System.IO.File.WriteAllText(@"FileFullPathToSave.txt", base64);

Tuesday, February 26, 2019

Http TLS Support for Legacy framework

   Recently i faced issue to make http call to WebAPI which is supporting latest TLS12 or TLS11. But our client project framework uses .net 4.0 so it not support by default. To resolve this issue added below code (constructor of API or global level)


 //Setting supported security protocol

   System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | (SecurityProtocolType)((SslProtocols)0x00000C00) | (SecurityProtocolType)((SslProtocols)0x00000300);



Here 

(SecurityProtocolType)((SslProtocols)0x00000C00) is equivalent to Tls12
(SecurityProtocolType)((SslProtocols)0x00000300) is equivalent to Tls11



Ref: https://support.microsoft.com/en-us/help/3154520/support-for-tls-system-default-versions-included-in-the-net-framework 

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"



Tuesday, August 7, 2018

SQL - Split different column names display with separator

In some situation, we need to show separator for firstname and middlename. This can be comma if there some values.

Lets take sample of employees data as below


With EmployeeCTE AS (
    SELECT * FROM (VALUES (1, 'Balaji', NULL),
    (2, 'Siva', NULL),
    (3,'Balaji', 'Prasad'),
    (4,NULL,'Raj'),
    (5,NULL,NULL),
    (6,'Karthi','m')) as E(Sno,FirstName,MiddleName) )


Now query this to get comma separate names out of this
      
SELECT    
p.sno,p.firstname,p.middlename,
IsNull(p.FirstName, '')
+ CASE
 WHEN p.MiddleName = ''
 THEN ''
 WHEN (IsNull(p.FirstName, '') <> '' and IsNull(p.MiddleName, '') <> '')
 THEN IsNull(', ' + p.MiddleName, '')
 ELSE IsNull(p.MiddleName, '') END As Name
FROM  EmployeeCTE AS p


Now the output will come as comma separated if there values present in firstname or lastname

sno
firstname
middlename
Name
1
Balaji
NULL
Balaji
2
Siva
NULL
Siva
3
Balaji
Prasad
Balaji, Prasad
4
NULL
Raj
Raj
5
NULL
NULL

6
Karthi
m
Karthi, m

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();

        }