Response Caching in .Net 6

This post explains how to configure Response Caching Middleware in an ASP.NET Core app using .Net 6. The middleware determines when responses are cacheable, stores responses, and serves responses from cache.

Caching response helps improve the performance and response time of Web APIs where it is possible. But it takes some effort to build out a caching infrastructure and manage it. The Response caching middleware which comes out of the box simplifies the implementation significantly. And also it does not require building custom implementation for caching, plus provides clients the option to choose whether to use a cached value or not.

Create a .Net 6 API, and modify the Program.cs file as below:

using Polly;
using Polly.Extensions.Http;

var builder = WebApplication.CreateBuilder(args);
var httpRetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
    //.CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddResponseCaching(x => x.MaximumBodySize = 1024);
builder.Services.AddHttpClient("errorApi", c => { c.BaseAddress = new Uri("https://localhost:7250"); });
builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(httpRetryPolicy);


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// UseCors must be called before UseResponseCaching
//app.UseCors();

app.UseResponseCaching();

app.Use(async (context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            Public = true,
            MaxAge = TimeSpan.FromSeconds(10)
        };

    context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = new string[] { "Accept-Encoding" };
    await next();
});

app.Run();

This API adds headers to control caching on subsequent requests:

  • Cache-Control: Caches cacheable responses for up to 10 seconds.
  • Vary: Configures the middleware to serve a cached response only if the Accept-Encoding header of subsequent requests matches that of the original request.

Add a ValuesController.cs and a simple Get endpoint:

[HttpGet]
public int Get()
{
    return DateTime.Now.Second;
}

Run the API and hit the Get endpoint through Postman and add Cache-Control Header with value “public” and you’ll observe the cached response for 10 seconds.

Retry and Circuit Breaker Policy example .Net 6 and Polly

In this example, we’ll implement the Wait and Retry and Circuit Breaker policy using .Net 6 Web API and Polly. For more details on what Circuit Breaker is, refer to the MSDN documentation.

Create a WebAPI with ValuesController in .Net 6 which will always return an Exception in the Get call.

using Microsoft.AspNetCore.Mvc;

namespace ExternalAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ValuesController : ControllerBase
    {

        private readonly ILogger<ValuesController> _logger;

        public ValuesController(ILogger<ValuesController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            throw new Exception("Error");
        }

    }
}

Let’s call this ExternalAPI and running on https://localhost:7250/.

Create another .Net 6 WebAPI called CircuitBreaker.Demo and install Polly and Newtonsoft.json Nuget packages.

Configure Polly and HttpClient in Program.cs file as shown below:

using Polly;
using Polly.Extensions.Http;

var builder = WebApplication.CreateBuilder(args);
var httpRetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
    
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient("errorApi", c => { c.BaseAddress = new Uri("https://localhost:7250"); });
builder.Services.AddSingleton<IAsyncPolicy<HttpResponseMessage>>(httpRetryPolicy);


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Now add the PollyController to call the ExternalAPI using the HttpClient:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Polly;

namespace CircuitBreaker.Demo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class PollyController : ControllerBase
    {

        private readonly ILogger<PollyController> _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IAsyncPolicy<HttpResponseMessage> _policy;

        public PollyController(ILogger<PollyController> logger, IHttpClientFactory httpClientFactory, IAsyncPolicy<HttpResponseMessage> policy)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
            _policy = policy;
        }

        [HttpGet(Name = "GetApiResult")]
        public async Task<ActionResult<IEnumerable<string>>> Get()
        {
            var client = _httpClientFactory.CreateClient("errorApi");
            var response = await _policy.ExecuteAsync(() => client.GetAsync("values"));
            response.EnsureSuccessStatusCode();
            return JsonConvert.DeserializeObject<string[]>(await response.Content.ReadAsStringAsync());
        }

    }
}

When you run both the APIs, the call to External APIs is automatically made using Wait and Retry policy after every retryAttempt number of seconds 3 times. After that, the calls are stopped as the ExternalAPI keeps giving 500 error.

CircuitBreaker example:

Now change the Http Retry Policy line in the Program.cs file to:

var httpRetryPolicy = Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));

The above line will open the circuit and will start giving Circuit Open Exception after 2 attempts and keep the circuit Open for 30 seconds, which means you cannot make further calls to the API for that duration. The Exception will now be shown as below:

Outsource Tasks To Improve Small Business Management

Image via Pexels

