<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Johnson on Medium]]></title>
        <description><![CDATA[Stories by Johnson on Medium]]></description>
        <link>https://medium.com/@jermaine_jay?source=rss-84d943c4e76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZlWZ987lseW0DRGlv3vhDQ.png</url>
            <title>Stories by Johnson on Medium</title>
            <link>https://medium.com/@jermaine_jay?source=rss-84d943c4e76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:24:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jermaine_jay/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Set Up Microsoft Authentication with Azure AD, MSAL integration with Angular, and ASP.NET]]></title>
            <link>https://medium.com/@jermaine_jay/how-to-set-up-microsoft-authentication-with-azure-ad-msal-integration-with-angular-and-asp-net-682b5dfe52d0?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/682b5dfe52d0</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 11:06:33 GMT</pubDate>
            <atom:updated>2026-01-05T15:15:42.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*SjoVpEJGtfYX4kTDKbrCUA.png" /></figure><p>OpenID providers like Microsoft are utilized to enable individuals to access resources on certain sites using single sign-on (SSO). Please visit the <a href="https://medium.com/@jermaine_jay/oauth-tokens-explained-a-complete-overview-of-oauth-tokens-375d3fb62c1c">OAuth token overview</a> to learn more about OAuth tokens.</p><p>This article details the implementation of authentication using Microsoft Azure Active Directory (Azure AD) in a single-page application built with Angular. It utilizes the Microsoft Authentication Library for Angular 16 (MSAL) and explains how to manage the data collected from this login using an ASP.NET Core web API.</p><h4>What You Will Learn</h4><p>— How to register an application in Azure AD<br> — How to configure MSAL in Angular<br> — How to secure an ASP.NET Core API<br> — How to pass and validate authentication tokens</p><h4>Prerequisites</h4><p>— Basic knowledge of Angular<br> — Basic knowledge of ASP.NET Core<br> — An Azure account<br> — Node.js and .NET SDK installed</p><blockquote>You can also visit <a href="https://www.pingidentity.com/en/resources/identity-fundamentals/authentication/single-sign-on.html">single sign-on operations</a>, <a href="https://openid.net/connect/">OpenID Connection</a>s, and <a href="https://auth0.com/intro-to-iam/what-is-oauth-2">Oauth 2.0</a> to learn more about what this post will discuss.</blockquote><h4>Register Your Application in Azure AD</h4><p>First, ensure you have a Microsoft 365 (formerly Office 365) account. Then, log in to your <a href="https://portal.azure.com/">Azure portal account</a> using your Outlook email address. Click on App Registration, and then click on New Registration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuWDVO4TLba1a9j5Dx9e4w.png" /></figure><p>Next, assign a name to your new application and select a supported account type, ideally one that accommodates multiple tenants for broader accessibility. For the Redirect URL, select Single Page Application (SPA), add your <a href="https://localhost:4200/">local Angular application</a> URL, and click register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6LUNSIh5-6pWWx51cIGWQ.png" /></figure><p>Next, obtain and record the Client ID and Tenant ID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r4TYfzAWE9BQGje9XniEQ.png" /></figure><p>Next, click Authentication. Add the Angular app URL for a single-page application, scroll down, and check the boxes for the token you want it to return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lev9aNTwtKFUYUC6kgeyzQ.png" /></figure><p>After checking these boxes, click save to make changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*17xcJQi9dNohXy2dalU3Ew.png" /></figure><p>Now, add permissions to our new application to retrieve user data. Go to API permissions &gt;&gt; Add a permission &gt;&gt; Microsoft Graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmPawO0PLONk-GUuLWQseQ.png" /></figure><p>Select the necessary permissions to get users&#39; data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bll-Rg04SG70jLVTZ-r7UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x63hMX0POp7_MfcpjfsUFA.png" /></figure><p>With these steps, the application can retrieve a JWT token.</p><h4>Configure MSAL in Angular</h4><p>To integrate Azure AD MSAL with Angular for single sign-on, follow these steps:</p><ol><li><strong>Create a new Angular application:</strong> we will create an app called “<em>LoginWithMicrosoft”</em>.</li></ol><pre>ng new LoginWithMicrosoft</pre><p>And then navigate to the project directory.</p><pre>cd LoginWithMicrosoft</pre><p><strong>2.</strong> <strong>Add the dependencies to the new project:</strong> Install the MSAL Angular library and MSAL Browser in your Angular application.</p><pre>npm i @azure/msal-angular @azure/msal-browser</pre><p><strong>3. Set up MSAL configuration in app.module.ts file: </strong>In the app.module.ts file. This configuration defines key details such as the client ID from your registered app on the Azure AD portal, authority URL, and redirect URI.</p><pre>import { APP_INITIALIZER, NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { AppRoutingModule } from &#39;./app-routing.module&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br>import { MsalModule, MsalInterceptor, MsalService, MSAL_INSTANCE, MsalGuardConfiguration, MSAL_GUARD_CONFIG, MsalInterceptorConfiguration, MSAL_INTERCEPTOR_CONFIG } from &#39;@azure/msal-angular&#39;;<br>import { PublicClientApplication, InteractionType } from &#39;@azure/msal-browser&#39;;<br>import { HTTP_INTERCEPTORS, HttpClientModule } from &#39;@angular/common/http&#39;;<br><br>const msalConfiguration = environment.mslConfig;<br><br>function MSALInstanceFactory() {<br>  return new PublicClientApplication({<br>    auth:{<br>      clientId:  msalConfiguration.clientId,<br>      redirectUri:  msalConfiguration.redirectUri,<br>      authority: msalConfiguration.authority,<br>    },<br>  });<br>}<br><br>function MSALGuardConfigFactory(): MsalGuardConfiguration {<br>  return {<br>    interactionType: InteractionType.Redirect,<br>    authRequest: {<br>      scopes: [&#39;user.read&#39;]<br>    }<br>  };<br>}<br><br>function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {<br>  const protectedResourceMap = new Map&lt;string, Array&lt;string&gt;&gt;();<br>  protectedResourceMap.set(&#39;https://graph.microsoft.com/v1.0/me&#39;, [&#39;user.read&#39;]);<br>  return {<br>    interactionType: InteractionType.Redirect,<br>    protectedResourceMap<br>  };<br>}<br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    AppRoutingModule,<br>    HttpClientModule,<br>    MsalModule,<br>  ],<br>  providers: [<br>    {<br>      provide: MSAL_INSTANCE,<br>      useFactory: MSALInstanceFactory<br>    },<br>    {<br>      provide: MSAL_GUARD_CONFIG,<br>      useFactory: MSALGuardConfigFactory<br>    },<br>    {<br>      provide: MSAL_INTERCEPTOR_CONFIG,<br>      useFactory: MSALInterceptorConfigFactory<br>    },<br>    {<br>      provide: HTTP_INTERCEPTORS,<br>      useClass: MsalInterceptor,<br>      multi: true<br>    },<br>    MsalService,<br>    {<br>      provide: APP_INITIALIZER,<br>      useFactory: (msalService: MsalService) =&gt; () =&gt; msalService.instance.initialize(),<br>      deps: [MsalService],<br>      multi: true<br>    },<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p><strong>4. Setup Environment.ts File:</strong> Create an Environment.ts file, which will hold every authentication key and URL.</p><pre>export const environment = {<br>  msalConfiguration: {<br>    clientId: &quot;your-registered-app-clientId&quot;,<br>    authority: &quot;https://login.microsoftonline.com/your-registered-app-tenantId&quot;,<br>    redirectUri: &#39;http://localhost:4200/&#39; // redirect the application authentication<br>  },<br>  apiConfiguration: {<br>    baseUrl: &quot;https://localhost:5000&quot;,<br>    path: &quot;/api/OpenIdConfig/outlook-user&quot;,<br>  }<br>};</pre><p><strong>5. Setup Services.ts File:</strong> Create a Services.ts file, let us call the name of the service “<strong><em>API</em></strong>”, then run this command:</p><pre>ng generate service services/Api</pre><pre>import { HttpClient, HttpHeaders } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { environment } from &#39;src/environments/environment&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ApiService {<br><br>  readonly fullUrl = `${environment.baseUrl}${environment.path}`;<br>  constructor(private http: HttpClient) { }<br><br>  validateToken(token: string): Observable&lt;any&gt; {<br>    const headers = new HttpHeaders({ &#39;Content-Type&#39;: &#39;application/json&#39; });<br>    return this.http.post&lt;any&gt;(`${this.fullUrl}`,JSON.stringify({token}), {headers: headers} );<br>  }<br>}</pre><p><strong>6. Set up the app.Component.ts File:</strong> In the app.component.ts file, add the MsalService, the Service we created in step 5 (Apiservice), in the constructor, and call the validateToken method in the ngOnInit class.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { MsalService } from &#39;@azure/msal-angular&#39;;<br>import { AuthenticationResult } from &#39;@azure/msal-browser&#39;;<br>import { ApiService } from &#39;./services/api.service&#39;;<br><br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br><br>export class AppComponent implements OnInit {<br>  <br>  user: any;<br>  loggedIn: boolean = false;<br><br>  constructor(private msalService: MsalService,private service: ApiService) {}<br><br>  ngOnInit(): void {<br>    this.msalService.instance.handleRedirectPromise().then((response) =&gt; {<br><br>      if (response) {<br>        const token = response.idToken;<br><br>        this.service.validateToken(token).subscribe(<br>          (apiResponse) =&gt; {<br>            console.log(&#39;API Response:&#39;, apiResponse);<br>          },<br>          (error) =&gt; {<br>            console.error(&#39;Error sending token to API:&#39;, error);<br>          }<br>        );<br>      } else {<br>        console.log(&#39;No redirect response&#39;);<br>      }<br><br>      this.loggedIn = (this.users != null);<br>      if (this.loggedIn) {<br>        console.log(&#39;User Token: &#39;, this.users); <br>      }<br>    }).catch(error =&gt; {<br>      console.error(&quot;Error handling redirect promise:&quot;, error);<br>    });<br>  }<br><br>  async login() {<br>    this.msalService.loginRedirect();<br>  }<br><br>  async logout() {<br>    this.msalService.logout();<br>  }<br>}</pre><p><strong>7. Designing the app.component.html File:</strong> Customize the structure and layout of your Angular application’s main component by editing this file</p><pre>&lt;div&gt;<br>  &lt;div *ngIf=&quot;!loggedIn&quot; class=&quot;sign-in-buttons&quot;&gt;<br>       &lt;a (click)=&quot;login()&quot; href=&quot;#&quot; class=&quot;btn btn-microsoft&quot;&gt;<br>          &lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/4/44/Microsoft_logo.svg&quot; alt=&quot;Microsoft Logo&quot;&gt;<br>          Sign in with Microsoft<br>      &lt;/a&gt;<br>  &lt;/div&gt;<br><br>  &lt;div *ngIf=&quot;loggedIn&quot; class=&quot;sign-in-buttons&quot;&gt;<br>    &lt;button (click)=&quot;logout()&quot;&gt;Logout&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><blockquote>The Angular application (client side) sends the ID token generated by the Azure AD authorization server to our endpoint. After successfully validating the ID token, our application issues a JWT (JSON Web Token) that is sent to the backend server and allows the user to access other resources within the application.</blockquote><p>8.<strong> Styling the app.component.css File:</strong> Add some styling in</p><pre>body {<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>    height: 100vh;<br>    margin: 0;<br>    background-color: #f5f5f5;<br>    font-family: Arial, sans-serif;<br>}<br><br>.sign-in-buttons {<br>    text-align: center;<br>}<br><br>.btn {<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    width: 250px;<br>    padding: 10px 15px;<br>    margin: 10px auto;<br>    border: none;<br>    border-radius: 5px;<br>    font-size: 16px;<br>    font-weight: bold;<br>    cursor: pointer;<br>    color: white;<br>    text-decoration: none;<br>    transition: background-color 0.3s ease;<br>}<br><br>.btn img {<br>    width: 20px;<br>    height: 20px;<br>    margin-right: 10px;<br>}<br><br>.btn-microsoft {<br>    background-color: #2F2F2F;<br>}<br><br>.btn-microsoft:hover {<br>    background-color: #1a1a1a;<br>}</pre><p>After setting up your Angular app this way, you can build and run the project with this command:</p><pre>ng serve -o</pre><h4>Secure the ASP.NET Core Backend</h4><p>The server side of the application will be developed using .NET 6, Microsoft’s framework for creating web applications. This project will be structured as a Web API.</p><p>The first step is to create a new API project with all its dependencies. For faster integration, you can check the <a href="https://www.nuget.org/packages/SocialAuthentication.NET">ScoialAuthentication.NET </a>NuGet package. It is easy to integrate and will keep your code clean.</p><p>We can approach this in two ways: either extract the payload from the ID Token (JWT) while performing various checks to ensure its validity, or utilize the built-in .NET class to validate the tokens and retrieve the necessary claims.</p><p>This post will focus on the latter approach, which involves using the .NET built-in class to validate tokens and obtain the claims needed for user authentication. If you want to learn about the first method, please visit this <a href="https://github.com/Jermaine-jay/SocialAuth.NET">GitHub repository</a>.</p><p>First, we need to store our Client ID and Tenant ID obtained from our registered application on the Azure portal, in our appSettings.json file</p><pre>&quot;MicrosoftConfig&quot;: {<br>    &quot;ClientId&quot;: &quot;your-app-clientId&quot;,<br>    &quot;TenantId&quot;: &quot;your-app-tenantId&quot;<br>  },<br><br>&quot;OpenIdConfig&quot; : {<br>    &quot;MetadaDataPath&quot; : &quot;/.well-known/openid-configuration&quot;,<br>    &quot;BaseUrl&quot; : &quot;https://login.microsoftonline.com&quot;,<br>    &quot;CommonTenantId&quot; : &quot;9188040d-6c67-4c5b-b112-36a304b66dad&quot;<br>}</pre><blockquote>If the user logs in with a personal Microsoft account (e.g., @outlook.com or @hotmail.com), the tenant ID in the JWT token will be a common Microsoft tenant ID (9188040d-6c67-4c5b-b112-36a304b66dad) instead of your Azure AD tenant ID.</blockquote><p>. Create a class to bind the objects</p><pre>public class MicrosoftConfig {<br>  public string ClientId {get; set ;},<br>  public string TenantId {get; set;}<br>}<br><br>public class OpenIdConfig {<br>  public string MetadaDataPath {get; set;},<br>  public string BaseUrl {get; set;},<br>  public string CommonTenantId {get; set;}<br>}</pre><p>Bind the appsettings.json object to the respective class object.</p><pre>public static IServiceCollection BindConfig(this IServiceCollection services, IConfiguration configuration)<br>{<br>  <br>    MicrosoftConfig microsoftConfig = new();<br>    OpenIdConfig openIdConfig = new();<br><br>    configuration.GetSection(&quot;MicrosoftConfig&quot;).Bind(microsoftConfig);<br>    configuration.GetSection(&quot;OpenIdConfig&quot;).Bind(openIdConfig);<br><br>    services.AddSingleton(microsoftConfig);<br>    services.AddSingleton(openIdConfig);<br><br>    return services;<br>}</pre><blockquote>Binding JSON to a class makes applications adaptable to changes by simplifying configuration management. For example, third-party service settings can be managed independently of code changes, facilitating better security practices and streamlined deployments. By utilizing this feature, developers ensure clean, and scalable application design.</blockquote><p>Add the BindConfig to your startup class.</p><pre>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>      WebApplicationBuilder builder = WebApplication.CreateBuilder(args);<br>    <br>      builder.Services.ConfigurationBinder(builder.Configuration);<br>    }<br>}</pre><h4>Connect Angular to ASP.NET Core</h4><p>Create a service folder and add a new class, for example, with the name “OpenIdConfiguration.”</p><pre>public class OpenIdConfiguration<br>{<br>   private readonly string _issuer;<br>   private readonly string _dataUrl;<br>   private readonly OpenIdConfig _openIdConfig;<br>   private readonly IConfiguration _configuration;<br>   private readonly MicrosoftConfig _microsoftConfig;<br><br>   public OpenIdConfiguration(IConfiguration configuration, <br>    OpenIdConfig openIdConfig, MicrosoftConfig microsoftConfig )<br>   {<br>      _openIdConfig = openIdConfig;<br>      _configuration = configuration;<br>      _microsoftConfig = microsoftConfig;<br>   }<br><br>  public async Task&lt;ClaimsPrincipal&gt; ValidateMicrosoftIdToken(string idToken)<br>  {<br>      TokenValidationParameters parameters = new TokenValidationParameters<br>      {<br>          ValidIssuer = $&quot;{_openIdConfig.BaseUrl}/{_openIdConfig.CommonTenantId}/v2.0&quot;,<br>          ValidateAudience = true,<br>          ValidAudience = $&quot;{_microsoftConfig.ClientId}&quot;, // Replace with your client ID<br>          ValidateLifetime = true,<br>      };<br><br>      HttpClient httpClient = new();<br>      string metadataUrl = $&quot;{_openIdConfig.BaseUrl}/{_openIdConfig.CommonTenantId}/v2.0/.well-known/openid-configuration&quot;;<br>      string metadataResponse = await httpClient.GetStringAsync(metadataUrl);<br><br>      JObject metadata = JObject.Parse(metadataResponse);<br>      string jwksUri = metadata[&quot;jwks_uri&quot;].ToString();<br><br>      string keysResponse = await httpClient.GetStringAsync(jwksUri);<br>      JsonWebKeySet keys = new JsonWebKeySet(keysResponse);<br>      parameters.IssuerSigningKeys = keys.Keys;<br><br>      JwtSecurityTokenHandler handler = new();<br>      SecurityToken validatedToken;<br><br>      ClaimsPrincipal principal = handler.ValidateToken(idToken, parameters, out validatedToken);<br>      string name = principal.Claims.FirstOrDefault(c =&gt; c.Type == &quot;name&quot;)?.Value;<br>      string preferredUsername = principal.Claims.FirstOrDefault(c =&gt; c.Type == &quot;preferred_username&quot;)?.Value;<br><br>      return principal;        <br>  }<br>}</pre><p>Create a controller, which we will call “OpenIdConfigController” in this example, and create a new class object from it.</p><pre>[EnableCors(&quot;AngularApp&quot;)]<br>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class OpenIdConfigController : ControllerBase<br>{<br>    [HttpPost(&quot;outlook-user&quot;)]<br>    public async Task&lt;IActionResult&gt; GetMicUserProfile([FromBody] string token)<br>    {<br>        OpenIdConfiguration openIdConfiguration = new OpenIdConfiguration();<br>        string outlooktUser = openIdConfiguration.ValidateMicrosoftIdToken(token);<br>        return Ok(outlookUser);<br>    }<br>}</pre><p>Adjust the localhost port of this project to run on “https://localhost:5000”, so you need to locate your lunchSettings.js by clicking the properties folder. Once done, go to your program class and configure Cross-Origin Resource Sharing (CORS) in ASP.NET.</p><pre>builder.Services.AddCors(options =&gt;<br>{<br>    options.AddPolicy(name:&quot;AngularApp&quot;, builder =&gt;<br>        builder.WithOrigins(&quot;http://localhost:4200&quot;)<br>               .AllowAnyHeader()<br>               .AllowAnyMethod());<br>});<br><br>var app = builder.Build();<br><br>app.UseCors(&quot;AngularApp&quot;);</pre><blockquote>This configuration is designed to enable Angular applications running on http://localhost:4200 to communicate with the ASP.NET Core API without being restricted by CORS policies.</blockquote><p>After completing the steps to implement Microsoft login with Angular MSAL and ASP.NET Core Web API, run both applications.</p><blockquote>Misconfigured ports can cause failures in authentication and communication. It’s important to verify that the ports specified in your redirectUri for the Angular app match the actual ports where your applications are hosted. This step ensures smooth interaction between the front-end and back-end during the login process.</blockquote><p>Verify that the Angular application and the ASP.NET Core API are operating on the correct ports.</p><h4>Common Issues and Troubleshooting Tips</h4><p>— Ensure redirect URIs match exactly between Azure AD and Angular<br> — Confirm that tokens are sent in the Authorization header<br> — Check token audience and authority values in ASP.NET Core<br> — Review browser console and API logs for authentication errors</p><h4>Conclusion</h4><p>You have successfully implemented Microsoft authentication using Azure AD, MSAL, Angular, and ASP.NET Core. This setup provides a secure and scalable authentication solution for modern applications. You can extend this implementation by adding logout functionality and refresh token handling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=682b5dfe52d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth Tokens Explained: A Complete Overview of OAuth Tokens]]></title>
            <link>https://medium.com/@jermaine_jay/oauth-tokens-explained-a-complete-overview-of-oauth-tokens-375d3fb62c1c?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/375d3fb62c1c</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 13:32:15 GMT</pubDate>
            <atom:updated>2025-01-16T23:21:13.837Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction to OAuth 2.0</strong></h3><p>Open authorization is an industry-standard framework for managing permissions across various platforms and technology sectors. It enables users to share their data with applications while keeping their sensitive information private.</p><p>This framework allows third-party applications, such as social media and finance apps that rely on OpenID Providers (OPs), to access users’ data for a limited time. It also eliminates the need for users to share their sensitive information with every service they use.</p><h4><strong>How OAuth Tokens Work</strong></h4><p>To access a user’s resources, they must grant permission to the services or applications to which they want to access their resources. In return, they receive a token, which allows the application to perform specific actions, such as accessing contacts, emails, and social media posts.</p><h4><strong>Types Of Tokens</strong></h4><p>OpenID Providers (OPs) can provide three types of tokens.</p><ol><li>Access Token: These tokens are short-lived, typically lasting a few minutes to a few hours, and are used for making API requests to the platform.</li><li>Refresh Token: This token gets a new access token when the old one expires. It has a longer lifespan and is obtained by sending the refresh token to the platform’s token endpoint.</li><li>ID Token: These tokens are typically encoded as a JSON Web Token (JWT) which usually provides authenticated user’s information such as claims, email, name, and unique ID.</li></ol><h4><strong>Forms Of Tokens</strong></h4><p>OAuth 2.0 tokens, such as access and ID tokens, can be issued in two primary formats: JWT (JSON Web Token)and opaque tokens.</p><p>A JWT is a self-contained token that contains data about the user or session, such as claims. It is usually Base64-encoded and can be validated without contacting the server, making it ideal for distributed systems.</p><p>An Opaque token is a randomly generated, non-readable string that refers to the user’s data on the authorization server. Validation requires the server to perform a lookup, making them more secure, and easy to revoke but less efficient for distributed environments.</p><p>OpenID Providers (OPs) like Google often use JWTs for ID tokens in OpenID Connect, while Facebook commonly issues opaque access tokens for API access.</p><h4><strong>Usage and </strong>Lifecycle</h4><p>Understanding the lifecycle and usage of OAuth tokens is key to grasping how they function in real-world applications. The process begins with the application asking for a user’s permission also known as an <strong>authorization request</strong>, to access specific resources, such as their email or contacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*OYU0qNaJL90IexkJxys4Sg.png" /><figcaption>Authorization process</figcaption></figure><p>This is done by redirecting the user to the authorization server, where they can review and either grant or deny the requested permissions.</p><p>After the user grants access, token issuance is the next step, where the authorization server issues an access token and, if needed, a refresh token. These tokens confirm that the application can access the user’s resources.</p><p>The <strong>token usage</strong> phase ensures that the issued access token is used. The application includes this token in API requests to retrieve the user’s data or perform specific actions on their behalf. For example, a social media platform might allow an application to fetch a user’s profile information.</p><p>The fact that for security reasons, access tokens are generally short-lived, they expire. When this happens, the application can enter the <strong>token expiration and refresh</strong> phase. For a seamless experience, the application can use the refresh token to request access, instead of logging in again.</p><p>Finally, revocation can render tokens invalid, which occurs when users log out, change passwords, or revoke permissions. Applications should handle these situations smoothly to avoid errors or unauthorized actions.</p><p>By understanding these stages, developers can design secure and efficient systems that use OAuth tokens effectively.</p><h4><strong>Token Best Practices</strong></h4><p>Adhering to best practices is crucial for ensuring secure implementation when working with OAuth tokens. One underlying principle is secure token storage.</p><p>To prevent access by client-side JavaScript and reduce the risk of cross-site scripting attacks(XSS), tokens in web applications should be stored in HTTP-only cookies. To protect sensitive token data, use secure storage solutions like Keychain for iOS and Secure Storage for Android.</p><p>Another important practice is to avoid exposing tokens in URLs. Including URL tokens can unintentionally log them in browser history or server logs, making them vulnerable to unauthorized access. Tokens should be sent in HTTP headers, like Authorization: Bearer &lt;token&gt;, for secure communication.</p><p>It is mandatory to use <strong>HTTPS</strong> for all token transfers. This guarantees that the tokens are encrypted during transit, protecting them from attackers&#39; interception. Without <strong>HTTPS</strong>, tokens are exposed to man-in-the-middle attacks, significantly increasing security risks.</p><p>Another essential step is to limit the scope of token permission. Requests made by the applications should only be the permissions they need to function. This principle of scope<strong> </strong>limitation minimizes the potential damage if a token is compromised, as it restricts an attacker’s actions.</p><p>Tokens should have a short lifespan to reduce misuse if stolen. To maintain a seamless user experience while ensuring security, applications can use refresh tokens to get new access tokens when the old ones expire.</p><p>Finally, <strong>token revocation mechanisms</strong> are critical for managing security in real-time scenarios. For instance, when a users log out or reset their password, all associated tokens should be invalidated. This ensures that any previously issued tokens can no longer be used to access resources.</p><p>Developers can create reliable systems that safeguard user data and stop illegal access by implementing these practices.</p><p>Let us talk about some real-world scenarios where these things are applied:</p><p>Logging into your social media application with Google:<br>When you log into an application like X (formerly known as Twitter) using their Google account. The application (X) uses an ID token to retrieve your profile information from Google.</p><p>Facebook API Integration:<br>Meta marketing tools also use access tokens to fetch analytics data from a user’s Facebook page.</p><h4>Conclusion</h4><p>Developers can implement secure and efficient authentication and authorization mechanisms in their applications by understanding the types, forms, and best practices of OAuth tokens.</p><p>Tokens like JWTs and opaque tokens have their strengths, and the choice depends on the use case. Whether integrating with social media platforms or building secure APIs, following these guidelines ensures a robust implementation.</p><p>I hope you find this post useful, thank you for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375d3fb62c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dockerize Your Asp.Net]]></title>
            <link>https://medium.com/@jermaine_jay/dockerize-your-asp-net-database-a-guide-to-postgresql-sql-server-and-redis-integration-cd979943c1d9?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd979943c1d9</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 01:07:41 GMT</pubDate>
            <atom:updated>2025-01-29T10:35:23.281Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to Dockerize Your Asp.Net Core Application Database: A Guide to PostgreSQL, SQL Server, and Redis Integration</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*7yYnFCmJAHJXLa8APxzSWg.png" /></figure><p>Containerization in software development is a method used to package and deploy software. It encapsulates all the components of an application and its dependencies such as code, runtime environment, system tools, libraries, and settings into a unit known as a “container”.</p><p>It is a lightweight, portable, and efficient way of packaging, distributing, and executing software applications. Containers are independent of each other and the underlying operating system. By using containerization, several benefits can be achieved such as</p><ul><li>Containerized applications are easy to share, facilitating teamwork and code sharing, thus improving collaboration.</li><li>Developers and testing applications can streamline the process of building an application in isolated containers, allowing faster development and deployment.</li><li>In Addition, isolation and portability, which are enhanced by containerization, can minimize conflicts and vulnerabilities, thereby increasing application reliability and security.</li><li>Provision of a standardized approach to application packaging and deployment, which simplifies infrastructure management is made possible by Containerization.</li></ul><p>Docker, Kubernetes, and RKT are the most popular containerization platforms. These platforms provide tools used for the containerization of applications.</p><p>According to the definition of containers, Docker is a platform that simplifies the process of building, shipping, and running container applications.</p><p>Containers are like self-contained tiny homes that contain the necessary amenities for comfortable living, such as furniture, appliances, and clothing, Similarly, Docker contains everything your application requires to operate, such as code, runtime, system tools, and settings.</p><p>Key components of containerization include:</p><ol><li><strong>Container Image</strong>: This standalone, executable package includes everything required to run the software without external dependencies. Images are built from instructions provided in a Dockerfile (in the case of Docker containers) or another containerization tool.</li><li><strong>Container Engine</strong>: The container engine is responsible for building, running, and managing containers. Docker is one of the most popular container engines, but other tools like Podman, containerd, and others also exist.</li><li><strong>Orchestration Tools</strong>: Container orchestration tools are utilized to manage and coordinate the deployment, scaling, and operation of containerized applications. Kubernetes is a widely used container orchestration platform that automates these processes.</li></ol><p>A database is a structured set of data stored in a computer system. It contains details such as customer information, website traffic, and scientific research.</p><p>Some functions of databases include Storing, Sorting, organizing, finding, and updating data.</p><h4>Setting up database Docker container and connecting it to ASP.NET application.</h4><h4>Requirements</h4><ul><li>You need Docker installed on your development machine. Make sure it is working properly.</li><li>The Docker engine should be running throughout this process.</li><li>The database(PostgreSQL, SQL Server, Redis ) should be installed and working properly on your development machine.</li><li>You will need tools such as Database Management Tools (DBMTs)( help manage and interact with a database), and Database Administration Tools (DBATs) (handle administrative tasks beyond basic queries and data manipulation) e.g. Pgadmin 4, SSMS, and Redisinsight.</li></ul><p>First, add Docker to your ASP.NET project, then add a container orchestrator support. You can proceed to the next step if you already added it when setting up your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbg37EHPaEvI0APCmGtq8Q.png" /><figcaption>Adding docker support to the ASP.NET application</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtNuhsM_Ue6lat2u9tiIUg.png" /><figcaption>Adding a container orchestrator support to the ASP.NET app(docker-compose)</figcaption></figure><h4>For PostgreSQL</h4><p>Pull the Docker PostgreSQL image. To pull the image, run this command in your machine command line.</p><pre>docker pull postgres</pre><p>Open the Docker desktop, and check if the image was created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVdjufPqKl-8JFxzlWkT9Q.png" /><figcaption>PostgreSQL image in docker desktop.</figcaption></figure><p>You can also run the command “docker images” and look for the name Postgres, to confirm if the image was created successfully.</p><p>Next, add the PostgreSQL image instance and tag to your docker-compose yml file.</p><pre>version: &#39;3.4&#39;<br><br><br>services:<br><br>  app_database:<br>    image: postgres:latest<br>    container_name: app_db<br>    environment:<br>      - POSTGRES_USER=your-postgres-username<br>      - POSTGRES_PASSWORD=your-postgres-password<br>      - POSTGRES_DB=your-database-name<br>    ports:<br>      - 5432:5433<br><br>    restart: always<br><br><br>  taskmanager.api:<br>    image: ${DOCKER_REGISTRY-}ExampleApp<br>    build:<br>      context: .<br>      dockerfile: your-app-directory/Dockerfile<br> <br>    depends_on:<br>        - &quot;app_database&quot;<br>    environment: <br>         - ConnectionStrings:DefaultConnection=&quot;Host=app-database;Database=your-database-name;Username=your-postgres-username;Password=your-postgres-password;&quot;<br>         - ASPNETCORE_URLS=http://+80;</pre><p>Let us take a deep dive into what this means piece by piece.</p><ol><li>version: &#39;3.4&#39;: This line specifies the version of the YAML file format used. In this case, it’s version 3.4, which is the latest stable version.</li></ol><p>2. services:: This marks the start of the definition of individual services within the Docker Compose configuration.</p><p>3. app_database:: This defines a service named app_database. This will be a separate container running a PostgreSQL database server.</p><p>4. image: postgres:latest: This specifies the image used to create the app_database container. It uses the official PostgreSQL image with the latest tag, meaning it will use the newest version available.</p><p>5. container_name: app_db: This specifies a custom name for the container created from the app_database service. It will be named app_db.</p><p>6. environment:: This section defines environment variables that will be set within the app_db container. These variables are crucial for configuring the PostgreSQL server:</p><ul><li>POSTGRES_USER: Replace your-postgres-username with your actual username for accessing the database.</li><li>POSTGRES_PASSWORD: Replace your-postgres-password with your actual password for accessing the database.</li><li>POSTGRES_DB: Replace your-database-name with the actual name of the database you want to use.</li></ul><p>7. ports:: This section maps ports from the container (internal) to the host machine (external).</p><ul><li>5432:5433: This maps the default PostgreSQL port (5432) in the container to a different port (5433) on the host machine. This allows you to avoid conflicts with other services running on your machine that might also use port 5432.</li></ul><p>8. restart: always: This specifies that the app_database container should be automatically restarted if it crashes or exits unexpectedly.</p><p>9. task:: This defines another service named taskmanager.api. This will presumably be a container running your actual application code.</p><p>10. image: {DOCKER_REGISTRY-}ExampleApp: This specifies the image used to create the container for your application. Here:</p><ul><li>{DOCKER_REGISTRY-}: This is a variable that might be defined elsewhere in your configuration, and if it’s not defined, it will default to being empty.</li><li>ExampleApp: This is the actual name of the Docker image for your application. Make sure to replace &quot;ExampleApp&quot; with the name of your application’s Docker image.</li></ul><p>11. build:: This section specifies that the taskmanager.api image should be built instead of being pulled from a remote registry.</p><ul><li>context: .: This tells Docker to use the current directory as the build context.</li><li>dockerfile: your-app-directory/Dockerfile: This specifies the path to the Dockerfile within your project that defines how to build the image.</li></ul><p>12. depends_on:This section specifies that the taskmanager.api service depends on the app_database service. This means that the taskmanager.api container will not be started until the app_database container is up and running.</p><p>13. environment:Similar to the app_database service, this section defines environment variables for the taskmanager.api container:</p><ul><li>ConnectionStrings:DefaultConnection: This defines a connection string for your application to access the app_database service. Replace the placeholder values with your actual database information.</li><li>ASPNETCORE_URLS: This defines the URL where your application will be accessible. The http://+80; part specifies that it will be available on port 80 of the host machine.</li></ul><p>This <strong>structure</strong> defines a two-container application; One container runs PostgreSQL, while the other container, using environment variables builds and runs your application, connecting to the SQL Server container.</p><p>Go to the code and edit your connection string with the details used in the docker-compose yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hI7uT4I3n_ectBVq4KEVPA.png" /></figure><p>Build and run the application from Visual Studio or you can locate your project on the development machine, open it in the terminal or with git, and run</p><pre>docker-compose build</pre><p>This will build your project and after that, you should run the container with this command;</p><pre>docker-compose up</pre><p>To stop this container from running, you can use this command;</p><pre>docker-compose down</pre><h4>For SQL Server</h4><p>First, you have to Pull the Docker SQL Server image. To pull the image, run this command in your machine command line.</p><pre>docker pull mcr.microsoft.com/mssql/server</pre><p>With this command by default, the tag will be “Latest”. To confirm if the image was created successfully, use the “docker images” command or check your docker desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPpsotjhcnQ2edVZ9hY8QQ.png" /><figcaption>SQL Server image in docker desktop</figcaption></figure><p>Next, add the SQL Server image instance and tag to your application docker-compose yml file.</p><pre>version: &#39;3.4&#39;<br><br>services:<br>  <br>  mssql:<br>    image: &quot;mcr.microsoft.com/mssql/server:2022-latest&quot;<br>    container_name: sql_server2022<br>    ports:<br>      - &quot;1432:1433&quot;<br><br>    environment:<br>      - ACCEPT_EULA=Y<br>      - SA_PASSWORD=<br>     <br>    restart: always<br><br>  ExampleProject:<br>    image: ${DOCKER_REGISTRY-}Your-app-name<br>    build:<br>      context: .<br>      dockerfile: app-directoty/Dockerfile<br>    depends_on:<br>    - &quot;mssql&quot;</pre><p>Here’s a breakdown of each line:</p><p>1. version: &#39;3.4&#39;: This specifies the version of the YAML format used, which is 3.4 in this case.</p><p>2. services:This marks the beginning of service definitions for different containers in your application.</p><p>3. mssql:Defines a service named <strong>mssql</strong> for running Microsoft SQL Server 2022.</p><p>4. image: &quot;mcr.microsoft.com/mssql/server:2022-latest&quot;: This line specifies the Docker image to use for the mssql service. This pulls the latest version of Microsoft SQL Server 2022 from Microsoft&#39;s official registry.</p><p>5. container_name: sql_server2022: This gives a custom name to the container created from the mssql service. It will be called &quot;sql_server2022&quot;.</p><p>6. ports: - &quot;1432:1433&quot;: This will map the SQL Server port (1432) inside the container to a different port (1433) on your development machine. Remember to update firewall rules accordingly if needed.</p><p>7. environment:Sets environment variables within the mssql container:</p><ul><li>ACCEPT_EULA=Y: Accepts the Microsoft SQL Server End User License Agreement.</li><li>SA_PASSWORD=: Defines a password for the SQL Server Service Account (SA). You need to replace &quot;&quot; with your desired password.</li></ul><p>8. restart: always: Ensures the <strong>mssql</strong> container automatically restarts if it crashes or exits unexpectedly.</p><p>9. ExampleProject:Defines a service named ExampleProject for running your application.</p><p>10. image: {DOCKER_REGISTRY-}ExampleApp: This specifies the image used to create the container for your application. Here:</p><ul><li>{DOCKER_REGISTRY-}: This is a variable that might be defined elsewhere in your configuration, and if it’s not defined, it will default to being empty.</li><li>ExampleApp: This is the actual name of the Docker image for your application. Make sure to replace &quot;ExampleApp&quot; with the name of your application’s Docker image.</li></ul><p>11. build:Indicates that the ExampleProject image should be built instead of downloaded from a registry:</p><ul><li>context: .: Uses the current directory as the build context.</li><li>dockerfile: app-directoty/Dockerfile: Specifies the path to your application&#39;s Dockerfile for building the image.</li></ul><p>12. depends_on:Specifies that the ExampleProject service depends on the <strong>mssql</strong> service. This ensures your application starts only after the SQL Server container is up and running.</p><p>Overall, this configuration defines a two-container application; One container runs Microsoft SQL Server 2022, while the other container builds and runs your application, connecting to the SQL Server container using the specified environment variables.</p><p>Go to the code and edit your connection string with the details used in the docker-compose yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vx2PYv5i3KPoXo_ZyfS_1Q.png" /></figure><p>Build and run the application from Visual Studio or you can locate your project on your machine, open it in the terminal, and run</p><pre>docker-compose build</pre><p>This will build your project and after that, you should run the container with this command;</p><pre>docker-compose up</pre><p>To stop this container from running, you can use this command;</p><pre>docker-compose down</pre><h4>For Redis Database</h4><p>To pull the docker image for Redis, run this command on your development machine;</p><pre>docker pull redis</pre><p>By default, the tag for this image will be “latest”. Next, add the image instance to the docker-compose yml file</p><pre>version: &#39;3.4&#39;<br><br>services:<br>  redis:<br>    image: redis:latest<br>    ports:<br>      - &quot;6379:6379&quot;<br><br>  ExampleProject:<br>    image: ${DOCKER_REGISTRY-}your-app-name<br>    build:<br>      context: .<br>      dockerfile: app-directory/Dockerfile<br>    depends_on:<br>    - &quot;redis&quot;</pre><p>Just like the previous databases&#39; docker-compose yaml file being explained one line after another, the same explanation applies to the redis docker-compose yaml file.</p><p>To complete the implementation process, the Redis service “redis” will be included in the ASP.NET program class.</p><pre>builder.Services.AddSingleton&lt;IConnectionMultiplexer&gt;((option) =&gt;<br>{ <br>    var connectionMultiplexer = ConnectionMultiplexer.Connect(&quot;redis&quot;)<br>    return connectionMultiplexer;<br>});</pre><p>Build and run the application from Visual Studio or you can use this command to run the container.</p><pre>docker-compose up</pre><p>In summary, the potential uses of databases in Dockerized Asp.Net applications are continuously evolving. As containerization technology advances and new database solutions emerge, we can expect even greater efficiency, agility, and innovation in the future.</p><p>I hope you find this post useful, thank you for your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd979943c1d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying ASP.NET]]></title>
            <link>https://medium.com/@jermaine_jay/building-and-deploying-asp-net-apps-to-render-com-with-docker-and-github-actions-ci-cd-59c7ef94e9d9?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c7ef94e9d9</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 13:32:26 GMT</pubDate>
            <atom:updated>2026-01-12T07:18:36.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building and Deploying ASP.NET Core Web Application to Render.com with Docker and GitHub Actions (CI/CD)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*FDij3Bu0rbRHnDD5v3BuVg.png" /></figure><p>Rapid iteration and seamless deployments are essential for progress, eliminating manual deployments and extended margin time in the present speedy software development scene. Developers depend on amazing assets and automation to smooth the development cycle and convey updates rapidly and efficiently.</p><p>This article will direct you through building a strong CI/CD pipeline, utilizing the collaboration of Docker, GitHub Actions, and the inventive stage Render.com. We’ll explore each element in detail, from creating Docker images to setting up automated workflows in GitHub Actions.</p><p><strong>By the end of this guide, you will have:<br></strong> — A Docker container for your ASP.NET app<br> — A GitHub Actions workflow that builds and pushes that container<br> — An automated deployment to Render each time you push changes to GitHub</p><p><strong>Why Docker and GitHub Actions?<br></strong>Render does not offer a quickstart for ASP.NET applications; it provides a quickstart for Docker, so deploying an ASP.NET application on Render.com typically involves containerization.</p><p>To automate the process of creating new images, we utilize GitHub actions. Whenever changes are made to the code, an image is created in the build server. The GitHub server is then triggered, which initiates the creation of a Docker container in the test server.</p><p>When building and pushing the image to Dockerhub is successful, the deployment process to render is triggered, while the process is halted when it fails.</p><h3>Requirements</h3><ul><li>It is assumed you already have an ASP.NET project with a Docker file.</li><li>Your project needs to be pushed to a repository in your GitHub account.</li><li>Docker runs correctly on your machine.</li><li>You should have a Docker Hub account. If you don’t have an account, sign up at <a href="https://hub.docker.com/signup">https://hub.docker.com/signup</a></li><li>Docker desktop installed on your development machine. This is not a requirement, but it will help you keep track of existing images and containers.</li><li>Signup to render at <a href="https://dashboard.render.com/register?next=%2F">https://dashboard.render.com/register?next=%2F</a></li></ul><p>First, you have to add Docker and Docker support orchestrator to your ASP.NET project. thus your Docker daemon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbg37EHPaEvI0APCmGtq8Q.png" /><figcaption>(fig 2) Adding a docker file to the ASP.NET app.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtNuhsM_Ue6lat2u9tiIUg.png" /><figcaption>(fig 3) Adding Docker support to the ASP.NET app.</figcaption></figure><p>Locate the project directory on your computer, open it with Powershell or git, then enter “docker-compose build”, (fig 4). This will create a new image with the tag “Latest”. You can check if the image was successfully created by entering “docker images”(fig 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVG--XuqNyY_175G9kw3aA.png" /><figcaption>(fig 4) Building the docker image of an ASP.NET app</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNlRGmkUIhVCKwxRKpOWdQ.png" /><figcaption>(fig 5) Checking the newly created image</figcaption></figure><p>Next, you will move your image to the Dockerhub registry. To achieve this, you must create a new repository and image tag for your terminal on your Dockerhub account.</p><pre>docker tag local-image:tagname dockerhub-username/new-repo:tagname</pre><p>After tagging the new image, you must push it to your Docker Hub with this command.</p><pre>docker push dockerhub-username/new-repo:tagname</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuISw5id6qaKBFu2PoruGQ.png" /><figcaption>(fig 6) Pushing the tagged image to the Dockerhub repository</figcaption></figure><p>Pull the image from the repository and get the Docker image reference.</p><pre>docker pull dockerhub-username/new-repo:tagname</pre><p>Once you’ve accessed your account on Render, proceed to create a new web service. From the options presented, select “Deploying an existing image from a registry.” Next, retrieve your image reference by copying the format “docker.io/dockerhub-username/new-repo:tagname.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWcKmKiLfuTI5EVex0S7fA.png" /><figcaption>(fig 7) Deploying Docker image on Render</figcaption></figure><p>Paste this reference into the designated “Image Url” field, then click “next” to proceed as shown in (fig 7). Choose a name for your app on render as well as your preferred plan. The deployment process will start immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ9ykBbxvpKFY783nXyQUQ.png" /><figcaption>(Fig 8) App deployment in progress.</figcaption></figure><h3><strong>Building the CI/CD pipeline with GitHub actions</strong></h3><p>It is crucial to have a reliable system in place that can handle push and pull requests on the master branch. That’s where our workflow comes in, giving you the peace of mind that all necessary actions will be taken automatically.</p><p>First, create a repo for your application, click on <strong>Actions</strong> &gt;&gt; <strong>set up a workflow yourself</strong>, give the yml file a name, and paste this;</p><pre>name: Build<br><br>on: <br>  push:<br>    branches: <br>      - master<br><br>jobs:<br>  build:<br>    name: Building image<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v2<br><br>      - name: Buildx<br>        id: buildx<br>        uses: docker/setup-buildx-action@v1<br>        <br>      - name: DockerHub login<br>        uses: docker/login-action@v1<br>        with:<br>          username: ${{ secrets.DOCKERHUB_USERNAME }}<br>          password: ${{ secrets.DOCKERHUB_TOKEN }}<br>          <br>      - name: Build and push<br>        uses: docker/build-push-action@v2<br>        with:<br>          context: .<br>          file: ./directory/Dockerfile <br>          push: true<br>          tags: dockerhub-username/new-repo:tagname</pre><p>To understand this workflow for building and deploying an image to DockerHub. Let’s break it down piece by piece:</p><p>1. Name:</p><ul><li>“name: Build ” — This simply gives a name to the entire workflow.</li></ul><p>2. On:</p><ul><li>“on: push” — This triggers the workflow whenever there’s a push to the repository.</li></ul><p>3. Branches:</p><ul><li>“branches: — master” — This specifies that the workflow will only run when there’s a push to the “master” branch.</li></ul><p>4. Jobs:</p><ul><li>“jobs:” — This section defines the different jobs that will be run as part of the workflow.</li></ul><p>5. Build Job:</p><ul><li>“name: Building image” — This gives a name to the job responsible for building the image.</li><li>“runs-on: ubuntu-latest” — This specifies that the job should run on the latest version of the Ubuntu operating system.</li><li>“steps:” — This defines the specific steps that will be executed within the job.</li></ul><p>6. Checkout Step:</p><ul><li>“name: Checkout” — This step checks out the code from the Git repository.</li><li>“uses: actions/checkout@v2” — This tells GitHub Actions to use the built-in action for checking out code.</li></ul><p>7. Buildx Step:</p><ul><li>“name: Buildx” — This step sets up the Docker Buildx tool for building multi-platform container images.</li><li>“uses: docker/setup-buildx-action@v1” — This tells GitHub Actions to use the official Docker action for setting up Buildx.</li></ul><p>8. DockerHub Login Step:</p><ul><li>“name: DockerHub login” — This step logs in to DockerHub using your credentials.</li><li>“uses: docker/login-action@v1” — This tells GitHub Actions to use the official Docker action for logging in to DockerHub.</li><li>“with:” — This section provides additional information to the action.</li><li>“username: ${{ secrets.DOCKERHUB_USERNAME }}” — This uses a secret stored in GitHub Secrets for your DockerHub username.</li><li>“password: ${{ secrets.DOCKERHUB_TOKEN }}” — This uses a secret stored in GitHub Secrets for your DockerHub access token.</li></ul><p>9. Build and Push Step:</p><ul><li>“name: Build and push” — This step builds and pushes the Docker image to DockerHub.</li><li>“uses: docker/build-push-action@v2” — This tells GitHub Actions to use the official Docker action for building and pushing images.</li><li>“with:” — This section provides additional information to the action.</li><li>“context:” — This tells the action to build the image from the current directory.</li><li>“file: ./directory/Dockerfile” — This specifies the Dockerfile to use for building the image.</li><li>“push: true” — This tells the action to push the image to DockerHub.</li><li>“tags: jermaine31/taskmanager_api: latest” — This specifies the name and tag for the image to be pushed.</li></ul><p>To get your Dockerhub token, click on your Dockerhub profile &gt;&gt;My Account &gt;&gt; Security &gt;&gt; New Access Token. Enter the name and click generate. Copy the new token and save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osIn3BFYEWBog61_703mTQ.png" /><figcaption>(fig 9) Generating a new Dockerhub access token.</figcaption></figure><p>Next, you will add the token and username to your GitHub secrets. On your GitHub repo, go to <strong>settings </strong>&gt;&gt; <strong>secrets and variables</strong> &gt;&gt; <strong>actions </strong>&gt;&gt; New repository secrets. Input the name and paste the Dockerhub access token in the “secret*” field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*IhnjtrNIxhkhBgKMozf5Ag.png" /><figcaption>(fig 10) Adding a new GitHub secret.</figcaption></figure><p>After adding the username and Token secrets, GitHub Actions will build the application image and deploy it to Docker Hub.</p><p>To auto-deploy to Render, create a “deploy-to-render” workflow and paste this in.</p><pre>name: Deploy<br><br>on:<br>  workflow_run:<br>    workflows: [ &quot;Build and Deploy&quot; ]<br>    types:<br>      - completed<br>  workflow_dispatch:<br>  <br>jobs:<br>    <br>  deploy:<br>    name: Deploy<br>    runs-on: ubuntu-latest<br>    <br>    steps: <br>      - name: Deploy to production<br>        uses: johnbeynon/render-deploy-action@v0.0.8<br>        with:<br>           service-id: ${{ secrets.RENDER_SERVICE_ID }}<br>           api-key: ${{ secrets.RENDER_API_KEY }}</pre><p>This section describes another workflow that focuses on deploying the already-built image to production. Let’s break it down step-by-step:</p><p>1. Name:</p><ul><li>“name: Deploy” — This gives a name to the workflow responsible for deployment.</li></ul><p>2. On:</p><ul><li>“on:” — This section defines the events that trigger the workflow.</li></ul><p>3. Workflow Run Trigger:</p><ul><li>“workflow_run:” — This triggers the workflow when another workflow finishes.</li><li>“workflows: [ “Build and Deploy” ]” — Specifies that the “Build and Deploy” workflow must finish before this one starts.</li><li>“types: — completed” — Only triggers when the “Build and Deploy” workflow completes successfully.</li></ul><p>4. Workflow Dispatch Trigger:</p><ul><li>“workflow_dispatch:” — This allows you to manually trigger the workflow from the Actions tab in your repository.</li></ul><p>5. Jobs:</p><ul><li>“jobs:” — This section defines the different jobs that will be run as part of the workflow.</li></ul><p>6. Deploy Job:</p><ul><li>“name: Deploy” — This gives a name to the job responsible for deploying the application.</li><li>“runs-on: ubuntu-latest” — This specifies that the job should run on the latest version of the Ubuntu operating system.</li></ul><p>7. Deploy to Production Step:</p><ul><li>“name: Deploy to production” — This step deploys the application to production using the Render platform.</li><li>“uses: johnbeynon/render-deploy-action@v0.0.8” — This utilizes a pre-built action designed for deploying to Render.</li><li>“with:” — This section provides additional information to the action.</li><li>“service-id: ${{ secrets.RENDER_SERVICE_ID }}” — This uses a secret stored in GitHub Secrets for your Render service ID.</li><li>“api-key: ${{ secrets.RENDER_API_KEY }}” — This uses a secret stored in GitHub Secrets for your Render API key.</li></ul><p>To get the render API key, go to your account settings &gt;&gt; Api keys &gt;&gt; Create Api Key, copy the Api key generated, and save it. Go to GitHub and add it to GitHub secrets. To get the service ID, click on the deployed app &gt;&gt; <strong>Settings</strong> &gt;&gt; <strong>Deploy Hook</strong>, and copy the string that starts with “srv”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxh2VTkLKsk7qFbkjvC6nQ.png" /><figcaption>(fig 11) Retrieving the service ID.</figcaption></figure><p>Save the service ID in the GitHub secrets. This deployment process to render will only be triggered if the build process is successful.</p><p>In Summary when you push the changes to GitHub. The workflow will run again and deploy a new image to Dockerhub, and if it is successful, the workflow for deployment will deploy to render.com (fig 1).</p><h4>Conclusion</h4><p>Now, every time you push code to GitHub:</p><ol><li>GitHub action builds your Docker image</li><li>The image goes to Docker Hub</li><li>Your app automatically deploys to render</li></ol><p>You can focus on writing code while your CI/CD pipeline handles delivery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c7ef94e9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication using custom Apikey in ASP.NET Core]]></title>
            <link>https://medium.com/@jermaine_jay/authentication-using-custom-apikey-in-net-6-0-72fc03197faa?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/72fc03197faa</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 09:19:27 GMT</pubDate>
            <atom:updated>2026-01-03T02:45:45.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>Authentication using a custom API key in .NET Core</h3><p>Authentication is a process that verifies the identity of a user or system. Ideally, a username and password will be required, but methods such as biometrics, Keys, or tokens are required.</p><p>Authentication enforces access control, determining who has access to resources. It is implemented with the help of authorization policies and authorization schemes.</p><p>An authorization policy is a set of rules that define what actions a user is allowed to perform. Typically, it is based on the user’s identity and role. For example, an administrator might be allowed to create and delete users, while a regular user might only be allowed to view their profile.</p><p>An authorization scheme implements an authorization policy. Typically, it is implemented by a security framework or middleware. For example, the API key authentication scheme forces users to enter a valid API key before they can access a resource.</p><p>In this article, I will demonstrate how to create an authorization scheme that requires an API key assigned to a user to grant access to resources in a system.</p><h4>Define the Authentication Handler</h4><p>The AuthenticationHandler class is a base class for classes that handle authentication in ASP.NET Core. It provides methods to authenticate users, such as HandleAuthenticateAsync() and HandleChallengeAsync(). Create a class ApiKeyAuthenticationHandler.</p><p>We extend AuthenticationHandler&lt;ApiKeyAuthenticationOptions&gt; to create an API key authentication handler. The handler inspects incoming requests for an API key and validates it</p><pre>public class ApiKeyAuthenticationHandler : AuthenticationHandler&lt;ApiKeyAuthenticationOptions&gt;<br>    {<br><br>        public ApiKeyAuthenticationHandler(IOptionsMonitor&lt;ApiKeyAuthenticationOptions&gt; options,<br>            ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)<br>        {<br>           <br>        }<br>    }</pre><p>The ApiKeyAuthenticationHandlerclass extends AuthenticationHandler and implements API Key authentication for users.</p><p>We define options inApiKeyAuthenticationOptions extending AuthenticationSchemeOptions So we can configure header name, scheme, and other behaviors.</p><pre>public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions<br>{<br><br>}</pre><p>The ApiKeyAuthenticationOptions class is a class that defines the options for the ApiKeyAuthenticationHandler class. It inherits from the AuthenticationSchemeOptions class, which provides a common set of options for all authentication schemes.</p><p>The ApiKeyAuthenticationOptions class has a few properties that can be used to configure the ApiKeyAuthenticationHandler class, such as:</p><ul><li>HeaderName: The name of the header that contains the API key.</li><li>AuthenticationScheme: The name of the authentication scheme.</li><li>AllowMultipleKeys: Whether or not multiple API keys are allowed for a single user.</li><li>RequiresHttps: Whether or not the API key must be sent over HTTPS.</li></ul><p>The ApiKeyAuthenticationOptions class is a powerful tool that can configure the ApiKeyAuthenticationHandler class to meet your specific needs.</p><p>Here are some of the benefits of using the ApiKeyAuthenticationOptions class:</p><ul><li>It allows you to customize the behavior of the ApiKeyAuthenticationHandler class.</li><li>It makes it easier to configure the ApiKeyAuthenticationHandler class for your specific project.</li><li>It helps to ensure that the ApiKeyAuthenticationHandler class is configured securely.</li></ul><p>If you are using the ApiKeyAuthenticationHandler class, then you should use the ApiKeyAuthenticationOptions class to configure it. This will help you to ensure that the ApiKeyAuthenticationHandler class is configured to meet your specific needs and to protect your API keys.</p><h4><strong>User and Key Generation</strong></h4><p>Create a user class that inherits from IdentityUser, adding an ApiSecretKey property that the system generates with a cryptographic RNG.</p><pre>public class User : IdentityUser<br>{<br>    public string ApiSecretKey { get; set; } = GenerateAnApiKey();<br>}<br><br><br>public static string GenerateAnApiKey()<br>{<br>    var rng = new RNGCryptoServiceProvider();<br>    var bytes = new byte[32];<br>    rng.GetBytes(bytes);<br>    return Convert.ToBase64String(bytes);<br>}</pre><h4>Database Context</h4><p>Create a DbContext class that inherits from IdentityDbContext, and create a DbContextFactory class that inherits from IDesignTimeDbContextFactory. The DbContextFactory class will set up your SQL Server database. After setting it up, Add-Migration and Update-Database.</p><pre>public class DbContext : IdentityDbContext&lt;ApplicationUser, ApplicationRole, string&gt;<br>    {<br>        public PaymentGatewayDbContext(DbContextOptions&lt;DbContext&gt; options)<br>            : base(options)<br>        {<br><br>        }<br>}</pre><pre>public static class TestClass<br>{<br>    private readonly UserManager&lt;User&gt; _userManager;<br>    public TestClass( UserManager&lt;User&gt; userManager)<br>    {<br>      _userManager = userManager;<br>    }<br><br>  public static async Task&lt;User&gt; UserQuery(string ApiKey)<br>  {<br>      var userQuery = await _userManager.Users.Where(u=&gt; u.ApiSecretKey == ApiKey);<br>      return userQuery;<br>  }<br>}</pre><h4>Handle API Key Lookup</h4><p>The UserQuery method takes in an ApiKey parameter, searches for a match in the database, and returns the user or returns null if there is no match.</p><pre>    public class ApiKeyAuthenticationHandler : AuthenticationHandler&lt;ApiKeyAuthenticationOptions&gt;<br>    {<br><br>        public ApiKeyAuthenticationHandler(IOptionsMonitor&lt;ApiKeyAuthenticationOptions&gt; options,<br>            ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)<br>        {<br>            <br>        }<br><br><br>        protected override async Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()<br>        {<br>            if (!Request.Headers.ContainsKey(&quot;Authorization&quot;))<br>            {<br>                  var header = Request.Headers[&quot;Authorization&quot;].ToString();<br>                  var key = header.Substring(7);<br>      <br>                  var user = await TestClass.UserQuery(key);//Checks if the apikey being passed in the header is valid.<br>                  <br>                  var identity = new ClaimsIdentity(<br>                      new[] { new Claim(ClaimTypes.Name, user.UserName),<br>                          new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),<br>                          new Claim(ClaimTypes.Email, user.Email),<br>                      }, Scheme.Name);<br>      <br>                  var principal = new ClaimsPrincipal(identity);<br>                  var ticket = new AuthenticationTicket(principal, Scheme.Name);<br>      <br>                  return AuthenticateResult.Success(ticket);<br>             }<br>             return AuthenticateResult.Fail(&quot;Authorization failed: No API key provided&quot;);<br>        }<br><br>        protected override Task HandleChallengeAsync(AuthenticationProperties properties)<br>        {<br>             if (!Request.Headers.ContainsKey(&quot;Authorization&quot;))<br>             {<br>                 Response.StatusCode = 401;<br>                 Response.ContentType = &quot;text/plain&quot;;<br>                 return Response.WriteAsync(&quot;Authorization failed: No API key provided&quot;);<br>             }<br>             else<br>             {<br>                 var header = Request.Headers[&quot;Authorization&quot;].ToString();<br>                 <br>                 var user = await TestClass.UserQuery(key);//Checks if the apikey being passed in the header is valid.<br>                 if (header.Length &lt;= 7 || user == null)<br>                 {<br>                     Response.StatusCode = 401;<br>                     Response.ContentType = &quot;text/plain&quot;;<br>                     return Response.WriteAsync(&quot;Invalid API key&quot;);<br>                 }<br>                 else<br>                 {<br>                     Response.StatusCode = 404;<br>                     Response.ContentType = &quot;text/plain&quot;;<br>                     return Response.WriteAsync(&quot;Authorization failed&quot;);<br>                 }<br>             }<br>        }<br>    }</pre><h4>Add a Database Seed</h4><p>Now, we insert values into the database so the system generates a unique API key for the new user’s authentication.</p><pre> public static async Task SeededUserAsync(this IApplicationBuilder app)<br>{<br>    var user = new()<br>    {<br>        UserName = User1,<br>        Email = User1@Email.com<br>     }<br><br>    using (var scope = app.ApplicationServices.CreateScope())<br>    {<br>        UserManager&lt;User&gt; userManager = scope.ServiceProvider.GetRequiredService&lt;UserManager&lt;User&gt;&gt;();<br>        await userManager.CreateAsync(user, user.PasswordHash)<br>    }<br>}</pre><h4>Enable the API Key Scheme</h4><p>In Program.cs, we register our custom authentication scheme and enable identity with SQL Server. Then we call our seeding extension to populate initial users</p><pre>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        var builder = WebApplication.CreateBuilder(args);<br>        <br>        builder.Services.AddDbContext&lt;DbContext&gt;(options =&gt;<br>            options.UseSqlServer(<br>                Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br><br>        builder.Services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true)<br>                 .AddDefaultUI()<br>                 .AddEntityFrameworkStores&lt;DbContext&gt;()<br>                 .AddDefaultTokenProviders();<br>        <br>         //Add the authentication scheme<br>         builder.Services.AddAuthentication(&quot;ApiKeyAuthorization&quot;)<br>                .AddScheme&lt;ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler&gt;(&quot;ApiKeyAuthorization&quot;, options =&gt; { });<br>        <br>        var app = builder.Build();<br>        app.UseAuthentication();<br>        app.UseAuthorization();<br><br>        app.SeededUserAsync();//Seeded User<br>    }<br>}</pre><h4>Protect Controllers</h4><p>The ApiKeyAuthorization authenticationScheme attribute is added to the controller.</p><pre>[Authorize(AuthenticationSchemes = &quot;ApiKeyAuthorization&quot;)]<br>[HttpGet(&quot;Test&quot;, Name =&quot;Test&quot;)]<br>public async Task&lt;IActionResult&gt; TestApiKey()<br>{<br>       var user = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.Name);<br>      return Ok($&quot;Welcome to my app{user}&quot;);<br>}</pre><h4>Testing</h4><p>Once the user has an API key, clients include it in the Authorization header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkzMumtp_CVi33lmLfOgvw.jpeg" /></figure><p>After verifying the API Key, it will return the associated claims available to the user. Here, User1 successfully gains access. If the verification fails, an error message will be thrown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgM77EzFfjI9ERBsgMIZJw.jpeg" /></figure><p>This article will help you learn how to secure your ASP.NET Core API with custom API key authentication. It will guide you through building the authentication scheme, integrating it with user data, and configuring authorization.</p><p>By following these steps, you can ensure that only authorized users have access to valuable resources, providing robust protection for your API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72fc03197faa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COVARIANCE AND CONTRAVARIANCE]]></title>
            <link>https://medium.com/@jermaine_jay/covarience-and-contravarience-e2290145a981?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2290145a981</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 09:58:00 GMT</pubDate>
            <atom:updated>2023-01-24T10:35:42.229Z</atom:updated>
            <content:encoded><![CDATA[<p>When programming in c#, Knowing how to follow the inheritance of class definition hierarchies is crucial. Covariance and contravariance are concepts that allow you to be flexible when dealing with class hierarchies and the compatibility of assignments.</p><p>consider this example:</p><pre>public class Vehicle<br>{ <br><br>}<br>public class Car: Vehicle<br>{<br><br>}<br>public class Bus: Car<br>{ <br>    <br>}<br><br>//Initialization<br>Vehicle vehicle = new Vehicle();<br>Vehicle vehicle = new Car();<br>Vehicle vehicle = new Bus();<br><br>Car car = new Car();<br>Car car = new Bus();<br><br>Car car = new Vehicle(); //Compile Error</pre><p>from the example above, the derived classes (Bus and car) will always have more properties that they can have access to than the base class Vehicle. From the code block above, the initialization code shows that an instance can accept a derived class even when a base class is needed.</p><p><strong>Covariance:</strong></p><p>Covariance measures how two random variables interact with one another and how much they change together. In c#, It is believed that the base class and other derived classes are the same class types that enhance the base type’s functionality. covariance allows you to pass a derived class where a base class is needed.</p><p>Covariance in C# is a concept of preserving assignment compatibility between parent and child relationships during dynamic polymorphism.</p><pre>    public class Coffee { }<br>    public class MixCoffee : Coffee { }<br><br><br>    public class Example<br>    {<br>        public static Coffee PourCoffee()<br>        {<br>            Console.WriteLine(&quot;Pouring coffee!!!&quot;);<br>            return new Coffee();<br>        }<br>        public static MixCoffee ReadyCoffee()<br>        {<br>            Console.WriteLine(&quot;coffee is ready&quot;);<br>            return new MixCoffee();    <br>        }<br>        public static void Main()<br>        {<br>            Coffee cup = PourCoffee();<br>            Coffee cup2 = ReadyCoffee();<br>            Console.WriteLine(&quot;Drinking coffee!!!&quot;);<br><br>            //MixCoffee cup3 = PourCoffee(); //compile Error, cannot pass a base type where a derived type is required<br>            MixCoffee cup3 = ReadyCoffee();<br>        }<br>    }</pre><p>From the above code block, we can assign a more derived class ‘’mixcoffee’’, to the less base class “coffee” but gives a compile-time error when we try to assign a less derived class to a more derived class.</p><p>Let&#39;s take a look at a similar example:</p><pre>public class Coffee<br>    {<br>        public void PourCoffee()<br>        {<br>            Console.WriteLine(&quot;Pouring Cofee!!!&quot;);<br>        }<br>    }<br>    public class MixCoffee : Coffee <br>    {<br>        public void mixCoffee()<br>        { <br>            Console.WriteLine(&quot;Mixing the Coffee!!!&quot;);<br>        }<br>    }<br><br>    public class Example<br>    {<br>        public static void Main()<br>        {<br>            Coffee cup = new Coffee();<br>            MixCoffee cup2 = new MixCoffee();<br>            Coffee cup3 = new MixCoffee();<br><br>            cup.PourCoffee();<br>            //cup.mixCoffee(); //Invalid Expression<br>            cup2.mixCoffee();<br>            //cup2.PourCoffee // A valid expression <br>            cup3.PourCoffee();<br><br>            //cup.mixCoffee(); //Compile error<br>            //cup3.mixCoffee(); //compile error<br><br>            Console.WriteLine(&quot;coffee is ready&quot;);<br><br>            Console.WriteLine();<br>            <br>            //Another initialization<br>            Coffee drink = MakeCoffee();<br>            drink.PourCoffee();<br><br>            MixCoffee drink2 = readyCoffee();<br>            drink2.mixCoffee();<br>            drink2.PourCoffee();<br><br>        }<br>        public static Coffee MakeCoffee()<br>        {<br>            Console.WriteLine(&quot;mixing another coffee&quot;);<br>            return new Coffee();<br>        }<br>        public static MixCoffee readyCoffee()<br>        {<br>            Console.WriteLine(&quot;pouring another coffee&quot;);<br>            return new MixCoffee();<br>        }<br><br>    }</pre><p>The example above shows once again that a derived class can be assigned to a base class but a base class cannot be assigned in place of a derived class and thus will not have access to other properties of the derived class.</p><p>Covariance with delegates:</p><p>With covariance, we can use a method with a more derived return type than the delegated method. As a result, we now have more options when it comes to delegate method return types:</p><pre>    public class Vehicle { }<br>    public class Car : Vehicle { }<br><br>    public class Example <br>    {<br>        public static Vehicle GetVehicle()<br>        {<br>            Console.WriteLine(&quot;This is from the vehicle class&quot;);<br>            return new Vehicle();<br>        }<br>        public static Car GetNewCar()<br>        {<br>            Console.WriteLine(&quot;Get a new car&quot;);<br>            return new Car();<br>        }<br>        public static void Run()<br>        {<br>            Func&lt;Vehicle&gt; getvehicle = GetVehicle;<br>            getvehicle += GetNewCar;<br>            getvehicle();<br>            //or<br>            //Vehicle getV = getvehicle();<br><br>            Func&lt;Car&gt; getcar = GetNewCar;<br>            //getcar += GetVehicle; //Compile Error<br>        }<br>    }</pre><pre>using System;<br><br>public class Vehicle { }<br><br>public class Car : Vehicle { }<br><br>public class SportCar : Car { }<br><br><br>public class Program<br>{<br>    public delegate Vehicle AllVehicles(Car car);<br><br>    public static Car Method1(Car car)<br>    {<br>        Console.WriteLine(&quot;Method1&quot;); <br>        return new Car();<br>    }<br>    <br>    public static Vehicle Method2(Car car)<br>    {<br>        Console.WriteLine(&quot;Method2&quot;);    <br>        return new Vehicle();<br>    }<br><br>    public static AllVehicles GetVehicle;<br><br>    public static void Main(string[] args)<br>    {<br>        GetVehicle = Method1;<br>        Vehicle vehicle = GetVehicle(new Car());<br><br>        GetVehicle = Method2;<br>        GetVehicle(new SportCar());       <br>    }<br>}</pre><p>As can be seen, despite their distinct return types, covariance enables us to assign the ‘’Method1&#39;’ method to the AllVehicles delegate. This is Because the Car class is derived from Vehicle, and these operations are permitted.</p><p><strong>Contravariance:</strong></p><p>Covariance is the opposite of contravariance in C#. It is essential to keep in mind that the idea of contravariance is more applicable to parameters than to objects and variables. It permits us to reverse the covariance-preserving assignment compatibility.</p><p>However, contravariance does allow us to assign a method with a parameter of a base class or less derived type to a delegate with a parameter of a derived class or more derived class:</p><pre>public class Person { }<br>public class Employee : Person { }<br><br>delegate void personDelegate(Employee employee);<br><br>public class Program<br>{<br>  static void GreetPerson(Person person)<br>  {<br>     // Logic to greet person.<br>  }<br>  public static void Main()<br>  {<br>    personDelegate del = GreetPerson;<br>  }<br>} </pre><pre>using System;<br><br>public class Vehicle { }<br><br>public class Car : Vehicle { }<br><br>public class SportCar : Car { }<br><br>public class Program<br>{<br>    public delegate Vehicle AllVehicles(Car car);<br><br>    public static Car Method1(Car car)<br>    {<br>        Console.WriteLine(&quot;Method1&quot;); <br>        return new Car();<br>    }<br>    <br>    public static Vehicle Method2(Car car)<br>    {<br>        Console.WriteLine(&quot;Method2&quot;);    <br>        return new Vehicle();<br>    }<br><br>    public static Vehicle Method3(Vehicle vehicle)<br>    {<br>        Console.WriteLine(&quot;Method3&quot;);    <br>        return new Vehicle();<br>    }<br><br>    public static AllVehicles GetVehicle;<br><br>    public static void Main(string[] args)<br>    {<br>        GetVehicle += Method1;<br>        GetVehicle += Method2;<br>        GetVehicle += Method3;<br><br>        //Vehicle vehicle = GetVehicle(new Car());        <br>        GetVehicle(new SportCar());       <br>    }<br>}</pre><p>As can be seen, Method3 has a Vehicle class parameter, whereas the delegate expects a Car class parameter. Method3 can still be used with the delegate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2290145a981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SHADOWING IN C#]]></title>
            <link>https://medium.com/@jermaine_jay/shadowing-in-c-67e66f50dd8?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/67e66f50dd8</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 07:59:53 GMT</pubDate>
            <atom:updated>2022-12-30T07:59:53.307Z</atom:updated>
            <content:encoded><![CDATA[<p>When a class inherits another class, the derived class will only be allowed to use the already existing implementation of fields, methods, or any of its objects with the same name in the base class, Shadowing helps to solve this problem.</p><p>Shadowing is a feature in c# that allows a derived class that wants to provide its own implementation for a method, property, or field already defined in the base class. Shadowing is frequently referred to as “hiding by name” or “name hiding.”</p><p>By declaring the identical member in the derived class, a derived class in C# can use the shadowing feature to cover up a method, property, or field in its base class. Utilizing the new Keyword is how it is done.</p><p>Example:</p><pre>public class Vehicle<br>{<br>    public string Name { get; set; }<br>}<br><br>public class Car: Vehicle<br>{<br>    public new string Name { get; set; }<br>}</pre><p>In this example, the Name property of the Vehicle class is hidden (or shadowed) by the Name property of the Car class. However, this concept should not be used in place of polymorphism in c#.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67e66f50dd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[POLYMORPHISM]]></title>
            <link>https://medium.com/@jermaine_jay/polymorphism-7a524fb53251?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a524fb53251</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 00:04:53 GMT</pubDate>
            <atom:updated>2024-05-29T11:29:08.176Z</atom:updated>
            <content:encoded><![CDATA[<p>Polymorphism in programming is a concept that allows code to be written in a way that objects of different types can be treated in the same way. In other words, an object might take on various forms or have a single name that serves several purposes.</p><p>This means that a single piece of code can be used to perform different tasks depending on the type of object it is applied to. Polymorphism is a powerful tool for writing more efficient and easier-to-understand code.</p><p>There are two(2) types of polymorphism which are: Static/ Compile Time and Dynamic/ Runtime polymorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*_Z-m310hPvDW9rjqNbXDQg.jpeg" /><figcaption>Polymorphism in c#</figcaption></figure><p><strong>Static / Compile Time:</strong></p><p>This is a type of polymorphism that the response to a method is determined at compile time. This indicates that the code is already known at compile time and that the execution of the code is unaffected by the object type or parameters passed to the method/function.</p><p>In an object-oriented language like c#, for instance, the response to a method call is determined at compile time when overriding it. It is also known as Early Binding.</p><p>There are two types of static polymorphism which are: Method overloading and operator overloading. The idea of method overloading is when the names of more than one method are the same but they have different parameters.</p><p>At compile time the compiler checks the type and number of parameters declared/passed, then decides on which method to call and it throws an error if no method match is found.</p><pre>public class StaticPolymorphism<br>{  <br>    public int Add(int num1, int num2, int num3)  <br>    {  <br>        return num1 + num2 + num3;  <br>    }  <br>    public int Add(int num1, int num2)  <br>    {  <br>        return num1 + num2;  <br>    }  <br>}  <br>class Program  <br>{  <br>    static void Main(string[] args)  <br>    {  <br>        StaticPolymorphism MethodOverloading = new StaticPolymorphism();  <br>        int addFirstMethod = MethodOverloading.Add(55, 45, 35);  <br>        int addSecondMethod = MethodOverloading.Add(25, 15);  <br>    }  <br>} </pre><p>In the above code block, the class contains two(2) methods called “Add” which have three(3) and two(2) parameters respectively.</p><p>However, in C#, operator overloading is the process of redefining an operator’s meaning to make it work with user-defined data types. With this, objects, structs, classes, and other types of data can be handled with the same operator.</p><p>Similar to how it is used with primitive types, operator overloading is used to perform operations on user-defined types like classes and structs.</p><pre>   public class OperatorOverloading<br>    {<br>        public static void AddNumbers(int num1, int num2)<br>        {<br>            int addNumber = num1 + num2;<br>            Console.WriteLine(&quot;Sum of numbers is = {0}&quot;,addNumber);<br>        }<br>        public static void AddString(string str1, string str2) <br>        {<br>            string AddString = str1 + str2;<br>            Console.WriteLine(&quot;Sum of stringss is = {0}&quot;,AddString);<br>        }<br><br>        public static void Run() <br>        {<br>            OperatorOverloading.AddNumbers(1, 2);<br>            OperatorOverloading.AddString(&quot;1&quot;, &quot;2&quot;);<br>        }<br>    }<br>//Result<br>//Sum of numbers is = 3<br>//Sum of strings is = 12</pre><p>Depending on the types of data that are provided (from the above example’s case, strings, and integers), the + operator performs specific operations. When the + operator is applied to mathematical sorts, the outcome is the summation of the operands. String concatenation, on the other hand, occurs when string types are given the + operator.</p><p><strong>Dynamic/ Runtime Polymorphism:</strong></p><p>When a call to a member function is resolved at runtime rather than compile time, dynamic polymorphism takes place. The type and values of the arguments passed to the function are used at runtime to determine the function’s call in dynamic polymorphism.</p><p>In C# is the ability of a method, property, or field to be overridden or redefined in a derived class. This allows various implementations of the same method/function, property, or field to be utilized relying upon the runtime sort of the object. This is also known as late binding or runtime binding.</p><pre>    class DynamicPolymorphism<br>    {<br>        public class Shape<br>        {<br>            protected const double PI = Math.PI;<br>            protected static double _x,_y; <br>            public Shape() { }<br>            public Shape(double x, double y) <br>            {<br>                _x = x;<br>                _y = y;<br>            }<br>            public virtual double Area()<br>            {<br>                return _x * _y;<br>            }<br><br>        }<br>        public class Circle : Shape <br>        {<br>            public Circle(double r) : base(r, 0)<br>            {<br><br>            }<br><br>            public override double Area()<br>            {<br>                return PI * _x * _x;<br>            }<br>        }<br><br>        public class Square : Shape<br>        {<br>            public Square(double r) : base(r, 0)<br>            {<br>                <br>            }<br>            public override double Area()<br>            {<br>                return _x*_x;<br>            }<br>        }<br>        public class Sphere : Shape<br>        {<br>            public Sphere(double r) : base(r, 0)<br>            {<br><br>            }<br>            public override double Area()<br>            {<br>                return 4 * PI *_x * _x;<br>            }<br>        }<br>        public class Cylinder:Shape<br>        {<br>            public Cylinder(double r, double h) : base(r, h)<br>            {<br><br>            }<br>            public override double Area()<br>            {<br>                return 2 *PI*_x* _x + 2 * PI * _x * _y;<br>            }<br>        }<br><br>        public static void Main()<br>        {<br>            double r = 3.0, h = 5.0; //r is the radius, h is the height<br>            Shape area = new Circle(r);<br>            Shape areaOfSquare = new Square(r);<br>            Shape areaOfSphere = new Sphere(r);<br>            Shape areaOfCylinder = new Sphere(r,h);<br><br>            Console.WriteLine(&quot;Area of a circle is {0}&quot;, area.Area());<br>            Console.WriteLine(&quot;Area of a square is {0}&quot;, areaOfSquare.Area());<br>            Console.WriteLine(&quot;Area of a sphere is {0}&quot;, areaOfSphere.Area());<br>            Console.WriteLine(&quot;Area of a cylinder is {0}&quot;, areaOfCylinder.Area());<br>        }<br>    }<br>    /*<br>    Output:<br>    Area of Circle   = 28.27<br>    Area of Square   = 9<br>    Area of Sphere   = 113.10<br>    Area of Cylinder = 150.80<br>    }*/</pre><p>Although the compiler successfully compiles despite requiring an Area() method, the appropriate version is determined at runtime rather than compile time.</p><p>Here is another example using Abstract classes:</p><pre>    public abstract class Shape<br>    {<br>        protected const double PI = Math.PI;<br><br>        protected static double _x, _y;<br><br>        public abstract void Area();<br><br>    }<br><br>    public class Circle : Shape<br>    {<br>        public Circle(double radius) =&gt; _x = radius;<br>  <br>        public override void Area()<br>        {<br>            var area = PI * _x * _x;<br>            Console.WriteLine(&quot;Area of a circle is {0}&quot;, area);<br>        }<br>    }<br><br>    public class Sphere : Shape<br>    {<br>        public Sphere(double radius) =&gt; _x = x;<br>        <br>        public override void Area()<br>        {<br>            var area = 4 * PI * _x * _x;<br>            Console.WriteLine(&quot;Area of a sphere is {0}&quot;, area);<br>        }<br>    }<br><br>    public class Cylinder : Shape<br>    {<br>        public Cylinder(double x, double y)<br>        {<br>            _x = x;<br>            _y = y;<br>        }<br><br>        public override void Area()<br>        {<br>            var area = 2 * PI * _x * _x + 2 * PI * _x * _y;<br>            Console.WriteLine(&quot;Area of a cylinder is {0}&quot;, area);<br>        }<br>    }<br><br>    public abstract class Example<br>    {<br>        public static void Run()<br>        {<br>            var Radius = 4;<br>            var Height = 5;<br><br>            Shape AreaOfCirclecircle = new Circle(Radius);<br>            AreaOfCirclecircle.Area();           <br><br>            Console.WriteLine();<br><br>            Shape AreaOfSphere = new Sphere(Radius);<br>            AreaOfSphere.Area();<br><br>            Console.WriteLine();<br>            <br>            Shape AreaOfCylinder = new Cylinder(Radius,Height);<br>            AreaOfCylinder.Area();<br><br>        }<br><br>        //Area of circle is 50.2654824574367<br><br>        //Area of sphere is 201.061929829747<br><br>        //Area of cylinder is 226.194671058465<br>    }</pre><p>Finally, the virtual or abstract method that is overridden in the derived class must have the same name, number of parameters, and type as the base class method’s virtual or abstract method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a524fb53251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BITWISE OPERATORS IN C#]]></title>
            <link>https://medium.com/@jermaine_jay/bitwise-operators-in-c-2247ae71a15b?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/2247ae71a15b</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 23:11:56 GMT</pubDate>
            <atom:updated>2022-11-24T23:11:56.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Characters known as bitwise operators are used to represent actions (bit operations) that can be carried out on individual bits. A bitwise operation in can be performed on a bit string, bit array, or the binary numerical level of its bits.</p><p>The processor directly conducts these operations, which are fundamental to high-level arithmetic operations. The int, uint, long, and ulong types have their own definitions for these operators.</p><p>The values of both operands are converted to the int type, which is also the type of an operation’s result, when they are of different integral types (sbyte, byte, short, ushort, or char). Values of operands of different integral types are converted to the integral type closest to the containing element.</p><p>With integral numeric or char operands, the following operators perform bitwise or shift operations: Binary (left shift), &gt;&gt; (right shift), and &gt;&gt;&gt; (unsigned right shift) operators, Binary &amp; (logical AND), | (logical OR), and &gt;&gt;&gt; (unsigned right shift) operators and Unary ~ (bitwise complement)operator.</p><p>We are aware that all 1s are true in binary, while 0s are regarded as false.</p><h3>Logical AND operator &amp;</h3><p>The bitwise logical AND of its integral operands is computed by the &amp; operator. The &amp; operator calculates the logical AND of its operands for bool operands. The address-of operator is the unary &amp; operator.</p><p>When AND operations are done on the binary value following are the results of AND.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*x00wiZwioG9GRsK-R7ntpQ.jpeg" /><figcaption>Truth table for AND operation.</figcaption></figure><p>The AND operation only returns True when both values are True.</p><pre>using System;<br>class LogicalAndOperation{<br>    public static void Main() {<br>        byte A = 10; // binary equivalent for 10 is 01010<br>        byte B = 20; // binary equivalent for 20 is 10100<br>        long result = A &amp; B; // AND operation result should be 00000<br>        Console.WriteLine(&quot;{0} AND {1} Result :{2}&quot;, A, B, result);<br>        A = 10; // binary equivalent for 10 is 01010<br>        B = 10; // binary equivalent for 10 is 01010<br>        result = A &amp; B; // AND operation result should be 01010<br>        //so the result will contain 10 in decimal<br>        Console.WriteLine(&quot;{0} AND {1} Result : {2}&quot;, A, B, result);<br>    }<br>}</pre><h3>Logical exclusive OR operator ^</h3><p>The bitwise logical exclusive OR, also known as the bitwise logical XOR, of its integral operands is computed by then ^ operator. When the exclusive OR operation is used, FALSE is returned when both values are true and FALSE when neither value is true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*nBT19hIq-0xRWVTWg26LSw.jpeg" /><figcaption>Truth table for Logical exclusive <strong>OR</strong> operation.</figcaption></figure><pre>using System;<br>class LogicalExclusiveOrOperation{<br>    public static void Main() {<br>        byte A = 10; // binary equivalent for 10 is 01010<br>        byte B = 20; // binary equivalent for 20 is 10100<br>        result = A ^ B; // OR operation result should be 00000<br>        //so the result will contain 0 in decimal<br>        Console.WriteLine(&quot;{0} OR {1} Result : {2}&quot;, A, B, result);<br>    }<br>}</pre><h3>Logical OR operator |</h3><p>The bitwise logical OR of its integral operands is computed by the | operator. Only when both values are false does the logical OR operation return FALSE. In any remaining cases OR activity gives valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*8xqGd2AMOsuxWQX4RjWZvA.jpeg" /><figcaption>Truth table for Logical <strong>OR</strong> operation.</figcaption></figure><pre>using System;<br>class LogicalOrOperation{<br>   public static void Main() {<br>        byte A = 10; // binary equivalent for 10 is 01010<br>        byte B = 20; // binary equivalent for 20 is 10100<br>        result = A ^ B; // OR operation result should be 00000<br>        //so the result will contain 0 in decimal<br>        Console.WriteLine(&quot;{0} OR {1} Result : {2}&quot;, A, B, result);<br>    }<br>}</pre><h3>Shift operators</h3><p>Right Shift operation (&gt;&gt;): The bits are moved to the right side using the. Left Shift operation(&lt;&lt;): The bits are moved to the left by using the.</p><h4>Right-shift operator &gt;&gt;</h4><p>Bits are shifted to the right when a binary value is subjected to Right Shift operations. For example, 1010 is the binary equivalent of the decimal 10. Therefore, this value will be used in the Right Shift operation. The bits on the right will be truncated, and the bits on the left filled with zeros.</p><p>If 1010 is moved to the right, its value will be 0101. Therefore, 5 is the decimal equivalent of 0101.This indicates that the value of the decimal number 10 decreases to 5 when moved to the right.</p><p>As the following example demonstrates, the left-shift operation sets the low-order empty bit positions to zero and discards the high-order bits that are outside the range of the result type.</p><pre>using System;<br>class RightShiftOperation{<br>    public static void Main() {<br>        byte varA = 10; // binary equivalent for 10 is 01010<br>        long result = varA &gt;&gt; 1; // Right Shift operation result should be 0101<br>        //so the result will contain 5 in decimal<br>        Console.WriteLine(&quot;{0} is Right Shifted to 1 position Result :{1}&quot;, varA, result);<br>    }<br>}</pre><h4>Left-shift operator &lt;&lt;</h4><p>When a binary value is subjected to Left Shift operations, its bits are shifted one position to the left. For example, 1010 is the binary equivalent of the decimal 10. Therefore, when the left shift is performed, this value is set, the most significant bit on the left will be truncated, and the most significant bit on the right will be filled with zero.</p><p>1010 will have a value of 10100 if moved one position to the right.<br>Therefore, 20 is the decimal equivalent of 10100.This indicates that the value of the decimal number 10 increases to 20 when moved to the left one position.</p><pre>using System;<br>class LeftShiftOperation{<br>    public static void Main() {<br>        byte varA = 10; // binary equivalent for 10 is 01010<br>        long result = varA &lt;&lt; 1; // Left Shift operation result should be 10100<br>        //so the result will contain 20 in decimal<br>        Console.WriteLine(&quot;{0} is Left Shifted to 1 position Result :{1}&quot;, varA, result);<br>    }<br>}</pre><h3>Unsigned right-shift operator &gt;&gt;&gt;</h3><p>The &gt;&gt;&gt; operator, which is available in C# 11 and later, shifts its right-hand operand by the number of bits defined by its left-hand operand.to learn more about how the right-hand operand defines the shift count.</p><p>The &gt;&gt;&gt; operator always carries out a logical shift. That is, the high-request void piece positions are constantly set to zero, no matter what the kind of the left-hand operand.</p><p>An arithmetic shift is carried out by the &gt;&gt; operator, transferring the value of the most significant bit to the high-order empty bit positions.For a negative left-hand operand,</p><pre>int x = -8;<br>Console.WriteLine($&quot;Before:    {x,11}, hex: {x,8:x}, binary: {Convert.ToString(x, toBase: 2), 32}&quot;);<br><br>int y = x &gt;&gt; 2;<br>Console.WriteLine($&quot;After  &gt;&gt;: {y,11}, hex: {y,8:x}, binary: {Convert.ToString(y, toBase: 2), 32}&quot;);<br><br>int z = x &gt;&gt;&gt; 2;<br>Console.WriteLine($&quot;After &gt;&gt;&gt;: {z,11}, hex: {z,8:x}, binary: {Convert.ToString(z, toBase: 2).PadLeft(32, &#39;0&#39;), 32}&quot;);<br>// Output:<br>// Before:             -8, hex: fffffff8, binary: 11111111111111111111111111111000<br>// After  &gt;&gt;:          -2, hex: fffffffe, binary: 11111111111111111111111111111110<br>// After &gt;&gt;&gt;:  1073741822, hex: 3ffffffe, binary: 00111111111111111111111111111110</pre><h3>Bitwise complement operator ~</h3><p>By reversing each bit, the operator ~ generates a bitwise complement of its operand.</p><pre>uint a = 0b_0000_1111_0000_1111_0000_1111_0000_1100;<br>uint b = ~a;<br>Console.WriteLine(Convert.ToString(b, toBase: 2));<br>// Output:<br>// 11110000111100001111000011110011</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2247ae71a15b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[INHERITANCE IN C#]]></title>
            <link>https://medium.com/@jermaine_jay/inheritance-in-c-d3d9804fa24b?source=rss-84d943c4e76------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d9804fa24b</guid>
            <dc:creator><![CDATA[Johnson]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 08:37:24 GMT</pubDate>
            <atom:updated>2022-11-21T08:37:24.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Inheritance is the process by which an object automatically acquires all of its parent object’s properties and behaviors. The attributes and behaviors defined by another class can thus be reused, extended, or modified.<br>In C#, the derived class is the class that inherits another class’s members, and the base class is the class whose members are inherited. The specialized class for the base class is the derived class.</p><h3>Types of Inheritance</h3><p>Depending on how the classes are inherited, C# supports a variety of inheritance types.</p><h3>Single Level Inheritance</h3><p>Only one derived class inherits a single base class in a single inheritance. Inheritance in c# can be through fields or methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*hdrt3f2OPiZPTusSCe_Erw.jpeg" /></figure><pre>//Inheritance through fields<br>namespace iherit<br>{ <br>   public class Student<br>    {<br>        public int Allowee = 40000;<br>    }<br>    public class Expenses : Student<br>    {<br>        public int book = 10000;<br>    }<br>    class TestInheritance<br>    {<br>        public static void Main(string[] args)<br>        {<br>            Expenses student= new Expenses();<br><br>            Console.WriteLine(&quot;Allowee: &quot; + student.Allowee);<br>            Console.WriteLine(&quot;Book: &quot; + student.book);<br>        }<br>    }<br>}</pre><pre>//inheritance via methods <br>public class StudentA<br>    {<br>        public void studentA() <br>        { <br>            Console.WriteLine(&quot;This is Student A...&quot;); <br>        }<br>    }<br>    public class StudentB : StudentA<br>    {<br>        public void studentB() <br>        { <br>            Console.WriteLine(&quot;This is Student B...&quot;); <br>        }<br>    }<br>    class TestInheritance2<br>    {<br>        public static void Main(string[] args)<br>        {<br>            StudentB student = new StudentB();<br>            student.studentA();<br>            student.studentB();<br>        }<br>    }</pre><h3>Multi Level Inheritance</h3><p>A derived class inherits from a base class in multi-level inheritance, and the same derived class becomes a base class for another derived class.Practically, the amount of inheritance is unlimited, but you should steer clear of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*qLjOHHbjyGr-Ei5y5CrVrQ.jpeg" /></figure><pre>public class Dog<br>    {<br>        public void dog() <br>        {<br>            Console.WriteLine(&quot;This is from the Dog class...&quot;); <br>        }<br>    }<br>    public class Bitch : Dog<br>    {<br>        public void bitch() <br>        { <br>            Console.WriteLine(&quot;This is from the Bitch class...&quot;); <br>        }<br>    }<br>    public class Puppy : Bitch<br>    {<br>        public void puppy() <br>        {<br>            Console.WriteLine(&quot;This is from the Puppy class...&quot;);<br>        }<br>    }<br>    class TestInheritance2<br>    {<br>        public static void Main(string[] args)<br>        {<br>            Puppy dog = new Puppy();<br>            dog.dog();<br>            dog.bitch();<br>            dog.puppy();<br>        }<br>    }</pre><h3>Hierarchical Inheritance</h3><p>In hierarchical inheritance, more than one derived classes inherit from a single base class. In terms of object-oriented terms, it is a technique for passing features from a parent class to a base, child, or subclass. The class from which the properties, or features, are inherited is the parent class, or super-class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*U2zPZYh3F6y4yamhjjjmsA.jpeg" /></figure><pre>public class Father<br>    {<br>        public string FatherName()<br>        {<br>            return &quot;Chukwu&quot;;<br>        }<br>    }<br><br>   <br>    public class FirstChild : Father<br>    {<br>        public string ChildName()<br>        {<br>            return &quot;Johnson&quot;;<br>        }<br>    }<br><br>    public class LastChild : Father<br>    {<br>        public string ChildName()<br>        {<br>            return &quot;Ositadimma&quot;;<br>        }<br>    }<br><br>    class FullName<br>    {<br><br>        static public void Main()<br>        {<br>            FirstChild first = new FirstChild();<br>            Console.WriteLine(&quot;My name is {0} and my father&#39;s name is {1} &quot;, first.ChildName(), first.FatherName());<br>            <br>            LastChild second = new LastChild();<br>            Console.WriteLine(&quot;My name is {0} and my father&#39;s name is {1} &quot;,second.ChildName(),second.FatherName());<br>        }<br>    }</pre><h3>Hybrid Inheritance</h3><p>It’s a combination of two or more of the aforementioned inheritance types. Hybrid inheritance is also impossible with classes because C# does not support multiple inheritance. Interfaces are the only way to implement hybrid inheritance in C#. Multi-level and hierarchical inheritance are combined in hybrid inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*qbW7P_gjzOMYD70yO2w-UA.jpeg" /></figure><pre>    internal class Program<br>    {<br><br>        public void OnWrite(IPerson person, string message)<br>        {<br>            person.Write(message);<br>        }<br>    }<br>        public interface IPerson<br>        {<br>            void Write(string message);<br>        }<br><br>        public class Teacher : IPerson<br>        {<br><br>            public void Write(string message)<br>            {<br>                Console.WriteLine(&quot;In Teacher&quot;);<br>                Console.WriteLine(message);<br>            }<br>        }<br><br>        public class Student : IPerson<br>        {<br>            public void Write(string message)<br>            {<br>                Console.WriteLine(&quot;In Student&quot;);<br>                Console.WriteLine(message);<br>            }<br>        }<br><br>        public class Admin : IPerson<br>        {<br>            public void Write(string message)<br>            {<br>                Console.WriteLine(&quot;In Admin&quot;);<br>                Console.WriteLine(message);<br>            }<br>        }<br><br>    public class Inter<br>    {<br>            public static void Main()<br>            {<br><br>                Program Interfaces = new Program();<br><br>                IPerson student = new Student();<br>                IPerson teacher = new Teacher();<br>                IPerson admin = new Admin();<br><br>                Interfaces.OnWrite(student, &quot;Na God go understand this handwriting&quot;);<br><br>                Interfaces.OnWrite(teacher, &quot;What a handwriting🙂&quot;);<br><br>                Interfaces.OnWrite(admin, &quot;Query to Nneka!!&quot;);<br>            }<br>        }<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d9804fa24b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>