Sunday, April 20, 2014

C# ref parameter

One of the most vague point in C.#NET is passing argument by reference, or shortly by ref.
Though it is very simple idea in passing arguments to function:


  • If argument is passed by reference then it represents link to the source data (Pointer in C).
    This is true for structures and classes.
  • Otherwise for a class copy of link is passed. And for a struct copy of whole struct is passed (except class property objects).

Take an example without ref:

 class Cat
 {
     public string Name {get;set;}
 }

 class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // By default copy of reference is passed (without ref keyword)
        // Same as copy of Pointer can be passed in C language
         private static void ChangeCatToSimba(Cat cat)
        {
            // reassign source will do nothing with Oscar
            cat = new Cat { Name = "Simba" };
        }
    }

And here is example with ref:
class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(ref catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // Ref takes memory address reference to cat object
        private static void ChangeCatToSimba(ref Cat cat)
        {
            // reassign source
            cat = new Cat { Name = "Simba" };
        }
    }


In the first example (without ref) result is "Oscar". In the second example reassigning occurs and result is "Simba".

Sunday, April 13, 2014

HTML 5 Data-* Attribute

Data-* attribute is special novelty in HTML 5 that can be used for own purposes.

For example, we can use our own data-author, data-title, data-text, data-car-model attributes (anything starting with data-) and it will be valid HTML. Custom data attribute can be used on any element:

<span data-author>Miguel de Cervantes Saavedra</span>
<span data-title>Don Quixote</span>


One of the big architecture flaw appears: there is no namespace!
And I predict there will be lots of conflicts, especially when one famous javascript framework will use same data- designation as another framework, or it will conflict with you own clear attribute names.
Microsoft already uses data-* attributes in ASP.NET MVC for validation.


Thursday, March 27, 2014

Windows Map disk D: to disk C:

As stupidity is inherent part of humanity :) the next case occurred:

In our big corporate project we must install external program and use special libraries. This external application can be installed only on disk D:\ and there is no way to change it. Yes, 21st century.

And what to do if you do not have disk D:?

One of the simplest solution in such case can be mapping all calls of the disk D: to disk C: with regedit:


REGEDIT4

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices]
"D:"="\\??\\C:\\D"

Wednesday, March 12, 2014

Digits in Regular Expression

There are two ways for matching any digit via regular expression: \d and [0-9].
[0-9] matches any arabic numeral, i.e. 0,1,2,3,4,5,6,7,8,9;
\d matches any unicode number.

In addition to arabic numeral unicode contains more than 300 numbers from different cultures. For example, indian numbers  (0),  (1),  (2), etc.

With simple C# script all possible unicode numbers can be found (up to 65536 characters)
0: 0,٠,۰,߀,०,০,੦,૦,୦,௦,౦,೦,൦,๐,໐,༠,၀,႐,០,᠐,᥆,᧐,᭐,᮰,᱀,᱐,꘠,꣐,꤀,꩐,0
1: 1,١,۱,߁,१,১,੧,૧,୧,௧,౧,೧,൧,๑,໑,༡,၁,႑,១,᠑,᥇,᧑,᭑,᮱,᱁,᱑,꘡,꣑,꤁,꩑,1
2: 2,٢,۲,߂,२,২,੨,૨,୨,௨,౨,೨,൨,๒,໒,༢,၂,႒,២,᠒,᥈,᧒,᭒,᮲,᱂,᱒,꘢,꣒,꤂,꩒,2
3: 3,٣,۳,߃,३,৩,੩,૩,୩,௩,౩,೩,൩,๓,໓,༣,၃,႓,៣,᠓,᥉,᧓,᭓,᮳,᱃,᱓,꘣,꣓,꤃,꩓,3
4: 4,٤,۴,߄,४,৪,੪,૪,୪,௪,౪,೪,൪,๔,໔,༤,၄,႔,៤,᠔,᥊,᧔,᭔,᮴,᱄,᱔,꘤,꣔,꤄,꩔,4
5: 5,٥,۵,߅,५,৫,੫,૫,୫,௫,౫,೫,൫,๕,໕,༥,၅,႕,៥,᠕,᥋,᧕,᭕,᮵,᱅,᱕,꘥,꣕,꤅,꩕,5
6: 6,٦,۶,߆,६,৬,੬,૬,୬,௬,౬,೬,൬,๖,໖,༦,၆,႖,៦,᠖,᥌,᧖,᭖,᮶,᱆,᱖,꘦,꣖,꤆,꩖,6
7: 7,٧,۷,߇,७,৭,੭,૭,୭,௭,౭,೭,൭,๗,໗,༧,၇,႗,៧,᠗,᥍,᧗,᭗,᮷,᱇,᱗,꘧,꣗,꤇,꩗,7
8: 8,٨,۸,߈,८,৮,੮,૮,୮,௮,౮,೮,൮,๘,໘,༨,၈,႘,៨,᠘,᥎,᧘,᭘,᮸,᱈,᱘,꘨,꣘,꤈,꩘,8
9: 9,٩,۹,߉,९,৯,੯,૯,୯,௯,౯,೯,൯,๙,໙,༩,၉,႙,៩,᠙,᥏,᧙,᭙,᮹,᱉,᱙,꘩,꣙,꤉,꩙,9 

