Attach to Process

CSharp

Fire and forget template for C#/.NET to run something that you don't need to wait on and don't care about the results.

Task.Run(() =>
{
	//code goes here
});

In ReactJS, if ESLint says you cannot use inline arrow functions to pass in props in JSX, a solution is to wrap them with the useCallback hook.

Reference: https://stackoverflow.com/a/36677798/5041911


Modals — can be used to add dialog or popup info boxes on your ReactJS app.


So using this library actually helped me solve my Azure Application Insights logging issue. The issue being, since I had a dateOfBirth object in my formData object, app insights would save it as an object, as opposed to something like dateOfBirth: 2024-04-16. The solution was to flatten the formData object so it will get logged properly in Azure App Insights.


Rendering the HTML string in React — short tutorial on how to render an HTML string in ReactJS/Gatsby.


Series: #DevNotes Tags: #CSharp #DotNet #Template #ReactJS #Azure #ApplicationInsights #Gatsby

Discuss... or leave a comment below.

How to check if array contains a specific item

To check if an object or item is contained in a JavaScript array, you can use the includes function, like so:

const customerIds = [1, 2, 3, 4, 5];
console.log('IsIncludedInArray', customerIds.includes(3));

To do the same thing in C#, you can use the Contains or Any LINQ method, like so:

var customerIds = new int[5] { 1, 2, 3, 4, 5};
Console.WriteLine("IsIncludedInArray " + customerIds.Contains(3));
Console.WriteLine("IsIncludedInArray " + customerIds.Any(n => n == 3));

How to filter out contents in an array

To filter out the contents of an array in JavaScript, you can use the filter function., like so:

const customerIds = [1, 2, 3, 4, 5];
const filteredCustomerIds = customerIds.filter(n => n <= 3);
console.log('Filtered CustomerIds', filteredCustomerIds);

To do the same thing in C#, you can use the Where LINQ method.

var customerIds = new int[5] { 1, 2, 3, 4, 5};
var filteredCustomerIds = customerIds.Where(n => n <= 3);

foreach (var n in filteredCustomerIds)
{
  Console.WriteLine(n);
}

Tags: #JavaScript #CSharp #DotNet

Discuss... or leave a comment below.

A week ago I was running a test and kept running into a WCF BindingConfiguration Error. I would not allow myself to check-in my code unless my tests passed. So, I battled with this error for over an hour.

The binding at system.serviceModel/bindings/basicHttpBinding does not have a configured binding named ‘BasicHttpBinding_IXXXXXX’. This is an invalid value for bindingConfiguration.

It's your basic, run of the mill, WCF BasicHttpBinding configuration error.

I double-checked my test project's app.config file and the relevant client.config files – everything looked right. I know it was a configuration issue. The error message itself made it obvious that it was a configuration issue. But everything looked right. I didn't see any issues with the config files I was looking at.

It must be noted that it was already close to midnight at this point. I was working late that day and decided to push myself by resolving to check-in my changes before the night ends. I have no doubt that being tired and sleepy didn't help.

Anyway, after awhile I realized that the service method that I was trying to test, was running inside another service. So, in addition to the test project’s app.config file, I also needed to double-check that other service’s Web.config file. When I ran into this error earlier that night, I actually updated that other Web.config file. I added the entry it needed just to cover my bases. I didn't know then that it was the Web.config file that was causing the error.

For some reason, possibly due to fatigue and needing sleep, I didn't think about checking that Web.config file again. Out of frustration, I decided to take a break and headed to the kitchen to drink a glass of water. After hanging out in the kitchen for a bit, then listening to some good music, I finally had the bright idea to check this other Web.config file again. And there it was, a typo on the BasicHttpBinding entry I added. Can't believe I didn't check on it sooner.

Lesson learned here is to take a break whenever you're stuck with a problem. Give your mind time to rest. Chances are, your subconscious will kick in and tell you what to try next. And if the problem points to a configuration issue, with WCF, it most likely is. So, check all the config files, again.

Tags: #WCF #CSharp #DotNet

Discuss... or leave a comment below.

In this post, I'll share my thoughts regarding the use of the Single Responsibility Principle based on my experiences with it.

The Single Responsibility Principle is one of the five design principles listed in SOLID. Gary McLean Hall in his book “Adaptive Code via C#” says,

“The single responsibility principle instructs developers to write code that has one and only one reason to change. If a class has more than one reason to change, it has more than one responsibility. Classes with more than a single responsibility should be broken down into smaller classes, each of which should have only one responsibility and reason to change.”

It is my favorite principle out of the five because of two reasons:

