Taswar Bhatti
The synonyms of software simplicity
aws-cdk-csharp

I wanted to start a series of how to use AWS Cloud Development Kit (CDK) to create infrastructure on Amazon. In our first example we will tackle the fundamental of a Virtual Private Cloud (VPC). We will be using AWS CDK to create a VPC in C#. You may wonder what about CloudFormation json or yaml files that Amazon allows one to create infrastructure that you maybe very comfortable in doing it, is CDK replacing that?

What about CloudFormation?

AWS CloudFormation enables you to do many things, below are some of the things that the CDK allows us to do. (https://docs.aws.amazon.com/cdk/latest/guide/home.html)

  • Create and provision AWS infrastructure deployments predictably and repeatedly.
  • Leverage AWS products such as Amazon EC2, Amazon Elastic Block Store, Amazon SNS, Elastic Load Balancing, and Auto Scaling.
  • Build highly reliable, highly scalable, cost-effective applications in the cloud without worrying about creating and configuring the underlying AWS infrastructure.
  • Use a template file to create and delete a collection of resources together as a single unit (a stack).

Rest assure that Cloudformation is here to stay and CDK is not a way to replace it, but think of it in terms of a SDK for you to create infrastructure in the language of your choice.

Ok tell me more about CDK?

The advantage of AWS CDK is that you can define your cloud resources in a familiar programming language. As it stands the AWS CDK supports TypeScript, JavaScript, Python, Java, C#/.Net, and (in developer preview) Go lang. As a developers you can use one of the supported programming languages to define reusable cloud components known as Constructs. You compose these together into Stacks and Apps. The other advantages of the AWS CDK include listed below:

  • Use logic (if statements, for-loops, etc) when defining your infrastructure
  • Use object-oriented techniques to create a model of your system
  • Define high level abstractions, share them, and publish them to your team, company, or community
  • Organize your project into logical modules
  • Share and reuse your infrastructure as a library
  • Testing your infrastructure code using industry-standard protocols
  • Use your existing code review workflow
  • Code completion within your IDE
More information at (https://docs.aws.amazon.com/cdk/latest/guide/home.html)

What is an Amazon Virtual Private Cloud (VPC)?

Before we get started I wanted to provide some information on VPC. With Amazon Virtual Private Cloud (Amazon VPC), you can launch AWS resources in a logically isolated virtual network that you define. You have complete control over your virtual networking environment. This includes selecting your own IP address range, creating subnets, and configuring route tables and network gateways. And the reason to use a VPC is that your applications and database will be accessible over the network, but you may not want them to be accessible to everyone over the internet. Using an Amazon VPC, you can control who accesses which resources over the network.

Show me what we are building

The diagram below shows us the VPC that contains two Availability Zones, and in each one you will see there are 2 subnets a public and a private subnet. The public subnet will allow internet traffic while the private will not.

Usually you want to put your infra in private and only allow certain traffic to go through and reach them through the public
VPC-subnet

VPC-subnet

Requirements for CDK

In order to work with the cdk we will need 2 things, nodejs and the other is of course .NET 5 or 6. If you have nodejs and .net 5 or 6 ready then all you have to do is open your command line terminal and execute the following command to install cdk.

Now that the cdk is ready lets create a directory and intiliaze our application creation.

Lets take a look at what was created.

Below we have a list of generated application has created.

  • A cdk.json file, with AWS CDK configuration
  • A README.md file with some documentation that you may add for your project
  • A src folder with the C# application
    • A CdkVpcSample folder with the generated C# code
    • Program.cs contains the main file., where we define how we will connect to our cloud env.
    • CdkVpcSampleStack.cs contains the code for one CloudFormation stack (a stack is a collection of AWS resources that you can manage as a single unit), we use this to create the stack that we want.
    • CdkVpcSample.csproj is the project file.
    • GlobalSuppressions.cs deactivates one compiler warning.
  • Last but not least the solution file, CdkVpcSample.sln

We can now open the sln file in our visual studio and lets modify the Program.cs file. We will modify the code to use the Account Id that you have for AWS and also the Region you plan to use. If you wish to use Env variables you can use the first block also. For simplicity sake I am using the second block to target only the region I plan to use.

Now we can jump into CdkVpcSampleStack.cs file and add the code we wish to create the vpc. We will also use nuget to install the Amazon.CDK.AWS.EC2 package.
You can also just use Visual Studio and add the package through the UI, just search Amazon.CDK.AWS.EC2 and click on install.

Below is the vpc code that we will add to our CdkVpcSampleStack.cs file. Below we are creating a VPC with a CIDR 10.0.0.0/16 and 2 subnet one is public subnet with CIDR Mask of 24 and a private with a CIDR Mask of 24.

Let’s now try to build the project going to the root directory where src directory is and type in command line

Remember to target to .NET 5 or 6, you can change that in Visual Studio by right click and properties section.

How do deploy

In order to deploy first you will need a user who has programmatic access to your aws account. Reach into the IAM service on AWS console and create a user. You can read my other IAM post on how to create a user.

Once created you can use aws cli to configure the user you will use like below I have used an access key id and secret access for it.

Now you can finally deploy with cdk using the cdk deploy command.

Warning: This may incur AWS charges

If you now login to the AWS console you will see in Cloudformation section that your Stack was created, and also in your VPC section the VPC was create with public and private subnet.

Challenges

  • How to destroy the stack can you use cdk?
  • What happens when you do cdk deploy again
  • Change the Subnet CIDR to a different range
  • Play around with the MaxAzs option

Summary

I hope this helps in teaching and learning how to deploy a VPC using AWS CDK to create a VPC in C#, we will continue on with explorer more on CDK with .NET in the following with AWS RDS Database.

Source code located at https://github.com/taswar/AWSCDKSamples/tree/main/CdkVpcSample

BrotherPrinterRaspberryPi

I had this printer which is not a wifi built-in printer but nevertheless its a laser printer and I wanted to use it to print from any machine on my local network. I thought to myself why not use a raspberry pi and use cups. Thus my post on how to Setup Brother 1110 Printer on Raspberry Pi, I actually reuse the pi I had that is running pihole to block all the ads coming into my home network. Long story short I thought CUPS would be easy to setup and hoped everything will work, well of course things don’t just work without me tinkering on it, so here are the steps I used to finally to get it to work and hopefully it may help you also in your journey 🙂

First things first what is CUPS?

CUPS is a modular printing system for Unix-like computer operating systems which allows a computer to act as a print server. To install CUPS on a PI you can use the commands below.

Install cups and drivers from the Brother website
Login to your pi

Brother only provides i386 driver but as you may know Pi is a Arm processor so we need to somehow get them to work but first lets download the deb packages.

We will also add the architecture

We will also need to use Kali linux libc6 in order for this to work.

We will then extract the libc into a directory so that we dont need to mess with apt and then copy them over.

As you can see above we have 3 directories etc, lib and usr extracted into data directory. Now we will copy them over.

We will also add this to our env variable to build and then we can install our packages. You can ignore the warning, also you will get this error in cups also when you print so you can ignore that also.

Now lets install the cups wrapper.

Finally we need to restart our cups server

If you wish to manage cups with pi user use the commands below and then you can access cups with the web user interface on http://localhost:631

If you are using windows 10 you dont really need to install Samba you will be able to see your pi printer by just opening printer and add it will auto scan your network for it. Hopefully this will help you out and enjoyed reading How to setup Brother 1110 Printer on Raspberry Pi 🙂

aws

I needed to increase my disk size of my Windows 2016 server on AWS EC2. I though I will share this just in case it can help you or myself in the future on How to increase the disk size of a Windows EC2 machine?. First thing first you need to increase the volume space that you have, easiest way is to use the aws console.

Below I have logged in and am on the windows ec2 machine and have clicked on storage tab to find the volume I wish to increase.

Note: You can only increase there is no decrease

EC2-Stoage-Tab

EC2-Stoage-Tab

Click on the storage volume link and it will take you to the storage section on the console. Right click and choose Modify Volume.
A window will show up like below, enter the size of the volume you wish to increase it into.

EC2-Modfy-Volume

EC2-Modfy-Volume

Once successful you will see the message like below.

EC2-Modify-Volume-Success

EC2-Modify-Volume-Success

At this point you might be thinking you have completed and it will automagically increase your size. Unfortunately that is not the case, and you will be required to restart your instance and Remote desktop into it to increase it inside of windows also.

We will need to restart the instance and once restarted let us check the disk size.
As it states it is still 300G, we have changed it to 400G but nothing has changed. What the hell???

EC2-Windows-Disksize

EC2-Windows-Disksize

We will need to launch disk manager (diskmgmt.msc) and we will see that there is 100G that is not allocated yet.

EC2-Unallocated-Space

EC2-Unallocated-Space

We will need to right click on our existing volume and choose extend volume like below.

EC2-Extend-Volume

EC2-Extend-Volume

It will bring up a wizard where you click next, next and it will increase your volume like below.

EC2-Final-Result-Extended-Volume

EC2-Final-Result-Extended-Volume

Summary

I hope this helped in showing how to increase the volume size for your windows server running on EC2.

aws-dotnetcore-lambda

If you are using AWS S3 C# TransferUtilityUploadRequest and when you try to upload objects onto S3 you can potentially get Access Denied. The reason could your IAM Role is not defined to have access or your bucket name is incorrect.

What do you mean bucket name is incorrect? Basically it boils down to that buckets used with Amazon S3 Transfer Acceleration can’t have dots (.) in their names. So if you created a bucket with name e.g “my.fancy.bucket.” this will not work with TransferUtilityUploadRequest. You will need to change the name to “my-fancy-bucket” rather.

Example below I am using this code to upload some excel data.

Now if you change the code to use dash for the bucket name it will succeed in uploading, make sure you do have a bucket with that name already created.

Make sure to check the Role given to the lambda function also, use least privileges for s3 if possible to and if you are logging any information you need to give the Cloudwatch permission to your lambda also.

Hope this helps 🙂

aws-dotnetcore-lambda

If you are working on AWS Lambda Dotnet with C# and find out that you are getting something like an error like below.

Error message
Could not find the specified handler assembly with the file name ‘LambdaTest, Culture=neutral, PublicKeyToken=null’. The assembly should be located in the root of your uploaded .zip file.: LambdaException
[WARN] (invoke@invoke.c:331 errno: No such file or directory) run_dotnet(dotnet_path, &args) failed
START RequestId: b7bb069b-3f44-4cd6-8b63-43a37098cd5e Version: $LATEST
Could not find the specified handler assembly with the file name ‘LambdaTest, Culture=neutral, PublicKeyToken=null’. The assembly should be located in the root of your uploaded .zip file.: LambdaException

The main reason is that you most likely created the lambda on the console first and then tried to upload the code using dotnet cli e.g dotnet lambda deploy-function “functionName”.

In order to fix it, its quite simple you have to go back on the console and into the configuration section of the lambda function console. Find the Runtime Settings and click on Edit and change the Handler to the function name you are using. E.g MyTransformFunc::MyTransformFunc.Function::ProcessFile as you can see the ProcessFile is my method that I have in my code that needs to be executed based on the namespace I am using.

I hope this helps 🙂

Csharp-MS-Dotnet

In C#7 there is an enhancement in the main method Async Main in C# that will allow you to await in your main method. Let me show you an example of how it was in C#6 and then how it has changed in C#7.

You will remember this most likely

One will need to get the Awaiter and then GetResult in order for it to work. But now in C#7 you can write it like below.

And to add cherry to the icing, if you have a method that doesn’t return a value you can also just return Task.

Summary

The above code shows the ease that C#7 provides with its main method an great improvement from C#6 I would say, hope that helps you in learning C#.

Csharp-MS-Dotnet

In C#7 there is an improvement on using out parameter. Some of you may remember writing code like below.

The improvement that C#7 brings is you can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement like below:

And it doesn’t end there we can also use the var keyword if we choose to.

Summary

What are the benefits of this out parameter, well it does make the code is easier to read. You are not declaring it where you use it. Not to mention you don’t need to initialize the variable either.

Csharp-MS-Dotnet

In C# 7 there the new feature called Local functions in C#. Basically Local functions allow one to write a function within the body of another method or function. It comes in handly in the case lets say you are creating a helper function that are mostly just used in one class or where the declaration makes the code clear of the intention. Local functions also come in handly to write recursive functions rather than using a Lambda for it.

Here are some places where you can use local functions.

  • Methods, especially iterator methods and async methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

Below is an example where I Anonymize a string of emails, you can see that I am actually calling the local function below the return statement. Therefore where you can declare a local function below a return statement and also the Pattern variable is available inside the local function, since it is within its scope.

If you wish to read more on local functions take a look at the Microsoft documentation of local functions.

Csharp-MS-Dotnet

In C# 7 there are Expression Bodied Accessors which allows you to write getter and setters somewhat more functional way, somewhat lambda’ish. Let me show you an example. You may remember the old way of writing getter and setters like below.

Pre Expression Bodied Accessors Getter and Setter

Expression Bodied Accessors in C# 7

When using C# 7 you can use Expression Bodied Accessors like below which makes the code wayyyyy cleaner in my opinion. As you can see below, I have also added the null exception into the setter.

Summary

I hope I have explained how Expression Bodied Accessors can make your code way cleaner and easier to understand, not to mention that you can include exception into the setter since Exceptions are also Expression now. If you wish to learn more you can also visit Microsoft Learn Site on Express Bodied Accessors. Btw you can also use the Expression Accessors for Constructors and Destructors.

Csharp-MS-Dotnet

In C#7 there are Digit Separators and Binary Literals which were added. One may wonder what these are? Basically you can replace long number values with underscore (_) such that code readability is improved.

Let me give you couple of examples of it to make it clear.

Neat but it doesn’t end there you can also use it for Binary literals and Hex also, like the examples below, where they all are 2020 the year we all despise 🙂

Summary

I hope the C#7 Digital Separators and Binary Literals will give you a hand in writing more clear code 🙂

UA-4524639-2