Thursday, December 21, 2023

Two Factor Authentication using .Net Core

Install Package

dotnet add package GoogleAuthenticator --version 3.1.1


Model Changes

public bool IsAuthenticatorReset { get; set; }

public string UniqueAuthenticatorKey { get; set; }

Method for updating AuthenticationKey

 public async Task<string> UpdateUniqueAuthenticatorKey(AppUser user, string UniqueAuthenticatorKey)

        {

            //var user = (await _appUserRepository.List(x => x.Email == email)).FirstOrDefault();

            if (user != null)

            {

                user.UniqueAuthenticatorKey = UniqueAuthenticatorKey;

                await _userManager.UpdateAsync(user);

                return "success";


            }

            return "error";

        }


Steps ActionMethod

public async Task<IActionResult> LoginWithAuthenticatorStepOne(string email, string userName, string returnUrl)

        {

            try

            {

                var user = await _userManager.FindByEmailAsync(email);

                string googleAuthKey = _configuration["ApplicationSettings:GoogleAuthKey"].ToString();

                string UserUniqueKey = (user.Id.ToString() + googleAuthKey + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString());

                await _appUserService.UpdateUniqueAuthenticatorKey(user, UserUniqueKey);

                //Two Factor Authentication Setup

                TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();

                var setupInfo = TwoFacAuth.GenerateSetupCode("CDS", userName, ConvertSecretToBytes(UserUniqueKey, false), 300);

                ViewBag.BarcodeImageUrl = setupInfo.QrCodeSetupImageUrl;

                HttpContext.Session.Remove("QrCodeSetupImageUrl");

                HttpContext.Session.SetString("QrCodeSetupImageUrl", setupInfo.QrCodeSetupImageUrl);

                ViewBag.SetupCode = setupInfo.ManualEntryKey;

                return View(new LoginModel { Username = userName });

            }

            catch (Exception ex)

            {

                ModelState.AddModelError("Error", ex.Message);

                return View(new LoginModel { Username = userName });

            }

        }

public async Task<IActionResult> LoginWithAuthenticatorNext(LoginModel model, string returnUrl = null)

        {

            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null && user.IsActive)

            {

                return RedirectToAction("LoginWithAuthenticatorStepTwo", new { user.Email, user.UserName, returnUrl });

            }

            else

            {

                ModelState.AddModelError("Error", "Invalid or Inactive User");

                return View("LoginWithAuthenticatorNext", model);

            }

        }


        public async Task<IActionResult> LoginWithAuthenticatorStepTwo(string email, string userName, string returnUrl)

        {

            try

            {

                var user = await _userManager.FindByEmailAsync(email);

                if (user != null && user.IsActive)

                {

                    return View(new LoginModel { Username = userName });

                }

                else

                {

                    ModelState.AddModelError("Error", "Invalid or Inactive User");

                    return View("LoginWithAuthenticatorStepTwo", new { user.Email, user.UserName, returnUrl });

                }

            }

            catch (Exception ex)

            {

                ModelState.AddModelError("Error", ex.Message);

                return View(new LoginModel { Username = userName });

            }

        }

Method for checking Authenticator

        public async Task<IActionResult> TwoFactorAuthenticate(LoginModel model, string returnUrl = null)

        {

            ViewData["returnUrl"] = returnUrl;

            var version = await _settingService.GetVersionSetting();

            ViewData["downloadURL"] = version.Where(x => x.Name == "DesktopAppURL").FirstOrDefault()?.Key;


            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null && user.IsActive)

            {

                var role = await _userManager.GetRolesAsync(user);

                TwoFactorAuthenticator TwoFacAuth = new TwoFactorAuthenticator();

                string userUniqueKey = user.UniqueAuthenticatorKey;

                bool isLoggedIn = Convert.ToBoolean(HttpContext.Session.GetString("isLoggedIn"));

                bool isValid = TwoFacAuth.ValidateTwoFactorPIN(userUniqueKey, model.OTP, false);

                if (isValid && isLoggedIn)

                {

                    HttpContext.Session.SetString("isLoggedIn", "false");

                    await _appUserService.ResetAuthenticator(user.Id, true);

                    await _signInManager.SignOutAsync();

                    await _signInManager.SignInAsync(user, true);

                    var token = _tokenCreationService.CreateJWTtokenForWeb(user, role.FirstOrDefault());

                    ViewData["Token"] = token.Token;

                    ViewData["RefreshToken"] = token.Refresh_Token;

                    UserRefreshToken obj = new UserRefreshToken

                    {

                        RefreshToken = token.Refresh_Token,

                        UserName = user.UserName,

                        IsActive = true,

                        CreatedAt = DateTime.Now,

                    };


                    _jWTRepository.AddUserRefreshTokens(obj);

                    _jWTRepository.SaveCommit();

                    TempData["LoginName"] = user.FirstName + " " + user.LastName;

                    TempData.Keep("LoginName");

                    return Redirect("/Dashboard");

                }

                else

                {

                    ViewBag.BarcodeImageUrl = HttpContext.Session.GetString("QrCodeSetupImageUrl");

                    ModelState.AddModelError("Error", "Invalid Code");

                    return View("LoginWithAuthenticatorStepTwo", model);

                }

            }

            ViewBag.BarcodeImageUrl = HttpContext.Session.GetString("QrCodeSetupImageUrl");

            ModelState.AddModelError("Error", "Invalid or Inactive User");

            return View("LoginWithAuthenticatorStepTwo", model);

        }


 private static byte[] ConvertSecretToBytes(string secret, bool secretIsBase32) =>

           secretIsBase32 ? Base32Encoding.ToBytes(secret) : Encoding.UTF8.GetBytes(secret);



