Monodevelop – system.xml error

I use monodevelop to create my c# applications etc and just noticed that if you want to have more references to assemblies like System.Xml then you will have to add them via the GUI.

For example, if you get the error.

Description=The type or namespace name `Xml' does not exist in the namespace `System'. Are you missing an assembly reference?(CS0234)

then you will need to add the System.Xml assembly reference into the GUI solutions manager to compile in that assembly.

If you goto Solutions box -> References -> (Right click) Edit References. In the packages tab scroll down in the list and find the System.Xml and add it to the solution. Compile again and it will work :).. well you may get other errors but at least this one is sorted.

If you do not have the Solutions box, goto the main monodevelop menu View -> Solution.

Wordsearch – c# Grid class

When coding in c#/csharp, I use monodevelop. Here is the wordsearch base Grid class in c#, I am coding in different languages just for fun as such, but here is the main idea for the wordsearch. I have already done a basic version in php which is at the present state in creating a grid (but without any intersection of words with others). But here is the Grid class in php, and below is the similar setup in csharp.

The main class, is where the application executes from, it is very similar to c++ in that there is a main function

public static void Main(string[] args)

which takes the string[] args as a parameter, which is what is passed in on the command line.

Anyway, here is the code.. I have added in some comments to what the code is doing.

using System;
 
namespace wordsearchcsharp
{
	class Grid {
		protected int _size = 0;
		protected char[][] _grid;
 
		// the ": this(11)" means call the Grid(int size) constructor with 11 as a parameter
		public Grid() : this(11)
		{
			// default size of a grid = 11
		}
 
		public Grid(int size)
		{
			this._size = size;
			// create a new row (Y direction)
			this._grid = new char[this._size][];
			for (int i =0; i < this._size; i++)
			{
				// create new X direction row.
				this._grid[i] = createGridRow();
			}
		}
 
		// createGridRow, this can be inherited and thus altered to create any type of character in the grid 
		public virtual char[] createGridRow()
		{
			// need to insert a good seed into the random generator.. else same characters
			Random random = new Random((int)DateTime.Now.Ticks);
 
			// create a new row (X direction) and place characters into it.
			char[] grid_insert = new char[this._size];
			for (int i = 0; i < this._size; i++)
			{
				// 0 - 25 = alphabet, and also +97 is the ascii start for the character 'a'
				grid_insert[i] = (char)(random.Next(0,25)+97);
			}
			return grid_insert;
		}
 
		// printOutGrid, will print out the grid created above.
		// i = Y direction, and j = X direction.
		public void printOutGrid()
		{
			Console.WriteLine("The Grid");
			for (int i = 0; i < this._size; i++)
			{
				Console.Write(i + " ..");
				for (int j = 0; j < this._size; j++)
				{
					Console.Write(j + " = " + this._grid[i][j]);
				}
				Console.WriteLine("");
			}
		}
 
		public int returnSize()
		{
			return this._size;
		}
 
		// insert a character into the grid at position X, Y and the character 
		public void insertCharIntoGrid(int pX, int pY, char character)
		{
			this._grid[pY][pX] = character;
		}
 
		//  return the grid reference 
		public char[][] returnGrid()
		{
			return this._grid;
		}
 
	}
 
	class MainClass
	{
		public static void Main(string[] args)
		{
			Grid grid = new Grid();
			grid.printOutGrid();
		}
	}
}

And here is the output.

The Grid
0 ..0 = m1 = y2 = p3 = d4 = d5 = y6 = g7 = p8 = m9 = i10 = t
1 ..0 = k1 = c2 = y3 = n4 = i5 = m6 = q7 = f8 = g9 = p10 = j
2 ..0 = o1 = r2 = v3 = q4 = a5 = i6 = y7 = h8 = k9 = y10 = c
3 ..0 = h1 = u2 = f3 = s4 = v5 = r6 = p7 = g8 = h9 = j10 = b
4 ..0 = n1 = j2 = y3 = u4 = v5 = q6 = n7 = b8 = y9 = w10 = g
5 ..0 = g1 = m2 = i3 = x4 = r5 = a6 = e7 = a8 = w9 = i10 = f
6 ..0 = m1 = c2 = c3 = a4 = r5 = y6 = c7 = v8 = o9 = u10 = k
7 ..0 = f1 = e2 = k3 = c4 = n5 = j6 = s7 = t8 = m9 = g10 = j
8 ..0 = l1 = t2 = f3 = e4 = n5 = i6 = q7 = p8 = e9 = t10 = p
9 ..0 = e1 = w2 = n3 = h4 = j5 = r6 = h7 = o8 = b9 = e10 = o
10 ..0 = y1 = x2 = u3 = j4 = n5 = g6 = n7 = h8 = m9 = t10 = a

I use linux and thus mono is my csharp virtual machine setup, but here is a output of the file command in linux which tells me that the wordsearchcsharp.exe if a mono assembly and thus if you ./wordsearchcsharp.exe will goto the mono virtual machine.. it will link/expand to mono wordsearchcsharp.exe on the command line.

