Skip to main content

· 4 min read
Ragavendra Nagraj

It might be that I already have documented about Csharp or dotnet and JS already. owever in this article I will ty to bring about pros and cons of them along with PHP.

  1. Basics - All the three languages Csharp, JS or TS have some common syntax like the ? to check if a value is null or ??= which is an assignment if the left hand value is a null. Not sure of PHP on this though.

String concatenation is similar for Csharp and JS or TS which is + sign, but for PHP one has to use the . operator.

var, let and const are used for variable types for string, numeric, [] array and {} keyvalue object in JS or TS. Csharp has var alone or the actual static type like int, long, double, string to name a few. In PHP all variables are declared without either of these, instead all variables start with dollar sign like $sdf. Types in PHP include string, int, float, index and associative array() like key values $arr = ["one" => "this is val one", 2 => "this is for 2"]

TS is more or less like a wrapper language on top of JS to help make it strictly typed with the support of some additional features likes enums and others like in csharp.

JS and PHP are loosely typed or strongly typed language whereas Csharp is strongly typed. However PHP expects ; at the end of the statements and will not interpret if there is a syntax error like missing colon.

  1. Uses - PHP was built back in the day to build web pages and websites and it can be evident from its in built methods such as $_SESSION, $_POST, $_GET, $_SERVER and similar global variables.

ASP .NET or Csharp was built to benefit both the Web development and game development with its strong object oriented programming support.

JS was mainly built to enhance user experience of the web pages. However with the development of Node, it is more or less solely used for web development along with CSS support from TailwindCSS and strict type support from TS.

JSX or TSX is a HTML templating type engine similar to PHP itself or which uses Blade or similar.

  1. Object oriented programming - Csharp is the modern strict type object oriented programming language inheriting a lot of its features from other languages as well. It supports class, interfactes, single inheritance through clasess, multiple interface inheritance, lambda's and similar.

JS supports class and is similar to Java, hence its name. Private variables in its class are prefixed with # like #gfd.

PHP seems to have a reasonable OOP support with classes, interfaces, inheritance and access modifiers like public, private and protected similar to Csharp.

  1. History and popularity - In terms of timelines, PHP with its nice features has been for a while like claiming to dominate about 70% of the web share with its popular CMS like Wordpress, Magento, Joomla or frameworks such as Laravel and similar.

Csharp is supposed to be more or less the next popular web development language with a share of about 10%. Along with C++, Csharp is the next programming language in gaming.

  1. Package managers - JS or TS use npm with them in packages.json file

PHP had similar with compose utility with packages listed in composer.json file

Csharp uses the dotnet install command to install the packages.

Summary

Irrespective of the features available in the modern programming languages, almost all of them are more less equally competitive. In terms of complexity, JS or TS seem to have loosing reputation. However, similar is heard of others as well. Csharp has a lot of features in its Blazor ASP .Net releases for support of Components and similar like from react or the ones in PHP. Date or time methods in JS can be a bit here and there. Csharp seem to have a better hold of it, I haven't tried them in PHP or did it a long time ago and I doubt much issue is there with it. Once good with one strict type OOP language, similar concepts like patterns Singleton, Factory, Facade, Remote and principles like SOLID can be easily applied. Csharp and PHP may have better support for dependency injection, like injecting them for each route or similar.

Authentication is done via middleware for Csharp and PHP which is similar in JS like in Next using next-auth npm.

Livewire is one PHP library which boasts about being better than its react counter part showcasing similar if not better results acheived in an easier way.

VSCode is a popular editor wo work on any of these programming languagesas of this writing.

· 4 min read
Ragavendra Nagraj

In this article I will bring about some of the RDBMS to consider for Node applications. Having used SQLite for one of the .Net applications I thought to use the same for a Node application without doing any prior research into it. Besides it it one of those areas where it is not enough the benefits of each. Without any further delay let me bring about the comparisons of them.

  1. Functionality -

    Both the sqlite3 or sqlite and the mysql2 npm's do as stated and there is no issues with that. Sqlite and the mysql packages has implementation of single threaded execution of queries in cases where you like to do one transaction after the other like say CREATE table abc IF NOT exists; and INSERT INTO table abc VALUES ("one", 2, "three");

  2. Performance -

    I will bring about the comparison in terms of data retrieval through an api and data load as well. i. Data retrieval - Both sqlite and mysql did fairly similar in terms of fetching data and not considerable differeneces were found. ii. Data load - I had a table of about three columns ( int(11), int(11), time) types. The time to load about preciseley 1879691 rows in sqlite was about eleven hours. The same table was loaded in about six minutes.

  3. Disk usage -

    In terms of size it was not possible to do a one to one comparison. However, the size of the app's sqlite database was about 116 mb whereas the mysql export dump stood to about 56 mb with an additional medium sized table.

  4. Data concurrency -

