How to serve static files from the nodemodules in ASP.NET Core

Here I am going to explain how to serve static files from the nodemodules

Step 1 : Add a NPM package.json file
Right click on Visual Studio Add > NewItem and select NPM configuration files and add to the project.


Step 2 : Update the package.json with required dependencies for application.

Make sure name should be lowercase without space.

Once you save the package.json , you can see the npm package in project dependencies and also node modules are downloaded in to the project directory.You can include the node_modules folder in to your VS Project by clicking show all files and include in to the project.

Step 3 : Create Middle ware to serve the files from node_modules directory
In order to create your own middleware , First you have to create an extension method for the builder to serve the files from the node_modules directory

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.FileProviders;
using System.IO;

namespace Microsoft.AspNetCore.Builder
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app,string rootPath)
{
//Combine the rootpath to the node_modules to get the absolute path
var path = Path.Combine(rootPath, "node_modules");
var fileProvider = new PhysicalFileProvider(path);
var options = new StaticFileOptions();
options.RequestPath = "/node_modules";
options.FileProvider = fileProvider;
app.UseStaticFiles(options);
return app;
}
}
}

When you set a RequestPath , static files Middleware only try to respond to request starts with node_modules.

FileProvider is where does it goes to FileSystem to look for the file.

Finally Call the method by passing the application rootPath

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Builder
{
public class Startup
{

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IConfiguration configuration ,ILogger logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseStaticFiles();
app.UseNodeModules(env.ContentRootPath);
app.UseMvcWithDefaultRoute();
app.UseMvc(ConfigureRoutes);

}
private void ConfigureRoutes(IRouteBuilder routeBuilder)
{
routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id}");
}
}
}

Note : Please make sure the namespaces for extension method and startup.cs class are same. This is the approach that Microsoft uses to resolve the extension method for IApplicationBuilder to ensure method is more diiscoverable.

What is WebHost builder in ASP.NET Core?

A WebHost builder is an object , which is responsible for setting up the web server environment.These settings are completely customizable by writing our own builder. By default Web host builder is using Kestrel web server, which is a cross platform web server supported by .NET Core. This Webserver will listen all the http request connections. Also This builder set ups IIS integration. If your application are running under IIS , it is the integration that allows IIS to pass through Windows Credentials to the Kestrel server.

5

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost?view=aspnetcore-2.1

How to subscribe and unsubscribe the window load event in Rxjs

I know every web programmers are aware of adding window.addeventlistener to ensure some codes are executing once when loading the web page. You can remove the listener by removing using removeEventListener to make avoid the memory leak.

You can do the same thing in a RxJs fashion using take(1). So you no need to unsubscribe it explicitly to avoid the memory leak.
var onWindowLoad=Observable.fromEvent(window,'load');

var onLoadSubscription=onWindowLoad.take(1).forEach(function(event){
alert("onLoadFireEvent");
});

How Map and Filter function works in RXJS

In order to understand how Map and Filter works , we can implement our own map function.
Map
Map in Rxjs used for projection, means you can transform the array in to entirely new array.

Array.prototype.map = function(projectionFunction){
var results=[];
this.forEach(function(item) {
results.push(projectionFunction(item));
});
return results;
};

You can see I have written a map function which accepts an anonymous function as a parameter. This will be your function to apply the projection to transform the array. Inside the map function you can see iterating each item in a array , call the project function by passing each item and finally the result of the projection function will push to the results array.

JSON.stringify([1,2,3].map(function(x){return x+1;}))

Output
[2,3,4]

https://www.learnrxjs.io/operators/transformation/map.html

Filter
Filter is used to filter an array based on some condition. You can specify the condition through an anonymous function. The implementation of Filter and Map are almost same only the difference is Map will transform each item in an array and will push to the main array. But the filter will only push to the main array if the condition pass.
var hotelCollection = [
{
"id": 9999,
"name": "Hotel XXX",
"place": "Wayne",
"rating": 5.0
},
{
"id": 8888,
"name": "Hotel YYY",
"place": "WoodCliff Lake",
"rating": 4.5
},
{
"id": 7777,
"name": "Hotel ZZZ",
"place": "Franklin Lake",
"rating": 5.0
},
{
"id": 6666,
"title": "Hotel PPP",
"place": "Lancester",
"rating": 4.3
},
];

