Comments TODO and HACK in C#

Hello everybody,

today I want to leave one more note, which you can use for boosting your productivity.

Imagine following scenario. On the meeting with customer you've got some list of to do points. You have them on your email. You've made some research, and found that you need to make changes to 5 C# files. How not to forget about all of those files?

On rescue comes two comments in C#:

  1. TODO
  2. HACK

Leave those comments in your 5 files -> save all files -> Open Task List, and you'll see something like this:

As you can see from presented screenshot, after you leave TODO or HACK comments in 5 C# files, you'll be in perfect position of usage of code.

What is even more interesting, with help of double click you can navigate to exact comment location.

Three states of fields in Acumatica

Hello everybody,

today I want to write a short note on three states of fields existing in Acumatica:

  1. Exists but is empty
  2. Exist and have value
  3. Has null

If to speak about string, it can exist like this:

  1.  
  2. Some value
  3.  

Do you see difference between 1 and 3? Not easy. As usually developers of C#, show this difference like this:

  1. ""
  2. "Some Value"
  3. null

And following screenshot with explanation shows how it works in case of SOAP contracts:

 so, while you make integration, keep that in mind

Strong name validation by pass

Hello,

here I want to leave a short notice how to manage strong name validation in Windows. For this purpose you can manage via following keys in regedit:

To enable the strong-name bypass feature for all applications: switch the value for AllowStrongNameBypass to 1 in
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework keys

With those changes you'll get your validation turn off. If you want to set it on, then set AllowStrongNameBypass to 0

Logical sequence of T-SQL operations

Hello everybody,

Today I want to note that SQL Server has following order of processing:

  1. From
  2. Where
  3. Group by
  4. Having
  5. Select
  6. [Expressions]
  7. [Distinct]
  8. Order By
  9. [TOP/OFFSET-FETCH]

By looking on this order you may understand why in C# LINQ from goes first and not select. That is because C# is imperative language, while SQL is declarative.

Some Solidity data types from C# standpoint

Hello everybody,

today I want to write a few words about data types in Solidity, language of programming for Ethereum and how they can be declared.

First of all there are simple types like byte, int, int256, uint128, bool etc. All of them are value types.

There are also bytes, string which are reference types. 

Reference types has interesting features. 

bytes a; is equal to byte[] a; in C#.

mapping is something like Dictionary in C#. For example you can make following dictionary Dictionary<string, int> prices; in Solidity like this:

mapping (string => int) prices;

In that case prices will a bit like a Dictionary in C#. For example you can write something like this:

prices["potatoes"] = 32;

As well as in C#, Solidity supports enums. Enums look like this:

enum Colour {Red, Gree, Blue, Yellow };

After such a declaration in your code you can write like this:

Colour public chosenColour;

Then in your code you can write like this:

chosenColour = Colour.Red; 

very similar to C#

As in C# you can convert enum to uint ( well, in C# it is more common to make it as int )

uint newColour = uint(chosenColour);.

Also enumeration order is the same as in in C#. In our case value of newColour will be 0.

Another feature of Solidity similar to C# is structures. Consider structure Student:

struct student

{

     uint age;

     uint height;

     address walletAddress;

}

Then in your code you can write something like this:

student public studik;

 

What is solidity

Hello everybody,

Today I want to write a few words about what is solidity, and why on Earth it was invented.

Before I'll do that few words about blockchain.

Blockchain consists of two main words: block and chain.

And special feature of blockchain is that it is made in a way, that each new part of it is made with taking into account previous blocks of information ( through hasing ). Another part is that everybody who is involved in blockchain has that information on theirs computers. In other words new additions somehow include information about previous pieces. 

Then consider the following. Suppose government of some country want's to print more money. As usually they want to do it for some purpose: medicine, army, police, etc. 

But what can bitcoin do, if new pices of Bitcoins are created? Well, not much. Reward somebody with bitcoins and that's it. 

And imagine if instead of rewarding you can make something more cooler. That after transaction you can run some code? For example if somebody sold for his e-currency home, then some code will be executed that will send you and email that one more home was sold. Or if somebody was happy with doctor in your native city, then send potential customers of that doctor one more notification and so on. How do gain such flexibility?

Bitcoin doesn't have such. But Ethereum has. Ethereum invented Solidity language in order to execute some chain of events after some transaction happened which satisfy your needs. 

