Monday, March 10, 2014

Debug and trace in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics; // need this to use the Debug class

namespace DebugAndTrace
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a path to the My Documents folder and the file name
            string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                                Path.DirectorySeparatorChar + "examplefile.txt";

Garbage collection in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GarbageCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Allocated memory is: {0}", GC.GetTotalMemory(false));
            Console.WriteLine();
            Console.ReadLine();

Variable Param in c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VariableParams
{
    class Program
    {
        static void Main(string[] args)
        {
            int result;

            result = addNumbers(4, 6, 8);
            Console.WriteLine("result is {0}", result);

            result = addNumbers(12, 20, 31, 5, 7, 9);
            Console.WriteLine("result is {0}", result);

            Console.ReadLine();
        }

        static int addNumbers(params int[] nums)
        {
            int total = 0;

            foreach (int x in nums)
            {
                total += x;
            }

            return total;
        }
    }
}

Using Events iN C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace UsingEvents
{
    public delegate void myEventHandler(string newValue);

    class EventExample
    {
        private string theValue;
        public event myEventHandler valueChanged;

        public string Val
        {
            set
            {
                this.theValue = value;
                this.valueChanged(theValue);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EventExample myEvt = new EventExample();

            myEvt.valueChanged += new myEventHandler(myEvt_valueChanged);

            string str;
            do
            {
                str = Console.ReadLine();
                if (!str.Equals("exit"))
                    myEvt.Val = str;

            } while (!str.Equals("exit"));
        }

        static void myEvt_valueChanged(string newValue)
        {
            Console.WriteLine("The value changed to {0}", newValue);
        }
    }
}

Using Delegates in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace UsingDelegates
{
    public delegate int NumberFunction (int x);

    class Program
    {
        static void Main(string[] args)
        {
            NumberFunction f = Square;
            Console.WriteLine("result of the delegate is {0}", f(5));

            // now change the delgate
            f = Cube;
            Console.WriteLine("result of the delegate is {0}", f(5));

            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }

        static int Cube(int num)
        {
            return num * num * num;
        }
    }
}

Namespaces and Optional Params iN C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NamedOptionalParams
{
    class Program
    {
        static void Main(string[] args)
        {
            // call the Named parameters example
            myNamedParamExample(stateName: "Washington", zipCode: 98121, cityName: "Seattle");
            myNamedParamExample(cityName: "San Francisco", zipCode: 94109, stateName: "California");
            myNamedParamExample(zipCode: 94109, cityName: "New York", stateName: "New York");

            // call the Optional parameters example
            myOptionalParamFunc(15);
            myOptionalParamFunc(10, 2.71828d);
            myOptionalParamFunc(10, 2.71828d, "a different string");
            // myOptionalParamFunc(10, "a different string");

            // Now do both
            myOptionalParamFunc(10, param3: "named and optional in same call!");

            Console.ReadLine();
        }

        static void myOptionalParamFunc(int param1, double param2 = 3.14159d, string param3 = "placeholder string")
        {
            Console.WriteLine("Called with: \n\tparam1 {0}, \n\tparam2 {1}, \n\tparam3 {2}",param1, param2, param3);
        }

        static void myNamedParamExample(string cityName, string stateName, int zipCode)
        {
            Console.WriteLine("Arguments passed: \n\tcityName is {0}, \n\tstateName is {1}, \n\tzipCode is {2}",
                        cityName, stateName, zipCode);
        }
    }
}

Functions Param Modifiers in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FuncParamModifiers
{
    class Program
    {
        static void SquareAndRoot(double num, out double sq, out double sqrt)
        {
            sq = num * num;
            sqrt = Math.Sqrt(num);
        }

        static void Main(string[] args)
        {
            double n = 9.0;
            double theSquare, theRoot;

            SquareAndRoot(n, out theSquare, out theRoot);
            Console.WriteLine("The square of {0} is {1} and its square root is {2}", n, theSquare, theRoot);
           
            Console.ReadLine();
        }
    }
}

ReadingWritingData

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadingWritingData
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a path to the My Documents folder and the file name
            string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                                Path.DirectorySeparatorChar + "examplefile.txt";

            // if the file doesn't exist, create it by using WriteAllText
            if (!File.Exists(filePath))
            {
                string content = "This is a text file." + Environment.NewLine;
                Console.WriteLine("Creating the file...");
                File.WriteAllText(filePath, content);
            }

            // Use the AppendAllText method to add text to the content
            string addedText = "Text added to the file" + Environment.NewLine;
            Console.WriteLine("Adding content to the file...");
            File.AppendAllText(filePath, addedText);
            Console.WriteLine();

            // Read the contents of the file
            Console.WriteLine("The current contents of the file are:");
            Console.WriteLine("-------------------------------------");

            // Read the contents of the file using ReadAllText
            string currentContent = File.ReadAllText(filePath);
            Console.Write(currentContent);
            Console.WriteLine();

            // Read the contents of the file using ReadAllLines
            /*
            string[] contents = File.ReadAllLines(filePath);
            foreach (string s in contents)
            {
                Console.WriteLine(s);
            }
            Console.WriteLine();
            */

            Console.ReadLine();
        }
    }
}

PathOperations

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // need this for file and directory information

namespace PathOperations
{
    class Program
    {
        static void Main(string[] args)
        {
            // get the path to the documents folder from the Environment class
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            thePath += @"\testfile.txt";

            // Exercise the Path class methods
            Console.WriteLine("The directory name is {0}", Path.GetDirectoryName(thePath));
            Console.WriteLine("The file name is {0}", Path.GetFileName(thePath));
            Console.WriteLine("File name without extension is {0}", Path.GetFileNameWithoutExtension(thePath));
            Console.WriteLine("Random file name for path is {0}", Path.GetRandomFileName());
        }
    }
}

namespace ExistingDir

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // need this namespace to work with files and directories

namespace ExistingDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // Check to see if a directory exists
            bool dirExists = Directory.Exists(thePath);
            if (dirExists)
                Console.WriteLine("The directory exists.");
            else
                Console.WriteLine("The directory does not exist.");
            Console.WriteLine();

            // Write out the names of the files in the directory
            string[] files = Directory.GetFiles(thePath);
            foreach (string s in files)
            {
                Console.WriteLine("Found file: " + s);
            }
            Console.WriteLine();

            // Get information about each fixed disk drive
            Console.WriteLine("Drive Information:");
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                if (d.DriveType == DriveType.Fixed)
                {
                    Console.WriteLine("Drive Name: {0}", d.Name);
                    Console.WriteLine("Free Space: {0}", d.TotalFreeSpace);
                    Console.WriteLine("Drive Type: {0}", d.DriveType);
                    Console.WriteLine();
                }
            }

            Console.ReadLine();
        }
    }
}

namespace Existing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // we need to add this reference to use Files and Directory information

namespace Existing
{
    class Program
    {
        static void Main(string[] args)
        {
            bool fileExists = false;
            string thePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string theFile = thePath + @"\testfile.txt";

            fileExists = File.Exists(theFile);

            if (fileExists)
            {
                Console.WriteLine("The file exists");
            }
            else
            {
                Console.WriteLine("The file does not exist, creating it");
                File.Create(theFile);
            }

            if (fileExists)
            {
                Console.WriteLine("It was created on {0}", File.GetCreationTime(theFile));
                Console.WriteLine("It was last accessed on {0}", File.GetLastAccessTime(theFile));

                Console.WriteLine("Moving the file...");
                File.Move(theFile, thePath + @"\newfile.txt");
            }

            Console.ReadLine();
        }
    }
}