INTERVIEW JOB CODING TASKS – XML file manipulation

It’s been a while, once again, since my last post. But due to a much of stuff, I’m doing in the background, I guarantee you, it’s going to be worth it! Bunch of changes is going to be presented to you very soon as well as new content, in a much more professional way.

Anyway, the topic for today is in the category of INTERVIEW QUESTIONS / TASKS, so let’s get rolling.

The task

Create a console application that is going to read a specific cell value from an XML based on our test schema (XSD) according to our console input.

I.e. if you type -1 -1 in our console, the application will exit. If you input values 1 3 the app will read XML value from row 1 and cell 3. Input values are digits only, all values must be of type string and XML is based on our TestSchema.XSD file.

Test XML

So we have a structured XML like this one:

<?xml version="1.0" encoding="utf-8" ?> 

<sheet> 

  <row> 

    <cell>Some string one</cell> 

    <cell>Random string cell two</cell> 

  </row> 

  <row> 

    <cell>Some kind of a value we are looking for</cell> 

  </row> 

</sheet> 

Based on that we created our test schema XSD:

Test schema XSD

<?xml version="1.0" encoding="utf-8"?> 

<xs:schema id="TestSchema" 

    targetNamespace="http://tempuri.org/TestSchema.xsd" 

    elementFormDefault="qualified" 

    xmlns="http://tempuri.org/TestSchema.xsd" 

    xmlns:mstns="http://tempuri.org/TestSchema.xsd" 

    xmlns:xs="http://www.w3.org/2001/XMLSchema" 

> 

  <xs:element name="sheet"> 

    <xs:complexType> 

      <xs:sequence> 

        <xs:element minOccurs="1" maxOccurs="1000" name="row"> 

          <xs:complexType> 

            <xs:sequence> 

              <xs:element minOccurs="1" maxOccurs="1000" name="cell" type="xs:string" /> 

            </xs:sequence> 

          </xs:complexType> 

        </xs:element> 

      </xs:sequence> 

    </xs:complexType> 

  </xs:element> 

</xs:schema> 

As seen in this XSD file, we defined our XML file to have rows and cells with a minimum of 1 and a maximum value of 1000. We also defined our cell element to be of a type string.

Next step is to define our schema model so we can easily manipulate our objects in code:

Schema model

namespace Task.Models 

{ 
    [XmlRoot(ElementName = "sheet")] 

    public class TestSchemaModel 

    { 
        [XmlElement(ElementName = "row")] 

        public List<Row> Rows { get; set; } 

    } 
  
    [XmlRoot(ElementName = "row")] 

    public class Row 

    { 
        [XmlElement(ElementName = "cell")] 

        public List<string> Cell { get; set; } 
    } 

} 

What we did here is we defined our XML as a model in our code. This way we are going to easily load XML in our application.

So basically we created a schema model which consists of a list of rows and we also defined a row model which consists of lists of cells that are of type string.

The next step is to create a custom class with methods that we are going to use to do XML file manipulation.

XML file manipulation

public static class XmlFileManipulation 

    { 
        public static TestSchemaModel GetXmlDeserializedData(string fileName) 

        { 

            TestSchemaModel schemaModel = default; 

 
            var doc = ValidateXDocument(fileName); 


            schemaModel = DeserializeFromXml<TestSchemaModel>(doc.ToString()); 

             

            return schemaModel; 

        } 

  

        private static XDocument ValidateXDocument(string fileName) 

        { 

            XDocument doc = default; 

            try 

            { 

                var path = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) ?? throw new InvalidOperationException()).LocalPath; 

  
                var concatenatedStringPath = string.Concat(path, "\\TestSchema.xsd"); 

  

                XmlSchemaSet schema = new XmlSchemaSet(); 

                schema.Add("http://tempuri.org/TestSchema.xsd", concatenatedStringPath); 

  

                XmlReader rd = XmlReader.Create($"{path}\\{fileName}"); 

                doc = System.Xml.Linq.XDocument.Load(rd); 

  

                doc.Validate(schema, ValidationEventHandler); 

            } 

            catch (Exception ex) 

            { 

                Console.WriteLine($"Error during validating file: {ex.Message}"); 

            } 

  

            return doc; 

        } 

        public static void ValidationEventHandler(object sender, ValidationEventArgs e) 

        { 

            XmlSeverityType type = XmlSeverityType.Warning; 

  

            if (!Enum.TryParse<XmlSeverityType>("Error", out type)) return; 

  

            if (type == XmlSeverityType.Error) 

            { 

                Console.WriteLine(e.Message); 

            } 

        } 

  

        public static T DeserializeFromXml<T>(string xml) 

        { 

            T result = default; 

  

            try 

            { 

                XmlSerializer ser = new XmlSerializer(typeof(T)); 

                using (TextReader tr = new StringReader(xml)) 

                { 

                    result = (T) ser.Deserialize(tr); 

                } 

            } 

            catch (Exception ex) 

            { 

                Console.WriteLine($"Error while deserializing file: {ex.Message}"); 

            } 


            return result; 

        } 

    } 

