AdBrite

Your Ad Here

Tuesday, April 26, 2011

Read File into Byte Array

string filePath = @"C:\test.doc";
byte[] byteArray = File.ReadAllBytes( filePath );

C# Convert String to Byte Array

string s = "Test String";
byte[] byteArray = Encoding.ASCII.GetBytes( s );

C# Convert Byte Array to String

byte[] buffer = new byte[10];
// todo: populate the buffer with string data 
string s = Encoding.ASCII.GetString( buffer );

Monday, April 25, 2011

Pass parameters to the timer in C#


These days I am using C# to develop the timer component running as a windows service, which runs automatically in a specific interval.

In C#, there are 3 kinds of timer type definitions:

1. System.Windows.Forms.Timer
2. System.Threading.Timer
3. System.Timers.Timer

In my project, I choose to use the third one: System.Timers.Timer
Here is the sample usage of this kind of timer:

System.Timers.Timer timer = new System.Timers.Timer();
timer. Interval = 10000; // set the interval as 10000 ms
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed); // set the event to execute
timer.AutoReset = true; // false: only execute once
timer.Enabled = true; // to decide if execute the event of timer specified


public void timer_Elapsed(object sender, EventArgs e)
{

}

From the above sample, we know it is quite easy to use it.

Next, I have a problem if I need pass some parameters to be used in the timer event defined above: timer_Elapsed(…). The two input parameters of this event interface are fixed, you can’t add more in.

There is a tricky to achieve it. Since we can’t add more input parameters in this event, we can set the parameters into the unused property of that sender object. This way is simple, but not good.

After researching, i find a better way to deal with it: creating a new timer to extend the system timer , and then defining the additional parameters inside this new timer.

Here are the sample codes:

// define a class to extend the timer,
// then define those additional parameters to be used in the event.
// for example: add one more parameter: param1.
namespace XXX
{
public class TaskTimer : Timer{
private string param1;

public string Param1
{
get
{
return param1;
}
set
{
param1= value;
}
}

public TaskTimer() : base()
{
}
}
}

// usage of this timer
using XXX;

TaskTimer timer = new TaskTimer();
timer.Interval = 10000;



// the event definition
public void timer_Elapsed(object sender, EventArgs e)
{
String param1 = (TaskTimer) sender).Param1;
}

Saturday, April 23, 2011

C# Delegate


        // This "DoMath" delegate can point to ANY method that:
        //   - Returns an int
        //   - Accepts two ints as parameters
        public delegate int DoMath(int x, int y);

      
        private void button1_Click(object sender, EventArgs e)
        {
            int result;

            DoMath a = new DoMath(Add);
            result = a(3, 4);
            MessageBox.Show(Convert.ToString(result));

            UseDelegate(a);
        }


        public void UseDelegate(DoMath x)
        {
            int r = x(6, 6);
            MessageBox.Show(Convert.ToString(r));

        }

       
        //This method can be pointed to by the DoMath delegate
        public int Add(int x, int y)
        {
            return x+y;
        }

        //This method can be pointed to by the DoMath delegate
        public int Subtract(int x, int y)
        {
            return x - y;
        }

        //This method can NOT be pointed to by the DoMath delegate
        //because it has a different signature (only one argument)
        public string Test(string y)
        {
            return "Test method";
        }
    }

C# Split String


=== Example program for splitting on spaces (C#) ===

using System;

class Program
{
    static void Main()
    {
        string s = "there is a cat";
        //
        // Split string on spaces.
        // ... This will separate all the words.
        //
        string[] words = s.Split(' ');
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }
    }
}

=== Output of the program ===

