Translate

Thursday, June 19, 2014

Introduction to vCloud Director

What is vCloud Directior?

vCloud director is a cloud provider (Amzon EC2, openstack are other examples of cloud providers). More specifically, its an Iaas (infrastructure as a service) cloud provider. (Check this out for introduction to cloud computing. ) As a use case, think of this, your organization needs some application deployed into your private data center on the click of a button. vCloud director lends itself very well to this scenario. vCloud director is ideal for setting up a private cloud within your organization.







Tuesday, June 17, 2014

How to make a thread wait for another thread in C# (Signaling C#)

If you need a thread to wait for another thread to complete, then you could use ManualResetEvent Class. What this class does is that it acts as a signal that a thread can use to decide when to proceed.

In the example below, thread 1 waits for a signal from thread 2 to proceed.

using System;
using System.Threading;
 
internal class Signaling
{
    private static ManualResetEvent _signal;
 
    private static void Main()
    {
        _signal = new ManualResetEvent(false);
 
        var thread1 = new Thread(Wait);
        var thread2 = new Thread(CountToTen);
        thread1.Start();
        thread2.Start();
    }
 
    public static void Wait()
    {
        Console.WriteLine("Waiting for a signal");
        _signal.WaitOne(); //Suspend thread until signal is open
        _signal.Dispose();//Once the signal is open, dispose it
        Console.WriteLine("Green Signal! Lets go!");
    }
 
    public static void CountToTen()
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }
        _signal.Set(); //Open signal
    }
}


Monday, June 16, 2014

C# captured variables made simple (aka C# closures)

What do you think the following piece of code will do?

using System;
using System.Collections.Generic;
 
internal class Test
{
    private static void Main()
    {
        var actions = new List<Action>();
  
        for (int i = 0; i < 3; i++)
        {
            actions.Add(() => Console.WriteLine(i));
        }
     
        foreach (Action action in actions)
        {
            CallAction(action);
        }
    }
 
    public static void CallAction(Action action)
    {
        action();
    }
}

You might expect it to print 0 1 2, but what it actually does is print 3, three times.









The reason for this happening is that a lambda expression retains the last value of the variable. This phenomenon is called closure in computer science. In .net its called a captured variable. The code above can be fixed as shown below. What we are doing is that for every iteration we are declaring a new variable.


using System;
using System.Collections.Generic;
 
internal class Test
{
    private static void Main()
    {
        var actions = new List<Action>();
 
        for (int i = 0; i < 3; i++)
        {
            int temp = i;
            actions.Add(() => Console.WriteLine(temp));
        }
 
        foreach (Action action in actions)
        {
            CallAction(action);
        }
    }
 
    public static void CallAction(Action action)
    {
        action();
    }
}














However, you must remember, if you change the value of the variable temp, after its used inside the lambda expression, then you will get that latest value of temp.

Friday, June 13, 2014

Windows batch file to replace all occurrences of a file

You can use the batch file below to loop through all the folders inside
 C:\my destination and replace any occurrences of a.txt with the one from
 C:\my source\a.txt

To use the batch file just replace the values of the variables in red

I have tested this in windows 7

@echo off
set sourceFileFolder=C:\my source
set sourceFileName=a.txt
set ReplaceInChildFoldersOf=C:\my destination

REM DO NOT MODIFY ANYTHING BELOW THIS LINE!!

set sourceFileName=%sourceFileName: =%
set fullSource="%sourceFileFolder%\%sourceFileName%"
set ReplaceInChildFoldersOf="%ReplaceInChildFoldersOf%\"


echo Replacing all occurrences of %sourceFileName%
echo in %ReplaceInChildFoldersOf%
echo with the one in %fullSource%
echo Do you wish to continue?

pause

FOR /R %ReplaceInChildFoldersOf% %%I IN (%sourceFileName%)  DO if exist "%%~fI" COPY /Y %fullSource% "%%~fI" 

pause
                                                                                                

Tuesday, June 10, 2014

How to pass data into a thread in C# (Call a thread with input parameters)

Using a Lambda expression, you can pass any number of parameters into a method when calling it thru a thread.

using System;
using System.Threading;

namespace ThreadInputParam
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var t = new Thread(() => Print("my input string",3));
            t.Start();
        }

        public static void Print(string s,int i)
        {
            Console.WriteLine(s);
            Console.WriteLine(i);
        }
    }
}


XmlSerializer tutorial with example (C# XML serialization)

What is Serialization?

Serializing means writing out an object into a form that can be written to a file. The main uses of serialization are

  • Transmitting objects over the network (eg wcf serializes objects to transmit over the wire)
  • Storing of objects in a database (eg Raven db serializes objects into a json format to store it in its database)
  • Deep cloning of objects

Serialization support in the .net framework

There 3 main forms of serializing mechanisms in the .net framework
  • The data contract serializer
  • The binary serializer
  • The XML serializer
In this article I will cover the XML serialization.

XML Serializer class

The XML serializer class in the System.Xml.Serialization namespace is used to serialize and deserialize objects into and from XML documents.

In this simple example below, I serialize an instance of the Person class into XML and write it out into the console window.

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLSerializationExample
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var p = new Person
            {
                Name = "Jack",
                Age = 64,
                Pets = new List<Pet>
                {
                    new Pet {Name = "Pluto", Species = "Dog"},
                    new Pet {Name = "Felix", Species = "Cat"}
                }
            };

            SerializePerson(p);
        }

        public static void SerializePerson(Person person)
        {
            var xmlSerializer = new XmlSerializer(typeof (Person));
            using (var s = new StringWriter())
            {
                xmlSerializer.Serialize(s, person);
                Console.WriteLine(s.ToString());
            }
        }
    }


    public class Person
    {
        public int Age;
        public string Name;
        public List<Pet> Pets;
    }

    public class Pet
    {
        public string Name;
        public string Species;
    }

}

This is how the output looks like


<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Age>64</Age>
  <Name>Jack</Name>
  <Pets>
    <Pet>
      <Name>Pluto</Name>
      <Species>Dog</Species>
    </Pet>
    <Pet>
      <Name>Felix</Name>
      <Species>Cat</Species>
    </Pet>
  </Pets>

</Person>