Right Click Is Disabled...

Author name: Nayan Makvana

NuGet packages

Create and publish a NuGet package using Visual Studio

  1. Visual Studio 2022 Installation:
    • To begin, you’ll need to install Visual Studio 2022 for Windows. This can be done by downloading the free Community edition from visualstudio.microsoft.com. Alternatively, if you possess licenses, you can opt for the Professional or Enterprise edition.
  2. NuGet Capabilities:
    • Visual Studio 2017 and later versions automatically incorporate NuGet capabilities upon installing any .NET-related workload. This simplifies package management within your projects.
  3. .NET CLI Installation (if necessary):
    • If the .NET CLI (Command Line Interface) isn’t already installed on your system, it’s essential to do so. For Visual Studio 2017 and newer versions, the .NET CLI comes bundled with any .NET Core-related workload installation. However, if you’re using a different setup or require standalone installation, you’ll need to install the .NET Core SDK. The .NET CLI is particularly crucial for projects utilizing the SDK-style format, indicated by the SDK attribute. Notably, the default .NET class library template in Visual Studio 2017 and later incorporates the SDK attribute.

Registration and Installation

Before you can leverage NuGet’s package management capabilities and effectively contribute to the .NET ecosystem, it’s imperative to complete a few initial steps to register and install the necessary tools. This preface outlines the essential actions required to ensure seamless integration with NuGet.

  1. NuGet.org Account Registration:
    • If you haven’t already, you’ll need to register for a free account on nuget.org. This account is pivotal for managing and uploading NuGet packages. Upon registration, be sure to confirm your account to unlock its full functionality.
  2. NuGet CLI Installation:
    • To interact with NuGet from the command line, you’ll need to install the NuGet CLI. This can be accomplished by downloading the nuget.exe file from nuget.org. Once downloaded, place the nuget.exe file in a suitable directory and ensure that this directory is added to your system’s PATH environment variable. This enables seamless access to the NuGet CLI from any command prompt or terminal session.

By completing these preliminary steps, you’ll be equipped with the necessary credentials and tools to seamlessly integrate NuGet into your development workflow. Let’s proceed with these setup tasks to ensure a smooth transition into utilizing NuGet for package management within your .NET projects.

Creating a Class Library Project

Before you embark on the journey of packaging your code into a NuGet package, you’ll need to establish a foundation by creating a class library project. This preface provides step-by-step guidance on setting up your project within Visual Studio.

  1. Launch Visual Studio and Begin Project Creation:
    • Open Visual Studio and navigate to the menu bar. From there, select File > New > Project to initiate the project creation process.
  2. Specify Project Type and Template:
    • In the “Create a new project” window, ensure that you’ve selected C# as the programming language, Windows as the platform, and Library as the project type from the dropdown lists.
  3. Choose Class Library Template:
    • From the list of project templates, locate and select Class Library. This template is designed for creating a class library that targets either .NET or .NET Standard. Proceed by selecting Next.
  4. Configure Project Details:
    • In the “Configure your new project” window, designate a meaningful name for your project, such as calculator. Then, select Next to proceed.
  5. Select Framework and Create Project:
    • In the “Additional information” window, choose an appropriate framework for your project. If uncertain, opting for the latest framework version is a prudent choice, as it can be adjusted later if needed. Once you’ve made your selection, proceed by selecting Create.
  6. Verify Project Creation:
    • To ensure the successful creation of your project, navigate to Build > Build Solution. Confirm that the project builds without errors. You can locate the resulting DLL within the Debug folder (or Release if that configuration was used).
  7. Optional: Add Functional Code (if desired):
    • While not necessary for this quickstart, you have the option to include additional code within your class library project. If you opt to do so, you can add the provided functional code to enhance the functionality of your NuGet package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Calc
{
    public class Calculator
    {
        public int Add(int x, int y)
        {
            return x+y;
        }
    }
}

Configuring Package Properties

Once your project is established, the next crucial step is configuring the properties of your NuGet package. This preface provides a comprehensive guide on customizing the settings of your package within Visual Studio.

  1. Navigate to Project Properties:
    • Begin by selecting your project within the Solution Explorer. Then, navigate to Project > [Your Project Name] Properties. Replace [Your Project Name] with the actual name of your project.
  2. Access Package Settings:
    • Within the project properties window, locate and expand the Package node. From there, select General to access the package properties.
  3. Note on SDK-style Projects:
    • It’s important to note that the Package node only appears for SDK-style projects in Visual Studio. If your project is targeting a non-SDK style (typically .NET Framework), you have two options:
      • Migrate the project to an SDK-style project to access the package settings within Visual Studio.
      • Refer to alternative resources such as “Create and publish a .NET Framework package” for step-by-step instructions tailored to non-SDK style projects.