What’s the purpose of this class? Well, obviously we are using this class for getting data out of our XML file. But before we retrieve our data we need to validate our XML file. That’s why we have the ValidateXDocument method which validates current XML against our XSD file. If our XML file is validated then we will retrieve our data, if not it will throw an error (ValidationEventHandler). The last method DeserializeFromXml is used to retrieve data.

And finally, here is the main code for our application:

Solution – our application

        static void Main(string[] args) 

        { 

            if (args.Length <= 0) 

            { 

                Console.WriteLine($"Please start program with the file name!"); 

                return; 

            } 

  

            var fileName = GetExistingFile(args); 

  

            var testSchemaModelData = XmlFileManipulation.GetXmlDeserializedData(fileName); 

  

            if (testSchemaModelData == null) 

            { 

                Console.WriteLine($"Cannot retrieve deserialized data."); 

                return; 

            } 

  

            var userInput = string.Empty; 

  

            Console.WriteLine("Please enter cell address:\n"); 

  

            while (userInput != "-1 -1") 

            { 

                userInput = Console.ReadLine(); 

  

                if (UserInputHasValues(userInput)) continue; 

  

                if (UserInputHasDigitsOnly(userInput)) continue; 

  

  

                if (UserInputHasTwoParamsOnly(userInput, out var rowCell)) continue; 

  

                var row = int.Parse(rowCell[0]); 

                var cell = int.Parse(rowCell[1]); 

  

                if (testSchemaModelData.Rows.ElementAtOrDefault(row) != null) 

                { 

                    var selectedRow = testSchemaModelData.Rows[row]; 

  

                    Console.WriteLine(selectedRow?.Cell.ElementAtOrDefault(cell) != null 

                        ? $"{selectedRow.Cell[cell]}" 

                        : "EMPTY"); 

                } 

                else 

                { 

                    Console.WriteLine("EMPTY"); 

                } 

            } 


            Environment.Exit(0); 

        } 

  

        private static string GetExistingFile(string[] args) 

        { 

            string fileName = args[0]; 

  

            while (!File.Exists(fileName)) 

            { 

                Console.WriteLine($"File {fileName} does not exist!\nTry adding new one:"); 

                fileName = Console.ReadLine(); 

            } 

  

            return fileName; 

        } 

  

        private static bool UserInputHasValues(string userInput) 

        { 

            if (!string.IsNullOrEmpty(userInput)) return false; 

            Console.WriteLine("Please enter TEXT values."); 

  

            return true; 

        } 

  

        private static bool UserInputHasDigitsOnly(string userInput) 

        { 

            var isDigit = userInput.Trim().Split(' ').All(s => s.All(char.IsDigit)); 

  

            if (isDigit) return false; 

  

            Console.WriteLine("Please enter DIGIT values."); 

  

            return true; 

        } 

  

        private static bool UserInputHasTwoParamsOnly(string userInput, out string[] rowCell) 

        { 

            rowCell = userInput.Trim().Split(' '); 

  

            if (rowCell.Length == 2) return false; 

  

            Console.WriteLine("Please enter only two(2) values."); 

 
            return true; 

        } 

    } 

Our code get’s XML data, check’s valid input, parses row and cell value and outputs it into the console.

That’s it, hope this helps you!

Cheers

How to check if a picture is an image or a floor plan by using Javascript

Hi there! Oh, maaaan… This Coronavirus situation was pretty difficult. I hope you all managed to overcome it without any serious consequences. As you might have guessed, it did impact my writings on my blog and youtube video recordings as well.

The home office proved to be much more exhausting than it sounds at first. My productivity did increase but it was hard to separate work from leisure. But that’s going to be a blog post for itself.

Let’s get going with some new cool content. 

The challenge

Recently, I had the opportunity to work on some awesome reactjs project. And I stumbled upon a feature request to determine if a picture is an image or a floor plan by using Javascript. And without using any Google, Microsoft, machine learning, AI whatsoever hyper-cool trending stuff.

What does that mean? 

Well, it means that you need to upload some photos and determine if it’s a proper photo taken by a camera or if it’s a floor plan (schema). The very tricky part of this feature was that the floor plan can be in color, not just black and white. Which would significantly make my life easier of course? But hey, we love challenges! Especially this kind of Javascript challenges, don’t we!? 🙂

