How to Bypass Login Credentials for Debugging & Integration Test purposes in ASP.NET MVC?

While debugging ASP.NET MVC applications often we need to Bypass login credentials to accelerate the debugging process. You can wrap the following code inside a Debugger.IsAttached block and invoke during the Login action – preferably on the Login button click Or authentication invoker area.

var claims = new List<Claim>

{

new Claim(“name”, “Developer”),

new Claim (“email”, “email@domain.com”)

};

var claimsIdentity = new claimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties

{

AllowRefresh = true,

ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(600), // Too far

IsPersistent = true,

IssuedUtc = DateTime.UtcNow,

};

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

// Redirect

HttpContext.Rsponse.Rediret(“yourUrl”);

Advertisement

7 Habits of Highly Effective Developers

Software Development is one of the most-rewarding & fulfilling Job in the world.  I would like to Jot down the Best Developer Practices so that it can help the coding community in forming High-Performance Teams.

Take Away: Distributed Architecture | Clean Code | Less Chaos | High Refactor | High ROI

image

#1 Be Accurate on Estimates

Estimating the Story points accurately is an Important skill for developers.  I have seen that many Scrum Teams are not properly doing the Estimations & Retrospectives so that the Team is spending lot extra hours on development.

Few points of improvement are: Setting 6 hour day, Adding buffer hours, Job Design of separating API-Developer, UI-Developer, Buffering Hours on External Dependencies, Deployment Overheads can improve the Credibility of the team.

#2 Begin with the Distributed in Mind

The world of Monolithic application is completely gone.  We are seeing Microservices & Distributed components are racing towards replacing older codes.  The advantages are Smaller Teams, Independent Deployments, Individual Scalability etc.  These strongly emphasize the need to modularly design the application components.

Another point to note is the Distributed Component should be Self-Health-Check ready.  Each component can tell whether it is running correctly or not.  We can introduce REST API calls like api/health to validate the health of each component.  In this way the Invoker or Application Validator can quickly validate all the underlying distributed component health quickly.

#3 Put Test things First

More the often, I see Developer writing the Code first then the Unit Tests.  This often lead to the state that “There are no unit tests!” 

In fact, if we adapt TDD (Test Driven Development) we can ensure the Unit Test is written first.  Code will definitely follow!

Enforcements CICD team can enforce check-in rules that requires 80% Code Coverage or more.

#4 Think Subscription

Often in the world of Cloud, I have seen more & more applications getting converted into Subscription model.  This mainly involves writing an application, test it right with one customer, then replicate the same with multiple customers. 

Few design elements which help in improving the Subscription Adaptability are:

  • Design Database with GUID Identifiers which are Faster like Integers link | Integers will Fail on Copy/Paste data scenarios involving Foreign Keys
  • Design APIs with Client ID passed through HTTP Header | Rather than changing the method parameters

#5 Seek first to Design Then to Refactor

As you know the Lifetime of the Code is mostly undergoing Refactor! Refactor is the element of Software which gives High ROI on the investments.  The code should be Refactor Ready.

As an example, an application which is tightly coupled with SQL Server will be difficult to Refactor & Reuse against an Oracle database.  We need to use Interface Segregation principle of S.O.L.I.D to enable easier refactoring of the code. 

Another example would be Support of Unit Tests.  The more number of unit tests are present, the Refactoring will be more easier & controllable.  Otherwise we would not know which code will break at later phase of the application.

#6 Synergize

Overall the product development is a Team Effort.  Often times I have seen a Scrum Team is failing due to  Dependency on external Folks etc.

Solution: Adding a shared resource into Scrum Team will Accelerate their Performance thereby Improving the Spirit of Team. Synergizing!

#7 Sharpen the Coder

Software Development is one of the Most Rewarding Job!  We will start coding & we don’t know when time passed by and End-of-Day has reached.

Following are few aspects which can Sharpen the Coder inside you:

  • Map with a Like-minded Coder | This will make the coding world more interesting
  • Spend 1 hour daily on learning | Keeping a MVP Target can help you focused on learning & blogging
  • Share knowledge 1 hour a week | Sharing gets more focus on your knowledge, question & optimize
  • Powerful Hardware | Have a powerful machine – preferably desktop / mechanical keyboard which makes the Coding Life Fun

Summary

I hope this will add value to your day-to-day Development activities.  Please let me know your comments.

Full Book