Give your package a unique Package ID and fill out any other desired properties. For a table that shows how MSBuild properties (SDK-style projects) map to .nuspec file properties, see pack targets. For a description of .nuspec file properties, see the .nuspec file reference. All of these properties go into the .nuspec manifest that Visual Studio creates for the project.

Running the Pack Command

  1. Set Active Solution Configuration:
    • Begin by navigating to Build > Configuration Manager within Visual Studio. From there, ensure that the active solution configuration is set to Release. This configuration ensures that the generated NuGet package is optimized for distribution.
  2. Select Project and Pack:
    • Next, locate and select your project (in this case, the “Calculator ” project) within the Solution Explorer. With the project selected, choose the Pack option. This action prompts Visual Studio to initiate the packaging process.
  3. Package Creation:
    • Visual Studio will then proceed to build your project and create the corresponding NuGet package. Upon completion, the .nupkg file, containing your packaged project, will be generated.
  4. Examine Output Details:
    • To confirm the successful creation of the NuGet package, examine the Output window within Visual Studio. This window provides detailed information about the build process, including the path to the generated package file. Typically, the path will be within the “bin\Release\net8.0” directory, corresponding to a .NET 8.0 target.

Publish the package

Acquiring Your API Key

Prior to publishing your NuGet package, it’s essential to create an API key to authenticate the publishing process. This preface outlines the steps required to generate and acquire your API key from nuget.org.

  1. Sign into nuget.org:
    • Begin by signing into your nuget.org account. If you don’t have an account already, you’ll need to create one to proceed.
  2. Navigate to API Keys:
    • After signing in, locate your user name at the upper right corner of the screen. Click on your user name, and then select API Keys from the dropdown menu.
  3. Create API Key:
    • Within the API Keys section, select Create. You’ll be prompted to provide a name for your key to help identify its purpose.
  4. Select Push Scope:
    • Under Select Scopes, ensure that Push is selected. This scope grants the necessary permissions for pushing packages to nuget.org.
  5. Define Package Glob Pattern:
    • In the Select Packages > Glob Pattern field, enter an asterisk (*) to allow pushing packages with any name.
  6. Generate API Key:
    • Once all necessary configurations are in place, select Create to generate your API key.
  7. Copy API Key:
    • After the key is created, select Copy to copy the newly generated API key to your clipboard. This key will be used to authenticate the publishing process when pushing your NuGet package.

Publish with the .NET CLI or NuGet CLI

Each of the following CLI tools allows you to push a package to the server and publish it. Select the tab for your CLI tool, either .NET CLI or NuGet CLI.

Using the .NET CLI (dotnet.exe) is the recommended alternative to using the NuGet CLI.

From the folder that contains the .nupkg file, run the following command. Specify your .nupkg filename, and replace the key value with your API key.

dotnet nuget push Contoso.08.28.22.001.Test.1.0.0.nupkg --api-key qz2jga8pl3dvn2akksyquwcs9ygggg4exypy3bhxy6w6x6 --source https://api.nuget.org/v3/index

Use NuGet package in other project

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

namespace NayanTest
{
    public class test
    {
        public void MyMethod()
        {
            // Create an instance of the Calculator class
            Calculator calculator = new Calculator();

            // Now you can use the methods of the Calculator class
            int result = calculator.Add(5, 10);
            Console.WriteLine("Result of addition: " + result);
        }
    }
}

Create and publish a NuGet package using Visual Studio Read More »

OAuth 2.0 Using Asp .Net Core

What Is OAuth?

OAuth, which stands for “Open Authorization,” allows third-party services to exchange your information without you having to give away your password.

The OAuth (open authorization) protocol was developed by the Internet Engineering Task Force and enables secure delegated access. It lets an application access a resource that is controlled by someone else (end user). This kind of access requires Tokens, which represent delegated right of access.

It’s a process through which an application or website can access private data from another website. It provides applications the ability for “secure designated access.” For example, you can tell Google that it’s OK for abc.com to access your google account or contact without having to give abc.com your google password.