This is interesting as my app needed to load data periodically say every fifteen minutes or so. Unfortunately this happened to be one of the app's important requirement. The interesting fact found here was that I noticed the api calls needing the data from the databases were not able to do so as the database was locked during the process although the retrieval call was for an irrelevant table. This was one aspect which made to think about other options and some were posgres and mysql. Although I never tried posgres, mysql already catered to most of the requirements. This might necessarily be database specific I did not want to spend further time as I had options.

  1. Installation or setup -

Adapters for both are an easy npm i sqlite3 or npm i sqlite or npm i mysql2. I tries the sqlite3 as it had higher downloads, however I saw that sqlite seemed to be newer which I didn't try.

Installing the mysql ot the sqlite client on a *nux should be pretty straight forward and there should be relevant pages for your distribution for the same. Mysql involves a bit of more time in setup as you may have to run security script, create users, add priveleges and all.

  1. Database server -

I am afraid ony the mysql can run as a systemctl service and can be hosted on a remote server and might not be the same for sqlite which is a file database.

  1. Other options -

If using large data, I mean like large large data, say for machine learning or data science or similar, might be posgres is a better option which I haven't tried yet. I am assuming it to be equivalent to Oracle and have complex features and lot of addons exist for it.

One other package I like to bring to light is the nedb nosql which I used initially for the app. The interesting facts that lead me to RDBMS I will document in another post in this blog.

Summary -

This article is a rough comparison on the avilable open source RDBMS for your NodeJS app. The decision can solely lie on the aspects of your situation. Say if you need a simple file only data store or a server running for it. Might be the features are better in a different ecosystem like dotnet. It all depends on the cases to case by situations.

· 3 min read
Ragavendra Nagraj
Ankitha

In this article I will talk about the reasons for why to choose either a SQL or a NoSQL or even having an hybrid of both or your NodeJS applications. I will talk about the nedb for NoSQL and say mysql for the SQL.

  1. Installation -

    Both nedb and mysql installation is similar like npm i nedb or npm i mysql2. In terms of mysql you might have to follow a few additional steps as documented in the other article.

  2. Disk size -

With nedb one part is evident is that data is stored, however there is a higher chance that you have more duplicates in it than the SQL one. The json object is more or less saved as is. With the SQL option the duplicates can be mitigated before loading the data into the table.

  1. Performance -

Data retrieval times for both the SQL and the NoSQL seem to be similar but SQL could fair better in terms of how data is organized and adding indexes to the relevant column or columns.

One aspect here is working more with the SQL is always helpful. There could be situations where data retrieval is really slow and all that was needed was to add an index to required column.

In terms of data load the NoSQL could take like for about eight plus hours for about 1879691 rows of three columns ( int(11), int(11), time) types and SQL like mysql could do it in about six minutes. One situation I faced was say I had a table about six hundred unique fields and since it was taking forever to load it, I tried to separate the unique files into independent tables or databases. However, there were other issues like file wrtes as well when this was done and a higher chance of data loss or discrepencies.

  1. Data retrieval -

Complex data retrieval is mainly possible through the RDBMS soltuion alone like the SQL JOINS or the INs . One might consider having additional columns instead of a JOIN could do for now, but it is all situational as well.

  1. Skills -

Having used the SQL for quite some time ago, it was one part to revisit it and learn it. Honestly identifying the data types like CHAR(10), INT(11), TIME(), DATETIME() and implementing it in the app was well worth the effort I must agree.

Summary -

No doubt that NoSQL is the word in every one's mouth lately, however it mainly depends on the need fo the application. Say if it is a simple log store is what is needed, nedb might be the way. Even for situations like mine where the data needed on the website is fetched from another system, nedb was failry doing well.

· 2 min read
Ragavendra Nagraj

Have you ever been in a situation where you have spent hours together trying to debug as to why that database query is not awaited even after using the await for an async method.

Lately, I ran into an issue where the database call was passed and the method run finished with the undefined in the database response even after using await. After spending hours trying to fix it, one article took me back top using a Promise in javascript. Unfortunately this did not end the story as little was known to me that the two methods resolve and reject passed as params to the lambda call can be utilized to fetch the return response from that call like below.