file wordsearchcsharp.exe
wordsearchcsharp.exe: PE32 executable for MS Windows (console) Intel 80386 32-bit Mono/.Net assembly

C++ DLL Objects accessed from C#

Because there is a few things that c# cannot do compared to c++, e.g. cpu/memory management. And also there is probably allot of dll’s out there are still required for some events, c# is able to communicate with these files and use there functions within the c# language.

To create an dll within Visual Studio 2005 within the language c++, if you do the following

1. New project -> c++ -> empty project
2. Enter project name (e.g. hellocdll)
3. Right click source files ( in the solution explorer) add-> new item
enter an cpp filename.
4, Right click on the main project heading in the solution explorer -> properties
configuration properties->general inner screen project defaults -> configuration type, alter to dynamic library (.dll)
5. Copy and paste code and then compile.

#include <stdio.h>
 
extern "C"
{
  __declspec(dllexport) void DisplayMessageFromDLL()
  {
              printf ("Hi From the C DLL!\n");
  }
 
  __declspec(dllexport) int DisplayValueAndReturn(int i)
  {
         printf("Value %i\n", i);
         return i+2;
  }
}

The extern “C” means that the references within the code are going to be available externally and marco __declsepc(dllexport) is for the MS compile to inform that functions are to be available within an dll file.

To create an c# project to communicate with the above dll

1. New project -> c# -> empty project
2. Enter project name (e.g. hellodlltest)
3. Right click on the project name ( in the solution explorer) add-> new item
select class and enter a filename
4. Copy and paste the code and then compile. (you may need to change the Dllimport to the dll file name that has been created from the c dll project)

using System;
using System.Runtime.InteropServices;     // DLL support
 
namespace hellodlltest
{
    class hellodllC
    {
        [DllImport("hellocdll.dll")]
        public static extern void DisplayMessageFromDLL();
 
        [DllImport("hellocdll.dll")]
        public static extern int DisplayValueAndReturn(int i);
 
        static void Main ()
           {
                  Console.WriteLine ("C# program 'talking' to an C DLL");
            DisplayMessageFromDLL();
            Console.WriteLine(DisplayValueAndReturn(3).ToString());
           Console.ReadLine()
           }
    }
}

5. Copy the dll file from the debug directory of the c++ created dll project and place into the created bin/debug directory for this c# project

Operator

The standard class function are not able to utilize the standard operators within the c# language, for example the multiple, add, subtraction and divide in a mathematics example.

To overcome this problem, there is a ‘operator’ special syntax that allows for this to take place. The operator can work with any of the c# language standard functions of which you are able to program there functional aspects within the class. The syntax for this is

public static <return type> operator <operator type>(<parameter list of passed variables>);

for example if there was an return type of int and two integer values passed in the parameter list and using the addition operator.

public static int operator +(int a, int b)

Below is some code that will demonstrate this further within a general code development.

using System;
 
class operatorBase
{
       private int i;       // private member of the class
 
       public operatorBase() 
       {
              i = 0;       
       }
 
       public operatorBase(int init)  
       {
              this.i = init; 
       }
 
       // get and set the value for the private member i
       public int Value
       {
              get { return i;}
              set { i = value;}
       }
 
       // the operator +, parameters are the two values that you want to add, can be overloaded with different values
       // e.g. (int i2, int i3) for example.
       public static operatorBase operator +(operatorBase i2, operatorBase i3)
       {
              // create the return;
              operatorBase locali= new operatorBase();
              locali.i = i2.i + i3.i;  have access to the internals of passed parameters
              return  locali;       // return the operatorBase class
       }
}
 
class operatorTest
{
 
       public static void Main()
       {
              operatorBase opBase = new operatorBase();
 
              // set the value to 3 and also output the value;
              opBase.Value = 3;
              Console.WriteLine(opBase.Value);
 
              operatorBase opBase2 = new operatorBase(4);
 
              // to add to the operatorbases together, but will return an operatorBase, thus bracket the equation and use the .Value to get the value. 
              Console.WriteLine((opBase + opBase2).Value);
 
              // since creating two new on the fly operatorBase, then the result is an int value again.
              Console.WriteLine((new operatorBase().Value = 3) + (new operatorBase().Value = 2));
       }
}

Yielding results

Yield is a new syntax word within the .net 2 language. This allows for the IEnumerable interface to have direct interaction instead of using the IEnumerator interface to iterate though a result set. For easier demonstration, I think, the code examples, the first code is a .net 1 version of the interface IEnumerable.

using System;
using System.Collections;
 
