C Task Continuewith

 

Hello everybody,

today I want to write few words about Task Paralel library, and in particular two methods: Task.Start, and Task.ContinueWith.

Snippet

System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(
                () => {
                    //some heavy code like intensive calculations, reading from db, etc.
                    
                }
            );
 
            System.Threading.Tasks.Task t2 = t.ContinueWith(
                (a) => {
                //Code to update UI
                },
                TaskScheduler.FromCurrentSynchronizationContext()
            );

Following template has the following structure. You need to split your code in two parts. First one, is code which will be executed for non-Gui. Then the same task will work with GUI context and will be able to update GUI with results from Task t.

Another method which is worth menitioning is

Snippet

System.Threading.Tasks.Task.Factory.StartNew(
                () =>
                    {
                        //this code will be executed immediately
                    }
            );

Main difference is that code from factory will be executed immediately

No Comments

Add a Comment
 

 

Generate Typescript From Enum

 

Hello everybody,

today I want to share with the world code, which generates typescript from enum declaration. I suppose everything should be understandable from code itself:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace System
{
public static class AttributesSimplification
{
/*
 
[Description("Enumerations")]
public enum EnumSample
{
[Description("Choice One")]
ChoiceOne,
 
[Description("Choice Two")]
ChoiceTwo,
}
 
   gives following ts:
 
module Enumerations {
export module EnumSample {
export enum Enum {
ChoiceOne = 0,
ChoiceTwo = 2
}
 
export function describe (enumValue: Enum) {
switch (enumValue) {
case Enum.ChoiceOne:
return "Choice One";
case Enum.ChoiceTwo:
return "Choice Two";
default:
throw Error("Unknown Enum Value");
}
}
}
}
export = Enumerations;
*/
 
 
 
// Since Enum Type implements IConvertible interface we can pass into method enum
//http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
public static string GetTypeScriptRepresentation<T>() where T :struct , IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
 
StringBuilder sb = new StringBuilder();
var defaultInstance = new T();
var values = Enum.GetValues(typeof(T)).Cast<T>().ToList();
var descAttribute = (DescriptionAttributeAttribute.GetCustomAttribute(defaultInstance.GetType(), typeof(DescriptionAttribute));
string moduleName = string.Empty;
 
if (descAttribute == null || string.IsNullOrEmpty(descAttribute.Description))
{
moduleName = defaultInstance.GetType().Namespace;
}
else
{
moduleName = descAttribute.Description;
}
 
var enumName = defaultInstance.GetType().Name;

string openingBr = "{";
string closingBr = "}";

sb.Append($"module {moduleName} \r\n {openingBr} \r\n");
sb.Append($"\texport module {enumName} \r\n\t {openingBr} \r\n");
sb.Append($"\t\texport enum Enum \r\n\t\t{openingBr}");
var lastValue = values[values.Count - 1];
foreach (var value in values)
{
var intPresentation = Convert.ToInt32(value as System.Enum);
sb.Append($"\r\n\t\t\t\t{value.ToString()} = {intPresentation.ToString()}" );

if (value.ToString() != lastValue.ToString())
{
sb.Append(",");
}
else
{
sb.Append("\r\n");
}
}
sb.Append($"\t\t{closingBr}");

sb.Append("\r\n\texport function describe (enumValue: Enum) \r\n\t{");
sb.Append("\r\n\t\tswitch (enumValue) \r\n\t\t{\r\n");

foreach (var value in values)
{
sb.Append("\t\t\t\tcase Enum.");
sb.Append(value.ToString());
sb.Append(":");
sb.Append("\r\n\t\t\t\t\t return \"" + GetDescription(value as System.Enum) + "\"");
sb.Append(";\r\n");
}

sb.Append("\t\t\tdefault:\r\n");
sb.Append("\t\t\t\tthrow Error(\"Unknown Enum Value\");");

sb.Append("\r\n\t\t\t}\r\n\t\t   }\r\n\t}\r\n}\r\n");
return sb.ToString();
}

public static void WriteFile(string filePath, string content)
{
if (System.IO.File.Exists(filePath))
{
IO.File.Delete(filePath);
}
System.IO.File.WriteAllText(filePath, content);
}

public static string GetDescription(this Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}

public static T GetEnumValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException();
var fields = type.GetFields();
var field = fields
.SelectMany(f => f.GetCustomAttributes(
typeof(DescriptionAttribute), false), (
f, a) => new { Field = f, Att = a }).SingleOrDefault(a => ((DescriptionAttribute)a.Att)
.Description == description);
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
}
}