export function getDataFromDb() {
var response = new Promise((resolve, reject) => {
....
// lines to fetch data from db
....

if(error) {
reject(error);
}

resolve(dbData);
})

return response
}

....
....
// make async call
var result = await getDataFromDb();
....

The resolve() call actually returns the response from the database call or similar.

Promise actually helps in awaiting the response from this or similar async calls and it also gives the benefit of reject the response, if an error was found.

· 2 min read
Ragavendra Nagraj

In this article I will give some tips on how one can work with configuration with ASP .Net apps. Almost all or any ASP .Net app anyway have this Microsoft.Extensions.Configuration.IConfiguration or simply put it as type IConfiguration.

There are usually one or two json files appsettings.json or or and the appsettings.Development.json. These contain settings for the app to use depending on the type of environment the instance is being run on. The first is for production and the later for development environment and more can de added as well.

Now let's say or appsettings.json is like below. Most of these config have provision for logging settings. say in production, the default might be Information meaning anything below that like Debug or Trace might not be logged. For development, the default might be Debug meaning almost all except might be Trace may not be logged which deserves another article for sure.

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"SomeApp": {
"Host": "192.168.a.l",
"Email": "abc@comp.co",
"Location":
{
"First": "Gatsby"
}
}

}

In case we need to retrieve the Host address of our SomeApp, then in the class which is loaded by the ASP .Net server let's say FirstService class, the IConfiguration can be dependency injected and the app's settings retrieved like below.

public class FirstService
{
public readonly IConfiguration _configuration;

public FirstService(IConfiguration configuration)
{
_configuration = configuration
}

public void RunApp()
{
Console.WriteLine("Host Config - " + _configuration["SomeApp:Host"]);
}
}

The _configuration["SomeApp:Host"] should give the address value which is "192.168.a.l", in this case. The _configuration["SomeApp:Host:Location:First"] should give the location value and so on.

Similarly additional configurations as json files can be added to be loaded in the Startup or the Program class as well. The fetching mechanism need not be a string key, it can be _configuration.Get\<P>() to bind the configuration to type P and be retrieved in a more strict type way as well.

· 2 min read
Ragavendra Nagraj

Have you been in a situation where you are almost sitting the whole day in front of your browser and going through a document and find that the site's background color is too bright and you are tired of adjusting the brightness in your monitor.

Fear not, as you might not be the first person in that boat. In this article will show you exactly how to fix it.

First of all depending on your browser, usually it is Ctrl + Shift + I keys that should bring the Developer tools out.

A. Using javascript, in the Console, paste this command document.body.style.backgroundColor = 'rgb(255, 192, 0)' and press enter. Here the RGB values are updated, you can pick an appropriate color from here

B. If the above didn't work, you can try the html way below.

  1. Now all you need to do is, either click on the <html ......\>, or the <body ......> tag.

  2. You should now, see the element { ...... } tag in the right side.

  3. Click on it and try to add the key and value like background-color: darkgrey; or a suitable color for your needs.

  4. See, if the background color of the page changes. It may not work always but atleast 7 of 10 times it should.

  5. If it works, might be, the next part is updating the fonts color. For which you might need to add another key and value like color: black; or a suitable color.

  6. If it didn't work, I would suggest to keep on clicking on the sub sections under the <html ....> or div or body tag and keep trying to update the background-color element for each of it. Interesting part is when you click on each section, it more or less highlights the area that the specific section is responsible for.

  7. One other option is to right click anywhere on the section you like the background color to be updated and select the Inspect element option, which should directly open the developer tools with that section.

Hope this article helped to relieve the paint to your eyes. If yes, please see if you like to make a donation in the 'Buy me a pop' button on the side bar but no compulsion.

· One min read
Ragavendra Nagraj

This post is about trying to implement the circuit breaker pattern in your program. Analgous to the electrical circuit breaker in the house,the circuit breaker can be built and customized to improve system resilience.

Basic steps -

  1. Count the error API's say for a speicific API and store it.
  2. Once the count exceeds the limit say 10, move the client system to the Half - open state and start the timer.
  3. Set the timer to about say 15 seconds.
  4. After the timer expires, try the call(s) again slowly.
  5. If the calls fail, move the system to the Open state.
  6. Otherwise, the specific API can be put into Closed state again.

State definition -

Open - Client is not sending any calls (may be specific API). Half - Open - System in probe mode after failures to check resilience. Closed - System performing as normal and no issues from the server.