1. Easy to Implement

First, it is very easy to implement. You don't have to be an experienced software developer to start implementing the single responsibility principle in your code. All you need to keep in mind when writing code for a new class or sometimes even a method is, this block of code should be responsible for only one thing.

Are you writing code for a class to parse text files? Then make sure all the code in that class is oriented towards parsing text files. Are you writing code for a class that is supposed to send email notifications? Then keep the code focused on sending email notifications.

2. Better Code

Second reason is that it will always make your code better. Better in the sense that it helps decouples your classes/methods, which reduces the potential for bugs when refactoring code. This in turn also makes your code easier to test. In my experience, I have never seen code that was made worse by implementing the single responsibility principle.

Drawbacks?

The only argument or drawback I've heard to the use of this principle, is the possibility of increased maintenance of the code. Since each class is responsible for doing only one thing, you could end up with a lot more classes, methods, files and projects in your solution. Still, in my opinion, that is preferable if it means I have stable code that is less prone to bugs, than to have code that is low maintenance but is susceptible to bugs.

There is also the chance that a developer will try to implement this principle on a very simple app that doesn't need to change after it's been written. In this case, trying to implement the single responsibility principle will probably take more time and add complexity to the code. (I haven't exactly ran into a situation like this with this principle, but I think that's a possibility.) Sometimes you will have to pick and choose where and when to implement this principle, and that can only come with experience.

Example

Let me go through an example where I think the use of the single responsibility principle would help.

Say you have a business rule that needs to be implemented for various products. Say that Product A, B and C all use this business rule. One thing I've seen in my experience is that if the business rule logic is similar between Products A, B or C, some developers will opt to create just one class to implement the business rule for all products. Again the argument here is that since the business logic is the same, it is easier to maintain just one class for the specific business rule. Okay, fair enough. As long as the business rule doesn't have to change between any of the products, having one class/method for the business rule is acceptable. It is in violation of the single responsibility principle, but if the business rules won't ever change, then it is an acceptable implementation.

But what if the business rules does change for one product, say for Product C? Now you'll have to modify the one class that all products use, to accommodate changes for just one product. What this means is that while working on the new changes, you have an increased chance of introducing bugs to the rest of the products. This also means that any changes to that business rule for any one product, means you have to perform testing for all other products affected by the changes. That is extra work that could have been avoided by following the single responsibility principle.

Now what if you have to add new products that will also have the same business rule, except the new products have slightly different business rule logic in them? Will you modify the existing class to accommodate changes for the new products? If so, you'll run into the same issue above. Adding new products will almost feel like a way to introduce bugs to your code. You can avoid that by following the single responsibility principle.

With the use of the single responsibility principle, each product would have one class that implements a specific business rule. Any changes to the business rules for one product, will not affect the other products. Which means going forward, you only need to worry about testing the changes for the products that changed or the products that were added. Everything else should keep working the same way they've been working before. Stress free coding with minimal chances of introducing bugs, just the way I like it.

Tags: #CSharp #DotNet #SolidPrinciples #SoftwareDesignPrinciples

Discuss... or leave a comment below.

The most convenient way it seems to get .NET Core 3.0 installed on a Windows PC, is to download the free Microsoft Visual Studio 2019 Community edition. Installing Visual Studio 2019 will also install .NET Core 3.0 and after the installation is done, you can start playing around with it.

If you want to download the SDK or just the runtime separately, you can find them here.

To check if you already have .NET Core 3.0 installed, you can pull up a Command Prompt and run the dotnet --version command.

Lastly, if you're trying to learn ASP.NET Core like I am, this recommended learning path seems to be a good starting point.

Tags: #CSharp #DotNetCore

Discuss... or leave a comment below.

For the past month or so, I have noticed that I've been pointing out the need to do case-insensitive string comparisons in the code reviews that I've done. In light of that, I thought now would be a good time to do a refresher on string comparisons in C#.

Using the == operator

Doing string comparisons in C# is easy, and the easiest way to do it, is with the == operator.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = "dino";
   bool areStringsEqual = userName1 == userName2;
   Console.WriteLine(areStringsEqual.ToString());
}

Result: True

The main drawback to this approach is that it will only do a case-sensitive comparison. So, any typo like in the sample code below, will not work.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = "dinO";
   bool areStringsEqual = userName1 == userName2;
   Console.WriteLine(areStringsEqual.ToString());
}

Result: False

So, let's look at another approach to comparing strings...

Using ToUpper() or ToLower()