As a small business owner, you likely wear many hats and have little time to spare. But what if there were some tasks you could outsource to free up your time? When they hear the word “outsourcing,” many people’s first thought is that they’re sending work to another country, but it can simply mean hiring someone else to do a task that’s not in your area of expertise. Here are some tech-related tasks to outsource to improve your small business management, presented to you below by In The Tech Pit.

Web Design and Development

If you don’t have the time or expertise to design and develop a website for your small business, consider outsourcing this task. A professional web designer can create a website that looks great and functions well, and they can also help you choose the right hosting plan and domain name.

Most web design and development companies provide app development. Apps are a great way to improve customer service and engagement and promote and sell products. Check out online job boards to find top-tier app development companies that are the right fit for your business.

Social Media Management

Posting on social media is a great way to connect with customers and promote your products or services, but it can be time-consuming. It’s vital to post regularly and interact with customers.

If you don’t have the time to post regularly and interact with your followers, consider outsourcing social media management to someone who does. Many web design companies offer social media management services so that you can take care of two tasks with one vendor.

IT Services

If you’re not a tech expert, chances are you don’t have the time or knowledge to fix technical problems when they arise. It’s vital to have someone on call who can help you troubleshoot and resolve issues quickly.

IT services can be expensive, but they’re worth it if you don’t have the time or expertise to do it yourself. Look for an IT company that offers a flat-rate monthly fee, so you can budget for this expense.

Security

As a small business owner, you likely have sensitive data that you need to protect. Consider outsourcing cybersecurity if you don’t have the time or expertise to keep your data secure. Tech service providers often offer multiple services.

Choose Software To Support Your Tech Needs

Sometimes, you may avoid outsourcing altogether by using software to support your tech needs. For example, if you need help managing your social media accounts, consider using a tool, such as Hootsuite or Sprout Social. These platforms allow you to schedule posts, track analytics, and engage with your followers.

Another option is to use a project management tool, such as Asana or Trello, to keep track of tasks and deadlines. This type of software can be helpful if you have a team working on a project.

Support Your Business by Outsourcing Tech Needs

Outsourcing can be a great way to improve small business management, freeing up your time to focus on other tasks. You can outsource web design and development, social media management, IT services, and cybersecurity with tech-related tasks.

For more tips on tech and operating a successful small business, keep up with the latest news at In The Tech Pit.

How to Execute a Successful Home Business Venture

Image via Pexels

Are you faced with the dilemma of moving and starting a job? It’s hard enough to do one, but it can be difficult to manage both. It doesn’t have to be. InTheTechPit presents a guide that discusses the essential tips that will make your life easier.

Get the Best Deal on Your New Home

To start a home-based company, you must first buy the space. But as an entrepreneur, you want to get the best price possible. As you research homes in Sydney, think about how you can get the lowest price. One way is to buy a home as-is. But if you decide to go this route, you’ll want to make sure that you hire a local home inspector to thoroughly examine the property. While there are bound to be things you need to fix up on an as-is purchase, you don’t want to buy something with problems so serious that it causes you financial hardship.

Think About Your Business Formation

In many cases, business formation is a crucial step. Even if your goal is to hire employees or invest outside, it is important to form a company in order for you to limit your personal liability, pay taxes, and ensure that other details are taken care of.

How your business is organized will affect your liability and how taxes are paid. Shares of a corporation can be transferred more easily than LLC membership rights. Established investors prefer the predictable and well-established structure of a corporation.

Filing your own paperwork or using a service to file can help you avoid paying high-priced lawyers. There are different rules for forming corporations in each state. Before you proceed, make sure to check them out.

Essential Tips

When starting a business, it is important to decide whether you want to be an independent contractor or start your own corporation.

If your goal is to have a flexible work schedule and not be required to file taxes every year, then you might prefer to work as an independent contractor.

If you are looking to attract investors, however, shares of corporations can be transferred more easily than LLC membership rights. Established investors prefer the predictable and well-established structure of a corporation.

How your business is structured will affect your liability and how taxes are paid. Before making any decisions, it is a good idea to speak with an accountant or attorney. Instead, save money by hiring an LLC formation company.

More Tips for Success

  • You should research the tax implications of starting a home-based business.
  • Before purchasing a home, establish an LLC.
  • Before you file anything, make sure to check the regulations in your state for corporations.

Market Yourself