· 2 min read
Ragavendra Nagraj

This guide is for those who like to learn Java and are from the C# background or vice - versa or similar who are pretty much versed in it. I have documented the aspects which needs to be grasped and is different from C#.

  1. First line of code can be say a Pgm.java file like below.
class Pgm
{
public static void main(String[] args)
{
System.out.println("Learning Java!);
}
}
  1. The name of the file should be the same as the class inside. Main method is main here and string is String here.

  2. Inheritance -

  3. Use extends for inheriting from another class. This can be from one class only.

  4. No virtual or override, instead methods of the same signatures are overridden.

  5. Use implements to implement from an Interface and for multiple inheritance.

  6. If not implementing an interface, mark it as abstract. Only abstract classes can have abstract fields.

  7. Classes -

  8. Avoid modifiers to it, at least when learning. If using public it has to be in its own file.

  9. Lambda methods - Similar to C#, use -> instead, like Predicate<String> pred = s -> s.length() == 3; and do pred.test("111") which returns true if matching the predicate.

  10. Compiling the source code. javac Pgm.java

  11. Running the program. java Pgm

  12. Packages - Like namespaces, supposed to be the name of the folder but no compilation errors will be issued. Use like package abc.def.ghi; When compiling, one may have to do javac -d . Pgm.java and when running java abc.def.ghi.Pgm

  13. Statements -

  14. All if, else, while and for loops are similar.

  15. Switch cases can have multiple with comma separtions like case SATURDAY, SUNDAY -> "week end";

  16. Encapsulation - No properties here for classes. Create your own getter and setter individual methods.

  17. Concurrent List - To make a list concurrent or thread safe, you can do List newList = Collections.synchronizedList(eles);

  18. Generics seem similar

· 7 min read
Ragavendra Nagraj

In this article I will document about some of the nice features C# has to offer. This include reason(s) for choosing C# in terms of the amount of time needed to bring that app or technology to the market. This could only be a subset of all the features available or known yet.

  1. Entity Framework model - Helps in building apps with a decent list of SQL database support like SQLite, MSSQL, Oracle and all. All these are supported by simply inheriting the DBContext to your class and having declared DBSet<Type> in that class. You may install the entity framework CLI tool for migrations like below.

// Installs the CLI ef tool dotnet tool install --global dotnet-ef

// Installs the nuget package for EF operations in your project dotnet add package Microsoft.EntityFrameworkCore.Design

// Creates new migration for the model just created like Type dotnet ef migrations add InitialCreate

// Updates the model to the database dotnet ef database update

Benefits are no prior database knowledge or tools are required to create and manage the database and tables and all. The class Type easily translates to the table (schema) in the database. Having said that a good database architect knowledge helps in designing and updating the database with primary and foreign keys and all. Other than that it is a nice practice to commit the migrations to the source control.

  1. OData support - If you are building a MVC app with API's returning a bigger set of data like a list of objects. This new* library helps to pass custom query to filter and sort the returned data by just adding an annotation to the specific controller like [EnableQuery]. This in turn reduces the extra lines of code needed to be written in the controllers to perform the same.

  2. Razor pages support - If you are building a web app then Razor pages of the ASP .Net can help. Razor is the templating pages from MS. You can have both the C# code and the HTML in them. This helps in building web pages for the front end and accessing or calculating the data in the C# code. This can include independent services created and running using the Dependency injection adhering to the D (Dependency Inversion) in the SOLID principles of the OOP design pattern. Pages end with .razor extension was initially created as a component. Higher components can call the lower (or inner) components and data can be passed to them using the [Parameter] or [CascadingParameter] as annotations to the individual properties. Blazor uses razor pages and .cshtml pages can include .razor pages declared like

    html tags

  3. Multi threading or parallel programming -

a. Libraries like System.Threading.Monitor helps to lock thread execution to a single thread. Parameters include passing timeout(s), bool ref flag to check if thread is running ( in critical section ) or not.

b. Sempahore(minThreadCount = 0, maxThreadCount = 3) contructor to support OS level named semaphores which can be utilized by other programs in the OS as well using the same name. SemaphoreSlim to make use of the program level semaphores to control a small number of threads to run in parallel.

c. Data structures like Interlocked.Increment(.... int ....) or Decrement() help in parallel threads increasing or decreasing a number. ConcurrentDictionary, ConcurrentQueue, ConcurrentBag types can be used for thread safe data type operations.

d. A simple lock(obj) { ... } loop can be used for running or making thread safe single thread operation(s).

e. Parallel.Invoke(action1, action2, ..... ) is used to run as many actions as needed in parallel.