I am creating the Full Book along with DotNetSpark.  You can order it here which includes the Real-world 7 examples, technical POCs, design guidelines, unit testing techniques etc. supporting the above facts.  This book less than $10 can really save you $ K-Million depending on the size of your software projects.

image

Plus, bonus you will get a 1-hour webinar/meeting where you can discuss the same with author. 

How to do App Registration for Enterprise Application?

In this post we can see how to do an App Registration for a Web application so that it will become Enterprise Application.

Step 1  Open Azure Portal > Active Directory

Open Azure Portal > Go to Active Directory from Resources.

image

Step 2  Open App Registrations

Open App Registrations blade as shown below.

image

Step 3 Create New App Service

Click on the New Registration button. 

  • Enter Name for the service
  • Leave the default options
  • Enter the Redirect URI as the URL of your web application / web api

Click the Register button

Copy the Client ID  as displayed over there.

image

Step 3 Create Credentials

Go to the Certificates & secrets blade. 

  • Click on New client secret
  • Save changes

Copy the Password generated

image

Now you have the Client ID and the Client Secret for the App Registration.  Now any application authenticated using these will be given privilege of this App Registration.

Step 4  Open Enterprise Applications

Open Enterprise Applications blade from Active Directory.  Search for the name.

image

If you can find your Application – Congratulations!

You have just created an Enterprise Applications.  Now you can do the following & more with it.

  • Add Owners
  • Add Users
    • Internal & External
    • Enable Self-Servcie
  • Audit Logs
  • Troubleshoot

References

https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/what-is-application-management

Summary

In this post we have seen how to perform an App Registration.

Azure Infrastructure – Connecting On-Premise Network to Azure

One of the challenges of Organizations migrating On-Premise resources to Azure is Security. 

  • How to transfer data securely over the Internet?
  • What are the Alternatives?

VPN Gateway

Virtual Private Network is a Private Interconnected which uses Encrypted Tunnel to communicate between 2 Private Networks.  The untrusted internet problem is resolved by Encrypting the communications.

VPN Gateway is similar to Virtual Network Gateway which allows Site-to-Site, Point-to-Site and Network-to-Network connections.

  • Site-to-Site connections allow On-premise datacenter to connect to Azure Virtual Networks
  • Point-to-Site connections allow User Devices connections to Azure Virtual Networks.
  • Network-to-Network connections allow Azure Virtual Network to other Azure Virtual Networks.

ExpressRoute

Azure ExpressRoute allows secured, dedicated, high-bandwidth connections between your On-Premises and Azure.  This will bypass the Internet and hence more secured.

Following are the Features of Express Route:

  • Layer-3 Connectivity
  • Faster Access due to Peering of Networks
  • More Security
  • Higher Bandwidth
  • Bypasses Public Internet
  • Available in all Locations
  • Office365 Connectivity through Microsoft Peering

Following are the Drawbacks of Express Route:

  • ExpressRoute Circuit which is a Physical Connection needs to be created from Internet Provider
  • Cost is More

Few ExpressRoute providers are listed below:

image

Virtual Network Gateway

Virtual Network Gateway is required to connect 2 Networks either as:

  • VPN
  • ExpressRoute

When to choose VPN Gateway?

Low Bandwidth requirements

Point-to-Site scenarios

Occasional Connectivity

Moderate Data Security

When to choose ExpressRoute?

Dedicated Connection Required

High Security for Data

Faster & Continuous Access

References

https://docs.microsoft.com/en-us/learn/modules/connect-on-premises-network-with-vpn-gateway/2-connect-on-premises-networks-to-azure-using-site-to-site-vpn-gateways

https://docs.microsoft.com/en-us/azure/vpn-gateway/vpn-gateway-about-vpngateways#a-namep2sapoint-to-site-vpn-over-sstp

[InternalsVisibleToAttribute] for Unit Testing Private Methods

One of the unit testing challenge developers face is – How to Test a Private Method?

Solution: Use InternalsVisibleToAttribute method in .Net Core

// Enter the Assembly Name of the Unit Test project

// Use internal modifier instead of private

[assembly: InternalsVisibleToAttribute(“UnitTestProject1”)]

namespace ConsoleApp7

{

public class IndustryBL
{
internal int InternalMethod(int x, int y)
{
return x + y;
}
}

}

Now we can Invoke the method from Unit Test.

namespace UnitTestProject1

{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
IndustryBL bl = new IndustryBL();
bl.InternalMethod(2, 3);
}
}

}

Event Hub vs Event Grid vs Service Bus

