2011
06.20

Authentication

Enter login: MaciejLisCK
Enter password: **********

Authorization

MaciejLisCK not authorized to delete database
MaciejLisCK authorized to post a message
2011
05.21
Error code Windows Azure Tools: Start role failed for one or more roles
Problem too long path to project
Fix Place project in shorter path. Ex.: C:/Projects/Azure1/

Thats seems to be stupid. But it works!

2011
05.18

In C# there is no such function as eval. But i will show you a simple trick how to make code that works like eval function. The trick is to create in memory a C# code then compile it and use as evaluator. If you want to use a same eval many times it is recommended to compile it just once and then just call the assembly. That is important because compilation may take a long time.

Ok here is a code in with we can inject some custom code in a runtime.

private static object compiled = null;

static void Main(string[] args)
{
    Console.Write("Enter some C# code. (Eg. Math.Abs(x)+1): ");
    string code = Console.ReadLine();
    Console.Write("Enter a double value: ");
    double value = Convert.ToDouble(Console.ReadLine());

    Initialize(code);
    double result = ComputeResult(value);
            
    Console.WriteLine();
    Console.WriteLine("Result = {0}", result);
    Console.ReadKey();
}

public static void Initialize(string function)
{
    ICodeCompiler compiler = (new CSharpCodeProvider().CreateCompiler());
    CompilerParameters compilerParameters = new CompilerParameters();
    compilerParameters.ReferencedAssemblies.Add("system.dll");
    compilerParameters.GenerateExecutable = false;
    compilerParameters.GenerateInMemory = true;

    StringBuilder code = new StringBuilder();
    code.Append("using System; \n");
    code.Append("namespace Eval { \n");
    code.Append("  public class Evaluator { \n");
    code.Append("       public double Function(double x) {\n");
    code.Append("           return " + function + ";\n");
    code.Append("       }\n");
    code.Append("   }\n");
    code.Append("}\n");

    CompilerResults cr = compiler.CompileAssemblyFromSource(compilerParameters, code.ToString());
    Assembly assembly = cr.CompiledAssembly;
    compiled = assembly.CreateInstance("Eval.Evaluator");
}

public static double ComputeResult(double x)
{
    if (compiled == null)
        throw new NullReferenceException("To use this method you must initialize Eval by its paramether");
    MethodInfo mi = compiled.GetType().GetMethod("Function");
    return (double)mi.Invoke(compiled, new object[] { x });
}
Enter some C# code. (Eg. Math.Abs(x)+1): Math.Abs(x)+1
Enter a double value: -12345

Result = 12346
Enter some C# code. (Eg. Math.Abs(x)+1): x*x+Math.Sin(x)*10
Enter a double value: 3,1415

Result = 9,86994878589661
Enter some C# code. (Eg. Math.Abs(x)+1): Math.Pow(x,3)-Math.Pow(x,2)+x+1
Enter a double value: 2

Result = 7

Disadvantage of this method is that the CSharpCodeProvider().CreateCompiler() is obsolete but anyway it works well. Another way to make eval is by using a CodeDom.

Eval Console Application

2011
04.14

What is method group

Method group is an interesting way to enhance code clarity. Let’s look at code below which uses the method group.

List<string> words = new List<string> { "apple", "orange", "pear" };

words.ForEach(Console.WriteLine);
apple
orange
pear

How its work

As we see that code somehow display words on console. Method group allows us to enter only the name of the method, so we can treat it as a delegate variable. So let’s see how the ForEach method declaration looks like.

public void ForEach(Action<T> action)

As we see method requires action parameter which is simple generic delegate:

delegate void Action<in T>(T obj);

So the ForEach method looks for delegate, and in code we provide it just typing Console.WriteLine. As you know the WriteLine method have got many overloads. So if you just type Console.WriteLine the compiler have to fit in the right method, in our example it will be WriteLine(String), because we use List<string>.

WriteLine()
WriteLine(Boolean)
WriteLine(Char)
WriteLine(Char[])
WriteLine(Decimal)
WriteLine(Double)
WriteLine(Int32)
WriteLine(Int64)
WriteLine(Object)
WriteLine(Single)
WriteLine(String)
WriteLine(UInt32)
WriteLine(UInt64)
WriteLine(String, Object)
WriteLine(String, Object[])
WriteLine(Char[], Int32, Int32)
WriteLine(String, Object, Object)
WriteLine(String, Object, Object, Object)
WriteLine(String, Object, Object, Object, Object)