Some examples of it's job:
AttributesSimplification.GetTypeScriptRepresentation<System.UriHostNameType>()
As result gives the following:
declare module System {
interface Uri {
AbsolutePath: string;
AbsoluteUri: string;
Authority: string;
DnsSafeHost: string;
Fragment: string;
Host: string;
        HostNameType: System.UriHostNameType.Enum;
IdnHost: string;
IsAbsoluteUri: boolean;
IsDefaultPort: boolean;
IsFile: boolean;
IsLoopback: boolean;
IsUnc: boolean;
LocalPath: string;
OriginalString: string;
PathAndQuery: string;
Port: number;
Query: string;
Scheme: string;
Segments: string[];
UserEscaped: boolean;
UserInfo: string;
}
}
If you'll have the following declaration:

[Description("DomainModels.Location")]
public enum LocationLevel
{
     //Country - ProvincePart levels do not use as they are in nuts codes but can be added if necesary
     Country = 1,
     CountryPart = 2,
     Province = 3,
     ProvincePart = 4,
     Municipality = 5,
     City = 6,
 }

Then with following code
AttributesSimplification.GetTypeScriptRepresentation<QCore.Portal.Models.DomainModels.Location.LocationLevel>()

you'll see the following TypeScript generated:
module DomainModels.Location 
{ 
export module LocationLevel 
 { 
export enum Enum 
{
Country = 1,
CountryPart = 2,
Province = 3,
ProvincePart = 4,
Municipality = 5,
City = 6
}
export function describe (enumValue: Enum) 
{
switch (enumValue) 
{
case Enum.Country:
 return "Country";
case Enum.CountryPart:
 return "CountryPart";
case Enum.Province:
 return "Province";
case Enum.ProvincePart:
 return "ProvincePart";
case Enum.Municipality:
 return "Municipality";
case Enum.City:
 return "City";
default:
throw Error("Unknown Enum Value");
}
   }
}
}
Take note, how attribute Description was applied.

One more example:
[Description("Models.DomainModels")]
public enum AwardStatus
{
     [Description("Still in progress")]
     StillInProgress,
     [Description("Awarded")]
     Awarded,
     [Description("Withdrawn")]
     Withdrawn
}
AttributesSimplification.GetTypeScriptRepresentation<DomainModels.AwardStatus>()
gives following TS:

module Models.DomainModels 
{ 
export module AwardStatus 
 { 
export enum Enum 
{
StillInProgress = 0,
Awarded = 1,
Withdrawn = 2
}
export function describe (enumValue: Enum) 
{
switch (enumValue) 
{
case Enum.StillInProgress:
 return "Still in progress";
case Enum.Awarded:
 return "Awarded";
case Enum.Withdrawn:
 return "Withdrawn";
default:
throw Error("Unknown Enum Value");
}
   }
}
}
So, if you need some kind of enums generation, you can use my utility.

No Comments

Add a Comment
 

 

Cqrs In In C Most Trivial Possible Example

 

Hello everybody,

today I want to make compendium of CQRS for very simple case.

So, at one of the projects I seen following way of implementing code:

public class WriteModel
{
        //common properties
        public int SomeEntity {get;set; } // ID of some entity
}

public class ReadModel : WriteModel
{
        public string AdditionalProperty {get;set; }
}

and that way of implementing it was proudly named CQRS. To be honest I wasn't very agreeable on that part, so I decided to hear opinions of other people, not only mine understanding of what I read in book.

And I'd like to save one of the comments not only at stackoverflow, but also at my web site.

So, what's wrong with this approach?

Liskov Substitution Principal is one problem -- the WriteModel supports mutations (via commands); to inherit from the WriteModel as you do here implies that the ReadModel also supports commands. Which implies that the WriteModel is not the only way to mutate the state of the model. That's very bad. If reverse the hierarchy, then you have a ReadModel supporting queries (good), and then the WriteModel inheriting from it also supporting queries. That's bad, but not to such a degree.  In other words, by doing this, you are losing separation of the two models. When you abandon CQRS like this, you are giving up the benefits the pattern affords. Let's imagine this exercise -- suppose you start with a model representation using Command Query Separation (aka: CQS). A trivial implementation might look like