Reset Authenticator

public async Task<bool> ResetAuthenticator(int userId, bool isReset)

        {

            try

            {

                var user = await _appUserRepository.GetById(userId);

                user.IsAuthenticatorReset = isReset;

                await _appUserRepository.Update(user);

                return true;

            }

            catch

            {

                return false;

            }

        }



Note: so in this authentication, what we are achieving is, let's gather throw points:

i- Authentication setup code and qr code only setup once.

ii- if user deleted the app then he needs to again contact to the admin to reissue the qr code mean a new app.

iii- only one time QR code will show.



.net core migrations

Generate Script 



Package Manager Console


Script-Migration -From 20231221063632_UniqueAuthenticatorKey -To 20231221063632_UniqueAuthenticatorKey


.net CLI


dotnet ef migrations script -i -o "C:\Path\To\Your\Script.sql" -s YourStartupProject -p YourDataProject -from 20231221063632_UniqueAuthenticatorKey -to 20231221063632_UniqueAuthenticatorKey


===============================

No migrations configuration type was found in the assembly 'CompleteDiscoverySource.Website'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration)


EntityFrameworkCore\Add-Migration "migrationName"

===============================



Monday, July 17, 2023

JWT Token

 1. Insall packages

1. System.IdentityModel.Tokens.jwt 6+

2. Microsoft.IdentityModl.TOkens 6+

3. Micorsoft.AspNetCore.Authentication.JwtBearere 3.12

2. Update in Startup.cs File


3. Create the JWTService to generate Tokens in String Format.


4. Sent it whenever login is Successfull.


5. Receive this token in FrontEnd and stroe it in Browser's local storage.

for Angular

6. npm install @auth0/angular-jwt


Git Hub Links:
.NET Core: Fullstack.API  

Angular: Fullstack.UI



Friday, July 7, 2023

issues while working on .net core angular crud

 ===================================================================

Notes

===================================================================





===================================================================

VS Code Extension

these extension are installed when I was working on this project.

Angular Language Service

===================================================================





===================================================================

Issues faced on Angular Side

------------------------------------------------------------------

1- Angular CLI Version

I first install angular cli but due to old node js version it was not installing correctly so I did update the version of node js. but after updating the verion angular cli was

giving me another error:

Error: You need to specify a command before moving on. Use '--help' to view the available commands

so I used this technique to fix the issue

100


Uninstall Angular old version & Install latest version (14)


npm uninstall -g @angular/cli 

npm install -g @angular/cli

Use:


ng version | ng v

Instead of:


ng -v | ng --version


------------------------------------------------------------------

2- Now when I'm running my project after creating new angular project by running command (ng new {projectName}), I'm facing issue on running command: ng serve --open or ng server

issue: ng : File C:\Users\TK-LPT-654\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this system. For more information, 

see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.


you need to give permission to you CurrentUser as RemoteSigned, for this purpose enter the below command:


Set-ExecutionPolicy RemoteSigned -Scope CurrentUser 


one more thing I want to add, I was making a mistake while running this command. I'm running this command on window cammand prompt and I was getting error:

'Get-ExecutionPolicy' is not recognized as an internal or external command,

operable program or batch file.


so do not try to run on cmd instead use the visual studo code terminal and run this command and then it will work perfectly.


after running the above command

run another command

Get-ExecutionPolicy

result: RemoteSigned


also you can run this command 

Get-ExecutionPolicy -list

Result:

        Scope ExecutionPolicy

        ----- ---------------

MachinePolicy       Undefined

   UserPolicy       Undefined

      Process       Undefined

  CurrentUser    RemoteSigned

 LocalMachine       Undefined

------------------------------------------------------------------


I'm using angular 16 and I need to add baseapiurl in the environment but I noticed there is no such folder exists in the system. so now I came to know that in angular 15 and above versions

environment folder has been removed and now If we will have to add manually by running a command: ng g enviroments

then I was able to add the environment.


------------------------------------------------------------------


===================================================================