Marketing your home-based business in Sydney might feel intimidating, but it’s easy when you know what to do. Be sure to utilize social media, radio ads, billboards, bulletins, and video.

Conclusion

Starting a business and moving at the same time can be challenging, but it can be done. Follow these four steps to make the transition as easy as possible.

1. Invest time and energy into your decision to move to a new home

2. Apply for a business license and register your business name

3. Identify possible office space options near your new home

4. Understand how to set up utilities in your new location

Must-Have Tech Tools for Solopreneurs, Freelancers, and Small Business Owners

Image via Pexels

If you’re a solopreneur, freelancer, or small business owner, you may be hesitant to invest in technology, thinking that you’d rather keep your overhead costs low. However, buying the right tech tools can help you save time, stress, and—in the big picture—money at work. This guide explains where it’s worth putting your money.

Tech to Streamline Operations

More efficient business operations mean less waste and greater profits. Here are some technologies to enhance your work processes.

  • Project management tools help everyone in your team stay on top of deadlines. If you’re a solopreneur, they make it easy to track deliverables for clients.
  • Communication tools allow you to keep up with clients and workers alike.
  • API tools with microservice architecture can help your business stay secure and scalable.
  • Automation tools like Zapier and IFTTT help to save valuable hours.

Tools to Improve Your Financials

Maintaining control of money matters is a must for any business. These tools can help.

  • Accounting tools simplify your bookkeeping and tax filing processes.
  • Mobile apps help you manage your business finances when you’re on the go.
  • Cloud storage makes it easy to keep your digital documents organized.
  • The best invoice template makes it fast and easy to get the cash you’re due.

Technology to Keep Customers Happy

Your business relies on happy customers to survive. These tools can help keep them satisfied.

  • A great website manager allows you to maintain your online platform, which customers can consult for basic information.
  • Customer service solutions like Freshdesk and Zendesk allow you to meet customer needs and answer their questions.
  • Payment solutions like Authorize.net and Chargebee allow you to give customers varied payment options, enhancing convenience.
  • Customer feedback tools allow you to pinpoint where you can improve your customer service.

It might seem like investing in technology is a waste of money. After all, it will drive up your overhead costs, cutting into your profits. In fact, these kinds of tools can save you stress, time, and manpower—ultimately saving you money too.

How to create a subdomain?

If you’ve already bought a domain, and don’t want to purchase another for your sub-site, then you can create a sub-domain for your website. It can be a whole different website for which you can give the hyperlink on your main website.

Generally, the domain providers have an option to configure the sub-domain under the domain settings in the cPanel and we need to create A record there.

If you have a VPS or dedicated Server with a Public IP, the configure the IP value of the A record with the Public IP of the Server. So you need to provide following values:

Type: A record

Host: e.g. if your domain is mywebsite.com then put host as blog. So your subsite domain will be blog.mywebsite.com.

Value: Put the Public IP of the VPS or dedicated Server.

TTL: The TTL serves to tell the recursive server or local resolver how long it should keep said record in its cache. Usually, the recommended default is 1 hour but you can change as per your requirement.

Various domain providers like godaddy.com, cloudflare etc. have this kind of interface to point your subdomain to an IP address.

Microservices with .Net Core API and Azure Service Bus

Basic Microservice Architecture with Azure Service Bus and API Gateway

The above Architecture has the following components:

Front-end: ReactJS Application with a simple form hosted on App Service Plan which will hit the API Gateway with GET/POST requests.

Name Microservice: First Microservice hosted on App Service Plan that will take User Details from front-end and save PersonId and Name in it’s own Azure SQL database.

Azure Service Bus: The Name Microservice will forward the PersonId created and Address details from front-end to the Azure Service Bus Topic.

Address Microservice: Second Microservice hosted on App Service Plan will subscribe to the Topic that takes PersonId and Address data from the Name service and store the details in it’s own Azure SQL database.

This is not an ideal scenario for creating Microservice Architecture but it shows the idea how the individual components interact with each other.

*In addition to this, another Azure Function will subscribe to the Queue for new User creation and sends email to someone with the details. This is however, not shown in the above image.

The Front-end Application is a form created in ReactJS that takes in following fields from the User:

FirstName, MiddleName, LastName, Email, Phone Number and Address

The following front-end and back-end repositories have all the code for connecting to the required components.

Further, a separate Authentication Microservice can be created which will return a JWT token based on the credentials provided. The token can then be validated by the API Gateway configured with the API Manager Service and then allow the requests to go through to the other Microservices.