OAuth never share password data but instead uses authorization tokens to prove an identity between consumers and service providers. OAuth is an authentication protocol that allows you to approve one application interacting with another on your behalf without giving away your password.

The Authorization Code Flow

Flow

The client redirects the user to the authorization server having the following parameters in the query string.

Step 1

  • response_type having the value code
  • client_id having the client identifier
  • redirect_uri having the client redirect URI.
  • scope a space-delimited list of scopes
  • state having a random string

After successful authentication, the user will be redirected to the Consent screen where he needs to provide consent to abc.com to access the account detail.

Authorization code is generated by the authorization server and sent back to the client with redirect Uri.

Step 2

The client will now send a POST request to the authorization server with the following parameters:

  • Grant_type having the value of authorization_code
  • Client_id having the client identifier
  • Client_secret having the client secret
  • Redirect_uri having the same redirect URI the user redirected back.
  • Code having the authorization code from the query string

In the entire flow, the access token is never exposed to a web browser.
The client will ask the user for their authorization credentials (usually a username and password). The client then sends a POST request with following body parameters to the authorization server:

  • Grant_type having the value password
  • Client_id having the client’s ID
  • Client_secret having the client’s secret
  • Scope having a space-delimited list of requested scope permissions.
  • Username having a user’s username
  • Password having a user’s password

Client Credentials Grant

Using this flow the client can request an access token using only its client credentials (or other supported means of authentication). 

Asp .Net OAuth Using Github Example

->First Open GitHub  then Click on Profile -> settings -> Developer Setting ->OAuth Apps 

Display Below Screen After that and click on New OAuth App

Filling details for register a new OAuth application And then Click Register application.

If you have completed register successfully then showing below OAuthWithGitHub screen. Here show your Client Id and Client Secrets. Click on Generate a new Client Secrets For generating your own secrets.

Now Next Step is Create Asp .Net Core App

Here we need some packages for more process. so keep install below following packages.

AspNet.Security.OAuth.GitHub
Microsoft.AspNetCore.Authentication.Cookies
Microsoft.AspNetCore.Authentication.OAuth

launchSetting.json File

{
    "GitHub": {
        "ClientId": "0aa85390cf6d6c0018bd",
        "ClientSecret": "411661edf9968c89390b21f486800a26cd153a54"
    },
    "linkedin": {
        "clientid": "75xcbb4icwltx3",
        "clientSecret": "giSng0gfq81DTUzZ"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "AllowedHosts": "*"
}

Set port number given in github oauth Registration and give Secure Connection.

Startup.cs File

using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace OAuthApplication
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        private IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Step 1. Add Authentication Mechanisms
            services.AddAuthentication(o =>
            {
                o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(o =>
            {
                // set the path for the authentication challenge
                o.LoginPath = "/signin";
                
                // set the path for the sign out
                o.LogoutPath = "/signout";
            })
            .AddGitHub(o =>
            {
                 o.ClientId = Configuration["github:clientId"];
                 o.ClientSecret = Configuration["github:clientSecret"];
                 o.CallbackPath = "/signin-github";
                 // Grants access to read a user's profile data.
                 o.Scope.Add("read:user");
                 // Optional
                 // if you need an access token to call GitHub Apis
                 o.Events.OnCreatingTicket += context =>
                 {
                     if (context.AccessToken is { })
                     {
                         context.Identity?.AddClaim(new Claim("access_token", context.AccessToken));
                     }
                     return Task.CompletedTask;
                 };
            });
            services.AddRazorPages();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            
            // 2. add Authentication and Authorization Middleware
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                // 3. Sign out Endpoint
                // go to ./Pages/Signin.cshtml for 4.
                endpoints.MapGet("/signout", async ctx =>
                {
                    await ctx.SignOutAsync(
                     CookieAuthenticationDefaults.AuthenticationScheme,
                    new AuthenticationProperties
                    {
                        RedirectUri = "/"
                    });
                });
            });
        }
    }
}

Here You can Acces user Access Token if you needed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.DependencyInjection;
namespace OAuthApplication.Pages
{
    public class Signin : PageModel
    {
        public IEnumerable<AuthenticationScheme> Schemes { get; set; }
        [BindProperty(SupportsGet = true)]
        public string ReturnUrl { get; set; }
        public async Task OnGet()
        {
            Schemes = await GetExternalProvidersAsync(HttpContext);
        }
        public async Task<IActionResult> OnPost([FromForm] string provider)
        {
            if (string.IsNullOrWhiteSpace(provider))
            {
                return BadRequest();
            }
            return await IsProviderSupportedAsync(HttpContext, provider) is false
             ? BadRequest()
             : Challenge(new AuthenticationProperties
             {
                 RedirectUri = Url.IsLocalUrl(ReturnUrl) ? ReturnUrl : "/"
             }, provider);
        }