===================================================================

Issues faced on .NET 6 Side



------------------------------------------------------------------

when I was showing green lines on the model properties so when I tried to remove it by disabling the nullable from the project then I saw many errors

which were saying many type doesn't exist in the current context so I added manually then again I saw I added wrong namespace then I again went to the project

and saw I made a mistake I had disabled the ImplicitUsings instead of Nullable so be careful while changing Nullable.


------------------------------------------------------------------







===================================================================

rough work:

employee model:

id, name, email, phone, salary, department


===================================================================


Wednesday, September 21, 2022

ASP NET CORE ENTITY FRAMEWORK CODE FIRST APPROACH

******************************************************************************

******************************************************************************

//For Entity Framework

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

******************************************************************************

//For Swagger Installation

Install Swashbuckle.AspNetCore.SwaggerUI and Swashbuckle.AspNetCore.SwaggerGen.


Configure Services Method


 services.AddSwaggerGen(c =>

            {

                c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

            });


Configure Method


 app.UseSwagger();

            app.UseSwaggerUI(c =>

            {

                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V1");

            });

******************************************************************************

//For DbContext


public class DataContext: DbContext

    {

        public DataContext(DbContextOptions<DataContext> options): base(options)

        {


        }

        public DbSet<Department> Departments { get; set; }


// Adding Db Context in Configure Services Method in Startup class

services.AddDbContext<DataContext>(options =>

            {

                options.UseSqlServer(Configuration.GetConnectionString("myLocalDb"));

            });


******************************************************************************


// Specific Migration add

Add-Migration -context datacontext(class name in lowercase)


// specific database update

Update-Database -context datacontext


******************************************************************************

adding allowed CORS in Configure Serivces Method in Startup class

services.AddCors(c =>

            {

                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            });


using allowed CORS in Configure Method in Startup class



app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());


******************************************************************************



using static file option

in configure method in startup.cs file

app.UseStaticFiles(new StaticFileOptions

            {

                FileProvider = new PhysicalFileProvider(

                    Path.Combine(Directory.GetCurrentDirectory(),"Photos")),

                RequestPath = "/Photos"

            });


******************************************************************************


Adding Entity

public class DepartmentController : ControllerBase

    {

        private DataContext _dataContext;

        public DepartmentController(DataContext dataContext)

        {

            _dataContext = dataContext;

        }

        [HttpPost]

        public ActionResult<Department> AddDepartment(Department department)

        {

            _dataContext.Departments.Add(department);

            _dataContext.SaveChanges();

            return department;

        }

    }


******************************************************************************

connectionString in appsettings.json

{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft": "Warning",

      "Microsoft.Hosting.Lifetime": "Information"

    }

  },

  "ConnectionStrings": {

    "myLocalDb": "Server=(local)\\SQLEXPRESS;Database= CodeFirstDb;Trusted_Connection = true;MultipleActiveResultSets=True"

  },

  "AllowedHosts": "*"

}


******************************************************************************

******************************************************************************

Thursday, July 16, 2020

setting routes code

const appRoutes: Routes = [
    {
        path: "home",
        component: HomeComponent
    },
    {
        path: "employees",
        component: EmployeeListComponent
    },
    {
        path: "**",
        redirectTo: "/home",
        pathMatch : "full"
    }
];

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(appRoutes)],
    declarations: [AppComponent, EmployeeComponent, TutorialComponent, EmployeeListComponent,
        EmployeeTitlePipe, EmployeeCountComponent, SimpleComponent],
    bootstrap: [AppComponent]
})

Setting Route code

const appRoutes: Routes = [
    {
        path: "home",
        component: HomeComponent
    },
    {
        path: "employees",
        component: EmployeeListComponent
    },
    {
        path: "**",
        redirectTo: "/home",
        pathMatch : "full"
    }
];

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(appRoutes)],
    declarations: [AppComponent, EmployeeComponent, TutorialComponent, EmployeeListComponent,
        EmployeeTitlePipe, EmployeeCountComponent, SimpleComponent],
    bootstrap: [AppComponent]
})

Enable Routing rewrite rules in web config

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/src/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Cross origin error web config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods"
           value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Saturday, July 11, 2020

HttpClient Post Request (with Authentication and Header)

public OutputGetListOfUserContacts PostListOfUserContacts()
        {
            InputGetListOfUserContacts input = new InputGetListOfUserContacts
            {
                UserID = "2",
                PageIndex = "1",
                PageSize = "10"
            };

            using(var client =new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44367/api/");

                var byteArray = Encoding.ASCII.GetBytes("sdsol:CallTranslator99");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

                client.DefaultRequestHeaders.Add("access_token", "my access token value");

                var postTask = client.PostAsJsonAsync<InputGetListOfUserContacts>("v1/Users/GetListOfUserContacts", input);
                postTask.Wait();

                var result = postTask.Result;

                if (result.IsSuccessStatusCode)
                {
                    var responseTask = result.Content.ReadAsAsync<OutputGetListOfUserContacts>();
                    responseTask.Wait();

                    var res = responseTask.Result;
                    return res;
                }
                return new OutputGetListOfUserContacts();
            }
        }