The front-end code does not have Login page in this sample, however it directly passes the credentials to the Auth Service to generate the token. The token is then passed through to the subsequent calls to the API Management Gateway.

Select Validate JWT policy for Inbound Processing at the Operation Level for APIs under API Management.

Change the issuer signing key while adding the Inbound Policy under API Management as per the key used while generating the token from your Authentication Microservice.

<inbound>
        <base />
        <validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized">
            <issuer-signing-keys>
                <key>xxxxxxxxxxx</key>
            </issuer-signing-keys>
        </validate-jwt>
    </inbound>

Also, make sure the CORS policy is updated under the respective APIs Inbound Processing at the required operations or All Operations level:

<cors allow-credentials="false">
            <allowed-origins>
                <origin>https://mywebsite.azurewebsites.net</origin>
                <origin>http://localhost:3000</origin>
                <origin>https://mypoc.servicebus.windows.net</origin>
            </allowed-origins>
            <allowed-methods>
                <method>GET</method>
                <method>POST</method>
                <method>OPTIONS</method>
            </allowed-methods>
            <allowed-headers>
                <header>Authorization</header>
                <header>Content-Type</header>
            </allowed-headers>
        </cors>

Update the connection strings as per your Database and Service Bus Services from the Code Repository provided above.

Another example of Microservices Architecture for a real world scenario is as below:

Microservices Architecture for Online Shopping Application

Recognizing Red Flags: Preventing Computer Scams and How Employees Can Help

Image via Pixabay

If you’re skeptical that your business could be infiltrated by internet scammers, consider that the Federal Trade Commission received reports of fraud from 2.2 million Americans in 2020 and that people in 20 countries lost $172 billion in 2017 to hackers, including consumers of all ages. Scammers keep getting more inventive and elusive, constantly adapting to upgrades in computer security and the vigilance of people in the commercial and consumer sectors. Like good con men, scammers prey on human greed and fear, and a momentary lapse of attention can prove disastrous. Here are a few of the more common scams to watch out for.

Phishing

Phishing scams are among the most common cyber attacks that businesses face today; it’s the third-most-common form of internet-based crime, according to the FBI. Phishing scams come in the form of emails that appear legitimate, perhaps disguised as a communication from Apple, Amazon, PayPal, or Microsoft indicating there’s a problem with your account and encouraging you to click on a link, or luring you with the promise of a purchase refund or discount. Following their link can give scammers access to your login information. 

Ransomware

Ransomware is another tricky scam that entices victims to double-click on an email attachment or download an attached file, which delivers a virus or malware that locks up your PC and encrypts your files. This is generally followed by a message that if you’ll pay a specific amount of money (usually demanded in Bitcoin so they can’t be traced by conventional means), the perpetrators will unlock/decrypt your files. Your best guard against this fast-growing scam is right out of computer security 101—set up a continuous backup system and always accept Microsoft security protection updates. These “click here” scams are always dangerous: All it takes is a click of the mouse by a distracted employee and you’ve got a security problem that can be time-consuming and costly to counteract.

Email from the Boss

Most of us are hard-wired to respond promptly and obediently when we receive an email from a supervisor or high-ranking company official. It’s a knee-jerk reaction, and that’s what the inventors of a rapidly growing scam are counting on. Targets receive an email from someone pretending to be “the boss,” who claims to need money wired to him to deal with a business emergency while he’s on the road. These tend to be carefully targeted emails and are difficult for spam filters to weed out, so make sure staff knows that no company official would ever make such a request (without going through the chain of command), and that they’re to bring it to the attention of management and IT immediately. Also, it’s not a bad idea to fine-tune your money transfer security to make sure a situation like this doesn’t occur.

Digital Forensics

A data breach can happen in a matter of seconds and do a great deal of damage before anyone knows what’s happened. It’s important to have cybersecurity technology in place to help locate the source of the problem and put a stop to it. However, there’s more to it, as digital forensic specialists can also preserve and recover your valuable data and analyze the situation so that further breaches can be avoided. Your cyber threat recovery plan should identify what data you need to recover first, define objectives, and specify which staff will be responsible for your recovery efforts.

Employee Training

Employees are your first line of defense against computer scams, so it’s important that they know what to watch for. One of the best ways to guard against attacks is to teach them to recognize any red flags, such as emails that contain impersonal greetings, grammar or style errors, and warnings that “immediate action” is required. Your company’s computer security protocol should ensure that any suspected attack is reported to the IT department in a timely manner. Advise staff to communicate with co-workers if they identify a scam to prevent others from being victimized, and staff should be prohibited from sharing passwords or other sensitive data via email.  