For quick case-insensitive string comparisons, you can call ToUpper() or ToLower() on your strings before doing the comparison using the == operator.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = "DiNo";
   bool areStringsEqual = userName1.ToUpper() == userName2.ToUpper();
   Console.WriteLine(areStringsEqual.ToString());
}

Result: True

I don't see much drawbacks to using this approach, except if one of your strings is null, in which case you'll then have a NullReferenceException on your hands, like in the sample code below.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = null;
   bool areStringsEqual = userName1.ToUpper() == userName2.ToUpper();
   Console.WriteLine(areStringsEqual.ToString());
}

Result: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.

Note: The exception message above might look weird, but that is because I am running the sample code on TryDotNet.

So, there is an extra step of making sure the strings are not null before you call one of its methods, like in the sample code below.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = null;
   bool areStringsEqual = userName1 != null && userName2 != null && (userName1.ToUpper() == userName2.ToUpper());
   Console.WriteLine(areStringsEqual.ToString());
}

Result: False

The sample code above is still very much usable code, but having to do the null checks all the time can be tiring, which leads me to another way of doing string comparisons...

Using String.Compare

Using the static Compare method from the String class allows you to easily do a case-sensitive or case-insensitive string comparison using the ignoreCase parameter, like in the sample codes below.

Case-insensitive comparison:

public static void Main()
{
   string userName1 = "dino";
   string userName2 = "DiNo";
   bool areStringsEqual = String.Compare(userName1, userName2, ignoreCase: true) == 0;
   Console.WriteLine(areStringsEqual.ToString());
}

Result: True

Case-sensitive comparison:

public static void Main()
{
   string userName1 = "dino";
   string userName2 = "DiNo";
   bool areStringsEqual = String.Compare(userName1, userName2, ignoreCase: false) == 0;
   Console.WriteLine(areStringsEqual.ToString());
}

Result: False

The beauty of using the Compare method is that I don't even have to do null checks. So, taking the sample code above where I had to do null checks, and replacing it with a call to String.Compare, results in the much cleaner sample code below.

public static void Main()
{
   string userName1 = "dino";
   string userName2 = null;
   bool areStringsEqual = String.Compare(userName1, userName2, ignoreCase: true) == 0;
   Console.WriteLine(areStringsEqual.ToString());
}

Result: False

The only drawback to this approach is that it might be harder to read the first time around, because the String.Compare method returns an int, instead of a boolean value.

Normally when comparing strings, we are asking the question, are the strings equal? True or False? So, we are expecting a boolean value back. With the use of String.Compare method, you must compare the results to 0 to determine if the strings are equal. It might take a while to get used to, but the fact that you can throw any string object at this method and not worry about null checks and typos, to me that makes it the superior approach to string comparisons.

Which One Do I Use the Most?

When developing prototype applications or generally when I'm just testing something, I am fine with using the ToUpper() or ToLower() approach. When I'm guaranteed that none of the strings will be null, I would use the ToUpper() or ToLower() approach. Any other scenario, I prefer to use the String.Compare method.

Tags: #CSharp #DotNet

Discuss... or leave a comment below.

If you search for “how to delay message processing in RabbitMQ”, you'll most likely run into two possible solutions for it.

  • One solution is to make use of the message TTL argument with additional queues to route messages through. If I understood this approach correctly, you basically route your message to Queue A, where it will sit for some time before it expires and gets moved to another queue, say Queue B. Then you will have your consumer looking for messages at Queue B.
  • The second solution is to use the official RabbitMQ Delayed Message Plugin.

Both solutions presented above are valid solutions, but I ended up not implementing any of those solutions, and instead went with a solution that is configurable via the consumer application. First, my reasons for not going with the established solutions listed above.

  • I did not want to add any more queues or exchanges, especially if their purpose is to just move messages around.
  • The RabbitMQ Delayed Message Plugin as of this writing is still listed as an “experimental yet fairly stable” plugin. The “experimental” disclaimer is a matter of concern to me and I would prefer to wait until it matures enough that it is no longer called as such.
  • Lastly, I really wanted a solution that is configurable via the consumer application.

So, the solution I went with was to add a PublishDate via the message headers and then the consumer can delay message processing based on this date value.

Adding a PublishDate header value is easy, you add it to the Properties.Headers dictionary before publishing the message.

var properties = channel.CreateBasicProperties();
properties.Persistent = true;

properties.Headers = new Dictionary<string, object>();
properties.Headers.Add("PublishDate", DateTime.Now.ToString());

channel.BasicPublish(exchange: "",
    routingKey: "task_queue",
    basicProperties: properties,
    body: body);