HttpClient Get Request

using(var client = new HttpClient())
            {
                

                client.BaseAddress = new Uri(baseURL);
                var postTask = client.GetAsync("account/credentials/verify");
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    var insertedStudent = new JavaScriptSerializer().Deserialize<ResVerify>(result.Content.ReadAsStringAsync().Result);
                    return insertedStudent;
                    
                }
                else
                {
                    Console.WriteLine(result.StatusCode);
                    return new ResVerify();
                }
            }

Web Api remark code (header etc)


        {

            using (var client = new HttpClient())
            {
                var postJSON = new ReqCreateExtension();
                ReqCreateExtension(ExtensionNumber, Password, FirstName, LastName, Gender, Email, postJSON);

                client.BaseAddress = new Uri(BaseURL);



                //MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
                //HttpContent content = new ObjectContent<ReqCreateExtension>(postJSON, jsonFormatter);
                //HttpRequestMessage request = new HttpRequestMessage()
                //{
                //    RequestUri = new Uri(BaseURL + "extensions/create"),
                //    Method = HttpMethod.Post,
                //    Content = content,
                //    Headers = {
                //    { HttpRequestHeader.Accept.ToString(), "application/json" },
                //    { "access_token", access_token },
                //}
                //};
                //request.Headers.Remove("Content-Length");
                //request.Headers.Add("access_token", access_token);
                //request.Content = new StringContent("{\"access_token\":" + access_token + "}",
                //                                    Encoding.UTF8,
                //                                    "application/json");//CONTENT-TYPE header
                ////client.DefaultRequestHeaders.Add("Content-Type", "application/json");
                //client.DefaultRequestHeaders.Add("access_token", access_token);
                //    var httpRequestMessage = new HttpRequestMessage
                //    {
                //        Method = HttpMethod.Post,
                //        Headers = {
                //    { HttpRequestHeader.Accept.ToString(), "application/json" },
                //    { "access_token", access_token }
                //},
                //        Content = new StringContent(JsonConvert.SerializeObject(postJSON))
                //    };


                client.DefaultRequestHeaders.Add("access_token", access_token);
                var postTask = client.PostAsJsonAsync<ReqCreateExtension>("extensions/create", postJSON);

                postTask.Wait();

                var result = postTask.Result;

                //var result = client.SendAsync(request).Result;
                if (result.IsSuccessStatusCode)
                {

                    var response = new JavaScriptSerializer().Deserialize<ResCreateExtension>(result.Content.ReadAsStringAsync().Result);
                    return response;
                }
                else
                {
                    Console.WriteLine(result.StatusCode);
                    return new ResCreateExtension();
                }
            }
        }

Thursday, July 9, 2020

gallery


upload image to server through ftp of another project (controller actionmethod)

be.HostFilePath = Server.MapPath("/Resources/newsimages/" + NewImageName);
                //be.TransferFilePath = "ftp://184.107.73.104/httpdocs/Images/newsimages/" + NewImageName;
                be.TransferFilePath = "ftp://64.20.42.2/Images/newsimages/" + NewImageName;
                //be.TransferFilePath = "ftp://72.55.184.62/httpdocs/Images/newsimages/" + NewImageName;
                be.FileName = NewImageName;
                bool ISDone = FtpUploads.FtpUploadUsingFileUpload(be);
                sha.news.Photo2 = be.FileName;

upload image to server through ftp of another project