In this post we can see the different use cases of:

  • Event Hub
  • Event Grid
  • Service Bus




Service Purpose Type Use Case
Event Hub Big Data Handling Event Distribution (Discrete)

Telemetry Data

Eg: Application Insights, Logs

Event Grid Reactive Programming Event Streaming (Series)

Status Changes Reaction

Eg: Approval, Rejection

Service Bus Enterprise Messaging Messaging Order Processing & Financial Transactions

Example

In the below Microsoft example, Event Hub will capture the Big Data, pass to Azure Storage.

An even tis sent to Event Grid which will process the Meta Data.

Azure Function will perform the data migration to SQL Data Warehouse.

Tutorial: Migrate event data to SQL Data Warehouse - Azure Event ...

Computer Vision API–Testing SRK Photo

Computer Vision API provides ready algorithms for processing images – It can classify a picture as object, animal etc.  It can also validate it with Celebrities – all through the machine learning infrastructure of Azure under the hood.

image

Azure Service

For testing this you need to create the Computer Vision service from Azure > Marketplace.

image

Choose the S1 tier as most of the capabilities are residing there.

image

Console Application in C#

Create a Console Application in C# and add the following Nuget package.

image

SRK

As a test I am going to upload above SRK picture & let the Computer Vision API identify him.

Output

The API is successfully identifying SRK! Smile

image

The Code

using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Rest;
using System;
using System.IO;
using System.Net.Http;

namespace ComputerVisionAPI
{
     class Program
     {
         static void Main(string[] args)
         {
             var features = new VisualFeatureTypes[] { VisualFeatureTypes.Tags, VisualFeatureTypes.Description };

            ComputerVisionClient computerVisionClient = new ComputerVisionClient(
                 new ApiKeyServiceClientCredentials(“YOUR KEY”),
                 new DelegatingHandler[] { }
                 )
             {
                 Endpoint = https://URL.cognitiveservices.azure.com/
             };

            using (var fs = new FileStream(@”C:\temp\ShahrukhKhan.png”, FileMode.Open))
             {
                 ImageAnalysis result = computerVisionClient.AnalyzeImageInStreamAsync(fs, features).Result;

                Console.WriteLine(“TAGS >> “);
                 foreach (string tag in result.Description.Tags)
                     Console.Write($” {tag} “);

                Console.WriteLine(Environment.NewLine + Environment.NewLine + “CAPTION >>”);
                 foreach (ImageCaption caption in result.Description.Captions)
                     Console.WriteLine($”{caption.Text} – Confidence: {caption.Confidence} “);

            }
         }
     }
}

References

https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/#product-overview

Create an Angular App & Protect with Azure Easy Auth

In this post we can explore how to create an Angular App and Protect it with Azure Authentication Easy Auth without writing any line of code Nor making any configuration changes.

Create Angular App

  1. Install Node.js from https://nodejs.org/en/download/
  2. Open Command Prompt
  3. Run command npm install -g @angular/cli
  4. Create Project ng new AngularAAD
  5. Go inside folder & Run command ng serve
  6. Open the website http://localhost:4200

image

Publish to Azure

  1. Open Azure Portal
  2. Create new App Service
  3. Publish the Source
  4. Ensure Application accessible through URL

For Detailed Steps use this LINK

Azure AD – Easy Auth Protection

Go to App Service > Authentication Tab

Choose the following options.

image

Choose the Express settings.

image

Save Changes!

Now your Angular Application is protected with Azure AD Authentication.

Test Authentication

Go to the App Service > URL > Click to launch it

You will be prompted for Authentication.

image

This confirms Angular App protection with Azure Easy Auth.

Note

For advanced Configurations like Adding Users, Controlling Rules etc. you should use Azure AD Enterprise Applications page.

How to Disable Outbound Internet from a VM?

In this post we can see how to disable Outbound Internet Connectivity from a VM.

  • Outbound Connections are Originated From the system

Step1 : Create an NSG (Network Security Group)

image

Step 2: Disable Internet

Go to the Outbound Security Rules.  By default there will be 3 rules which enables Internet. 

We need to create a new rule with Lower Priority Number so it will be picked first.

Click the Add Rule button.  Make the following changes.

image

Save changes.

Step 3: Associate NSG with VM

Now go to the VM > Change the NSG to the new one.

Step 4: Test Connectivity

Restart the VM > Go to RDP > Open Internet Explorer > Try www.bing.com

You should not get the page displayed.  It ensures Internet Connectivity is disabled now.