Note that I'm adding the PublishDate value as a string, instead of a DateTime value. For some reason, adding it to the dictionary as a DateTime value causes an error. I don't remember what the error was, something about an invalid table value, so I just went with a string value.

On the consumer side, you will need to add code to retrieve the Publish Date from the headers.

consumer.Received += (model, ea) =>
{
    byte[] publishDateHeader = (byte[])ea.BasicProperties.Headers["PublishDate"];
    DateTime publishDate = Convert.ToDateTime(Encoding.UTF8.GetString(publishDateHeader));
    // Now you can delay message processing based on the publish date value

    var body = ea.Body;
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine(" [x] Received {0}", message);

    channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};

Note that I'm first casting the header value to a byte array, before converting it to a string, then finally to a DateTime value. For some reason, adding a string as a custom header turns it into a byte array. Thankfully somebody else ran into this issue before and shared a solution for it.

With a PublishDate value available, you can now delay message processing however you would like. In my case, I opted to compare the PublishDate value to the DateTime.Now value, which allowed me to check how old the message was. For example, if a message was 5 minutes old, it has been delayed enough and gets processed right away. If the message was only a minute old, the consumer thread will wait until such time that the message was now 5 minutes old, before it processes it.

There are some drawbacks to this approach, namely, you will have to go through the Publisher/Consumer classes to add the code for handling a PublishDate header value. Depending on how your queues are structured and how many publisher-consumer class files you have, you could end up with changes to multiple files just to add this feature. On the flip side though, if only one queue needs this “delayed message processing” feature, then you'll have minimal changes while your other queues continue as is. There are probably more pros and cons to this approach that I haven't thought of. Still I prefer the flexibility with this approach as I only must worry about editing a consumer's config file and it allows me to run multiple consumers each with their own specific message processing setting.

Have you had to design a solution to delay message processing in RabbitMQ? If so, I am curious to hear what approach you went with and why. Please do share in the comments below or send me an email and we can discuss.

Tags: #CSharp #DotNet #RabbitMQ

Discuss... or leave a comment below.

This is a problem I've seen in the past and just recently actually, where exceptions are made harder to troubleshoot, because of the way objects are instantiated. Allow me to explain.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            UserDto dto = new UserDto()
            {
                UserName = "Apatosaurus",
                LastLoginDate = null
            };

            User user = new User()
            {
                UserName = dto.UserName,
                LastLoginDate = dto.LastLoginDate.Value.ToString("MM-dd-yyyy")
            };

            Console.WriteLine("User Info:");
            Console.WriteLine("Username: " + user.UserName);
            Console.WriteLine("LastLoginDate: " + user.LastLoginDate);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
        }
    }
}

class User
{
    public string UserName { get; set; }
    public string LastLoginDate { get; set; }
}

class UserDto
{
    public string UserName { get; set; }
    public DateTime? LastLoginDate { get; set; }
}

Take for example the code above. What happens if the dto.LastLoginDate property is actually null when instantiating a User object?

at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Nullable`1.get_Value()
at NullRefErrorExample.Program.Main(String[] args) in C:\Users\dbansigan\source\repos\NullRefErrorExample\NullRefErrorExample\Program.cs:line 21

The error message above is what was displayed in the console app I was running. Line 21 points to User user = new User(), which is the line of code that was instantiating an object, but not the line of code that caused the exception. It should have pointed to Line 24 instead, LastLoginDate = dto.LastLoginDate.Value.ToString("MM-dd-yyyy"). However, since I followed Visual Studio's suggestion (IDE0017 Object initialization can be simplified), to simplify object initialization, this is what happened. So now you can see how it can make troubleshooting a more time-consuming task.

Note that this is a very simple example. Imagine if you had big class that had like 20 properties and multiple lines of initialization code that could cause an exception? It would be pretty hard to figure out which line of code caused the exception without having to debug the application.

So how do we fix it? Should we even still try to simplify object initialization?

Yes, we can still simplify object initializations, however we just have to be wary of using code that can cause exceptions when assigning property values. So the rule that I follow is that any line of code that could throw a null reference exception, or any exception for that matter, is taken out of the code that simplifies object initialization; they are instead moved to their own line.

So, taking the example from above, this is how I would initialize the object with the rule in mind. I basically just take out the code that assigns the value to the user.LastLoginDate property and move it outside the brackets containing the simplified initialization code.

User user = new User()
{
    UserName = dto.UserName
};
user.LastLoginDate = dto.LastLoginDate.Value.ToString("MM-dd-yyyy");

I run the app once again and this is what the stack trace tells me.

at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Nullable`1.get_Value()
at NullRefErrorExample.Program.Main(String[] args) in C:\Users\dbansigan\source\repos\NullRefErrorExample\NullRefErrorExample\Program.cs:line 25