there
is
a
cat
.........,,,,,,,,.....,...............,~:..,:::+++?????????,,,::,,:,,,,,,,,,,,,,
..,,,.,,,,,,,,,,......................,~...,~,::==+++++?III?,:~~,::,,,:::::,,,::
...,,,,,,,,,,,:,....,................,:,,,:,:~,,:=+=+++?III7,~::,,:,,,,,,,,,,,,,
.............,,,...,................,:~~.~=~=+~:,.,===??II77?~,,,.....,..,,,,,,,
............:,,...,..................:+=:~=+~:=~,,...,~??II77::,,.,...,...,..,,.
............:,..............,,......,~??+:++,~::~~:,..,:=+I77.,,,.,,,,,.........
...........,.,..............:,:::....~???=~.:,~,,:~:,,:,::.+7::,,.,,,,,...,...,.
..........,................:~~:::...,==?I?=........,,::=,,,.:,,,,,,,,,,..,,.,,,.
.............,.............:,,~:=,..,++++?+,,:,,,..,,+=7.,,~I..,,.,,,,,,.,,.,.,.
....,.,...................,:=:,+=~..~=+=++??=,=~:::~+?~I,..:=:,.,,,,,,,.,,,.,,,.
......,,..................~~~====~:..:+?+~+++=,~===+????:,..,:::..,,,,,..,,.,,,.
.......,...................:++++=+==.,,+++~=++=,===+????I:,,,.,.,...,,,,,,,,,,,,
...,.........................~====++?,.:==+=~=+=:~=+?I++=7?I~,:,,,,,,,,,,,,,,,,,
..............................,,.~=+??~..,+==~~=~:=~:..~,+?I=:,,,,,,.,,,,,,,,,,,
..............................,,,:=????+...:~~:~==~,:=,.~+I?:::,,,,,,,,,.,,,,,,,
..............................,,::=++???+~.,..::==++:?~I++++,,,,,,,,,,,,,,,.,,,,
.......,,....................,,:~:~=+++++++:,,..,,:,,,,~===~:::,.,,.,,,,,,,,,,.,
......,,.....................,::~~::~=+++++==:,..,.....,+=+:,:,,.,,,,,,,,,,.,,,,
.....,,......................,~:~~~~:~~=======~:,....~:,:+,~:,,,.........,......
.....,,.......................:~:~~~~:::~~~====~::,,...,=,.,,::,.,,......,......
.......,......................,~~:~~~:::::::~==~=~::?===....,,,,,..,,,...,......
....,,,....,...................:~~~~=~::,,,,:::~~:::+?+..:.,~,....,,,,.......,..
........,......................,~~~~==~:,,,,,,,,,,,:=?.....,,,,,,..,,...,.......
.,.....,,......................,,~~===~:,,,,,,............,,,~:,...,..,,........
,....,,.....................,...,,~==~::,,,,.......,........,~,:..,,,,,..,,,,,..
....,.........,............,,,...,,~~~::,,,,,,......,.......::~,..,,,,,.,...,,..
...,....,,....,...........:::,:....,~~::,:::,,,.............,::,......,...,.....
.........,...,,..........,~~==,~...,,:::::~::,,...............:,,~,,,,,,,,......
..............,..........:=+?++~,:...,,:~~=~::,.,.............,,.,...,..,,...,..
..............,..........=??I??++~:,...,~~~~::,,,,.............,,,,.,,,,,,..,,,,
..............,.......,~:+?II???+==:,,....,~::,,::..............,,.,,,,,,.,,,,,.
..............,,...::,~=,=?II???++=~::::,,,....,::...............:~:,.,,,,,.,,,,
.............,,~=~::,~==:=+II????+=~~=+++=:,:~~:.....,............:~,:=~,,,,,,,,
..........,.=~=~=++~:~=~,=?IIIIII+==+????????++==:,..................~~~=+,.,,..
.....,..====??????+??::~:+?IIIIII?+??IIIIIII?I???~~:~,,...,........,::,:~==.,,..
,,,,,~++???????:??~~~~~~+?IIIIIIII?IIIIII?IIIIII?~:::,,,..,,......,.,::,:~~+,,..
,.=++????????+?+=~~~~~=~=??IIIIIIIIIIIIII???IIIII=:~::,,,,~~~,......,,,:,:=+,,.,
?????+++????++=+=:~~=~=~~????IIIIIIIIIII?I?IIIIII+~~~:,,,,==~~........,:,:~+,,,,
???+=+==+???++~++~~~~~~==???IIIIIIIIIIIIIIIIIIIII+~~~::,,,=:=~:.......,:,:~=,...
++++~~==+++++?==~~~~~=~~=??IIIIIIIIIIIIIIIIIIIIII+=~~~::,,==~+=:......,:,::++,,,
++===:==++++++~+::~~==~~+?IIIIIIIIIIIIIIIIIIIIIII+=~~:::,,==~:=~,......,,:~~I:,:
++=~=~~=+?+=++~=::~~=~~~+???IIIII????IIIIIIIIIIII+=~::::::~==~:=~,......:~~~?::,
++==~=:~=+==+=~=:~~~~~~~+?????????????IIIIIIIIIII+~:~::~~:~=~::~~:.......,,~+~::
++===~~~====+=~~:~~~~~~~=????I???????IIIIIIIIIIII+~:::::::=~~::~~:,.......,,:?::
++==~~~:~~~~=~~~:~~~~~~~+???I???????IIIIIIIIIIIII+~:::,,::=~~:::~:,........~~~,:
++====~~~~~~=~::::~::~:~+??III???????IIIIIIIIIIII+~::::,::~~~:,:~:,,.......,~:,,
++=====~:~~:~~:~~~~:~~~~+??I?+++??????IIIIII+?III+~::::,,,:::,.~~~:::.......,~~,
=++====~~:~::::~~~~~~~~~+??I??+++~????IIII?+?IIII+~:::,,,,::,..:~~::::.......~:,
~+++++=~~::::::,:::::~:~??I?+++==~????III+++++?II=::::,,,,,,...:~~::::,......,I~
:=++++=~~:~:,,,,::::::::??III+==~++????I=+=+?+II?=:,::,,,,,,...:~:::~:,........:
:~++++==~~::,,,,:::::~:~?I?+?+=?==~++??I~=?+IIII+~:::,,,,,,,...,~:::::,,,......,
::++++==~~::,,.,:,,,~~:~?II??=====+++++++==+???++~:,,,,,,,,,...,~::::,,:........
:~=+++===~~::.,,,:,~:::~?II??+==+=+=++??++=+?III=~:,,,,,,,,,...,::,::,:,,:......
:~:+++===~:~:,..,,:::::~??I??=+=+~:=++++~+=++III=~,,,,,,..,,...:~:,::,:,:::.....
:~~=++=~=~~::,,.,,~::~::+?????+~~~:=??++~~=??+??=~,,,.....,,...:~,::::::::~,....
,:~~++==~=~~::,..,,,~==~=????+++~::~??~~~=+++???~~:.......,,..,~:,:,:::,:::~,...
,:~~++==~~=~:::,.,,,:~~~:++++++~~~=+??+==~~+++++~:,..........,,~,,:,:,,:::~~~...
,:~~:=+=~~=~::,,,....::::======~~~=++++=~~~:====::,..........,:,,,::::,~:::~~~,.
,,:~~:==:~=~~,::,......,::~~~~:~~~=+++++=~~,:~~~::...........,:,,,::::,::::~~~~:
,,:~~:~==~~=~::::,......:::~::::~=====++=~::::::::...........:,,,,:::,,~:~:~+=~=
,,,:~:~~==~~~~:,:,,.....,,::::::~======++=~::,,,,,..........,:,,,,:::,::~~~~~~~=
,,,::~~:~==~:~:,,,,.....,,,,,::~=======++++=:,,,,,..........,,,,,::::,:~~~~=====
,,:,:~:~:===~:~:,,,,.....,.,,:~~======++++++==~:,,.........,:,,,,,::,,~~~~~~~==+
,,,,:::~~~===:,:,,,,.....,.,:~~==+====++++++++=~:,.........,,,,,,,::,:~=~~:=~===
,,,,,:::~~~===:,:,,,,,...,,::~==+++==+++++++++==,,........,:,,,,,:::,:==~~~===++
,,,,,,::~~:~==~:,,,,,,....,:~~==+++++++++++++===,,........,,,,,,,::,,~==~=~====+