via GIPHY

The search

After googling around for a while I couldn’t find a proper copy/paste solution. Even more, I had a problem by only finding how to use google, to search what I needed. And after a while, I ended up on some forum posts which gave me an idea of how to solve this issue.

via GIPHY

The whole idea is to load an image and check each pixel of an image then based on that make some calculations regarding color size and saturation.

The solution (theory)

To determine if one photo is a floor plan or not:

  1. Check photo saturation and if it’s lower then XYZ it’s a floor plan
  2. Check the number of pixel colors. If it’s below certain color number then it’s a floor plan 

Okay, number of colors makes sense but what the heck is saturation?
If you google it, you will find a definition which says:

Saturation refers to the intensity of a color. The higher the saturation of a color, the more vivid it is. The lower the saturation of a color, the closer it is to gray. Lowering the saturation of a photo can have a “muting” or calming effect while increasing it can increase the feel of the vividness of the scene.”

So black and white colors have saturation 0 (zero) or almost 0 (zero) while photos are more saturated. So, camera taken photos is more saturated than the floor plan images (although) this might not always be the case.
The higher the resolution the image is more saturated. That’s why this solution isn’t 100% bulletproof. But does cover more than 98% of cases which was definitely more than enough.

via GIPHY

Pseudocode

Okay, let’s get more into pseudocode which says the following:

  • Obviously, load the image into pixel array
  • You should implement the function which loops through each pixel of an image, and then you need to find the average saturation number
  • If that number is below the constant number we set by ourselves (which proved to be around 0.03, but you can tune this a little bit more) we can assume it’s a floor plan.
  • To make our solution more rigid we will also implement a function that shall check the number of colors. 

Oh, by the way, I will only show you the snippets of code. If You want to challenge yourself, feel free to create a custom library based on this.

I will provide you in the end a more pseudocode steps to ease you the process.

The (partial) solution

getSaturation({ pixelArray, pixelCount }).then((saturationValue) => {
            if(saturationValue < 0.03){
              getPixelColorsSize({ pixelArray, pixelCount, imgData }).then(colorSize => {
                if (colorSize < 1000){
                  accept(true)
                } else { 
                  accept(false);
                }
              });
            } else {
              accept(false);
            }
          });


const getSaturation = ({ pixelArray, pixelCount }) => {
  return new Promise((resolve, reject) => {

   const sum = pixelArray.reduce((total, pixel) => total + calculateSaturation(pixel));

    const checkValue = sum / pixelCount;

    resolve(checkValue);
  });
};


const calculateSaturation = (pixel) => {
  let r = pixel[0];
  let g = pixel[1];
  let b = pixel[2];

  // Make r, g, and b fractions of 1
  r /= 255;
  g /= 255;
  b /= 255;

  // Find greatest and smallest channel values
  const cmin = Math.min(r, g, b);
  const cmax = Math.max(r, g, b);
  const delta = cmax - cmin;
  let s = 0;
  let l = 0;

  // Calculate lightness
  l = (cmax + cmin) / 2;

  // Calculate saturation
  s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));

  return (s);
};

Conclusion

I hope this article helped you a lot if you stumbled upon this kind of feature request. I surely know, if I had it it would be a breeze to implement it.

Anyways, thanks for reading and let me know if You managed to create a custom library based on this?

Cheers

The challenge (homework)

More pseudocode:

  1. Load image
  2. Get pixel array (hint: use get-pixels library)
  3. Use above explained saturation code
  4. Loop through pixel array and add each pixel r-g-b value to a collection to check color size

INTERVIEW JOB CODING TASKS – Calculate permutations

Today we are going to continue with interview coding tasks.

I really do hope this, solved, coding task is going to help you during your interview.

Task: Depending on input value i.e. (123) create all permutations i.e:(123,213,231,132,312,321)

Solution:


private static void Main(string[] args)
{
	WritePermutations();
        Console.ReadLine();
}
public static void WritePermutations()
{
	var permutations = GetPermutations("123");

	foreach (var permutation in permutations)
	{
		Console.WriteLine(permutation);
	}
}
public static List<string> GetPermutations(string inputString)
{
	return IsPermutated(inputString, out var permutations, out var list) ? list : ListOfPermutations(inputString, permutations);
}
private static bool IsPermutated(string inputString, out List<string> permutations, out List<string> list)
{
            permutations = new List<string>();
            list = null;

            if (inputString == null) return true;
            if (inputString.Length != 0) return false;
            
            permutations.Add("");
            {
                list = permutations;
                return true;
            }
}

