Wednesday, September 13, 2023

Browser background color or monitor brightness

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. 

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

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

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

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

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

6. 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.

7. 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.

8. 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.

Tuesday, August 29, 2023

C# vs Java programming comparison

 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!);
    }
}
```
a. 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 -
a. Use `extends` for inheriting from another class. This can be from one class only.
b. No virtual or override, instead methods of the same signatures are overridden.
c. Use `implements` to implement from an Interface and for multiple inheritance.
d. If not implementing an interface, mark it as abstract. Only abstract classes can have abstract fields.

3. Classes -
a. Avoid modifiers to it, at least when learning. If using public it has to be in its own file.

4. 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.

5. Compiling the source code.
`javac Pgm.java`

6. Running the program.
`java Pgm`

7. 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`

8. Statements -
a. All if, else, while and for loops are similar.
b. Switch cases can have multiple with comma separtions like `case SATURDAY, SUNDAY -> "week end";`

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

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

11. Generics seem similar


Monday, August 14, 2023

?? and ??= Null coalescence operators C#

 C# introduces the ?? and ??= operators which are known as the Null coalescence operators.

Purpose -
The ?? and ??= operators can help in cases where a comparison is made between two or more variable values and depending on the order in the statement, the variable valu is used.

Say for example there is variable either a and b to be returned by a method. Say if value is needed to be returned if it is not null and if yes, the value b is supposed to be returned.

```
public class NullCoal
{
public static int? Method(int? input)
{
    ....
    ....
    int? a;
    int? b;
    

    if(input > 10)
    {
        a = input * 6;
   
}
    else
    {
        b = input * 7:;
    }

    return a ?? b;
}
}

```
In the above example, a is returned if it is not null or b is returned.

Similarly the ??= operator adds the assignment operation as well, which can be used like

```
    int? a = null;
    int? b = 1;

    a ??= b;
```
where if a is not null, value of b is assigned to it, otherwise nothing happens with the above statement.

The null coalescence operator is a short form for writing the below code.

```
if( a is null)
{
    a = 1;
}

```
instead it can be written as

```
a ??= 1;
```
What if there is more than two variables to check, in such cases say like below
```
return a ?? b ?? c;
```
the expression is evaluated from right to left like this
```
return a ?? ( b ?? c)
```

Wednesday, July 26, 2023

Rabbit Message Queue and Redis

 In this article I will try to give some overview about why and when to use Rabbit Message Queue and Redis cache. Starting with Redis cache

Redis cache -

  • Mainly used for caching as call time to server ( say database server ) can delay. Using redis cache saves this time, as it is the cache of the database itself.
    • Whenever a database write has happened, a worker class can update the cache to be in sync with the database.
  • Key value pair type of database supporting strings, int, lists, hash as values.
  • The list can used as stacks or queues and other data structures as well like linked list,  circular queue and all.
  • Remember, the key has to be in lower case.
  • Redis say instead of sending many continuous updates in subsequent calls, these can be piped and send as a single call.
  • Calls can be direct or pub - sub type
  • StackExchange.Redis is a popular nuget package to perform almost all the database operations in the redis documentation.
  • redis - cli can be used locally to connect to the database and perform CRUD operations.
  • Convenience of using regex in calls to retrieve data fastly.

 

Rabbit Message Queue ( RMQ ) -

  • Queue or many queues behind an exchange.
  • The exchange does the routing to the particular queue based on the header information.
  • Data in a queue can be set to be durable, meaning data is not lost after RMQ is re started. For docker containers make sure to use common volumes across container restart(s).
  • Data in a durable queue can stay from two to three days.
  • MassTransit is one nuget package which can be used with different types of Enterprise service bus like RMQ, Azure queue, AWS queue, in memory queue and all without needing to write the adapters for each.
  • When a message is sent to a RMQ it first goes to the exchange and the exchange routes that message to its queue.
  • Used mainly for mass data transfers and Mass transit client consumes it almost in no time.
  • The main reason to use Enterprise service bus is to ensure reliability of the message sent. The recipient server may be busy with some operation(s) unable to provide cycles or bandwidth to consume the incoming messages from the client. These messages can be lost if not addressed in a timely manner, thereby giving poor experience to its caller.
  • Supports direct messaging to the recipient or publish subscriber mechanism where the Consumer is listening to the queue(s) in the RMQ for any new messages.

 