// the inital class is IEnumerable- means that it has to implement the GetEnumerator
public class Class : IEnumerable 
{
       // internal class to implement the IEnumerator interface, which inturn has to do the MoveNext, Current, Reset methods.
       private class ClassEnumerator : IEnumerator
       {
              // internal values to go through the array
              private int index = -1;
              private Class P;
              // setup the internal variable
              public ClassEnumerator(Class P) 
              {
                     this.P = P; 
              }
              // move within the array, if any values are present.
              public bool MoveNext()
              {
                     index++;
                     return index < P._Names.Length;
              }
              // set the internal to -1, thus restart
              public void Reset() 
              { 
                     index = -1;
              }
 
              // get the Current object
              public object Current 
              { 
                     get 
                     { 
                            return P._Names[index]; 
                     } 
              }
       }
 
       // return a IEnumerator object of the above with itself passed
       public IEnumerator GetEnumerator()
       {
              return new ClassEnumerator(this);
       }
 
       // the internal string array of names
       private string[] _Names;
       // the new class setup process, 
       public Class(params string[] Names)
       {
              _Names = new string[Names.Length];
              // copy the passed parameter starting at position 0
              Names.CopyTo(_Names,0);
       }
}
 
class ClassProgram
{
       static void Main(string[] args)
       {
              Class ClassArr = new Class("Student1", "Student2","Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

This is able to output a string of

Student1
Student2
Studentx

Since the Class class (it is a class of students), there is allot of code to iterate with the foreach function.

Within .net 2 there is a nice and more tighter method called yield, an yield will yield a result and be able to iterate though a result set with the IEnumerable return set. Again, here is the source code.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       static void Main(string[] args)
       {
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

Far less code and also the result is exactly the same.

Also there are other benefits of the yield attached to an IEnumerable interface, here is some more code to demonstrate how to implement a power function to display the power result being built up. This demonstrates how to use just a single method to return an iterate-able result.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       // IEnumerable linked to yield is new in .net 2, it allows for the 
       // iteration of this method, acting like array instead of a single return.
       public static IEnumerable Power(int number, int exp)
       {
              int counter = 0, result = 1;       // setup the default values.
              while (counter++ < exp)              // increament counter and whilst lower than the passed parameter exp
              {
                     result *= number;       // result = result * number;
                     yield return result;       // yield the result and return
              }
       }
 
       // can also just iterate though a array of strings (in this example)
       public static IEnumerable StReturn(params string[] names)
       {
              int counter = -1;
              while (counter++ < (names.Length-1))
                     yield return names[counter];
       }
 
       static void Main(string[] args)
       {
              // can do a return of a power function as well
              foreach(int e in Power(4,3))
                     Console.WriteLine(e.ToString());
 
              // you can just iterate a string 
              string[] st = {"student1","student2","studentx"};
              foreach(string s in StReturn(st))
                     Console.WriteLine(s.ToString());
 
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

I have also include the code from above to demonstrate the similar usage for iterate though a string array.

Output would be

4
16
64
student1
student2
studentx
Student1
Student2
Studentx

You will need to have .net 2 installed or mono (use the gmcs part of mono to use the .net 2 functions.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

using System;
 
// create a class with a generic type of T (e.g. pass in the type of your choice
public class GenTest<T>;
{
       // the private value
       private T genericValue;
 
       // default constructor for the class (same name as the class)
       // ~ is the deconstructor
       public GenTest(T generic) 
       {
              genericValue = generic;       // set the internal T = passed value
       }
 
       // return the value of the internal value
       public T ReturnValue()
       {
              return genericValue;
       }
}
 
public class MainProgram
{
       static void Main()
       {
              // create a integer type class, with the default value of 2
              GenTest<int> genInt = new GenTest<int>(2);
              Console.WriteLine("Int generic = " + genInt.ReturnValue());
 
              // same class create a string with the default value of "cool"
              GenTest<string> genString = new GenTest<string>("cool");
              Console.WriteLine("String generic = " + genString.ReturnValue());
       }
}

If you save the code and run with .net 2 or greater (.NET Framework) ( since this was part of .net 2 and not with .net 1). The output will be

Int generic = 2
String generic = cool

As you can see the same class is able to use both integer and strings as the default variable type.

Collections – ArrayList

Collections – ArrayList, the ArrayList is part of the Collections namespace. The ArrayList acts as the same as the array (Array Example) apart from it allows other functional aspects to access the list of array.

Shall comment more on the different aspects in later tutorials, but basically there many different parts to a class that allow for better functionality e.g
1. Interfaces = base of a class for strict implementation)
2. IEnumerable (which is a interface) = means that you implement GetEnumerator aspects of a class, e.g. for the foreach command)
3. Generics (which is part of .net 2) = Similar to templates (Generics) in c++ and also generics from Java).
4. Etc. shall comment more on these.

This is the code

using System;
 
namespace ArrayListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add("hi there");
 
            foreach (object obj in arrayList)
                Console.WriteLine(obj.ToString());
        }
    }
}

If you save as arraylisttest.cs, and then run, the output will be

2
3
hi there

It basically allows you to add in any object into the ArrayList, and since objects have the ToString() function, then it is able to print out the object, of course custom made objects will either display there type or the ToString() will have to be implemented.