Thursday, April 21, 2011

What is the difference between TCP and UDP

Difference between TCP and UDPThere are two types of internet protocol (IP) traffic, and both have very different uses.
  1. TCP(Transmission Control Protocol). TCP is a connection-oriented protocol, a connection can be made from client to server, and from then on any data can be sent along that connection.
    • Reliable - when you send a message along a TCP socket, you know it will get there unless the connection fails completely. If it gets lost along the way, the server will re-request the lost part. This means complete integrity, things don't get corrupted.
    • Ordered - if you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order.
    • Heavyweight - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together.
  2. UDP(User Datagram Protocol). A simpler message-based connectionless protocol. With UDP you send messages(packets) across the network in chunks.
    • Unreliable - When you send a message, you don't know if it'll get there, it could get lost on the way.
    • Not ordered - If you send two messages out, you don't know what order they'll arrive in.
    • Lightweight - No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets.

IUnknown Interface


Enables clients to get pointers to other interfaces on a given object through the QueryInterface method, and manage the existence of the object through the AddRef and Release methods. All other COM interfaces are inherited, directly or indirectly, from IUnknown. Therefore, the three methods in IUnknown are the first entries in the VTable for every interface.
When To Implement

You must implement IUnknown as part of every interface. If you are using C++ multiple inheritance to implement multiple interfaces, the various interfaces can share one implementation of IUnknown. If you are using nested classes to implement multiple interfaces, you must implement IUnknown once for each interface you implement.
When To Use