Writing Consumer in Mass transit should be as straight forward as implementing the `IConsumer` type and having a task named Consume with ConsumerContext parameter like below.


    public class AfceConsumer :
        IConsumer<AfceMessage>
    {

        public Task Consume(ConsumeContext context)
        {
            Console.WriteLine("Hello {name}", context.Message.Title);
            return Task.CompletedTask;
        }
    }
The above consumer will continuously consume each message one by one in almost no time when the message of type `AfceMessage` is available in the queue.
The AfceMessage can be any reference type like a class or a record or a struct.

Mass transit also has bulk message consumer to consume message in batches.

Asp .Net Configuration

 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.


Adding newer extension method(s) to struct types C#

 In this article, I will demonstrate on how one can add additional methods to existing struct types like int, string, char, long, etc,.

This can be beneficial when the existing methods for that type is like not handful for a certain situation say like reversing a string. Some of existing method say for string type includes `.ToUpper()`, `.ToLower()`, `.Trim()` and so on.

Let us call our new method Reverse().

First we need to have `static` class for it and `static` method like below.


```

public static class AfceClass

{

    public static string Reverse(this string theStr)
{

string theStrNew;

    foreach(char ch in theStr)
{

    thStrNew =+ ChangeCase(ch) ;

}

    return  thStrNew;


public static string ChangeCase(char chr)

{

    // steps to change or negate the char case
    return chr.toUpper();

}

}

```

Note, the use of the `this` keyword to the parameters which more or less makes the method chain.

Now, if you find any variables of type string, it should also have the Reverse() method as well and documentation if added in the comments for that method.

Extension method can be used of types other than struct or for user defined types as well. One aspect is the static class should not be nested in the same class where one is using it as well.

Sample using the generic type

```

public static class AfceClass

{

    public static E NewExtMethod<E, T>(this T theStr)
{

E theStrNew;

....

...

...

    return  thStrNew;

}

}

```
Now with Generics, the NewExtMethod<E, T> should populate with any types but make sure to pass the E and T types.

This can be further refined to be populated with only certain types with the `where` clause like below.

```

public static class AfceClass

{

    public static E NewExtMethod<E, T>(this T theStr) where T : long, int where E : long
{

E theStrNew;

....

...

...

    return  thStrNew;

}

}

```

Usage - One can use this to have like a common method say like add leading zeros to an int or a long and return as a string or even use as user types with much more options.

Monday, June 5, 2023

C# quality features

 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.

 2. 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.

3. 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 <ComponentName /> html tags

4. 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.

5. 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*.

6. 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.

7. 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.

8. 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.

9. 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.

10. 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.

11. 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.

12. 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.

13. 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.

14. 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.

15. 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.

Friday, June 2, 2023

Circuit breaker pattern algorithm

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.

Thursday, May 19, 2022

Interview preparation for professionals

     It is time that I thought that I should jot down a bunch of ideas to people trying to interview for the professional jobs.

    First and foremost instruction is to ask yourself before going to any interview is these important questions.

1. How important is that job to you? 

2. Are you currently employed?

3. Do you have enough savings to idle for a while?

4. Do you like to hit the ground right away?

  Apart from these there can be other questions too which can help shape your future like

 1. Do you plan to work in that position for a while?

    It is always a nice idea to have a short term goal and a long term one. The short term goals in sequential manner should more or less take you to your long term goal. In the current industry this can be really confusing or difficult having said that it is not that hard to plan for the next few years ahead of you.

     Now, getting back to our interview preparation. Lets say now that after answering all the above questions you are in a pretty eager situation to be employed for that position.

Enough time -

   Always give yourself enough time before and after the interview. Before the interview try and think of all the situation in your professional life be it a nice one or a regretful one. I say this because when asked during the interview you are in a very comfortable position to answer the interviewer. One easy way to do is to go through your resume and recollect all the work you had done the situations you had to overcome and failed. I say this because the interviewer are curious about your failures than your success. They like to know if you are experienced enough to get back from such failures or lament about it and not learned anything from it. Lot's of behavioural interviews focus on this irrespective of how good you are at the job. Companies like resources who can do their job well in a safe and a secure way.