       private static async Task<AuthenticationScheme[]> GetExternalProvidersAsync(HttpContext context)
        {
            var schemes = context.RequestServices.GetRequiredService<IAuthenticationSchemeProvider>();
            return (await schemes.GetAllSchemesAsync())
             .Where(scheme => !string.IsNullOrEmpty(scheme.DisplayName))
             .ToArray();
        }

        private static async Task<bool> IsProviderSupportedAsync(HttpContext context, string provider) =>
        (await GetExternalProvidersAsync(context))
        .Any(scheme => string.Equals(scheme.Name, provider, StringComparison.OrdinalIgnoreCase));
    }
}

Write Above Code in Signin.Cshtml.cs File to set retunUrl this file works like Controller Define Your methods. 

@page
@model OAuthApplication.Pages.Signin
@{
}
<div class="jumbotron">
    <h1>Authentication</h1>
    <p class="lead text-left">Sign in using one of these external providers:</p>
    @foreach (var scheme in Model.Schemes.OrderBy(p => p.DisplayName))
    {
        <form asp-page="SignIn" method="post">
            <input type="hidden" name="Provider" value="@scheme.Name" />
            <input type="hidden" name="ReturnUrl" value="@Model.ReturnUrl" />
            <button class="btn btn-lg btn-success m-1" type="submit">
                Sign in using @scheme.DisplayName
            </button>
        </form>
    }
</div>

Above Code is Signin.Cshtml file here fetach the user details and redirect our website. 

After that Display User Data in our Website.

Below Code is Account.Cshtml.Cs File To list Out User data.

using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OAuthApplication.Models;
using Octokit;
namespace OAuthApplication.Pages
{
    [Authorize]
    public class Account : PageModel
    {
        public async Task OnGet()
        {
            // We are reading claims that were
            //    supplied from our OpenID provider
            Claims = User.Claims.ToList();
            // From GitHub
            if (User.AccessToken() is { } accessToken)
            {
                var client = new GitHubClient(new ProductHeaderValue("test"))
                {
                    Credentials = new Credentials(accessToken)
                };
                GitHubUser = await client.User.Get(User.Identity?.Name);
            }
        }
        public User GitHubUser { get; set; }
        public List<Claim> Claims { get; set; }
    }
}

 This Is Account.CsHtml File Code.

@page
@model OAuthApplication.Pages.Account
@{
    var Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/";
}
<h2>User Claims</h2>
<table class="table table-bordered table-striped">
    <thead>
    <tr>
        <th>Type</th>
        <th>Value</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var claim in Model.Claims)
    {
        <tr>
            <td>@claim.Type.Replace(Uri, string.Empty)</td>
            <td>
                @if (claim.Type == "access_token")
                {
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="access-token">
                                &#128065;
                            </span>
                        </div>
                        <input id="access-token" 
                               type="password" value="@claim.Value" 
                               onclick="toggleVisibility(this)" 
                               class="form-control" 
                               title="click me to reveal password" />
                    </div>
                }
                else
                {
                    @claim.Value                    
                }
            </td>
        </tr>
    }
    </tbody>
</table>
@if (Model.GitHubUser is {})
{
    <h2>GitHub Octokit Response</h2>
    <table class="table table-bordered table-striped">
        <thead>
        <tr>
            <th>Type</th>
            <th>Value</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>@nameof(Model.GitHubUser.Bio)</td>
            <td>@Model.GitHubUser.Bio</td>
        </tr>
        <tr>
            <td>@nameof(Model.GitHubUser.Location)</td>
            <td>@Model.GitHubUser.Location</td>
        </tr>
        <tr>
            <td>@nameof(Model.GitHubUser.AvatarUrl)</td>
            <td>
                <img src="@Model.GitHubUser.AvatarUrl" alt="avatar"/>
            </td>
        </tr>
        </tbody>
    </table>
}

Source code

Source code for this sample is available on GitHub at https://github.com/xtsofttech/OAuthApplication

OAuth 2.0 Using Asp .Net Core Read More »