private static List<string> ListOfPermutations(string inputString, List<string> permutations)
{
	var firstCharacter = inputString[0];
	var remainder = inputString.Substring(1);
	var words = GetPermutations(remainder);
	foreach (var word in words)
	{
		for (var i = 0; i <= word.Length; i++)
		{
			permutations.Add(InsertCharacterAt(word, firstCharacter, i));
		}
	}

	return permutations;
}
public static string InsertCharacterAt(string word, char character, int i)
{
  var start = word.Substring(0, i);
  var end = word.Substring(i);
   return $"{start}{character}{end}";
}

Cheers

How-To setup global exception handler in .NET Core?

Today I’ll try to be precise and straight to the point as possible.
If you want to simplify your code by removing unnecessary try {} catch {} blocks of your code inside API Controllers, then you probably want to use some kind of global hook in which you are going to handle global exceptions.

The way we utilize global exception handler in .NET Core API is like this:

Startup.cs -> Configure method:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          await context.Response.WriteAsync(exceptionHandler.Error.Message);
     }
​
}); });

But this way we did not set up our CORS headers we only set our error message.

Add IHttpResponse extension

So to fix our CORS headers we need to add an extension which is going to do just that, set our CORS headers. We will also add the possibility to set our custom error message as well.

The way we do it, is like this:

public static class Extensions
{
    public static void AddApplicationExceptionHandlerCorsHeaderWithMessage(this HttpResponse httpResponse, string customErrorMessage)
    {
        httpResponse.Headers.Add("Application-Error", customErrorMessage);
        httpResponse.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
        httpResponse.Headers.Add("Access-Control-Allow-Origin", "*");
    }
}

And now we have proper global exception handler set up with CORS and header error message.

FINAL RESULT:

app.UseExceptionHandler(builder => { builder.Run(async context =>
{
     context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
​
     var exceptionHandler = context.Features.Get<IExceptionHandlerFeature>();
​
     if (exceptionHandler != null)
     {
          var errorMessage = exceptionHandler.Error.Message;
 
 context.Response.AddApplicationExceptionHandlerCorsHeaderWithMessage(errorMessage);
     await context.Response.WriteAsync(errorMessage);
    }
​}); });

When your best employee wants to leave

What does it mean and how to handle valuable member of your organization who wants to leave your company?

Well, obviously if he says: “I quit!” he wants to leave. Don’t be fooled and think like it’s out of the blue. Something has been cooking inside your team member for a longer period of time.

If you don’t pay attention, often this eureka moment:” I quit!” might seem to you like all of a sudden. 

But it is not!

In short, you have failed as a manager.

Be aware

Because you should have been aware of dissatisfaction which slowly but progressively has been accumulating inside your team member over-longer period of time.

By dissatisfaction, I don’t mean he or she is unsatisfied with salary.
I assume he or she is already satisfied with it. Since I am talking about a dedicated and loyal team member of your organization who is already established in the organization.

Most probably, this kind of individual will try to leave your company because his efforts were not recognized by you.

So how do we deal with this situation?

It all starts with pulling you aside and saying: “Do you have a minute or two!? I need to tell you something really important! Bla Bla Bla Bla… I quit!”.

This is the time when you surely don’t want to evade your valuable member. Drop everything you had in mind and focus on him/her! Otherwise, you only acknowledge what he already feels like, not valued!

Ask why! 

He or she will probably have prepared speech, so let them talk. Then try to really ask questions beyond prepared speech. Most probably this is when the real reasons will pop out.

DON’Ts

In any case don’t argue, panic or lecture. Because it won’t get you anywhere. It will only fortify the decision of leaving, made by an individual. 

Now you need to buy some time for yourself to get more prepared for additional talks with him or her. So it would be good to rally other managers if you are not sure of what and how to handle this situation. Talk with them about possible solutions. One of the solutions would definitely be transferring him to another department, project manager or project.

Anyhow, you need to offer as many solutions for an individual as possible.

Long, long, ago…

Most probably if you offer something, the individual will say that you should have done it long ago. Again, don’t argue. Just say that he is right and that his actions opened your eyes and that the time has come to correct obvious error.

Threesome

The last thing which an individual might say during your talk is that he has already committed to another company job offer. But you need to say to him that although he already committed to another company he is still committed to you as well. The connection between you two is far greater and stronger than the connection between him and the newly committed company.

Finale

Although this talk won’t be easy for any side, you have to give the best of you to keep your valuable member inside your organization.

If you lose that valuable member of your organization, more employees who respect that individual and identify with him will start to question themselves. Their morale will eventually deteriorate and you might face much more uncomfortable talks like the one described above!

Bottom line, keep your eyes wide open. Every now and then talk with your team members about what’s bothering them so you can act accordingly.