Interest and enthusiasm -

    Always remember that in any market condition the resource that shows the utmost interest and enthusiasm is the one having higher chances to land in that difficult to get job. It is okay to not go to all the interviews but make sure you always can give your 100% in which ever interview you give. Worse comes worse you will at least learn what not to do in your next one.

Dress professionally - 

    Be it a video interview or a face to face. It is always important to show how important that job is for you. In a way you are communicating that you have prepared for the interview.


Answering unknown questions -

    Now you are in the interview and answering most of the known questions. All of a sudden you are asked a question that you are unsure of how to answer. What you can do is a) to ask the interviewer enough time to able to think of the answer and talk about it. Now, let's say you have no such situation in your experience or no knowledge about that technology. What you could do is, you can say something like Unfortunately this didn't happen in your experience but a similar happened .... and you can go on answering like that. You can give similar answer if you didn't know that technology saying you didn't get chance to work on it but ..... you got chance to work on a similar technology and go on.

    The interviewer or the Company always like to know that you know the requirements in the job description and have experience working on them or similar technologies. You should be in a position to make them feel comfortable that you are ready to wear that hat and can work and navigate independently by yourself. 

No is not your answer -

    Based on the so many interviews given I have noticed that being honest to your full potential can not be the best thing for you in an interview. Which I do not like honestly. However I try to answer by saying that I know similar technologies or experienced similar situations. One healthy advice here is make sure you read the job details and description thoroughly and prepare for them accordingly. I know it may not be the best experience but remember that job is important for you?

Time after the interview -

    Now you are done with the interview and obviously tired. May be like later in that day or evening, recall all the questions that were asked and the answers you gave. Think how well you could have answered that difficult question? This is more like retro which if done will improve your interviewing or hiring skills too .

During the interview -

Look nice and kind. 

Be optimistic. 

Wait for the interviewer to talk first. 

If you have not finished with the answer excuse yourself to continue. These nitty gritty behaviours are the ones which really impact the interview and sets you apart fro the others. They help the interviewer feel comfortable to hire you. It is like the small detail sticker finish on your vehicle if not according to you can linger somewhere in your mind until fixed.

 

End of interview -

Ask Questions. Ask! Ask! Ask!

    This is the most important part in any interview. Make sure that you ask at least 2 - 3 questions after you interview. Say about the job, about the role, technologies and all. Be considerate about the interviewer as it can go against you if it is more specific. Asking these questions helps shows your interest in the job.

    Good luck with your interview. Do pass on this message if you find success with this information and don't forget to pass it on to the others in need. The same way I received it from another gentleman.

Acknowledgement(s)

I would like to thank the man in that video for giving so much thoughts and inputs. His enthusiasm for its viewers is the one need to land in that special job you are applying.

Most of all! Remember! If it didn't go well, don't abstain - It is not personally you, but your lack of preparation




Wednesday, May 4, 2022

Social engineering and identity theft

 During the period of difficult times, one of the prime concern for any resident is the ease at which their personal information could be used to steal them.


Credit or Debit Card real time use information

Say if someone have your credit or debit card transactions information alone in real time. Suppose you make a purchase in a jewellery store. They could virtually trace your location and rob you or mug in the parking lot. This can cause at least the below two losses.

a. Physical Injury
b. Loss of property
c. Damage to your car glass if it is broken into


Walking out of a jewellery store or similar

Say you just purchased that beautiful jewellery for your loved one and you are walking towards the car and driving away. Someone could notice that and in a way follow you. Now say you like to do a quick errand shopping in a grocery store and leave the gift in your dash or similar. Those thieves can literally break in to your car and steal your gift in almost no time.

 

Living in an unsecured home or apartment


Say you just finished purchasing that valuable gift and you drive home. Say you live near the jewellery store and someone just followed you. They can notice your absence by waiting outside and break into your house to grab that valuable of yours. With the rising cost of renting and in demand places to find a place to live. There can be compromises made in terms of security


Being Single

Please don't get me wrong here, but this is one of the prime concern here as well. At least here in BC a large percentage people are single or either living with their pet. Say the perpetrator knows that you are by yourself here. There is a high chance that the thief can target you.


Spy cameras

Say you have installed that groovy camera you bought online. There are ways that the thieves can dodge it like wearing hoodie or pulling the wire or similar. It may take several crimes committed until the perpetrator is confirmed of the crimes. Chances are the criminal may leave the country after several crimes and come back after a while making one forget about the incident all together.