public class Model {
    private Model.State state;

    // queries go here
    // these never change the model state

    // commands go here
    // these can change the model state
    // they don't usually return data
}

So for an example like a model of a bank account, a naive model might look like:

// CQS
public class Account {
    private Account.State state;

    // commands
    public void deposit(Money m) {...}
    public void withdraw(Money m) {...}

    // queries
    public Money getBalance() {...}

    private class State {...}
}

Superficially, all that CQRS adds here is the refactoring of the commands and queries into two separate implementations (ie: the "write model" and the "read model").

// CQRS
public class Account {
    public class WriteModel {
        private Account.State state;

        // commands
        public void deposit(Money m) {...}
        public void withdraw(Money m) {...}
    }

    public class ReadModel {
        private Account.State state;

        // queries
        public Money getBalance() {...}
    }

    private class State {...}
}

This, by itself, doesn't buy you very much -- two separate interfaces instead of one gives you some assurance that the compiler can enforce that the read only representation of the account can't be used to change it. Greg Young's key insight at this point: because we have separated the two models, we no longer need to use the same representation of the account state in both cases. In the abstract form, it might look more like:

// CQRS
public class Account {
    public class WriteModel {
        private WriteModel.State state;

        // commands
        public void deposit(Money m) {...}
        public void withdraw(Money m) {...}

        private class State {...}
    }

    public class ReadModel {
        private ReadModel.State state;

        // queries
        public Money getBalance() {...}

        private class State {...}
    }
}

This is a really big deal, because WriteModel.State can now be optimized for writes, and ReadModel.State can be optimized for reads. You can have completely different representations, completely different persistence strategies, even different skill levels of programmers working each model (programmers working with the read model may introduce bugs, but they can't possibly corrupt your client's data, because data modifications are restricted to the write model). But all of that goes away if you insist on the two models sharing a representation of state.

No Comments

 

Add a Comment
 

 

Override Equals Method Of Value Types

 

Hello everybody.

Today I want to give some demo.

using System;
using System.Diagnostics;

namespace StackOverflowQuest
{
    class Program
    {
        struct StructTest
        {
            public string TestString { get; set; }

            //public override bool Equals(object obj)
            //{
            //    var ct = (StructTest)obj;
            //    return ct.TestString == this.TestString;
            //}
        }
        class ClassTest
        {
            public string TestString { get; set; }

            public override bool Equals(object obj)
            {
                var ct = obj as ClassTest;
                if (ct == null)
                    return false;
                return ct.TestString == this.TestString;
            }
        }

        static void Main(string[] args)
        {
            StructTest st = new StructTest() { TestString = "water"};
            StructTest st2 = new StructTest() { TestString = "water" };

            ClassTest ct1 = new ClassTest() { TestString = "water" };
            ClassTest ct2 = new ClassTest() { TestString = "water" };

            int numberOfIterations = 500000;

            Stopwatch sw2 = new Stopwatch();
            sw2.Start();
            for (int i = 0; i < numberOfIterations; i++)
            {
                ct1.Equals(ct2);
            }
            sw2.Stop();
            Console.WriteLine("class perfomance = {0} Elapsed Milliseconds", sw2.ElapsedMilliseconds);

            Stopwatch sw1 = new Stopwatch();
            sw1.Start();
            for(int i = 0; i < numberOfIterations; i++)
            {
                st.Equals(st2);
            }
            sw1.Stop();
            Console.WriteLine("structs perfomance = {0}  Elapsed Milliseconds", sw1.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}

Take note of commented method of Equals method. If I execute that code on my machine, I'm getting difference in perfomance in 6 times. But if to uncomment Equals, then class and struct have comparable perfomance.

No Comments

 

Add a Comment
 

 

Search For Duplicates

 

Hello everybody,

Here is just shorp version of application which searches for duplicates in folder.

In  downloadable archive you can find my implementation of searcher with Task, ContinueWith and some other new features of C# 4.5

No Comments

 

Add a Comment