Internet Of Things(IoT) with Node-Red and Azure: Part 1

node14

In my upcoming series of posts, I will explain how to create IOT hub in Azure, how to create an IOT device using the Azure code and how to integrate our IOT Azure with Node-Red.

First of all, let us see what is IOT?

As per Wikipedia:

The Internet of things (IoT) is the network of physical devices, vehicles, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data.

what is Node red?
Node-RED is a programming tool for wiring together hardware devices, APIs and online services in new and interesting ways.

It provides a browser-based editor that makes it easy to wire together flows using the wide range of nodes in the palette that can be deployed to its runtime in a single click.

It is basically used for Internet of things(IOT) as it is a flow-based programming.

node12

It is browser based flow editing and it is built on Node.js

In this post, I will explain how to create IoT Hub in Azure.

Let us go step by step:

Make sure you have an account in Azure. You can create a free account which has the validity for a month.

First of all, we will create IOT Hub in Azure:

node4

Give some useful name and click on Create:

NODE5

It will take some time and once the process is complete, it will show below message:

node6

Once it is done, you can search newly create IOT hub from resource groups as below:

node8

Click on Shared Access policy and then click on iothubowner to get the connection string of your IOT:

node10

Save the connection string as shown below:

node11

You have just created your first IOT Hub.

In my next post, I will show how to create your IOT device(We will use Azure’s sample code for that) and then will integrate it with Node-red.

 

Advertisements

Step by step installation of .Net Core 2.0

core26

In my previous post, I have explained how to set up for .Net Core 2.0 which you can find here.

But in that post, it mainly focuses on how to do the setup if you already have .Net Core. So in this post, I will explain how to install .Net core 2.0(Without having Core 1.0) on your machine.

First of all, you need to install .Net Core 2.0 sdk from here.

Once you double click on the exe, it will start the process as below:

core21

Once the process is done, it will show below window:

core22

Once this is done, Open Visual Studio command prompt as below and run the command:

dotnet new console -o console-app

core23

It shows that .Net Core 2.0 has been installed on your machine. For more information, you can go through the documents by clicking on the links shown in the console.

Now we will run a console application from the command prompt.

One sample application is already provided which resides on below path(It may change):

C:\Windows\System32\console-app

Now run the command:

dotnet run

core25

Which will return “Hello World”, it shows your installation is successful.

You can even run below command to verify the version:

dotnet –version

It should return 2.0

You can open this sample project on Visual Studio 2017.

To Create new Core 2.0 project, you need to select the version in the drop down as shown below:

core27

 

 

 

 

 

Razor pages compilation on Publish: A .Net Core 2.0 feature

core5

.Net Core 2.0 is announced last week and it came up with some awesome features.

I am going to explain its one of the best features which is the compilation of views and pages on Publish.

Till now(before .Net core 2.0) whenever we publish any MVC application, Razor files are published as .cshtml files and they get compiled at runtime.

Which means:

  • It takes a bit more time just to compile all those cshtml files
  • Publish output size increases

.Net Core 2.0 has one inbuilt functionality which compiles page and views on publish.

It means:

  • Our Razor pages and views would get published with our app as a compiled assembly instead of being published as .cshtml source files that get compiled at runtime

So it has advantages as:

  • Reduces application startup time
  • Reduces Publish output size

So the conclusion is, our .Net Core 2.0 applications are faster than the older applications.

Please note that we can disable this feature if we do not require this.

It can be done by simply updating below property in csproj file:

<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>

Have a look here if you require more details.

 

C# 8.0 expected features Part – I

c#8

We all know that Microsoft always delivers awesome features in all the releases and they are already planning for the features of C# 8.0

As per a video on Channel 9, Mads Torgersen has explained about the possible features of C# 8.0

There are possibly 4 features till now which are as below:

  • Nullable reference types
  • Async Streams(Foreach Async)
  • Default Interface Implementations
  • Extension Everything

In this post, I will explain about the Async Streams.

For normal Async methods we write it as below:

async Task(int) Test()
{
    return x;
}

and we call it by:

await Test();

What it does is, it waits until the things returned from Test method and after that only, it goes to the next step.

But it works with only one resource.

Now imagine we want to work with some live stream where we get data in the continuous live stream. For example, some IoT where data comes every moment. But we want to process them in our own time like one at a time.

Here comes the Async version of IEnumerable:

IAsyncEnumerable<T>

So basically, it is just like an enumerable except that when you move next in an enumerable way, that is Async.

It is kind of a way of Lay loading enumerability in Async way.

When defining an async iterator, you would use this function signature:

async IAsyncEnumerable<string> MethodName()
{
   yield return "Test";
}

And can be used as:

foreach await (string s in asyncStream)

Above is nothing but the combination of Async and Enumerable, you wait inside it and you return inside it.

Though it looks like IObersable but it is different. The benefit of using this instead of IObservable<T> from Reactive Extensions is that the consumer controls the flow rate. This is referred to as a “pull model” and IObservable<T> is a “push model”.

In Foreach Async, consumers tell when it is ready and then it processes the next one.

I hope you liked this future feature of C#.

 

 

 

 

.Net Core 2.0 deployment on AWS

core 7

In my previous post, I have explained how to setup your .Net Core 2.0 which you can find here.

In this post, I will explain how to deploy your .Net Core 2.0 application into AWS Elastic Beanstalk.

First of all, let us see what is AWS Elastic Beanstalk?

AWS Elastic Beanstalk is an orchestration service offered from Amazon Web Services for deploying infrastructure which orchestrates various AWS services, including EC2, S3, Simple Notification Service (SNS), CloudWatch, autoscaling, and Elastic Load Balancers.

Please note that Elastic Beanstalk currently has Core 1.0 and it will be soon updated to have Core 2.0