Source

Array.prototype.filter=function(predicateFunction){
var results=[];
this.forEach(element => {
if(predicateFunction(element)){
results.push(element)
}
});
return results;
}

var collection = hotelCollection.filter(x=>x.rating===5);
https://www.learnrxjs.io/operators/filtering/filter.html
Thanks for reading

How Yield keyword works in C#

Yield in C# , can use with the return statement to build a collection of returns. For example , I have a method that we need to return a collection of integers in a lazy manner and expose it through an IEnumerable interface. Based on the value produce with the yield return , consumer can write some logic based on their need.

In the below example you can see I have a method ReturnSomeIntegers() , which return 1 to 10 by iterate using for loop with yield keyword and also two more yield return with 20 and 30 respectively.

class Program
{
static void Main(string[] args)
{

YieldDemo();
Console.ReadKey();

}
static void YieldDemo()
{
foreach ( int n in ReturnSomeIntegers())
{
if (n == 20)
{
Console.WriteLine("From Yield Return Two - " + n);
}
else if (n == 30)
{
Console.WriteLine("From Yield Return Three - " + n);
}
else
{
Console.WriteLine("From Yield Return One - " + n);
}
}
}
private static IEnumerable ReturnSomeIntegers()
{
for(int i = 1; i <= 10; i++)
{
yield return i;
}
yield return 20;
yield return 30;
}
}

Whenever ReturnSomeIntegers() method return a single value , the execution will switchback to YieldDemo() for each method and print the value based on the condition.

In Computer Science this is known as Continuation
https://en.wikipedia.org/wiki/Continuation

Publish and Consume Azure Service bus queues pro-grammatically in C#

You can easily publish messages in to the queue and subscribe messages from queue pro grammatically using C#
Publish messages in to queues

var connectionString = "Endpoint=sb://rack-messaging.servicebus.windows.net/;SharedAccessKeyName=messagecollectionlistener;SharedAccessKey=DnentJvFthm13IWicMJxrM68LK3c+zEeQb6QlQn71SA=;EntityPath=messagecollection";
var client = QueueClient.CreateFromConnectionString(connectionString);
var lastKey = ' ';
var count = 1;
while (lastKey != 'q')
{
var body = $"Message {count++}";
var message = new BrokeredMessage(body);
client.Send(message);
Console.WriteLine($"Sent {message.MessageId}");
lastKey = Console.ReadKey().KeyChar;
}

Consume

var connectionString = "Endpoint=sb://rack-messaging.servicebus.windows.net/;SharedAccessKeyName=messagecollectionlistener;SharedAccessKey=DnentJvFthm13IWicMJxrM68LK3c+zEeQb6QlQn71SA=;EntityPath=messagecollection";
var client = QueueClient.CreateFromConnectionString(connectionString);
client.OnMessage(message => {
Console.WriteLine($"Message : {message.MessageId} Message Body : {message.GetBody()}");
});
Console.ReadLine();

Connection string you can copy from here

Elastic Search – 403 – cluster_block_exception

I got an error while adding a new document to an existing index.

cluster_block_exception –  u’blocked by: [FORBIDDEN/12/index read-only / allow delete (api)]

Below are the put request I have tried to send

I resolved this error by sending a new put request to the products index( which are already created before) by updating the blocks.read_only_allow_delete to false.

Url you have to send the put request

http://localhost:9200/{{yourindex}}/_settings

In my case the index is products

http://localhost:9200/products/_settings

Body parameter that you are passing along with the request

{
“index”:{
“blocks.read_only_allow_delete”:false
}
}

After the successful request I got the exact result I am expected