Friday, February 28, 2020

based on number get alphabets in c#


public string GetAlphabets(int number)
{
   string strAlpha = "";
   try
   {
     strAlpha = ((char)number).ToString();
   }
   catch (Exception e)
   {
     string message = e.Message;
     throw;
   }
   return strAlpha;
}


Wednesday, February 26, 2020

An item with the same key has already been added

"exceptionType": "System.ArgumentException",
  "message": "An item with the same key has already been added.",  "exceptionType": "System.ArgumentException",
  "message": "An item with the same key has already been added.",

Solution: In your model or .cs file same keys
Ex: public class Student
{
 public int Sid {set; get;};
 public string Name {get; set;}
 public sting Sid {set; get;} //Same Name - here we will get above exception. if we chnage to another name this issue will resolve.

}

Saturday, February 22, 2020

stop confirm resubmission in page refresh time

<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>

Create hidden or private folder in windows

open notepad and paste below code and save .bat extension. password place changes your password. 

open your saved file. Here automatically create one folder like private. 
if you want to hide that folder open you're saved file it will open one command prompt type here "Y".
again if you want to open the private folder open you're saved file it will open one command prompt type here your password.



Quote: cls

@ECHO OFF
title Folder Private
if EXIST "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" goto UNLOCK
if NOT EXIST Private goto MDENTER PASSWORD TO OPEN
:CONFIRM
echo -----------------------------------------------------------
echo ================== Choulla Naresh ==================
echo -----------------------------------------------------------
echo Are you sure you want to lock the folder(Y/N)
echo Press (Y) for Yes and Press (N) for No.
echo -----------------------------------------------------------
set/p "cho=>"
if %cho%==Y goto LOCK
if %cho%==y goto LOCK
if %cho%==n goto END
if %cho%==N goto END
echo Invalid choice.
goto CONFIRM
:LOCK
ren Private "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
attrib +h +s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
echo Folder locked
goto End
:UNLOCK
echo -----------------------------------------------------------
echo ================== Choulla Naresh ==================
echo -----------------------------------------------------------
echo Enter password to unlock folder
set/p "pass=>"
if NOT %pass%== YOUR PASSWORD goto FAIL
attrib -h -s "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"
ren "Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}" Private
echo Folder Unlocked successfully
goto End
:FAIL
echo Invalid password
goto end
:MDENTER PASSWORD TO OPEN
md Private
echo Private created successfully
goto End
:End

Thursday, February 13, 2020

how to add project to GitHub repository

Open GitHub and create a repository
Next, execute a command in Gitbash
next, take update using GitHub repository URL
paste ur project and commit

Example : URL: https://github.com/C-Naresh/aspdotnet.git

Execute this command in GitBash

echo "# aspdotnet" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/C-Naresh/aspdotnet.git
git push -u origin master

Now take update using this url https://github.com/C-Naresh/aspdotnet.git

Add your existing project inside folder and commit that's it... 

send confirmation email after registration and forgot password in Asp.Net MVC

find out EmailService : IIdentityMessageService

and add these two methods---

public async Task SendAsync(IdentityMessage message)
   {
      await configSendGridasync(message);
   }

   // Use NuGet to install SendGrid (Basic C# client lib)
   private async Task configSendGridasync(IdentityMessage message)
   {
      var myMessage = new SendGridMessage();
      myMessage.AddTo(message.Destination);
      myMessage.From = new System.Net.Mail.MailAddress(
                          "Joe@contoso.com", "Joe S.");
      myMessage.Subject = message.Subject;
      myMessage.Text = message.Body;
      myMessage.Html = message.Body;

      var credentials = new NetworkCredential(
                 ConfigurationManager.AppSettings["mailAccount"],
                 ConfigurationManager.AppSettings["mailPassword"]
                 );

      // Create a Web transport for sending email.
      var transportWeb = new Web(credentials);

      // Send the email.
      if (transportWeb != null)
      {
         await transportWeb.DeliverAsync(myMessage);
      }
      else
      {
         Trace.TraceError("Failed to create Web transport.");
         await Task.FromResult(0);
      }
   }
------------------------------
add keys in web.config

<add key="mailAccount" value="xyz" />
      <add key="mailPassword" value="password" />