  1. LINQ - Language Integrated Query - Can be used on almost any Enumerable type which helps in mainly filtering and ordering data using .Select( ..... ) and .Where( ...... ) clauses in the enumerable types. Benefits include a ton of time saved writing the foreach or any loops with conditions to iterate and all with almost a single line in many cases*.

  2. Actions or Funcs or Delegates Actions\<T> are delegates but have no return value to them, unlike Funcs<T, U> for which the last parameter of type U can be the return type of the method.

  3. Generics Used in classes or methods are types which can be passed as different types and a subset of types can be specified. These help in class or method overriding meaning saving duplicate methods for each different methods.

  4. Dependency Injection In order to achieve the inversion of control support in the SOLID principles, C# offers injecting the Services or Types as dependencies during load time in an ASP .Net app like builder.Services.AddScoped<IService, Service>(); . The type Service can be Transient, Scoped or Singleton depending on the lifetime needed. Transient is new instance every time, Scoped is one instance for the lifetime of the app and the Singleton is the same instance forever like a static type.

  5. HttpFactory for clients Often there can be issues when trying to make http calls in terms of the resources utilized in the OS. The HttpFactory or the HttpClient typed cient can be injected to a particular service to let the DI handle such resources and try and avoid the socke exhaustion issues, HttpClientFactory helps to create http named clients which can be used in the app anywhere with the same settings. Or a factory for each different client can be created during launch and used within the app interchangeably.

  6. Grpc support Google's newer RPC using the http protocol internally is gaining ground in terms of the security offered during transportation and the communications. C# has OOB support for this, be it starting a complete client server app, enabling and making gRPC calls from the CLI and all.

  7. Mock or Stub testing There is a popular C# nuget package called Moq which help in creating stub or mock objects for interfaces with method definitions. This can be initiated to -Arrange the test data as desired to be returned by each or all the methods and -Assert ed at last to test the parts or services not covered by the stub or mock. This is mainly used when calling such dependencies (as mocks) include network or app being up and running. These are mainly used in unit test(s) and provide a reasonable coverage to the programs in that repository when deploying in the CI/ CD pipelines. Apart from helping write valuable test(s), this helps in building TDD apps and promotes programmers write unit tests first and then the classes after the interfaces. This helps in updating the OOP programs following say L (Linquist substitution) and O (Extend but not modify used classes) in SOLID priciples.

  8. Dotnet CLI One important aspect of the C# development worth mentioning is the CLI support. When installed on popular OS, C# can be easily compiled using dotnet build and run using dotnet run Debug, be it powershell or bash and all.

  9. Configuration management App configuration(s) are easily stored in appsettings.json for production and appsettings.Development.json for development. Indidividual json files with setting can be loaded on services load and used within the app as IConfiguration _configuration type which can load a setting like { "AppName": "AppOne" } and retrieved easily as var appName = _configuration["AppName"]; within the app.

  10. Parallel For loop Paraller.For or Paraller.ForEach loop is new feature where the loop runs in parallel and thread safety should be kept in mind when writing such programs.

  11. Editor Visual Studio is supposed to be the go to editor as it is from MS as well. Having said that VSCode the MS version is no less powerful compared to its multi OS support and some nice extensions such as C#, C# Extensions, Roslynator, GitHub Copilot, .Net Extension Pack, .Net Core Test Explorer and Solarized as well.

· One min read
Ragavendra Nagraj
  • Make sure your vim –version is 8+
  • Make sure you have vim plugin manager like Vundle
  • You can use the .vimrc from here
  • Open vim and do :PluginInstall
  • The above steps should be it!
  • You can use the .net 6 version by adding this in the vimrc file let g:OmniSharp_server_use_net6 = 1 if previous steps didn’t work or
  • You can use the default mono version if you like instead of the .net 6 version, for which you may have to do like below.
  • Install the mono dependencies sudo pacman -S mono mono-msbuild
  • Instead of the line let g:OmniSharp_server_use_net6 = 1 you should have let g:OmniSharp_server_use_mono = 1 in your .vimrc file.
  • You will anyway be asked to install the server every time this is updated.
  • Anytime in vim command mode you can do :OmniSharpStatus to check if the server is running.
  • To verify, say in Program.cs, type like System. , you should see the methods like Console and all. Type Ctrl-N or Ctrl-P to step over them.
  • When stepping over the methods, you should see the method signatures for each.