If you want to know about the .Net Core 1.0 deployment then have a look here.

So I will explain what can be done to deploy your Core 2.0 application on Elastic Beanstalk until the platform is updated to support Core 2.0

All we need to do is to add aws-windows-deployment-manifest.json file into our Core 2.0 application.

aws-windows-deployment-manifest.json is used to instruct Beanstalk to install .NET Core 2.0 on the instance during deployment.

Add below lines into to aws-windows-deployment-manifest.json file:

{
  "manifestVersion": 1,
  "deployments": 
  {
    "aspNetCoreWeb": [
    {
      "name": "app",
      "parameters": {
      "appBundle": ".",
      "iisPath": "/",
      "iisWebSite": "Default Web Site"
    },
      "scripts": {
      "preInstall": {
      "file": "./Scripts/installnetcore20.ps1"
       }
     }
   }
  ]
 }
}

Basically, above lines instruct Elastic Beanstalk to deploy .Net Core application.

But we want to deploy .Net Core 2.0 application, so for that we need to execute the ./Scripts/installnetcore20.ps1 PowerShell script which is already mentioned in above json file.

Now we need to add this ./Scripts/installnetcore20.ps1 Powershell file into Core 2.0 application.

Add below lines into PowerShell file:

$localPath = 'C:\dotnet-sdk-2.0.0-win-x64.exe' if(!(Test-Path $localPath)) { Invoke-WebRequest -Uri 'https://download.microsoft.com/download/0/F/D/0FD852A4-7EA1-4E2A-983A-0484AC19B92C/dotnet-sdk-2.0.0-win-x64.exe' -OutFile $localPath & $localPath /quiet /log c:\InstallNetCore20.log }

Above script downloads the .NET Core 2.0 installer and run the installer from the Microsoft site.

As we know that many times it is possible that link is broken or changed so in this case another option is to put Core 2.0 installer into the S3 bucket of AWS application (I did that way)

Our .Net Core 2.0 application looks as below:

core6

Another way is using Docker image if your application is Docker basked.

If you know any other way then please suggest in below comment section.

Logging in Asp .Net Core 2.0

core5

Logging is very important part of any application as almost all application requires proper logging.

.Net Core 2.0 has some simplified way of implementing logging.

Let us see what are the changes required to enable logging in .Net Core 2.0 application.

First of all, we need to make changes in appsettings.json file as below:

{
  "Logging": {
    "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
    }
  }
}

Here we have logger provider along with the levels so it allows us to configure logging levels per logging provider.

Previously, the entry in appsettings.json would only be applicable to the console logger but now the entry in the appsettings.json  has logger provider names in it like Debug, EventLog, TraceSource etc.

Do not forget to make these changes as it is required and it may throw the exception if you have missed this. I saw some StackOverflow questions mainly on this where people forgot to add related details in appsettings.json file.

Once it is done, in Main class, we can configure the logging details as shown below:

public static void Main()
{
  var host = new WebHostBuilder()
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .ConfigureAppConfiguration((hostingContext, config) =>
     {
       var env = hostingContext.HostingEnvironment;
       config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
       .AddJsonFile("hosting.json", optional: false)
       .AddEnvironmentVariables();
       })
       .ConfigureLogging((webhostContext, builder) => {
       builder.AddConfiguration(webhostContext.Configuration.GetSection("Logging"))
       .AddConsole()
       .AddDebug();
})
.UseIISIntegration() .UseStartup() .UseApplicationInsights() .Build(); host.Run(); }

So we can now move the logging configuration part into the WebHostBuilder.

In above code, concentrate on line:

logging.AddConfiguration(hostingContext.Configuration.GetSection(“Logging”));

This method sets up logging to look for configuration in a Logging section, in this case, we can write in appsettings.Development.json file as below:

{
 "Logging": {
   "IncludeScopes": false,
   "Debug": {
   "LogLevel": {
   "Default": "Information"
 }
 },
 "LogLevel": {
   "Default": "Debug"
 }
 }
}

Thus it overrides appsettings.json file.

After this, you can directly inject logger service into the controller as shown below:

private readonly IRepository _repository;
private readonly ILogger _logger;

public MyController(IRepository repository,
ILogger logger)
{
    _repository = repository;
    _logger = logger;
}

Now in your controller class, wherever you want to log for Information then it should be:

_logger.LogInformation(“Information”);

And if we want to log for warning then:

_logger.LogWarning(“WARNING!”);

Same goes for other levels as well.

Exception logging:

The logger method allows us to pass an exception as below:

catch (Exception ex) {
     _logger.LogWarning(ex, "Error");
}

Please note that different providers handle the exception information in different ways.

Some useful StackOverflow QAs:

https://stackoverflow.com/questions/45214468/asp-net-core-2-0-appsettings-development-json-not-working-with-logging-configura

https://stackoverflow.com/questions/45781873/is-net-core-2-0-logging-broken

 

SPA templates(Angular, React etc) with ASP .NET Core 2.0

In my last post, I have explained about the setup required for .Net Core 2.0 which you can find here.

Along with Core 2.0, there are some newly added default templates has been added by Microsoft team.

The major attraction is the SPA templates that are shipped with Core 2.0.

SPA templates like Angular, React.js, React.js and Redux etc can be seen in default template page:

core3

These three templates create actually the same sample application but the difference is in JavaScript libraries. Notice that these new templates are available only when ASP.NET Core 2 is selected from framework dropdown on top of the dialog.

The best part is, JavaScript Services functionality is used by these SPA templates to embed Node.js within .Net Core on the server. Thus it compiles the Javascript applications server-side as part of .Net build.

The advantage of having SPA templates in the default template section is, most of the required scripts, dlls and other required components are already added in the application so you can start building your application without worrying about the dependencies.