With all the above and living in the difficult times where more crimes could happen and may exceed the capacity of the local departments, it only adds stress and confusion to one's life.

 I remember quite some time ago when there were no gates to access the public transit and how they were added to reduce the illegal or free rides with more people coming in. How about the other gaps* like the house windows where one can easily barge in and walk away with your hard earned savings.

Monday, May 2, 2022

Running NUnit and .Net from command line

In this article I will show you how to go about running your .Net project from CLI . It is especially useful when you don't want to install Visual Studio on a machine to run the project or the NUnit tests like say in the case of a Selenium test project.

 

1. Download and install the .Net SDK from below (I am using 6 here)

https://dotnet.microsoft.com/en-us/download/dotnet/6.0


2. In your powershell, navigate to the .Net project dir and try to do `dotnet build` and `dotnet run` to see if the installation works


3. If you plan to use and run NUnit from the CLI as well, run the below commands from the same dir.

`dotnet add package nunit nunit.console`


4. NUnit.console exe is installed in the below path. Issue the command to add it to the env var for the session only

`$Env:PATH += ";C:\Users\UserName\.nuget\packages\nunit.consolerunner\3.15.0\tools\"`

PS - To add it permanently, add in the control panel

5. Now you should be able to run the below command to run the NUnit tests from the project.

`nunit3-console .\bin\Debug\net6.0\Tests.dll`

PS - You can play around nunit3-console options to run specific test or a set of tests


6. TestResults.xml file will be generated, which can be used to see the test run results in an online nunit results viewer like this one https://tkovacs-dev.github.io/nunit3viewer/

Friday, April 8, 2022

C# - Deserializing Json without the type

 Say you receive a json string response to an http call like a GET, POST, etc., and now you like to deserialize it. It is not necessary that the data type class of the response object be declared. This can be useful when doesn't know the response type. This can be achieved by using the System.Text.Json.Node directive like in the below example.

PS - System.Text.Json was introduced in .Net Core 3.0 and above. We do not have to use external libraries for it anymore.

        var jsonResponse = @"{""id"": ""3"", ""type"": ""some text here""}";
               
        var resp_ = System.Text.Json.Nodes.JsonNode.Parse(jsonResponse);
        Console.WriteLine(resp_);
        Console.WriteLine(resp_["id"]);

Thursday, April 7, 2022

C# - Deserializing json responses for valid and error cases

 Often times when de serializing a JSON we can get a valid response or an error message depending on various factors, say like resource not found, etc., . In these cases the de serialization should work for both the valid and the error cases. We can accomplish that by inheriting the error class into the ValidResponse class.

System.Text.Json was introduced in .Net Core 3.0 and above. We do not have to use external libraries for it anymore.

PS - To work with JSON in .net 6 (.Net Core 3.0 and above) you would need the below directives
using System;
using System.Text.Json;

If trying to de serialize for an http call, you will also need
using System.Net.Http;

Inheriting the ErrorResponse
public class ValidResponse : ErrorResponse     {
        //public string id { get; set; }
        public string type { get; set; }
    }

ErrorResponse object
public class ErrorResponse    {
        public string id { get; set; }
        public string message { get; set; }
    }

Deserializing the json response after an http call say like GET, POST, etc.,
        var resp = JsonSerializer.Deserialize<ValidResponse>(jsonResponse);
       
        Console.WriteLine(resp.message);
        Console.WriteLine(resp.type);

Wednesday, April 6, 2022

What to automate - Software Automation

    Everyone in the IT industry these days more or less know what software automation is and what the QA team work on. Software Automation QAs know how to go about automation and even manage them. Before getting into all these, the prior aspect is to identify test cases which need to be automated. In Agile methodology one of the key aspect for a QA resource is to identify which all manual test cases needs to be automated when writing them itself. Some manual test cases can be one off's like say visual ones like the fonts should be italic or the button should be cyan in color. These one off's need not be automated. There can be ones related to the functionality like say the login functionality which can be automated. If doing modular programming for automation this login module or method can be used in conjunction with the other aspects of automation as well like say updating personal details after login to the system.

    Regression test cases are ones which deserve automation almost 100% of the time. These tests include checking the system end to end with different flows like say create an account, add funds to the bank account, add a product and checkout, etc., to name a few. Other test cases which are more important to be automated can include the Smoke/ sanity test cases like check if able to launch or navigate to the app on the browser and perform a simple login.