Code

In online regex tool you can find the proof for this unicode test.
By the way java script does not support unicode in regular expressions by default, so there \d is the same as [0-9].
And here is code in C# that collects all numbers:

Does your e-mail checking regular expression have protection from unicode special numbers?
Or they will appear in a company database? :)

var stringBuilder = new StringBuilder();
 
 var digitRegex = new Regex(@"\d");
 var charDigitGroups = Enumerable.Range(Char.MinValue, Char.MaxValue)
                                 .Select(Convert.ToChar)
                                 .Where(ch => digitRegex.IsMatch(ch.ToString()))
                                 .GroupBy(ch => Char.GetNumericValue(ch));
 
foreach (var charGroup in charDigitGroups)
{
      string joinedValues = String.Join(",", charGroup);
      string rowResult = String.Concat(charGroup.Key.ToString(), ": ", joinedValues);
      stringBuilder.AppendLine(rowResult); 
} 

Idea is based on Turkey Test.

Go to Basic/ .NET Floating Numbers

One can surprise why d1 does not equal d2 in the next example

double d1 = 0.6 - 0.2;
double d2 = 0.4;
Assert.AreNotEqual(d1, d2); // d1 != d2

This is a normal behaviour :)

However there are some funny bugs in .NET (imho). For example,

Decimal.Convert(1.51m) != Convert.ToInt32(1.51m);

More cases with explanation can be found at my Go to Basic/ .NET Floating Numbers tips and tricks at codeproject.


Wednesday, January 29, 2014

WeakReference example

WeakReference is a great mechanism.
Usual references are called Strong References.
For example,
string referenceToString = new string("The string!");

Garbage Collector collects and destroys the object if there is no any Strong reference to it.

string referenceToString = null;
If there is no strong reference to "The string!" then it will be collected by garbage collector and destroyed.

WeakReference is a wrapper on top of a Strong reference with one core distinction "WeakReference does not protect from garbage collection".

string referenceToString = new string("The string!");
var wr = new WeakReference(referenceToString);
referenceToString = null;

// some execution time left
// here wr can point to: 
// 1) NULLL if it was garbage collected or
// 2) object "The string!" if it was not garbage collected

var wrTarget = wr.Target as string; // return internal object of weak reference

Usually weak references are used wrong. Take the dialog from my old interview:
Interviewer: What is WeakReference?
Me: I did not know.
Interviewer: (answers the definition)
Me: But where it can be applied?
Interviewer: Mmmm... for example, in a cache. You can have very heavy resources, and resource can be recreated after WeakReference internal object will be garbage collected.


It is very hard to find good example of proper usage for WeakReference. Why on the earth cache mechanism should depend on Garbage Collection time? There are lots of customisable and convenient solutions for caching.

One of the great example was found for Android development (Java).
UI thread can be locked if the image will be loaded not from memory (disk, net). This can be solved by creating asynchronous task that will load the image. The problem arises if user goes out from current page of the application or Android unloads invisible part of the page. Then the image container on the page (ImageView) will not be needed at all when async operation finishes. This can be smartly solved with WeakReference:

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }
    // Method for getting bitmap is removed for code clearness

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (imageViewReference != null && bitmap != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }
}
Now image container can be garbage collected.

Monday, January 13, 2014

Prettify does not work with Blogger

The solution is a tricky one:
<script>
$(window.blogger.ui()).on('viewitem', function (event, post, element) {
    prettyPrint();
});
</script>

Source: http://stackoverflow.com/a/14659603/304371