-----------------------
find out public async Task<ActionResult> Register(RegisterViewModel model)
Add
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
After
string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            var callbackUrl = Url.Action("ConfirmEmail", "Account",
               new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            await UserManager.SendEmailAsync(user.Id,
               "Confirm your account", "Please confirm your account by clicking <a href=\""
               + callbackUrl + "\">here</a>");
-------------------------
find out public async Task<ActionResult> Register(RegisterViewModel model)
comment await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

and comment return RedirectToAction("Index", "Home");
add
ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                         + "before you can log in.";

         return View("Info");
         //return RedirectToAction("Index", "Home");
=================
create info page shared folder inside
----------
Add attribute in contact page
[Authorize]
public ActionResult Contact()

--------------
findout public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
add
if (!ModelState.IsValid)
    {
        return View(model);
    }
after
// Require the user to have a confirmed email before they can log on.
    var user = await UserManager.FindByNameAsync(model.Email);
    if (user != null)
    {
       if (!await UserManager.IsEmailConfirmedAsync(user.Id))
       {
          ViewBag.errorMessage = "You must have a confirmed email to log on.";
          return View("Error");
       }
    }
---------------
Add error.cshtml inside

@{
   if (String.IsNullOrEmpty(ViewBag.errorMessage))
   {
      <h2 class="text-danger">An error occurred while processing your request.</h2>
   }
   else
   {
      <h2 class="text-danger">@ViewBag.errorMessage</h2>
   }
}
------------
find out public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
Add
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
        {
            // Don't reveal that the user does not exist or is not confirmed
            return View("ForgotPasswordConfirmation");
        }
after
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
        var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
        await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
        return RedirectToAction("ForgotPasswordConfirmation", "Account");

-------------------
uncomment Login.cshtml
inside
forget password link
-------
Add method
private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject)
{
   string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
   var callbackUrl = Url.Action("ConfirmEmail", "Account",
      new { userId = userID, code = code }, protocol: Request.Url.Scheme);
   await UserManager.SendEmailAsync(userID, subject,
      "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

   return callbackUrl;
}

How to check which version of .NET Framework I have installed in Command prompt

Goto To run and enter this path and "%windir%\Microsoft.NET\FrameWork" and enter 

next, find out latest version like "v4.0.30319" and open this folder

copy location and run cmd in administrator mode

Cd C:\WINDOWS\Microsoft.NET\FrameWork\v4.0.30319 press enter 

next, execute this command ".\MSBuild.exe -version" and enter that's it njoy... 

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.

https://www.google.com/settings/security/lesssecureapps

Allow less secure apps: OFF to On 

'Y' already has a dependency defined for 'Z' in Nuget


This has been solved by installing the latest NuGet package manager

https://visualstudiogallery.msdn.microsoft.com/4ec1526c-4a8c-4a84-b702-b21a8f5293ca

Don't forget to re-launch or (close and open) Visual Studio.

Monday, February 10, 2020

How to add a virtual directory..

Before adding a virtual directory we need to add authentication in two applications authentication web.server starting.
It will only work if it's in this order

Custom Registration In ASP.NET MVC

1.Add new properties
click Ctrl + F and find "ApplicationUser : IdentityUser"

public class ApplicationUser : IdentityUser
    {
        //New properties
        public string FirstName { get; set; }

        public string LastName { get; set; }
        // existing code
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }
2.Find out "public class RegisterViewModel"
Add new properties in this model
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

3.find out "public async Task<ActionResult> Register(RegisterViewModel model)"
Add properties in

var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
FirstName = model.FirstName, //new property
LastName = model.LastName    //new property
};

and build application

4. Goto Tools > NuGet Package Manager > Click "Package Manager Console"
Now add the following commands in Console Manager
  1. Enable-Migrations

  2. Add-Migration UpdateTable

  3. Update-Database –verbose

Build and Run the application


an unhandled exception of type 'system.typeinitializationexception' occurred in c# (or) web.config

Solution: Check once the web.config file. Case sensitive Issue

<configsections> to <configSections>
<appsettings> to <appSettings>

Chain of Responsibility Design Pattern


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

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Management management = new Management(null);
Exp exp = new Exp(management);
Employee emp = new Employee(exp);
emp.HandleRequest(30000);
emp.HandleRequest(25000);
emp.HandleRequest(10000);
Console.ReadLine();
}
public interface Ihandle
{
void HandleRequest(int id);
}
public class Employee :Ihandle
{
Ihandle _handle;
public Employee(Ihandle handle)
{
this._handle = handle;
}
public void HandleRequest(int id)
{
if (id > 1000 && id <= 10000)
{
Console.WriteLine("Fresher");
}
else if (this._handle != null)
{
this._handle.HandleRequest(id);
}
}
}

public class Exp : Ihandle
{
private Ihandle _handle;
public Exp(Ihandle handle)
{
this._handle = handle;
}
public void HandleRequest(int id)
{
if(id>=10001 && id<=20000)
{
Console.WriteLine("Experienced");
}
else if(this._handle!=null)
{
this._handle.HandleRequest(id);
}
}
}
public class Management : Ihandle
{
Ihandle _handle;
public Management(Ihandle handle)
{
this._handle = handle;
}
public void HandleRequest(int id)
{
if(id>=20001 &&id <= 30000)
{
Console.WriteLine("Management");
}
else if(this._handle!=null)
{
this._handle.HandleRequest(id);
}
}
}
}
}


Wednesday, February 5, 2020

Interface with real time Example


Interface means a class that has no implementation of its method, but with just declaration. Other hand, abstract class is a class that can have implementation of some method along with some method with just declarationno implementation.

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

namespace ConsoleApplication1
{
//interface no implementation only declaration
internal interface interfaceName
{
int GetSalary();
}
public class Fresher : interfaceName
{
public int GetSalary()
{
return 10000;
}
}
public class ExpSalary : interfaceName
{
public int GetSalary()
{
return 20000;
}

}
internal class Program
{
public static void Main(string[] args)
{
Fresher fresher = new Fresher();
int fresherSal = fresher.GetSalary();
Console.WriteLine(fresherSal.ToString());
ExpSalary exp = new ExpSalary();
int expSal = exp.GetSalary();
Console.WriteLine(expSal.ToString());
Console.ReadLine();
}
}
}


Abstract with real time Example


Abstract methods implementation and non-implementation method like

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.


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

namespace ConsoleApplication1
{
//Abstart methods implemetation and non implemetation method like

//abstract Class
public abstract class AbstractClass
{
public abstract void salary();

public void GetEmpName()
{
Console.WriteLine("Naresh");
}


}

//derived class

public class FresherSalary : AbstractClass //inheriting from abstract class
{
public override void salary()

{
Console.WriteLine("Fresher Salary = 10000");
}

}

public class ExpSalary : AbstractClass //inherting from abstract class

{
public override void salary()
{
Console.WriteLine("Exp salary = 20000");
//Console.ReadLine();
}

}

internal class Program
{
public static void Main(string[] args)
{
FresherSalary fresher = new FresherSalary(); //Creating object for fresher
fresher.salary();
ExpSalary exp = new ExpSalary();
exp.salary();
//and calling implemented method in abstart class
exp.GetEmpName();
Console.ReadLine();
}
}
}