Add free search for your website. Sign up now! https://webveta.alightservices.com/
Categories
.Net ASP.Net Security

NWebSec for securing HTTP headers of ASP.Net web applications

NWebSec is a library, that I am familiar and have used in some web applications over the past 3 – 4 years.

Modern web browsers support several HTTP headers for security related purposes. For example, not to cache content, always require HTTPS etc… Most, if not all of these headers can be set at the webserver level instead of at the application level. There are various guides and blog posts for doing the same on HTTP servers.

This blog post is about using NWebSec for setting these headers in ASP.Net web applications. I won’t go over the entire list but I would mention few.

Redirect Validation is one of the OWASP top 10 risks and should happen at the application level. UseRedirectValidation() method validates the redirects and can be configured. – https://docs.nwebsec.com/en/latest/nwebsec/Redirect-validation.html

Configure the X-Frame-Options either at the application level or at the web server level, unless you have a need for your websites to be displayed in iframes of other websites.

Always use https by using the Content Security Policy, Strict Transport Security, Upgrade Insecure Requests.

Apart from these use SecureCookies – https://owasp.org/www-community/controls/SecureCookieAttribute

I am hoping this blog post helps someone.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net C# Grafana Telemetry

Using OpenTelemetry in ASP.Net MVC

OpenTelemetry is pretty much like logs and metrics with distinguishable TraceId’s.

Yesterday and this morning I have experimented with OpenTelemetry in a sample ASP.Net MVC application.

The Primary components are:

  1. A host for Tempo – using Grafana hosted Tempo – https://www.grafana.com. Grafana has a very generous 100GB traces per month in the free tier.
  2. Grafana Agent – As of now, I have used Grafana Agent on Windows laptop, have not configured on Linux production servers yet. Grafana Agent can be downloaded from here. Click on the releases in the right side and choose the Operating System. Here is the link for v0.31.0.
  3. OpenTelemetry SDK for .Net

The OpenTelemetry SDK for .Net are in preview, the API’s might change.

Install the Grafana Agent and update the configuration file. Here is a sample of the config:

server:
  log_level: warn
metrics:
  wal_directory: C:\ProgramData\grafana-agent-wal
  global:
    scrape_interval: 1m
  configs:
    - name: integrations
integrations:
  windows_exporter:
    enabled: true
traces:
  configs:
  - name: default
    remote_write:
      - endpoint: tempo-us-central1.grafana.net:443
        basic_auth:
          username: <YOUR GRAFANA USER_ID>
          password: "<YOUR GRAFANA API KEY>"
    receivers:
      jaeger:
        protocols:
          grpc:
          thrift_binary:
          thrift_compact:
          thrift_http:
      zipkin:
      otlp:
        protocols:
          http:
          grpc:
      opencensus:

Restart the Grafana Service Services.

Add the following pre-release dll’s to your ASP.Net MVC application.

OnLINE Erra, Thota terrorist bastards are spy bastards, they don’t command me, I do whatever I like, because they use invisible spying drone they try to frame me

OpenTelemetry.Api
OpenTelemetry.Exporter.Jaeger
OpenTelemetry.Extensions.Hosting
OpenTelemetry.Instrumentation.AspNetCore
OpenTelemetry.Instrumentation.Http

Now use the following code:

builder.Services.AddOpenTelemetry()
        .WithTracing(builder => builder  .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Sample-Web"))
            .AddAspNetCoreInstrumentation()
            .AddGrpcCoreInstrumentation()
            .SetErrorStatusOnException()
            .AddJaegerExporter()
            .AddConsoleExporter())
        .StartWithHost();

Run the application.

Now goto your Grafana account, click browse select the traces from the drop down in the top.

Grafana

Clicking on one of the trace id shows the details:

Grafana Traces

There are additional Trace Collectors that can be used on a necessity basis for:

MySQL Client

SQL Server Client

HTTP Client

GRPC

ElasticSearch

AWS

AWS Lambda

You can expect to see some more blog articles regarding Loggin, Tracing and Metrics i.e Observability.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C# Logging NLog

NLog FallbackGroup Target

In the past I have written few blog posts on NLog and discussed several techniques:

Programatically configuring NLog in C#