Use IUnknown methods to switch between interfaces on an object, add references, and release objects.

Difference between Mutexes and Critical Sections

They are different synchronization mechanisms.  A mutex has thread affinity, a specific thread owns the mutex.  A critical section is "first-come-first-serve".  A critical section is not waitable like a mutex.  Calling WaitForSingleObject() for a mutex on the thread that owns it immediately succeeds.  If the mutex is owned by another thread, it won't return until the mutex is released.

Difference between Stack vs Heap memory

Stack
Stack memory stores variable types in address' in memory, these variables in programming are called local variables and are often stored for short amounts of time while a function/method block uses them to compute a task.
Once a function/method has completed its cycle the reference to the variable in the stack is removed.

Heap
Heap memory stores all instances or attributes, constructors and methods of a class/object.
Comparison
A Heap reference is also stored in Stack memory until the life cycle of the object has completed. Inside the Heap reference all the the contents of the object are stored whereas with a local variable only the variable contents are stored in the stack.
Example:
Stack
var blue
var red
ref 0x456783 (Heap reference)
var tom
ref 0x498702 (Heap reference)
var diane

Heap (0x456783)
name => Susan
age => 26
city => London
height => 5'7
sex => female

Heap (0x498702)
name => Paul
age => 21
city => Glasgow
height => 6'0
sex => male

Count the number of set bits in a byte/int32

int pop(unsigned x)
{
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0F0F0F0F;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x0000003F;
}
=======================================================
long count_bits(long n) {     
  unsigned int c; // c accumulates the total bits set in v
  for (c = 0; n; c++) 
    n &= n - 1; // clear the least significant bit set
  return c;
}=======================================================
unsigned int bitCount (unsigned int value) {
    unsigned int count = 0;
    while (value > 0) {           // until all bits are zero
        if ((value & 1) == 1) {   // check lower bit
            count++;
        }
        value /= 2;               // shift bits, removing lower bit
    }
    return count;
}
}
template<class T>
void priority_queue<T>::_dequeue(T& data)
{
 if(root==NULL) return;
 node* pre = root;     //remember the old position of the root node
 while(root->right != NULL) {
  pre = root;
  root = root->right;  //move the root node down the tree to the biggest value
 }//now i've got the biggest element and it's parent
  if(pre != root) {
   //if it doesn't have any childs
   if(root->left == NULL) {
    node* tmp = root;
    data = root->data;
    root = pre;
    root->right = NULL;
    delete tmp;
   } else {
    node* tmp = root;
    data = root->data;
    root = pre;
    root->right = tmp->left;
    delete tmp;
   }
   //if the previous node is the root
  } else {
   data = root->data;
   node* tmp = root;
   root = root->left;
   delete tmp;
  }
}

Arrays

You are given an array with integers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using little extra memory.
Algo:
  • Solution 1:
    1. Have a hash table
    2. Iterate through array and store its elements in hash table
    3. As soon as you find an element which is already in hash table, it is the dup element
      Pros:
      • It runs in O(n) time and with only 1 pass
      Cons:
      • It uses O(n) extra memory
  • Solution2:
    1. Sort the array using merge sort (O(nlogn) time)
    2. Parse again and if you see a element twice you got the dup.
      Pros:
      • it doesn't use extra memory
      Cons:
      • Running time is greater than O(n)

A simple Binary Search Tree written in C#