Consider some basic features of Solidity:

  • High-level object oriented language
  • Executes on Ethereum, block-chain virtual machine
  • Statically typed
  • Contract programming language that is similar to Javascript and C
  • Contract-specific features include modifier guard clauses, event notifiers for listeners and custom global variables
  • Compiled to bytecode that is executable at EVM

As C# developer I can say that it has some bird-vew similirities to C# or to Java. C# also statically typed, compiled into bytecode ( Microsoft names it MSIL ).

Entity Framework one to many relationship

Hello everybody,

today I want to make short post on how to confiugre one to many relationship in Entity Framework 6.

Imagine following: One group can have multiple students. So one to many relationship. For this purpose you can use following convention configuration agreement:

public class Student
{
    public int StudentId { getset; }
    public string StudentName { getset; }
}
 
public class Group
{
    public int GroupId { getset; }
    public string GroupName { getset; }
    public string Department { getset; }
 
    public List<Student> Students { getset; }
}

 

In presented example class group includes navigation property Students. 

Another convention is like this:

public class Student
{
    public int StudentId { getset; }
    public string StudentName { getset; }
 
    public Group CurrentGroup { getset; }
}
 
public class Group
{
    public int GroupId { getset; }
    public string GroupName { getset; }
    public string Department { getset; }
 
    public List<Student> Students { getset; }
}

 

as you can see, difference is that Student instance by itself knows to which Group it belongs. 

 

Linear regression behavior with free weight

Hello everybody,

recently I've decided to implement some ML library in C#. But mine ultimate goal of that C# library was to make it use as much as possible TPL features of C#. 

I'm aware about other ML libraries, but as often is said, if you wish to understand how some ML algorithm works, program it by yourself. I've decided to start with Linear regression.

Here you can see how mine library utilizes processor:

as you can see it uses 85% of mine 4-cores CPU, which is impossible with only one thread running.

First step for me was to understand how that algorithm works. In order to understand it I've took course Machine Learning Specialization
from University of Washington.

I'll omit formulas on how to implement linear regression, but I want to describe following case. 

In order to test correctness of mine linear regression model, I've decided to throw on it system of linear equations:

roots of this system of equations are the following: x1 = 3, x2 = 8, x3 = 24.

Below goes code, that feeds into Linear regression that system of equations, and executes linear regression training:

public void TestLinearRegression()
        {
            double [][] inputs = new double[3][];
            
            inputs[0] = new double[3];
            inputs[1] = new double[3];
            inputs[2] = new double[3];
 
            /*
              system of equations:
              x1 + x2 + x3 = 35
              x1 + x2 - x3 = -13
              x1 - x2 + x3 = 19
             
            x1 should be 3, x2 should be 8, x3 should be 24
 
             */
            inputs[0][0] = 1;
            inputs[0][1] = 1;
            inputs[0][2] = 1;
 
            inputs[1][0] = 1;
            inputs[1][1] = 1;
            inputs[1][2] = -1;
 
            inputs[2][0] = 1;
            inputs[2][1] = -1;
            inputs[2][2] = 1;
 
            double [] outputs = new double[3];
            outputs[0] = 35;
            outputs[1] = -13;
            outputs[2] = 19;
 
            var normalizer = new MultiThreadedNormalization();
            var regressor = new LinearRegressor(normalizer, epsilon:0.0000001);
            var matrix = new Matrix(inputs);
            var weights = regressor.Fit(matrix, outputs);
 
            var inputs2 = new double[1][];
            inputs2[0] = new double[3];
 
            inputs2[0][0] = 2;
            inputs2[0][1] = 2;
            inputs2[0][2] = 2;
            var inputMatrix = new Matrix(inputs2);
 
            var result = regressor.Predict(inputMatrix);

As a reesult of execution of this code following 4 weights were received:

You may wonder, why four weights? Why not three if we have just three roots? x1, x2, x3. In order to understand this, you should keep in mind that linear regression adds one more weight. So in total result linear regression will give you one more important kriteria which is treated like free element. 

Now let's take a look on those weights closer. As you can see we have four values: -1.435, 7.991, 23.991, 6.864. If to compare those four values with x1, x2, x3, we see that x2 is very close to weight2, x3 is close to weight3. Weight 1 is pretty far from 3. And even combined Weight 1 plus weight 4 doesn't give good approximation of x1. But if to throw on linear regression algorithm some values, result of calculations will be 67.96 which is relatively close to real value 70.

 

C# async/await usage

Hello everybody,

today I want to describe in simple words what C# does for .Net cases in IIS.

Before I continue, I want to point the following. As usually IIS has 500 threads. It means that one IIS server can simultaneously server 500 customers. Keeping this idea in mind

take a look at the following code:

[HttpGet]
public IEnumerable<string> GetSync()
{
    string val1 = "value" +  LongRunningMethod().ToString();
    string val2 = "value2";
    return new[] { val1, val2 };
}
 
private int LongRunningMethod()
{
    Thread.Sleep(10000);
    return 10;
}

and imagine that you have 600 customers simultaneously. For 500 lucky users of your web site it will mean that their requests will be server, but for other 100 it will mean... It will mean that they will nead to come at another more lucky time. How to fight with such situations? Prior to async/await pattern in C# following options were applicable:

  1. Create some separate threads that executed LongRunningMethod and overcome limitation of 500 threads in thread pool of IIS
  2. Create your own thread pool, again with flexible amount of threads ( it is almost like option 1, just with another entity )
  3. Increase number of threads in IIS via configuration ( aka task for admins )
  4. Use IAsyncResult interface with BeginSomething/EndSomething approach ( I've tested it and it works pretty fine, just a bit cumbersome in comparsion with async/await 
  5. Event based asynchronous pattern 

This list is not exhaustive because you can use combination of all 5 points as well as some other staff that I wasn't able to mention.

With async/await introduction it become very easy to overcome 500 threads limitation of IIS.

Take a look at method GetAsync:

[HttpGet]
 public async Task<IEnumerable<string>> GetAsync()
 {
     string val1 = "value" + await Task.Run( ()=> LongRunningMethod().ToString());
     string val2 = "value2";
     return new[] { val1, val2 };
 }

The biggest changes at this code are the following: 

  1. Added keyworkd async
  2. Before LongRunningMethod added keyword await.

Those two changes will cause significant changes. First of all let's consider case with one thread, and later scale it to before mentioned case with 600 simultaneous users.

For clarity also suppose that we have two threads instead of 500 and one user. Let's name those threads Thread a, Thread b.

User initiates action that causes execution of method GetAsync. Thread a become executor of method. Thread a initiated thread, located some space in memory for variable "value" and then Thread a sees keyword await. Thread a will execute method LongRunningMethod and leave it and will not wait for . After Thread a will leave method GetAsync IIS will have two threads ready to start their activity on some other staff. Imagine that user initiated some kind of activity and made Thread a busy, and while Thread a was busy, method LongRunningMethod finished. What will happen next? Thread b will pick up functionality and continue execution of method GetAsync. Now let's scale this scenario to 600 users. All 500 threads will be either busy with some practical functionality and non of them will waste time in waiting for result of LongRunningMethod function.

Summary

Keywords async and await allow you to not care about how to make your code asyncronous. Just add those two words with pair Task.Run to your code and you'll get scalability out of the box. 

C# feature nameof

Hello everybody,

today I want to share with you one cool feature of C#.  It is nameof. Take a look at the following code:

var abc = 3;
var varName = nameof(abc);

How do you think, what will go into varName? It will be equal to "abc". Probably you can puzzle why on earth I can need such an operator?

Consdier following cases:

1. If you work with reflection, then instead of rely on hard coding names of fields, you can rely on compiler to subsitute it instead of you. 

class Program
{
    public class NameOffDemo
    {
        public string SomePropertyOne { getset; }
        public string SomePropertyTwo { getset; }
    }
 
    static void Main(string[] args)
    {
        var demo = new NameOffDemo();
 
        //lets say you somehow read via reflection demo.
        //Here for demo purposes I hard code it, but you can have 
 
        string neededProperty = "SomePropertyTwo";
 
        switch (neededProperty)
        {
            case nameof(demo.SomePropertyOne):
            {
                break;
            }
 
            case "SomePropertyTwo":
            {
                //Compare hard coding and maintenance for the future
                break;
            }
 
        }
    }
}

As you can see from the presented code, if in future somebody will change the name of variable, the code will not be compilable untill person will fix it. But if hard-code strings, then compiler will pass this code, and during runtime you'll see the error.

2. For reading values from cofnig files. Consider following example:

public static readonly bool ParallelProcessing = WebConfig.GetBool(nameof (ParallelProcessing), true);

In this case you'll be able to read value from config file without hard coding it in your C# code.

If to summarize, nameof allows you to be compile time safe.