Custom class example

To better understand method group below there is a code describing the phenomenon based on custom class.

public static void Main()
{
    MethodGroup methodGroup = new MethodGroup();
    methodGroup.Foreach(Display);
}

static void Display (string text)
{
    Console.WriteLine(text);
}

class MethodGroup
{
    private string[] wegetables = { "apple", "orange", "pear" };

    public delegate void Method<in T>(T obj);

    public void Foreach(Method<string> action)
    {
        foreach (string wegetable in wegetables)
            action.Invoke(wegetable);
    }
}
apple
orange
pear

Using advantages

That method can really enhance code clarity. Otherwise we are forced to use one of other possibilities:

  • anonymous method:
    words.Foreach(delegate(string word)
                            {
                                Console.WriteLine(word);
                            });
    
  • lambda expression:
    words.ForEach(word => Console.WriteLine(word));
    
2011
04.02

Often in programming is necessary to create class that manages and aggregate some type of objects. In example:

  • class Cells aggregate and manage multiple Cell
  • class DNA aggregate and manage multiple Gene

It is desirable to use a Linq expressions with class that aggregate. To have ability to use Linq methods in that custom class we have to implement interface called IEnumerable or IEnumerable<>.
For example we have got a class Cell.

enum CellStates { Empty, Grain, Solid }

class Cell
{
    public CellStates State { get; set; }

    public Cell (CellStates state)
    {
        this.State = state;
    }
}

We need to have some class that can manage our Cell collection. Creating just List<Cell> cells don’t give us so much control. So we need some class that aggregates our cells. Creating class like that don’t enables the Linq mechanism.

class Cells
{
    List<Cell> cells;

    public Cells(int cellsSize)
    {
        this.cells = new List<Cell>();
        for (int i = 0; i < cells.Count; i++)
        {
            cells[i] = new Cell(CellStates.Empty);
        }
    }
}

 

var solidCells = Cells.Select(c => c.State == CellsStates.Solid); // Error!

To make that code working just implement an IEnumerable interface.

class Cells : IEnumerable<Cell>
{
    List<Cell> cells;

    public Cells(int cellsSize)
    {
        this.cells = new List<Cell>();
        for (int i = 0; i < cells.Count; i++)
        {
            cells[i] = new Cell(CellStates.Empty);
        }
    }

    #region IEnumerable
    IEnumerator<Cell> IEnumerable<Cell>.GetEnumerator()
    {
        return cells.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return cells.GetEnumerator();
    }
    #endregion
}

Of course class Cells can just derive from a List<Cell> but that reveals whole methods. And so on it breaks OOP encapsulation rule.

2011
03.31

This is little known method to perform that common use task.

var range = Enumerable.Range(1, 12);
var repeat = Enumerable.Repeat(1, 5);
range  = { 1, 2, 3, 4, 5, 6 }
repeat = { 1, 1, 1, 1, 1, 1 }
2011
03.30

You can convert int to its binary representation in two ways:

  • normal method

    int value = 14;
    List<bool> binaryValue = new List<bool>();
    do
    {
    	binaryValue.Add((value % 2 == 1) ? true : false);
    	value /= 2;
    } while (value != 0);
    binaryValue.Reverse();
    binaryValue = {true, true, true, false};
  • Convert.ToString(byte value, int toBase) method

    int value = 14;
    string binaryString = Convert.ToString(value, 2);
    bool[] binaryValue = binaryString.Select(c => c == '1').ToArray();
    binaryString = "1110"
    binaryValue = {true, true, true, false};
2011
03.28

Code shows how to use implicit and explicit conversion. Especially it shows how to assign a int value straight to custom object, and how to retrieve int value from custom object by casting.

class Program
{
    static void Main(string[] args)
    {
        ImplicitType implicitType = 12345;
        Console.WriteLine(implicitType.Value);

        ExplicitType explicitType = new ExplicitType { Value = 67890 };
        int explicitTypeValue = (int)explicitType;
        Console.WriteLine(explicitTypeValue);
    }
}

class ImplicitType
{
    public int Value { get; set; }

    public static implicit operator ImplicitType(int value)
    {
        return new ImplicitType {Value = value};
    }
}

class ExplicitType
{
    public int Value { get; set; }

    public static explicit operator int(ExplicitType explicitType)
    {
        return explicitType.Value;
    }
}

 

12345
67890
2011
03.24

Code shows how to get site as string in one line.

string siteCode = new System.Net.WebClient().DownloadString("http://google.com");