node search (node, key) {
       if node is null then return null;
       
       if node.key = key then
          return node
          
       if key < node then
          return search (node.left, key);
       else
          return search (node.right, key);
==============================================
// Create a new binary tree
bt = new TBinarySTree();

// Insert data
bt.insert ("Canis Minoris", 5.37);
bt.insert ("Gamma Cancri", 4.66);
bt.insert ("Phi Centauri", 3.83);
bt.insert ("Kappa Tauri", 4.21);
 
// Retrieve data  
TTreeNode symbol = bt.findSymbol ("Phi Centauri");
if (symbol != null)
   Console.WriteLine ("Star {1} has magnitude = {0}", symbol.name, symbol.value); 

Tuesday, April 19, 2011

string reversing algorithms

            charArray1 = textBox1.Text.ToCharArray();
            Array.Reverse(charArray1);
            label1.Text = new string(charArray1);

Pointer


To create linked list in C/C++ we must have a clear understanding about pointer. Now I will explain in brief what is pointer and how it works.
A pointer is a variable that contains the address of a variable. The question is why we need pointer? Or why it is so powerful? The answer is they have been part of the C/C++ language and so we have to use it. Using pointer we can pass argument to the functions. Generally we pass them by value as a copy. So we cannot change them. But if we pass argument using pointer, we can modify them. To understand about pointers, we must know how computer store variable and its value. Now, I will show it here in a very simple way.
Let us imagine that a computer memory is a long array and every array location has a distinct memory location.
Collapse
int a = 50 // initialize variable a 
image002.gif
Figure: Variable value store inside an array
It is like a house which has an address and this house has only one room. So the full address is-
Name of the house: a
Name of the person/value who live here is: 50
House Number: 4010
If we want to change the person/value of this house, the conventional way is, type this code line
Collapse
a = 100    // new initialization 
But using pointer we can directly go to the memory location of 'a' and change the person/value of this house without disturbing ‘a’. This is the main point about pointer.
Now the question is how we can use pointer. Type this code line:
Collapse
int *b;    // declare pointer b
We transfer the memory location of a to b.
Collapse
b = &a;    // the unary operator & gives the address of an object
image003.gif
Figure: Integer pointer b store the address of the integer variable a
Now, we can change the value of a without accessing a.
Collapse
*b = 100;  // change the value of 'a' using pointer ‘b’
  cout<<a;  // show the output of 'a'
When you order the computer to access to access *b, it reads the content inside b, which is actually the address of a then it will follow the address and comes to the house of a and read a`s content which is 50.
Now the question is, if it is possible to read and change the content of b without accessing b? The answer is affirmative. We can create a pointer of pointer.
Collapse
int **c;   //declare a pointer to a pointer
 c = &b;    //transfer the address of ‘b’ to ‘c’
So, we can change the value of a without disturbing variable a and pointer b.
Collapse
**c = 200;  // change the value of ‘a’ using pointer to a pointer ‘c’
  cout<<a;  // show the output of a

Thursday, April 14, 2011

linked list

From Wikipedia, the free encyclopedia
Jump to: navigation, search
In computer science, a linked list (or more clearly, "singly-linked list") is a data structure that consists of a sequence of nodes each of which contains a reference (i.e., a link) to the next node in the sequence.
Singly-linked-list.svg
A linked list whose nodes contain two fields: an integer value and a link to the next node
Linked lists are among the simplest and most common data structures. They can be used to implement several other common abstract data structures, including stacks, queues, associative arrays, and symbolic expressions, though it is not uncommon to implement the other data structures directly without using a list as the basis of implementation.
The principal benefit of a linked list over a conventional array is that the list elements can easily be added or removed without reallocation or reorganization of the entire structure because the data items need not be stored contiguously in memory or on disk. Linked lists allow insertion and removal of nodes at any point in the list, and can do so with a constant number of operations if the link previous to the link being added or removed is maintained during list traversal.
On the other hand, simple linked lists by themselves do not allow random access to the data other than the first node's data, or any form of efficient indexing. Thus, many basic operations — such as obtaining the last node of the list (assuming that the last node is not maintained as separate node reference in the list structure), or finding a node that contains a given datum, or locating the place where a new node should be inserted — may require scanning most or all of the list elements.

BidVertiser

pocket cents

PocketCents Local Online Advertising