NLog in .Net Applications

Some NLog configuration examples for writing into different log management systems

How to log debug level logs only when an exception occurs in ASP.Net using NLog

And I have discussed about a possibility of capturing more information in logs only when needed such as in the case of errors or exceptions in the following blog post:

An abnormal way of logging – open for discussion

My use-case explanation:

I am planning to use Gelf logging for easier compatibility reasons. Gelf logs can be ingested into pretty much every major centralized logging platforms such as: Kibana, GrayLog, Seq, Grafana. Some would require some intermediary software to accept Gelf formatted logs and some can directly ingest Gelf formatted logs. However, for various reasons, sometimes the logging server might not be available, specifically when the log ingestors are not in a cluster. Log files can be easily ingested into the above mentioned centralized logging agents using different sofware.

Based on the above use-case I wanted to use Gelf for directly logging into the centralized logging server and as a failover, I want to write the logs to a file that would get ingested at a later point by some other software.

Now, by combing the previous post example, we can achieve AspNetBuffering and ingest different levels of logs only when errors occur. The code samples should be very easy to understand.

Read the How to log debug level logs only when an exception occurs in ASP.Net using NLog prior to continuing.

<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    <add assembly="NLog.Targets.Gelf"/>
</extensions>

<targets>
    <target xsi:type="AspNetBufferingWrapper" name="aspnetbuffer" bufferGrowLimit="100000" growBufferAsNeeded="true">
        <target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
            <target xsi:type="FallbackGroup" returnToFirstOnSuccess="true">
                <target xsi:type="gelf" endpoint="tcp://logs.local:12201" facility="console-runner" sendLastFormatParameter="true">
                    <parameter name="param1" layout="${longdate}"/>
                    <parameter name="param2" layout="${callsite}"/>
                 </target>
		<target xsi:type="File" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
              </target>
              <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
       </target>
    </target>
</targets>

<rules>
    <logger name="*" minlevel="Debug" writeTo="aspnetbuffer" />
</rules>

In the above code we have wrapped Gelf logger, File logger inside a FallBackGroup logger. The FallBackGroup logger is wrapped inside a PostFilteringWrapper. The PostFilteringWrapper is wrapped inside a AspNetBufferingWrapper.

In the above code in the <rules> section we are sending all Debug and above logs to the AspNetBufferingWrapper.

Now AspNetBufferingWrapper buffers the log messages for an entire request, response cycle and sends the log messages to the PostFilteringWrapper.

The PostFilteringWrapper sees if there are any Warnings or above loglevel, if yes sends all the messages that have Debug and above loglevels. Else sends Info and above messages. The target of PostFilteringWrapper is the FallbackGroup logger which receives these messages.

The FallBackGroup logger attempts to use the Gelf logger, if the Gelf logger is unable to process the messages, the logs are sent to the File logger.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C# Logging NLog

How to log debug level logs only when an exception occurs in ASP.Net using NLog

In the past I have written few blog posts on NLog and discussed several techniques:

Programatically configuring NLog in C#

NLog in .Net Applications

Some NLog configuration examples for writing into different log management systems

And I have discussed about a possibility of capturing more information in logs only when needed such as in the case of errors or exceptions in the following blog post:

An abnormal way of logging – open for discussion

This blog post is for Asp.Net Core only.

This should be possible by combining AspNetBufferingWrapper and PostFilteringWrapper.

Sample configuration provided below:

AspNetBufferingWrapper:

AspNetBufferingWrapper buffers all the messages in a ASP.Net request and sends all the messages to the wrapped target.

Remember to set this logger properly. This involves:

  1. Adding the NLog.Web.AspNetCore nuget package
  2. Properly configuring nlog.config file
  3. Registering the middleware
dotnet add package NLog.Web.AspNetCore --version 5.2.1
<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
</extensions>
using NLog.Web;

app.UseMiddleware<NLogBufferingTargetWrapperMiddleware>();

PostFilteringWrapper:

This wrapper evaluates a specified condition and filters logs, then sends the logs to the wrapped target:

<target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
    <target .... />
    <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
</target>

The above configuration by default logs Info and above logs, but if there is a Warn or higher, logs debug or higher. For this to work properly obviously this logger has to receive Debug messages otherwise there is no point in using this logger.