Software bug practices

    A bug or a defect is an issue identified when trying to test a software or a website. When developing an application, the developed application is not meeting the acceptance criteria of the software requirement(s) a bug can be raised as well.

Fields in the software bug

a. Name - One line(r) to describe what the bug is really about

b. Description or steps -
    First para can have a brief description about what the bug is about.

    The steps to reproduce the bug in sequence. This can be organized into three columns. The first column with the step. The second column with the Actual Result and the last column with the Expected result like in the test cases.

c. Pre - requisites
    Steps to be done before running the actual steps. This can be running other test case(s) as well. If yes then the test id or a html link to them would suffice.

d. Screens
    of the actual issue can be attached to the Actual result column.

Friday, April 1, 2022

Software QA Automation framework/ scaffold/ setup

    When writing automated test cases the first and foremost part is to setup the scaffold or write the framework for writing the test cases. Since now a days we have mostly the websites being built, we will focus on the rough framework for it.

    We will use the Page Object Model or called as the POM model for writing the framework. Let's say the website has ten links for ten different pages on it. We are supposed to have one POM for one page each. These pages can be like Home, Products, ContactUs as a class each and so on.

    Each of these page objects contain the various objects in that page, say like the links, text boxes, buttons, text fields and so on.

    Since the header and the footer menus are a part of almost all the pages in the website, we can declare an abstract Base class which holds these link elements or objects. This Base is then inherited by all the other pages having the header and the footer menus in them.

Drawbacks of POM

    When using POM, one must note that when writing tests, each page object has to be initialized and actions be performed on them. When loading/ initializing each page object to the memory, the memory increases and this could slow the automation run(s). In some cases, one may want to perform only one operation on one page and don't have to load the other objects of that page.

Test support libraries usage

    Say if you are using NUnit which is a very good framework for writing your automated tests in C#. The browser initialization and using part can be done in the base tests file or tests fixture file and say each tests file/ class can have tests for each web page or similar. These page test(s) file can inherit the base test file and use the browser initialized from it.

    Make use of the attributes for tests like the TestCase, Order and all to make the tests report and run better

[TestCase = "Check links on Products page", Order(6)]
public void CheckLinksProductsPage(){}

Advices for better automation

    Keep the framework as loosely coupled as possible. What I mean by this is may be not to modular as well like writing independent methods to perform a task. I know may be one or two tests can use it but if not many then it may not be worth having that function at all. Having a method for a login function taking username and password makes sense as many tests can depend on these. This can help perform or even be easy to write robust tests. Otherwise the framework could be cumbersome to use and to write tests with it.

    Try data driven approach for running one test with many sets of data. Login to a site can be a very good example of this. User can have positive and negative test data and verify the results in the same test and trying to obey the DRY principle(s).

    Data structures used for storing data be light weight for large data sets say like using a simple array object instead of using dictionary or lists or similar which are mutable and these can slow test run(s).

    Avoid running UI tests in parallel as these can step on each other and affect the test run(s).

    




Software QA basics

Software testing can be categorized or organized into different processes or parts depending on the stage at which it is being performed.

Smoke/ Sanity Testing - Usually in the initial/ end stage of product development, when the product is being newly built or about to be launched. Perform a basic test to see if the software is loading/ starting/ launching depending on the software. Simple tests can include testing login or a basic check with most common functionalities are up and working fine.

Functional testing - test the software against the requirements in the product development cycle or in the sprints in the Agile methodology. This includes writing of the manual test cases before the feature/ requirement is ready and running the manual test cases once the feature is ready. If time permits, automated test cases can be added and run instead or both. These test cases can be vetted and organized for regression testing as well.

Regression testing - test cases written/ developed during the functional testing phase are organized and run before the release of the feature/ the whole product itself. This is done usually before the launch of the feature or the product to make sure that subsequent features added to the software has not introduced any bugs or issues.

Priority testing - testing is done when you have large suite of regression tests. Now, say a single feature is developed and the whole regression suite need not be run. A traceability matrix can be prepared mapping each of the testcases to its features. Only the testcases matching to its feature can be run. Ambiguously testcases related to a particular feature can also be run from the regression suite which may depend on the tester's knowledge and experience of the test cases.

Wednesday, March 23, 2022