using Microsoft.Ajax.Utilities;
using StudyAbroadMVCAdmin.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace StudyAbroadMVCAdmin.Models.Function
{
    public  class GernalFunction
    {
        public static string ImageCroping(string crop, string Filepath, bool thumbnail)
        {
            if (!String.IsNullOrEmpty(crop))
            {
                var fileName = "";
                var imageStr64 = crop;
                var imgCode = imageStr64.Split(',');

                var bytes = Convert.FromBase64String(imgCode[1]);

                using (var stream = new MemoryStream(bytes))
                {
                    using (var img = System.Drawing.Image.FromStream(stream))
                    {
                        var filename = "";
                        var fileext = "";
                        if (imgCode.Contains("png"))
                        {
                            filename = "Image" + DateTime.UtcNow;
                            fileext = ".png";
                        }
                        else
                        {
                            filename = "Image" + DateTime.UtcNow;
                            fileext = ".jpg";
                        }

                        string fileNameNew = filename;
                        fileNameNew = RemoveSpecialCharacters(fileNameNew);
                        fileNameNew = fileNameNew.Replace(" ", "");

                        var path = HttpContext.Current.Server.MapPath(Filepath);

                        var ext = Path.GetExtension(filename);

                        var i = 0;
                        while (File.Exists(path + fileNameNew + fileext))
                        {
                            i++;
                            fileNameNew = Path.GetFileNameWithoutExtension(filename);
                            fileNameNew += i;
                        }


                        fileName = fileNameNew + fileext;
                        var filePath = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath + Filepath + fileName);
                        File.WriteAllBytes(filePath, bytes);
                        if (thumbnail == true)
                        {
                            string ThumbImgName = fileName.Replace("Image", "Thumb");
                            Resize_Image_Thumb(filePath, fileName, 63, 51, ThumbImgName);
                        }
                    }

                }

                return fileName;
            }
            else
            {
                return null;
            }
        }

        public static void Resize_Image_Thumb(string filePath, string srcImgName, int newWidth, int newHeight, string ThumbImgName)
        {
            //Get Destinatino Path of image
            string newImgName = null;
            string newImagePath = null;
            string imgName = null;
            string imgExt = null;

            string[] NameExtArray = srcImgName.Split(new char[] { '.' });
            imgName = NameExtArray[0];
            imgExt = NameExtArray[1];
            newImgName = ThumbImgName;
            newImagePath = filePath.Replace(srcImgName, ThumbImgName);

            Image imgPhoto = Image.FromFile(filePath);

            int sourceWidth = 0;
            int sourceHeight = 0;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;
            double nPercent = 0;
            double nPercentW = 0;
            double nPercentH = 0;
            sourceWidth = imgPhoto.Width;
            sourceHeight = imgPhoto.Height;
            sourceX = 0;
            sourceY = 0;
            destX = 0;
            destY = 0;

            nPercent = 0;
            nPercentW = 0;
            nPercentH = 0;

            nPercentW = (Convert.ToDouble(newWidth) / Convert.ToDouble(sourceWidth));
            nPercentH = (Convert.ToDouble(newHeight) / Convert.ToDouble(sourceHeight));

            if ((nPercentH < nPercentW))
            {
                nPercent = nPercentW;
                destY = Convert.ToInt32(((newHeight - (sourceHeight * nPercent)) / 2));
            }
            else
            {
                nPercent = nPercentH;
                destX = Convert.ToInt32(((newWidth - (sourceWidth * nPercent)) / 2));
            }

            int destWidth = 0;
            int destHeight = 0;
            destWidth = Convert.ToInt32((sourceWidth * nPercent));
            destHeight = Convert.ToInt32((sourceHeight * nPercent));


            Bitmap bmPhoto = null;
            bmPhoto = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            Graphics grPhoto = null;
            grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);

            grPhoto.Dispose();
            bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmPhoto.Dispose();
            imgPhoto.Dispose();
        }

        

        public void SetCookie(EndUser user)
        {
            HttpCookie AdminCookie = new HttpCookie("AdminCookies");
            AdminCookie.Values["UserName"] = user.user_name.ToString();
            AdminCookie.Values["Password"] = user.password.ToString();
            AdminCookie.Values["ID"] = user.ID.ToString();
            AdminCookie.Values["IsWriter"] = "No";
            HttpContext.Current.Response.SetCookie(AdminCookie);
        }
        public void SetCookieForWriter(EndUser user)
        {
            HttpCookie AdminCookie = new HttpCookie("AdminCookies");
            AdminCookie.Values["UserName"] = user.user_name.ToString();
            AdminCookie.Values["Password"] = user.password.ToString();
            AdminCookie.Values["ID"] = user.ID.ToString();
            AdminCookie.Values["IsWriter"] = "Yes";
            HttpContext.Current.Response.SetCookie(AdminCookie);
        }

        public void CheckAdminLogin()
         {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["AdminCookies"];
            if (cookie == null || String.IsNullOrEmpty(Convert.ToString(cookie)))
            {
                HttpContext.Current.Response.Redirect("/User/Login");
            }
            else if (cookie.Values["IsWriter"] == "Yes")
            {
                HttpCookie Writercookie = HttpContext.Current.Request.Cookies["WriterCookie"];
                if (Writercookie != null)
                {
                    if (Writercookie.Values["Writer"] == "Writer")
                    {
                        HttpContext.Current.Response.Cookies.Remove("WriterCookie");
                        Writercookie.Expires = DateTime.Now.AddDays(-10);
                        Writercookie.Value = null;
                        HttpContext.Current.Response.SetCookie(Writercookie);
                    }
                }
                else
                {
                    HttpContext.Current.Response.Redirect("/User/Login");

                }
            }
            else if (cookie.Values["Password"] == "-")
            {
                string url = "/User/LockScreen?ID=" + cookie.Values["ID"].ToString();
                HttpContext.Current.Response.Redirect(url);

            }

        }
        public void CheckAdminLoginForWriter()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["AdminCookies"];
            if (cookie == null || String.IsNullOrEmpty(Convert.ToString(cookie)) )
            {
                HttpContext.Current.Response.Redirect("/User/Login");
            }
            else if (cookie.Values["IsWriter"] == "No")
            {
                HttpContext.Current.Response.Redirect("/User/Login");
            }
            else if (cookie.Values["Password"] == "-")
            {
                string url = "/User/LockScreen?ID=" + cookie.Values["ID"].ToString();
                HttpContext.Current.Response.Redirect(url);

            }
            else
            {
                HttpCookie CheckWriterCookie = HttpContext.Current.Request.Cookies["WriterCookie"];
                if (CheckWriterCookie == null)
                {
                    HttpCookie AdminCookie = new HttpCookie("WriterCookie");
                    AdminCookie.Values["Writer"] = "Writer";
                    HttpContext.Current.Response.SetCookie(AdminCookie);
                }
                
            }

        }

        public SelectList CitiesList()
        {
            var CategoryList = new SelectList(new CityModel().GetAll().Select(x => new { x.ID, x.cityName }).OrderBy(x => x.cityName).ToList(), "ID", "cityName");
            return CategoryList;
        }

        public SelectList TestList()
        {
            var TestList = new SelectList(new TestModel().GetAllTest().Select(x => new { x.ID, x.Title }).ToList(), "ID", "Title");
            return TestList;
        }

        //public SelectList BrandList()
        //{
        //    var BrandLst = new SelectList(new BrandModel().GetAll().Select(x => new { x.ID, x.Name}).OrderBy(x => x.Name).ToList(), "ID", "Name");
        //    return BrandLst;
        //}

        //public SelectList AlbumList()
        //{
        //    var Album = new SelectList(new AlbumModel().GetAllAlbum().Select(x => new { x.ID, x.Name }).OrderBy(x => x.Name).ToList(), "ID", "Name");
        //    return Album;
        //}

        public void EmailHostDetail(string toEmail, string fromEmail, string subject, string bodyHtml, string fileName)
        {
            //File Path
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Resources\\Files\\";

            //email sending code will appear here.
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();

            message.To.Add(new MailAddress(toEmail));

            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = bodyHtml;

            if (!String.IsNullOrEmpty(fileName))
            {

                //DOING ATTACHMENT:
                Attachment data =
                    new Attachment(filePath + fileName,
                        MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                ContentDisposition disposition = data.ContentDisposition;
                // Add the file attachment to this e-mail message.
                message.Attachments.Add(data);
            }


            string hostname = "smtp.sendgrid.net";// "smtp.gmail.com";
            client.Host = hostname;
            client.Port = 587;
            client.EnableSsl = true;
            string username = "alipk3";
            string password = "Emailsend94";
            message.From = new MailAddress(fromEmail, "NBK");
            var basicCredentials = new System.Net.NetworkCredential(username, password);
            client.Credentials = basicCredentials;
            client.Send(message);
        }
        public static string GetHmtlContentsFromDirectory(string FileName)
        {
            string Result = "";
            string FilePath = HttpContext.Current.Server.MapPath(FileName);
            System.IO.StreamReader MyFile = new System.IO.StreamReader(FilePath);
            Result = MyFile.ReadToEnd();
            MyFile.Close();
            MyFile.Dispose();
            return Result;
        }
        //public static ServiceReference1.EmailsHtml GetHmtlContentsFromDirectoryc( string FileName )
        //{
        //    ServiceReference1.EmailsHtml Result;
        //    string FilePath = HttpContext.Current.Server.MapPath( FileName );
        //    System.IO.StreamReader MyFile = new System.IO.StreamReader( FilePath );
        //    Result = MyFile.ReadToEnd();
        //    MyFile.Close();
        //    MyFile.Dispose();
        //    return Result;
        //}

        public static string RemoveSpecialCharacters(string input)
        {
            Regex r = new Regex("(?:[^a-zA-Z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
            return r.Replace(input, String.Empty);
        }

        public static void ResizePicture(int height, int width, string Filepath, string ResizePicPath)
            {
            Size newsize = new Size();
            newsize.Width = width;
            newsize.Height = height;

            using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(HttpContext.Current.Server.MapPath(Filepath)) as Bitmap)
            {
                using (Graphics newgraphics = Graphics.FromImage(newbmp))
                {
                    newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
                    newgraphics.Save();

                    newbmp.Save(HttpContext.Current.Server.MapPath(ResizePicPath));
                    newbmp.Dispose();
                    newgraphics.Dispose();
                }
            }
        }

        public static string BuildBootstrapPagination(decimal numberOfPages, string url, int pageNo, int NumberofRecordsToBeShown)
        {

            string html = string.Empty;
            html = Pagination(Convert.ToInt32(Math.Ceiling(numberOfPages / NumberofRecordsToBeShown)), pageNo, url);
            return html;

        }

        public static string Pagination(int numberOfPages, int pageNo, string url)
        {
            string html = string.Empty;
            pageNo = pageNo + 1;
            int numericLinksCount = 9;
            int noOfPages = numberOfPages;
            int n = noOfPages;
            if (noOfPages > 9)
            {
                n = 11;
            }

            int series = 0;
            series = pageNo / 9;
            if (pageNo < 10 || pageNo % 9 == 0)
            {
                series = pageNo / 10;
            }


            for (int i = 1; i <= n; i++)
            {
                int page = i + (9 * series);

                if (page > noOfPages)
                {
                    break;
                }

                if (page > 9 && i == 1)
                {
                    int less = page - 1;
                    html += @"<li><a href='/" + url + "?pageno=" + less + "'>Previous</a></li>";
                }

                if (pageNo == page)
                {
                    html += @"<li class='active'><a href='/" + url + "?pageno=" + page + "'>" + page + "</a></li>";
                }
                else
                {
                    if (i == 10)
                    {
                        html += @"<li><a href='/" + url + "?pageno=" + page + "'> Next</a></li>";
                    }

                    if (i < 10)
                    {
                        html += @"<li><a href='/" + url + "?pageno=" + page + "'>" + page + "</a></li>";
                    }
                }
            }
            return html;



        }

        public static string getLinks(string name, string id)
        {
            if (name == null)
            {
                name = "Company";
            }
            if (name.Length > 100)
            {
                name = name.Substring(0, 100);
            }
            string obj = "";
            if (name != null)
            {
                obj = RemoveWhiteSpaces(name) + "-" + id;
            }


            return obj;
        }
        public static string RemoveWhiteSpaces(string ab)
        {
            var re = new Regex("[;\\\\ / .,+=!@%#^)(${}~:*?\"<>|&']");
            ab = re.Replace(ab, "-");
            ab = ab.Replace("--", "-").Replace("--", "-");
            ab = ab.Replace(" ", "-").ToLower();
            ab = ab.TrimEnd('-');
            return ab;
        }

        public static string TrimData(string ab, int a)
        {
            string subab = ab;
            if (subab.Length == 0) return subab;
            if (subab.Length <= a) return subab;
            subab = subab.Substring(0, a);
            subab = subab + " ...";
            return subab;
        }

        public static void SendEmailSMPT(string ToEmail, string Body, string Subject)
        {
            MailMessage message = new MailMessage();
            SmtpClient client = new SmtpClient();
            message.To.Add(new MailAddress(ToEmail));
            message.Subject = Subject;
            message.IsBodyHtml = true;
            message.Body = Body;
            message.From = new MailAddress(ConfigurationManager.AppSettings.Get("MailingAddress").ToString().Trim(), "StudyAbroad.pk");
            //string hostname = ConfigurationManager.AppSettings.Get("MailServerName").ToString().Trim();
            //client.Host = hostname;
            client.Host = "64.20.42.2";
            string username = ConfigurationManager.AppSettings.Get("MailingAddress").ToString().Trim();
            string password = ConfigurationManager.AppSettings.Get("Password").ToString().Trim();
            //message.From = new MailAddress(username);
            System.Net.NetworkCredential basicCredentials = new System.Net.NetworkCredential(username, password);
            client.Credentials = basicCredentials;
            client.Port = 25;// 26;
            client.Send(message);
        }

        public static string CheckImageNameDuplication(string directory, string ImageName)
        {

            var i = 0;
            string filenewName = "";
            string ext = Path.GetExtension(ImageName);
            while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(directory + ImageName)))
            {
                i++;
                filenewName = Path.GetFileNameWithoutExtension(ImageName);
                filenewName += i;
                ImageName = filenewName + ext;
            }
            return ImageName;

        }

        public static void ResizePicture2(ImageResizeBE o)
        {


            Bitmap image = Bitmap.FromFile(HttpContext.Current.Server.MapPath(o.FromSource)) as Bitmap;
            // Get the image's original width and height
            //int originalWidth = image.Width;
            //int originalHeight = image.Height;

            //// To preserve the aspect ratio
            //float ratioX = (float)maxWidth / (float)originalWidth;
            //float ratioY = (float)maxHeight / (float)originalHeight;
            //float ratio = Math.Min(ratioX, ratioY);


            // New width and height based on aspect ratio
            int newWidth = o.ImageWidth;//(int)(originalWidth * ratio);
            int newHeight = o.ImageHeight;// (int)(originalHeight * ratio);

            // Convert other formats (including CMYK) to RGB.
            Bitmap newImage = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
            // Draws the image in the specified size with quality mode set to HighQuality
            Graphics graphics = Graphics.FromImage(newImage);
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.DrawImage(image, 0, 0, newWidth, newHeight);


            // Get an ImageCodecInfo object that represents the JPEG codec.
            System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = GetEncoderInfo(System.Drawing.Imaging.ImageFormat.Jpeg);

            // Create an Encoder object for the Quality parameter.
            System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;

            // Create an EncoderParameters object. 
            System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);

            // Save the image as a JPEG file with quality level.
            System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, o.ImageQuality);
            encoderParameters.Param[0] = encoderParameter;
            newImage.Save(HttpContext.Current.Server.MapPath(o.ToSource), imageCodecInfo, encoderParameters);

            graphics.Dispose();
            newImage.Dispose();
            image.Dispose();
            encoderParameter.Dispose();
            encoderParameters.Dispose();
        }




        private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(System.Drawing.Imaging.ImageFormat format)
        {
            return System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
        }


        public static void ResizePicture3(int height, int width, string path, string filename, string SavePath, double scaleFactor, Stream sourcePath)
        {
            Size newsize = new Size();
            newsize.Width = width;
            newsize.Height = height;

            using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(HttpContext.Current.Server.MapPath(path + filename)) as Bitmap)
            {
                using (Graphics newgraphics = Graphics.FromImage(newbmp))
                {
                    using (var image = Image.FromStream(sourcePath))
                    {
                        newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
                        newgraphics.Save();
                        string newfilename = filename;
                        var newWidth = (int)(image.Width * scaleFactor);
                        var newHeight = (int)(image.Height * scaleFactor);
                        // var thumbnailImg = new Bitmap(newWidth, newHeight);
                        //var thumbGraph = Graphics.FromImage(newbmp);
                        //thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                        //thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                        //thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        //var thumbGraph = Graphics.FromImage(newbmp);
                        newgraphics.CompositingQuality = CompositingQuality.HighQuality;
                        newgraphics.SmoothingMode = SmoothingMode.HighQuality;
                        newgraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        
                        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                        //thumbGraph.DrawImage(image, imageRectangle);
                        var s = HttpContext.Current.Server.MapPath(SavePath + newfilename);
                        newbmp.Save(s, image.RawFormat);
                        newbmp.Dispose();
                        //thumbnailImg.Save(targetPath, image.RawFormat);
                    }


                }
            }
        }

    }

    public static class FtpInformationOthers
    {
        //public static string FTPIP = "72.55.184.62";
        //public static string ftpName = "ftpstudyabroad";
        //public static string ftppassword = "mTrn#@$%^&937";
        //public static string Path = "ftp://72.55.184.62/httpdocs/";

        public static string FTPIP = "64.20.42.2";// "184.107.73.104";
        public static string ftpName = "ftpstudyabroad";
        public static string ftppassword = "2Nxpp2@7";
        public static string Path = "ftp://184.107.73.104/httpdocs/";
    }
    public class FTPBE
    {

        public string HostFilePath { get; set; }

        public string TransferFilePath { get; set; }

        public string FileName { get; set; }
        public bool DeleteFileAfterTransfer { get; set; }
        public FTPBE()
        {


        }
    }

    public static class FtpUploads
    {
        public static bool FtpUploadUsingFileUpload(FTPBE o)
        {

            //string url = HttpContext.Current.Server.MapPath(o.HostFilePath );
            string url = o.HostFilePath;
            string domainname =  o.TransferFilePath;
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(domainname);
            ftp.Credentials = new NetworkCredential(FtpInformationOthers.ftpName, FtpInformationOthers.ftppassword);
            //userid and password for the ftp server to given               

            ftp.KeepAlive = true;

            ftp.UseBinary = true;
            ftp.Proxy = null;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;
            FileInfo fileInfo = new FileInfo(url);
            FileStream fileStream = fileInfo.OpenRead();
            try
            {

                int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];


                Stream uploadStream = ftp.GetRequestStream();
                int contentLength = fileStream.Read(buffer, 0, bufferLength);
                try
                {
                    while (contentLength != 0)
                    {
                        uploadStream.Write(buffer, 0, contentLength);
                        contentLength = fileStream.Read(buffer, 0, bufferLength);
                    }

                    uploadStream.Close();
                    fileStream.Close();

                    uploadStream.Dispose();
                    fileStream.Dispose();
                }
                catch
                {
                    uploadStream.Dispose();
                    fileStream.Dispose();

                }

                ftp = null;
                #region DelFile
                try
                {

                    if (o.DeleteFileAfterTransfer == true)
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(o.HostFilePath + o.FileName));
                    }
                }
                catch
                {


                }
                #endregion


                return true;
            }
            catch
            {
                fileStream.Dispose();
                return false;

            }
        }
    }


}

Two Factor Authentication using .Net Core

Install Package dotnet add package GoogleAuthenticator --version 3.1.1 Model Changes public bool IsAuthenticatorReset { get; set; } public s...