These days, companies rise and fall based on the extent, quality, and security of their data. That’s why it’s so vital that employees understand the threat that scams present, know how to recognize the signs and act accordingly to prevent catastrophic infiltrations. Establishing a clear protocol for staff members is one of the best ways to get everyone thinking in terms of computer security.

This article is brought to you by InTheTechPit. For more information, please contact us today!

To Survive, Small Businesses Need to Invest in 5 Tech Tools

A business’s ability to leverage technology and get ahead is one of the keys to its success.
However, small businesses assume that their budgets have to be big to reap the benefits.
But that’s not true. There’s a sizable industry geared toward helping smaller businesses
reap the benefits of innovation at affordable prices.

Why You Should Invest in Tech

Time is money, and if you’re able to save more time while increasing your profits, that’s a
good reason to invest in that kind of leverage. Some types of easily accessible technology
that benefit  businesses include:

  • Business process automation. BPA is one of the most important ways for businesses to reap benefits. Repetitive tasks consume valuable time and automating them frees up the staff’s time to pursue more profitable directions. Because of that, 66% of organizations are moving towards automating at least one business process. 
  • Managing customer experience. If you want more satisfied customers and a fatter bottom line, then you need to improve your customer’s experience. Managing customer experience is a top priority for 45% of companies. Half of the top performers regularly invest in designing user journeys that are seamless and clear.
  • Tracking and monitoring. By getting a handle on strategic metrics, you can keep an eye on your business’s overall health. Knowing how your finances are doing or what customers want and don’t want makes your business more nimble.

Technology Small Businesses Need

Customer Relationship Management Software

When you’re able to monitor and understand customer behavior, you can tailor each buyer’s journey for profit and value. CRM software tools help businesses stay at the top of the minds of their customers.

Data Backup

When things go wrong, having a solid data backup reduces downtime and business loss. The good news is that 86% of businesses do regular backups, However, three out of five backups are incomplete. In addition to backing up your data, test your system regularly to ensure it’s complete.

Password Management 

Web security is more important now that cyberattacks are on the rise. Part of the way to protect your site and business is to automate the process of password management. This includes setting policies about the strength of the password and how often they need to be changed.

Accounting Software

Accounting software is like having an accountant or bookkeeper ready. Not only will it keep track of your cash flow and expenditures, but it can also remind you of when you need to file certain taxes. Features like this improve tax compliance which saves companies money. 

Email Marketing

Many businesses turn away from email marketing, thinking that it’s on the way out. On average, email marketing returns about $42 for every dollar spent. A well-curated customer email list is money in the bank. These are the people your business can rely on to build your brand as both buyers and advocates.

Tailor Your Own Technology Solution

There are many technology solutions available to help your business stay competitive and profitable. Focus on which ones suit your primary business goals and work your way from there. 

Get useful code snippets you can use for SQL, Azure, and more at IntheTechPit.

Image via Pexels

List SQL Server Objects

To list out all Databases in SQL Server run the following query under master:

SELECT name FROM master.dbo.sysdatabases

To list out all SQL Server Jobs with Job Owner details use:

SELECT s.name AS JobName, l.name AS JobOwner
FROM msdb..sysjobs s
LEFT JOIN master.sys.syslogins l ON s.owner_sid = l.sid
WHERE l.name IS NOT NULL
ORDER by l.name

To list out all SQL Server Logins use:

select sp.name as login,
       sp.type_desc as login_type,
       sl.password_hash,
       sp.create_date,
       sp.modify_date,
       case when sp.is_disabled = 1 then 'Disabled'
            else 'Enabled' end as status
from sys.server_principals sp
left join sys.sql_logins sl
          on sp.principal_id = sl.principal_id
where sp.type not in ('G', 'R')
order by sp.name;

To list out all Linked Servers:

select sp.name as login,
       sp.type_desc as login_type,
       sl.password_hash,
       sp.create_date,
       sp.modify_date,
       case when sp.is_disabled = 1 then 'Disabled'
            else 'Enabled' end as status
from sys.server_principals sp
left join sys.sql_logins sl
          on sp.principal_id = sl.principal_id
where sp.type not in ('G', 'R')
order by sp.name;