Vim popular shortcuts


    In this article I will walk you through some of the popular commands that you can use to get up fast and start using the Vim editor. Vim was written by Brian Moolenar as a charity ware, meaning all of its donations goes to the non - profit in Uganda I think.

Why one should learn vim?

    Vim is a popular visual editor from almost the beginning of computers whose predecessor was vi. It has been used widely by mainly Open source developers since the development of *nix systems.

    Today's popular editor's like Visual Studio Code has vim support through its extensions.

    Vim has three main modes Edit, Visual and Command, Enter Edit by typing i, Visual by typing v and Command by typing :

We will go through the commands for each of the modes below.

Edit mode

Editing of text is done in this mode and hence have no shortcuts.


i - insert or start typing or to enter edit mode
A - go to end of line and edit
o - creates new next line and you can start editing

Visual  Mode

Read only mode mainly for navigation, searching, register operations.

v - begin visual mode
Ctrl+v - visual block
gg - go to top of file
GG - go to end of file
y - yank ( copy ) selection
yy - yank line
p - paste after cursor
P - paste before cursor
3p - paste three times after cursor
/word - search for word in forward (top to down) direction
?word - search for word in reverse (bottom to up) direction
w - jump word
e - jump to end of word
b - jump word backwards
2w or 2e - jump two words or jump to end of two words
r - replace letter
x - delete letter
cw - change word
ce - change to end of word
c2w or c2e - change to two words or end of two words

Searching -
n - search for next position of word
N - search for previous position of word/ back search
* - find next word
# - find previous word

Navigation -
`" - go to last cursor position after opening a file
`. - go to last edit position after opening a file
0 - go to start of line
$ - go to end of line
A - go to end of line and edit
G - go to beginning of file
% - go to end or start of braces {} or [] or () .....
[{ - go to opening of braces
]} - go to ending of braces



Ctrl + I - go previous cursor positions even other files
Ctrl + O - go after cursor positions even other files
Ctrl + ] - on tag link goes to link
Ctrl + t - goes back to link

h - nav left
l - nav right
k - nav up
j - nav down

Command  Mode

Mainly to perform file operations of the file and run shell commands as well.

:w - write to disk
:wq - write to disk and close editor
:q! - close editor but not write any changes
:tabedit filename - creates new tab opening filename in it
:gt - go to next tab
:gT - go to previous tab
!ls - execute shell commands, in this case ls
:sort - after selecting say a list of words or numbers in visual. Typing this sorts them in alphabetical or numerical ascending order

:colorscheme solarized - switching themes found in $vimruntime/colors. Others include `morning` , `evening`, `peachpuff`, `industry`, `murphy`, `blue`, `darkblue`, `desert` and all
:set background=light - or `dark` depend on time of day for a specific theme.

:%s/word/new/gc - replace word with new in the whole file with confirmation each time. Regex patterns is supported here.

FAQ

How to copy text to command mode?
After yanking the text and pressing : Do Ctrl+R and "

How to paste the previously yanked ( copied ) text?
"0p - pastes the second last copied
:reg shows the paste registers. Use "6p to paste the 6th register


Tuesday, February 8, 2022

Bhagawadgita about food

 In Bhagawadgita, Lord Krishna says that the food we prepare must be consumed within first three hours after its preparation. A person who consumes food within the first three hours happens to be a Good person. A person who consumes the food from three hours to as long as it is good to eat seems to be a person with passion. A person who consumes food after it has gone bad has problems in his life and can be after something.

  In Bhagawadgita, human beings are classified as three types, the Good, the average and the passionate.

Thursday, February 3, 2022

Karma in real life action

 In this post I like to expose the truth of karma's existence with a live example. Lets say you are a principled person living with a set of rules or principles which may be personal or adhere to a specific religion.


X was worked in a company that doesn't hire its ex-employees back. At one stage it so happened that almost everyone in one city had worked for X before. Should I say unfortunately or obviously X reached a point of stepping on its own leg for its policy. Now X's competitor lets say Y which did not have such policy could hire X's ex employees as well in that city. In a way X paved the way for Y and isn't this the law of Karma.


This is similar in one's life as well. When one doesn't agree with the policies of a Company, he may not have to work for it. If all have the same disagreement, such a company will have very less or no chances of having any resources at all. Such is the power of human principles or religion in mankind.

Browser background color or monitor brightness

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 ...