Cheers

What motivates employees

Today, we will have an insight into what management is and what drives individuals in a team.

Although I had this kind of article in my mind long ago, I finally put it to “paper”. 

As a manager myself, I see how some managers work and miss the point.  I’ve made errors and sometimes I still do. But to keep or build your team, like, really a TEAM, you need to know how to motivate each individual.
So here are some of my thoughts regarding this issue.

If individuals work in a team, they need to be managed by someone, somehow. 

So what is management?

It’s a team activity. 

There is no I in a team. If person A performs bad, whole team is about to perform bad or lower at least. To put it in other words, a team is only as strong as its weakest player.

So each individual in a team needs to continually try to give the best they can do. 

If person A in a team is not doing his job, it’s either because it can’t do  or it won’t do.

In other words he’s not capable of executing assigned tasks or he’s not motivated to execute those tasks.

Manager task, on the other hand, is to find out what the problem is and to try to tackle it accordingly. As the team needs to give it’s peak performance during this marathon called “The project”.

So, to tackle these two issues, manager has two methods in his sleeves: 

  • Training
  • Motivation

But in reality, the manager can’t do much. All he is able to do is to create an environment in which his subordinates can shine. That said, it’s not realistic to expect that people who are not motivated, will, by doing any kind of training become as productive as they can be. So no training in the world won’t help any person in a team which is not motivated enough. And here is where Abraham Maslow’s theory of motivation comes into place.

Abraham Maslow’s pyramid

As Maslow says: “Motivation is closely tied to the idea of needs, which cause people to have drives, which in turn result in motivation.

Here is the thing: to maintain motivation as high as possible all the time, we need to keep some needs unsatisfied all the time.

Let’s see how Maslow defined hierarchy of needs from the ground up:

Image source Wikipedia

According to Maslow’s pyramid, when lower need is fulfilled, one higher is about to take over.

Let’s take a look at each level of Maslow’s pyramid.

Level 1: Physiological

This is the base of all other motivations. Not to be hungry.
In other words, this is a need which is aimed at things which money can buy i.e. food, clothes, drinks etc.

Level 2: Safety or Security

These needs are aimed at protecting oneself from going back to a state in which basic necessities are being deprived i.e. being medical insured.

Level 3: Love or Social Belonging

In every human there is DNA which drives humans to form some sort of a group. It is an inherent desire of each individual to belong to some kind of a group.

That is the fact. As I said, “some kind of a group”, not any group!
Each individual is drawn to a group whose members have or share common interests with themselves.

Social needs for belonging are very, very powerful. There are cases where, for example, freelancers give up of a good income in favor of working full time for a company. Just so they are not alone or to have that feeling of belonging to something or someone.

Like John Donne wrote: “No man is an island”.

Interlude

We can consider these three levels to be a basics for every employee.

These are considered fundamentals for being a worker, someone who will show up every day in the office.

But there is so much more to be fully motivated.

And here are the last two levels:

  • Esteem
  • Self-actualization

Level 4: Esteem or Recognition

Esteem or Recognition needs are basically self-limiting. Which means if we gratify them, motivation will lack and we will start looking for some other ways of motivating ourselves.

What do I mean by that!? If you want to be recognized by a group/team or if you are looking to be recognized by someone you admire, the moment you get that acknowledgment, your need is fulfilled and you start looking around how to motivate yourself further.

Let’s say you have been recognized/praised by a boss. That would boost your esteem and your desire for a recognition dramatically.

But, technically that praise would matter only to you, no one else would give a shit about few good spoken words to you. That’s why it’s self-limiting.

Level 5: Self-actualization

Maslow formulates this as: “ what I can be, I must be”.

Once someone reaches this kind of level, his performance is without any limits. They will try to perform better and better, doing this circular performance tuning without ending.

So there are two inner forces which will occupy one’s capabilities to reach the max:

  • Competence driven
  • Achievement driven

Competence driven

Competence driven is basically task-oriented, which means they will try to perfect their mastery by doing repetitive tasks to maximize their performance.

Imagine a football player trying to perfect his free-kicks by kicking a ball on training over and over again. Or imagine a Dota/LoL player trying to master his Hero by playing games over and over again.

In the latter example, you can probably imagine a kid who is bored while being in a class and waiting for those endless 45 mins to pass by, while when playing his favorite Hero in some of those games, those same 45 mins pass by as if it were only 5 mins passed by.

Achievement driven

Then we have achievement-driven people, which are a minority by the way, and have that strong need to excel and to achieve in all that they do.

The one thing that is common to competence driven and achievement-driven people is that they test the outer limits of their abilities. They try to max out themselves to fulfill their abstract needs.