Notice how the stack trace now points to Line 25 user.LastLoginDate = dto.LastLoginDate.Value.ToString("MM-dd-yyyy");, which is exactly the line of code that caused the exception. So now I get a head start on troubleshooting the exception. Also, any experienced developer will be able to tell almost immediately what caused the exception, if all they had to do was look at 1 line of code.

Are there alternative solutions to this?

An alternative is to check for null before even considering instantiating an object, like in the code below. I think this is a valid solution and it allows you to throw an exception with a detailed/specific message, or throw a custom exception. That said, if you are throwing an exception only because you cannot instantiate an object, then I don't see how it is significantly better than just letting it error out on the line of code assigning the property value. Your application is not going anywhere anyway, since you still cannot instantiate the object you need for your application to move forward.

if (!dto.LastLoginDate.HasValue)
{
    throw new NullReferenceException("dto.LastLoginDate cannot be null");
}

Another possible alternate solution could come from the use of nullable reference types in C# 8. However, this is something I have not been able to play with yet, so I cannot comment on the use of it.

I've seen this problem occur on other types of code as well, like for instance code where method chaining happens. If there is an exception, the end result is the same; you can hardly tell which method parameter, or which method call, or which specific part of the code caused the exception, because they are all essentially just one line of code. In situations like this, it is often advisable to break up the chain of method calls, unless you are absolutely sure that it can never cause an exception.

I'm curious to think if other developers also instantiate objects in this manner to avoid exceptions when creating objects. If you do, or you don't, I'm curious to hear your reasons for doing so. Please do send me a message so we can discuss.

Tags: #CSharp #DotNet

Discuss... or leave a comment below.

Have you ever had to do testing wherein you had to move your system date/time forward or back? If so, you will probably agree that one of the annoying things is remembering to reset the system date/time back to the current date/time. Most people will manually do this, which can be tiring when done multiple times during the day. If you are working in an office environment, then your workstation's system date/time can most likely be synced to a domain controller. Here is how you can easily do that using the command prompt in Windows.

Open up the command prompt and type in the command listed below:

net time /domain /set /y

You might have to open the command prompt in Administrator mode to get it to work.

Taking this a step further, what if you can automatically reset the system date/time on your workstation after a test finishes? I've had to do something similar since I've had to maintain some Coded UI tests, that can change the system date/time as part of their testing. So I wrote a utility method in C# that will reset the system date/time after a Coded UI test ends. This is called via the TestCleanup method that will run after a test ends.

[TestCleanup]
public void CleanUp()
{
    ResetLocalSystemTime();
}

private void ResetLocalSystemTime()
{
    using (Process netTime = new Process())
    {
        netTime.StartInfo.FileName = "NET.exe";
        netTime.StartInfo.Arguments = @"TIME /DOMAIN /SET /Y";
        netTime.StartInfo.UseShellExecute = false;
        netTime.StartInfo.CreateNoWindow = false;
        netTime.Start();

        Task.Delay(1000);
    }
}

Hope this helps some of the devs out there doing some testing. If you have a different way of doing this, do share them in the comments below or share them in a message.

Tags: #CSharp #DotNet #Tests

Discuss... or leave a comment below.

If you've ever needed to get a list of the base classes/types for an object in C#, this is one way of doing it. In my case, I had an object which was of the base class/type, but it was really a derived type.

Example: I had an object of type Animal, but it was really an instance of the Dog class, which is derived from the Animal base class.

The beauty of inheritance in object oriented programming is that the current instance of the object, can be an instance of the derived type, or the base type; it doesn't matter. As long as the code expects you to provide it an object of the base type, you can provide an instance of either one.

I needed to record the type hierarchy for that object when saving it to the database. So this utility method is what I came up with in short order. I am returning a list of strings in my example below, but there is nothing stopping you from returning an array of Types or whatever else you may need based on your scenario.

private List<string> GetTypeHierarchy()
{
    List<string> typeHierarchy = new List<string>();

    Type currentType = this.GetType();
    typeHierarchy.Add(currentType.Name);

    Type baseType = currentType.BaseType;
    while (baseType != null)
    {
        typeHierarchy.Add(baseType.Name);
        baseType = baseType.BaseType;
    }

    typeHierarchy.Reverse();
    return typeHierarchy;
}

I intentionally wrote this without recursion, because recursion hurts my head haha. There might be a better/cleaner way of doing this, if so, do share your solution with me.

#CSharp #DotNet

Discuss... or leave a comment below.