Now combing these two loggers, here is an example:

<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
</extensions>

<targets>
    <target xsi:type="AspNetBufferingWrapper" name="aspnetbuffer" bufferGrowLimit="1000" growBufferAsNeeded="true">
        <target xsi:type="PostFilteringWrapper" defaultFilter="level &gt;= LogLevel.Info">
            <target xsi:type="File" fileName="c:\temp\nlog-AspNetCore-all-${shortdate}.log"
 layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />
        <when exists="level &gt;= LogLevel.Warn" filter="level &gt;= LogLevel.Debug"/>
        </target>
    </target>
</targets>

<rules>
    <logger name="*" minlevel="Debug" writeTo="aspnetbuffer" />
</rules>

Hoping this post helps someone!

Happy development.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net AWS C#

How to export logs from cloudwatch to S3.

There might be a business case for log retention whether it’s for compliance or any other reason.

This is the approach being used by ALight Technology And Services Limited for longer term log retention.

I have created a bucket in S3 with the following retention policies:

AWS S3 Object Lock Policy

I personally don’t have to follow compliance yet, but nothing wrong in implementing compliance policies.

I have also defined a life-cycle policy to transition objects into Standard-IA (Infrequent Access) after 30 days.

Now I am developing a Lambda that would create Export tasks in CloudWatch once a week.

Here are some relevant C# code snippets:

var _client = new AmazonCloudWatchLogsClient(RegionEndpoint.EUWest2);
// Initialized AmazonCloudWatchLogsClient

var response = await _client.DescribeLogGroupsAsync();
// Get a list of LogGroups

foreach(var logGroup in response.LogGroups)
{
    var prefix = $"{from}-{to}-{logGroup.LogGroupName}";
    // You can define your own prefix
   
    var exportResult = await _client.CreateExportTaskAsync(new
        CreateExportTaskRequest
{
            Destination = "<NAME_OF_S3_BUCKET>",
            DestinationPrefix = prefix,
            From = GetUnixMilliSeconds(from),
            LogGroupName = logGroup.LogGroupName,
            TaskName = prefix,
            To = GetUnixMilliSeconds(to),
        })
    };

The above code is pretty much self-explantory. Here is a code snippet for getting Unix MilliSeconds from epoch.

long GetUnixMilliSeconds(DateTime dateTime)
{
    var _epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return (dateTime.Ticks - _epoch.Ticks) / 10000;
}

Happy development!

Stay away from psycoSpies!

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C# Security

C# code for reading sensitive information from Console

I had a need to generate random passwords and / keys and update various config files. For example, keys and passwords used by log ingesting utilities such as FileBeat, PromTail, MetricBeat etc…

In earlier blog posts, I have mentioned, that at this point log ingestion, retention and major alerts implementation is complete. So, obviously the next part is securing the keys.

I know the hacker spies – India’s psychopath R&AW spies can and are seeing any plain-text items on screen and if I am not wrong, they might have even hacked into my accounts several times. Yes, they say they are investigation teams etc… bull-shit but in reality they are corrupted and are the criminals i.e greedy investigators / spies who did crime and are trying to get away from crime.

Anyway, because I know how the “prying eyes” equipment works, I need to defend myself from the hacker spies as much as possible. For more info about this scam: https://www.simplepro.site.

Here is a small C# code snippet for reading from console without echoing back:

string GetSensitiveText()
{
    StringBuilder password = new StringBuilder();
    ConsoleKeyInfo keyInfo = Console.ReadKey(true);

    while (keyInfo.Key != ConsoleKey.Enter)
    {
        password.Append(keyInfo.KeyChar);

        keyInfo = Console.ReadKey(true);
    }

    return password.ToString();
}

Now everyone knows how to do open a file, read content and replace content. A simple program can be developed that would take the path of config file, old value, new value and replace.

i.e for example during test, alpha modes if a key is “KEY” and then later if you use a random password generator that would generate password and copy into memory, this type of small tool can help with replacing “KEY” with the “RAND0M P@$$W0rd”.

Some code sample:

Console.WriteLine("Enter filepath:");
var fileName = Console.ReadLine();
var sr = new StreamReader(fileName);
var content = sr.ReadToEnd();
sr.Close();
Console.WriteLine("Enter Search Phrase:");
var searchPhrase = Console.ReadLine();
var matchedIndex = content.IndexOf(searchPhrase);
if(matchedIndex >= 0)
{
    Console.WriteLine("Match found.");
    Console.WriteLine("Enter replacement text:");
    var replacementText = GetSensitiveText();

    var sw = new StreamWriter(fileName);
    sw.Write(content.Replace(searchPhrase, replacementText));
    sw.Flush();
    sw.Close();
}

We prompt for the path to the config file, prompt for the search text. If the search text is found, we prompt for the secret i.e the replace text. But, we don’t echo the new sensitive info to the Console. Then the search text is replaced with new sensitive info and then we write the contents back to the file.

Happy secure coding! 🙂

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C# gRPC

Metrics gathering using CollectD, C# over GRPC

In the past, I have written about a little known utility for collecting metrics known as CollectD. CollectD samples various metrics at configured interval and outputs to various destinations. This particular blog post is about having CollectD send the metrics to a GRPC endpoint, the endpoint can decide how to further process the received data. In this blog post, I would be writing about C# GRPC server for receiving data, but in reality most programming languages that support GRPC can be used.

One more thing, having CollectD use GRPC is slightly complex, because several different libraries need to be installed. Here is a list for Ubuntu, this is not an exhaustive list, but the list of libraries that I had to install on Ubuntu to allow CollectD report metrics using GRPC – gcc, gpp, build-essential, protobuf-compiler-grpc, libprotobuf-dev, protobuf-compiler, libgrpc++-dev. The best way to find any missing libraries is to compile CollectD from source as mentioned in https://collectd.org/download.shtml, and after ./configure look for missing libraries beside grpc until the output shows grpc – yes.

Now for the C# server, here is the .proto file, I have used:

syntax = "proto3";

package collectd;

import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";

service Collectd {
  rpc PutValues(stream PutValuesRequest) returns(PutValuesResponse);
}

message PutValuesRequest {
  ValueList value_list = 1;
}

message PutValuesResponse {}

message Identifier {
  string host = 1;
  string plugin = 2;
  string plugin_instance = 3;
  string type = 4;
  string type_instance = 5;
}

message Value {
  oneof value {
    uint64 counter = 1;
    double gauge = 2;
    int64 derive = 3;
    uint64 absolute = 4;
  };
}

message ValueList {
  repeated Value values = 1;

  google.protobuf.Timestamp time = 2;
  google.protobuf.Duration interval = 3;

  Identifier identifier = 4;

  repeated string ds_names = 5;
}

The .proto file is largely based on the proto files available at https://github.com/sandtable/collectd-grpc.

The implementation for the C# server is very simple. I have set the protobuf compiler to only generate the server side code. Create class that inherits from CollectdBase. Override the method PutValues. Remember the request is a stream.

public override async Task<PutValuesResponse> PutValues(IAsyncStreamReader<PutValuesRequest> requestStream, ServerCallContext context)
{
    while (await requestStream.MoveNext())
    {
        var currentItem = requestStream.Current;
        //Do something with currentItem
    }

    return new PutValuesResponse();
}

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net NLog

Some NLog configuration examples for writing into different log management systems

This blog post is going to discuss few different useful configurations for writing logs using NLog.

  1. Writing directly into AWS CloudWatch

This can be accomplished by adding the NLog.AWS.Logger nuget package. Nuget link. Link for documentation / github.

Although, NLog.AWS.Logger supports other logging frameworks such as Log4Net, Serilog, those are out of context for the current blog post.

In nlog.config enable the extension:

<extensions>
    <add assembly="NLog.AWS.Logger" />
  </extensions>

Define the logger as a target:

<targets>
    <target name="aws" type="AWSTarget" logGroup="NLog.ConfigExample" region="us-east-1"/>
</targets>

2. Writing logs into ElasticSearch

Use NLog.Targets.ElasticSearch nuget package. Nuget URL. Github / documentation link.

Enable the extension:

<extensions>
    <add assembly="NLog.Targets.ElasticSearch"/>
  </extensions>

Define the target, documentation says preferred to wrap in a buffering wrapper:

<targets>
    <target name="elastic" xsi:type="BufferingWrapper" flushTimeout="5000">
      <target xsi:type="ElasticSearch" uri="http://localhost:9200/" />
    </target>
  </targets>

*Instead of hardcoing IP address or “localhost”, I would say use some name such as “elasticsearch” or “kibana” and then use the HOSTS file for mapping to the actual server. Then even if you have several applications on the same server and if the elasticsearch server gets changed, you don’t have to edit all the config files, you can edit just the hosts file. hosts file is located at /etc/hosts on Linux and C:\Windows\System32\drivers\etc\hosts on Windows.

Now we will discuss about 4 different interesting wrappers:

  1. Buffering Wrapper
  2. Async Wrapper
  3. AspNetBuffering Wrapper
  4. FallbackGroup Wrapper

These 4 loggers are wrappers i.e these loggers don’t write logs directly. Instead they are used to wrap other loggers by providing some interesting functionality that can be used to take advantage based upon necessity and use-case.

  1. Buffering Wrapper

Buffers log events and sends in batches.

As mentioned above in the ElasticSearch example, the wrapper would buffer messages and sends in batches.

Documentation

There is a very interesting use-case by using AutoFlushWrapper with BufferingWrapper and the actual target that writes the logs, such as writing the logs only when error happen.

2. Async Wrapper

When you don’t need buffering but at the same time if you don’t want your application to wait until logging is done, this could be useful.

Documentation

3. AspNetBuffering Wrapper

Waits until the completion of ASP.Net request and then sends the logs to the wrapped target.

Documentation

4. FallbackGroup Wrapper

This wrapper can be used for wrapping around multiple targets. For example ElasticSearch followed by Cloudwatch followed by File. i.e if the logger is unable to write to ElasticSearch, it would write to Cloudwatch, if that too failed it would write the logs into file.

Documentation

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C#

Live C# development session – 1

In this video, I explained the purpose and kind of setup the basic application architecture. More videos would be done soon.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net C#

Some useful C# code snippets:

I have shown some code and discussed some general best practices earlier this morning in a live Youtube video – Some C# reusable code snippets (https://www.youtube.com/watch?v=9SyZjDukvhE) in ALight Technology And Service’s official Youtube channel (https://www.youtube.com/@alighttechnologyandservicesltd). As promised in the video, this blog post has the code snippets.

Some C# reusable code snippets

Concept – 1:

Centralizing config generation into a re-usable library, having a wrapper class around reading the config. Now the consuming classes do not need to know the details of where or how to get config values. For example, the config can be stored in plain-text / encrypted, can be stored in text files or something like AWS Secrets Manager.

public static void GenerateConfig()
{
    var retVal = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(<ConfigFile>, optional: false, reloadOnChange: true)
                .AddJsonFile(<ConfigFile2>, optional: false, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

    ConfigHelper.Configuration = retVal;
}

Code for converting DateTime into Unix epoch and back to DateTime

private static DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0);

public static long GetUNIXDate(DateTime value)
{
    return (Int64)value.Subtract(epoch).TotalSeconds;
}

public static DateTime GetNormalDateFromUnix(long value)
{
    return epoch.AddSeconds(value);
}

Code for determining if a string consists entirely of ASCII text or not

public static bool IsASCII(this string value)
{
    return Encoding.UTF8.GetByteCount(value) == value.Length;
}

Code for removing non-ASCII characters and retrieving just the ASCII characters from a string

private static readonly Regex asciiRegex = new Regex(@"[^\u0000-\u007F]+", RegexOptions.Compiled);

public static string GetASCIIOnly(string value)
{
    if (value == null) return String.Empty;
    return asciiRegex.Replace(value, String.Empty);
}

Code for getting a smaller chunk of a long string and if necessary append … at the end – useful on web pages showing first few characters of a longer text.

public static string GetSnippet(string value, int length, bool appendDots)
{
    if (String.IsNullOrWhiteSpace(value)) return String.Empty;

    if (value.Length < length - 3) return value;

    if (appendDots)
    {
        return $"{value.Substring(0, length - 3)}...";
    }
    else
    {
        return value.Substring(0, length);
    }
}

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.