Manager task

So the manager’s task is to give high goals that are reachable but not fully doable. That way an individual will stretch enough, will fail half the time. But in the end, will come up with the results that will motivate him/herself even more.

Using this kind of goal settings we tend to achieve peak performance of each team member

Money motivation

Money is pretty important when motivating individuals. But, there is a big but! 

The moment the individual reaches a level in which he or she expects of him/herself, meaning an individual has enough money to buy necessities which he/she needs to fulfill its inner satisfaction, the money will not matter anymore. Meaning money will not motivate anymore, period.

Most of the time, more money and a steady job, provide no more motivation.

Imagine some Wall Street guy earning 20 million for the first time. The second or third time when he earns 20 mils is not driven by esteem or recognition, because he already has his lower needs fulfilled.

Money is applicable only for the first two needs in Maslow’s pyramid.

So here is where self-actualization comes into place. Now if that Wall Street guy defines money as a measure of achievement than his motivation will be limitless.

An easy way to find out in which level of Maslow’s pyramid individual is bound to would be as follows:

If a salary, which an individual receives, is important to him, he’s mostly bound to physiological and safety levels. On the other hand, if an individual is comparing what other colleagues got, he’s then bound to esteem or perhaps self-actualization.

So for any individual which is bound to self-actualization level, some kind of measurement is needed. And here lies the catch!

The catch

If an individual is on this kind of level and has no competition, meaning it can’t grow anymore and thinks that his skills are diminishing then there is a high probability he will quit. 

So, employee measurement needs to be implemented and executed regularly!

Fear as a parameter

In the first two levels of Maslow’s pyramid, individual fears i.e. loss of a job.

While in the upper two levels fear is fear of failure.

Especially for individuals residing in self-actualization level, fear of not satisfying oneself is the greatest fear.

Thus, meaning it can cause individuals to back off, especially if he/she is constantly worried about failure.

Conclusion

To bring a good team into life, you need to establish some kind of measurement for your employees, subordinates or however you wanna call them.

Try to reach peak performance for each individual in your team.

Find out what motivates him/her and accordingly apply a strategy for reaching a level of motivation he/she expects. 

As a manager you should at least follow these basic principles to boost your team’s performance:

  1. Never take personal credit for the team’s success 
  2. Be critical and harsh to peak out that performance
  3. Have that social skill to be accessible and human after all

Please comment and share if you did like this post. Also, shout out if you want to have more content like this one.

Cheers

[OT] Changes

Hi! I’ve finally completed my first video for Youtube. I talk about choosing the right Javascript framework for newcomers and experienced Javascript developers.

It’s available online at: https://www.youtube.com/watch?v=Iy0fDW8Tk78&t=10s , so please take a look and like it or share it!

I know I currently suck in the video. I’ve got that video shooting issue(fright) as well as limited knowledge of video editing.
But hey, I need to start somewhere!
It will only get better over time! I can, for sure, guarantee You that!

I’ve also done some small changes to this blog.
Like, added link to my Youtube account and added, for the first time, one project I’ve worked on in Portfolio section.
As soon as I get more time I will add some more projects I’ve worked on.

Anyways, more things are to come and hopefully you will like it!

Cheers,
Denis

Top 10 quick code refactoring tips with C#

Hi there! A few weeks passed by since my last blog post.

Well, the holiday time was on and I wish you all the best in 2020. I hope you all had a great time. But it’s time to move on. So, buckle up your seat belts and let’s move on as we have a lot to cover in 2020.

Before we proceed I would like to inform you that I’m currently doing a lot of work in the background. Soon, I will add more content and I do plan to redesign, completely, my website during 2020.
I want it to become more appealing and more content-rich for you!

So stay tuned for upcoming upgrades.

Let’s see top 10 quick refactoring tips for C#:

Tip 1: CAPITALIZATION

Read only strings should be CAPITALIZED.

Tip 2: IF STATEMENT

When using IF statements always use brackets. It’s easy to get lost if not using brackets.

If somethigIsTrue
     doSomethingElse;

vs

If somethigIsTrue {
     doSomethingElse;
}

Tip 3: STRING CONCATENATION

When concatenating strings, use String.Concat(“”,””,””);
It’s more code efficient. 

If you use “+” you create multiple objects which consumes more memory but when using Concat you create only one object.

Tip 4: CONST vs READONLY

CONST is faster but needs to be recompiled (re-build) if it’s used in some DLL.

READONLY doesn’t need to be recompiled.

Tip 5: IDISPOSABLE USAGE

If class has IDISPOSABLE then ALWAYS use “USING”.

Tip 5: ENUM INITIALIZER

When dealing with ENUMS, always use 0 as invalid or none or unknown.

Tip 6: CONVERTING VALUES (TryParse vs Convert)

When converting values always use TryParse, as it won’t throw an error but will return false if it’s not parseable. This way you avoid writing try – catch block

Tip 7:  INHERITANCE

Don’t do excessive inheritance and try to simplify your code.
Make it 1 class = 1 file.

Tip 8: PROPS

Use auto properties.

Tip 9: OVERRIDES

Use virtual to override methods

Tip 10: LAZY LOAD

Disable lazy loading in Entity Framework.

CONCLUSION

These would be fast refactoring tips you should try to implement when the time comes for your code to be refactored.

If you have any other quick tips please, leave a comment.

Thank you.

INTERVIEW JOB CODING TASKS – Calculate Tree depth and a number of leaves

Season 1 – Prologue

So… You want to get that developer job, right?

You are preparing (or not) yourself and You pass all the “theory” questions. And then You are assigned more stuff to do…You get a bunch of coding tasks to complete. It seems so exhausting and daunting to do. It takes time and You are probably working somewhere and have a life of course. But the future employer doesn’t care and wants You to complete these tasks so You can be evaluated.

Well, to make your future interviews a little bit less stressful, I’ll share some of the most common interview coding tasks with You!

So You can, yes – You guessed it, have a life also and not just worry about some XYZ employer results. Which, if you are lucky, will give you some feedback after the whole process and will not behave like a black hole in a universe (like, thanks for the input, but completely lacks the output / their response).

I really don’t know if anyone of you were “victims” of a bad future wannabe employer, in a sense that they disrespected your precious time. Like having a marathon 5+ hours interview and then looping it for a few days and finally when this exhausting marathon is over, they don’t give you any response. Or worse, they say like: “Oooh, great! Everything looks fine and perfect, we think you are a match! We will give you an offer for sure.” and then nothing. Days passed, weeks passed, months passed and still nothing! And You are like wtf!?

I know for sure these things happen. It happened not just to me, but also to a bunch of guys I know!

So to spare your precious time I’ll be sharing coding tasks with you.

Please feel free to send me your coding tasks and I will gladly solve them for you.

Let’s make together a solid base of possible interview coding tasks so we can ease life for future developer interviews.

Task 1: Find the depth of a tree and the number of leaves for a defined “path” in an existing tree.

We have an already defined tree like this one:

Text Box

Each element of this string array is representing a node. Parent node is defined as a element in a row, followed by other node which is parent node of the next node. Root element is defined by “-1”.

So, root element is 5, and it is a parent to 6, 2 and 0 nodes. Node 2 is parent to 1 and 3. Node 1 is parent to 4.

If you enter in command prompt: “your_compiled_app.exe 5 2 5 2 1 -1 5 0” result is going to be:

Tree height: 3 Number of leaves: 4

Let’s get to the business – show me the code

Model:

public class TreeNode<T>
{
    public T Data { get; set; }
    public TreeNode<T> Parent { get; set; }
    public List<TreeNode<T>> Children { get; } = new List<TreeNode<T>>();
}

Extensions:

public static class StringArrayExtensions
{
    public static List<int> ConvertArrayOfStringsToListOfIntegers(this string[] array)
    {
        return Array.ConvertAll(array, int.Parse).ToList();
    }
}
public static class TreeNodeExtension
{
    public static int TreeHeight<T>(this TreeNode<T> root, int depth)
    {
        var result = depth;
​
        foreach (var node in root.Children)
        {
            result = Math.Max(result, TreeHeight(node, depth + 1));
        }
​
        return result;
    }
​
    public static int LeafCount<T>(this T rootNode, Func<T, IEnumerable<T>> childrenF)
    {
​
        return EnumerateLeaves(rootNode, childrenF).ToList().Count;
    }
​
    private static IEnumerable<T> EnumerateLeaves<T>(this T rootNode, Func<T, IEnumerable<T>> childrenF)
    {
        var children = childrenF(rootNode);
​
        var hasChildren = children != null && children.Any();
​
        if (!hasChildren)
        {
            yield return rootNode;
        }
        else
        {
            foreach (var node in childrenF(rootNode))
            {
                foreach (var child in EnumerateLeaves(node, childrenF))
                {
                    children = childrenF(child);
                    hasChildren = childrenF(child) != null && children.Any();
                    if (!hasChildren)
                    {
                        yield return child;
                    }
                }
            }
        }
    }
}

Main program:

static void Main(string[] args)
    {
        if (args.Length <= 0) return;
​
        var indexList = args.ConvertArrayOfStringsToListOfIntegers();
​
        var unLinkedTreeNodes = new List<TreeNode<int>>();
​
        for (var i = 0; i < indexList.Count; i++)
        {
            unLinkedTreeNodes.Add(new TreeNode<int>(){ Data = i });
        }
        
        TreeNode<int> rootNode = null;
        var linkedTreeNodes = new List<TreeNode<int>>();
​
        linkedTreeNodes = unLinkedTreeNodes;
​
        for (var index = 0; index < indexList.Count; index++)
        {
            var nodeName = indexList[index];
​
            var isRootNode = (nodeName == -1);
​
            if (isRootNode)
            {
                var parent = unLinkedTreeNodes[index];
                rootNode = parent;
            }
            else
            {
                var unlinkedNode = unLinkedTreeNodes[index];
                unlinkedNode.Parent = linkedTreeNodes.FirstOrDefault(n => n.Data == nodeName);
​
                linkedTreeNodes.FirstOrDefault( n => n.Data == nodeName)?.Children.Add(unlinkedNode);
            }
        }
​
        var treeHeight = rootNode.TreeHeight(0);
        var leafCount = rootNode.LeafCount(root => root.Children);
​
        Console.WriteLine($"Tree height: {treeHeight}");
        Console.WriteLine($"Tree number of leaves: {leafCount}");
​
        Console.ReadLine();
    }

Conclusion

This is only the beginning. More to come soon. If you have any questions regarding this, feel free to message me, mail me etc..

As stated before, feel free to send me your coding tasks and I will gladly solve them for you.

Let’s make together a solid base of possible interview coding tasks so we can ease life for future developer interviews.

Asynchronous Programming

Have you ever been irritated by unresponsiveness of GUI? Clicking something and then waiting for GUI to get responsive again? If so, you have probably been a victim of synchronous programming. 🙂

So let’s scrape synchronous programming and say “Hi!” to asynchronous programming in C#.

Why use Asynchronous programing?

  • To implement better GUI usability.
  • To make our code easier to understand and write.

Aren’t there already ways to do asynchronous development? Well try using callbacks or threads. I guess you want be that much satisfied while writing your code, trying to figure it out and debugging.

When to use Asynchronous programing?

If you want to do any cost operations like accessing database or doing any kind I/O operations on files etc.

Luckily, .NET provides us with a bunch of async methods, which we can use easily inside our own methods.

How do we code?

Easy. By using these keywords:

  • async
  • await

and these methods which we combine with above keywords:

  • Task
  • Task<T>

So each method has to have async and Task/Task<T> as footprint and await inside body method. If you don’t have await it will simply pop you an error and your code won’t compile.

Show me the code!

public async Task<int> RetrieveNumberOfHoursAsync(){
   return await SomeExternalMethod.GetHoursAsync();
}

In above example, when we trigger our RetrieveNumberOfHoursAsync() method, our inbody function will fire up but won’t block the main thread. When all hours from SomeExternalMethod are retrieved, only then will our method trigger up the results back.

Let’s make it more clear:

public async Task<int> RetrieveNumberOfHoursAsync(){
    int hours = await SomeExternalMethod.GetHoursAsync(); // line 1
    Console.WriteLine("I won't execute until I get the results from SomeExternalMethod()"); // line 2
    return hours;
}

So what the above code does is, it triggers SomeExternalMethod() and stops from further executing.

So at first RetrieveNumberOfHoursAsync() call, only line 1 will execute. Then, only when SomeExternalMethod() is able to complete retrieving all hours, will line 2 be executed.

Let’s make it even more clear:

public async Task<int> RetrieveNumberOfHoursAsync(){
   Task<int> getHoursTask = SomeExternalMethod.GetHoursAsync(); // line 1
   Console.WriteLine("I will execute immediately"); // line 2
   int hours = await getHoursTask; // line 3
   Console.WriteLine("I won't execute until I get the results from SomeExternalMethod()"); // line 4
   return hours;
}

Triggering our method RetrieveNumberOfHoursAsync() we are going to create a Task<int> getHoursTask, (line 1) but we won’t execute it right away. Instead, we still want to do some additional stuff (line 2) before executing our newly created task (line 3). Only when our getHoursTask is finished with retrieving hours, will our message be written to console (line 4) and return number of hours.

Conclusion

Using async/await operators we make our code easier to read and maintain. It’s pretty easy to use and code with async/await. Anyways, there is a lot more to Task class than written here. Since you can use built in methods of Task class to do a bunch of manipulations with async methods. But I will leave this as homework for you. Go figure it out and make code cleaner and apps more user friendly!

All about Task class

In case you want to read little more about Task class itself, please visit it here: https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=netframework-4.8