Friday 30 August 2013

Lambda Expressions

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

namespace ConsoleLambda
{
    class Program
    {
        public static double WArea(int a)
        {
            return 3.12 * a * a;
        }
        delegate double CalcArea(int r);
        static void Main(string[] args)
        {
            Console.WriteLine("Without Lambda");
            CalcArea Wca = new CalcArea(WArea);
            Console.WriteLine(Wca(10));

            Console.WriteLine("\n\nSimple Lambda");
            // Need to make new delegate. Lambda makes the code short and simple.
            CalcArea ca = r => 3.12 * r * r;
            Console.WriteLine(ca(10));

            Console.WriteLine("\n\nLambda + Func");
            /*No need to make new delegate. Func<> is the predefined generic function in delegate.
            function, takes the value and gives you new value on the based code behind.*/
            Func<double, double> MyFunc = r => 3.12 * r * r;
            Console.WriteLine(MyFunc.Invoke(10));
           
            Console.WriteLine("\n\nLambda + Action");
            /*No need to make new delegate. Action<> is the predefined generic function in delegate.
            Action, takes the value and shows the value on console.*/
            Action<string> MyAction = r => Console.WriteLine(r);
            MyAction.Invoke("Hello World!");
           
            Console.WriteLine("\n\nLambda + Predicate");
            Console.Write("Enter the string: ");
            string name = Console.ReadLine();
            //this line checking the word 'Entered String' is greater then 3 or not. and returs Boolean Value.
            Predicate<string> MyPredicate = z => z.Length > 3;
            Console.WriteLine(MyPredicate.Invoke(name)+"\n\n\n");
        }
    }
}






Lambda Source Code

Sunday 28 July 2013

enum (Enumeration)

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

namespace enum_sample
{
    class Program
    {
        public enum MeetingImportance
        { Trivial,Regular,Critical }
        static void Main(string[] args)
        {
            MeetingImportance meet = MeetingImportance.Critical;
            int value = (int)MeetingImportance.Critical;
            if (meet == MeetingImportance.Trivial)
            {
                Console.WriteLine("Trivial:{0}",value);
            }
            else if (meet == MeetingImportance.Regular)
            {
                Console.WriteLine("Regular:{0}",value);
            }
            else if (meet == MeetingImportance.Critical)
            {
                Console.WriteLine("Critical:{0}",value);
            }
        }
    }
}







Downlaod Enum Source Code


Wednesday 3 July 2013

Threading

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

namespace AbortExceptionSample
{
    class Abort_Exception
    {
        public static void ChildThreadcall()
        {
            try
            {
                Console.WriteLine("Child Thread Started");
                Console.WriteLine("Child thread - counting to 10");
                for (int i = 0; i <= 10; i++)
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("{0}...", i);
                }
                Console.WriteLine("Child Thread Finished");
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public static void Main(string[] args)
        {
            ThreadStart childRef = new ThreadStart(ChildThreadcall);
            Thread ChildThread = new Thread(childRef);
            ChildThread.Start();
            Console.WriteLine("Main -   Sleping for 2secs");
            Thread.Sleep(5000);
            Console.WriteLine("\nMain - Aborting Child Thread");
            ChildThread.Abort();
        }
    }
}







Download Thread Source Code

Monday 17 June 2013

Create and throw own exception

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

namespace Own_Exception
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Calculate c = new Calculate();
                c.calc();
            }
            catch (CountIsZeroException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
    public class CountIsZeroException : ApplicationException
    {
        public CountIsZeroException(string message) : base(message) { }
    }
    public class Calculate
    {
        public void calc()
        {
            Console.WriteLine("Enter the sum value");
            int sum = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the count value"); //Enter the Zero("0")
            int count = Convert.ToInt32(Console.ReadLine());
            float average;
            if (count == 0)
            {
                throw (new CountIsZeroException("Zero count in Calculate"));
            }
            else
            {
                average = sum / count;
            }
        }
    }
}


Click me for source code

Tuesday 28 May 2013

constructor overloading in c#

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

namespace Constructer_Overloading
{
class CalculateNumber
{
private int num1, num2, total;
public CalculateNumber()
{
num1 = num2 = total = 0;
}
public CalculateNumber(int numb1,int numb2)
{
num1 = numb1;
num2 = numb2;
total = 0;
}
public void AddNumber()
{
total = num1 + num2;
}
public void Display()
{
Console.WriteLine("The Sum of two number is {0}",total);
}
static void Main(string[] args)
{
CalculateNumber cn1 = new CalculateNumber(50,50);
CalculateNumber cn2 = new CalculateNumber(4,-3);
cn1.AddNumber();
cn1.Display();
cn2.AddNumber();
cn2.Display();
Console.ReadLine();
}
}
}





Sunday 28 April 2013

Guess The Number in 5 Attempts

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

namespace GuessNumber
{
    class GuessNumber
    {
        static void Main(string[] args)
        {
    Console.Clear();
            Console.WriteLine("Welcome to Guess a Word Program (0-100) with in 5 attempts.");
            System.Random r = new Random();
            int x = r.Next(100);
             bool bGuessedCorrectly = false;
                for (int i = 1; i <= 5; i++)
                {
                      Console.Write("ATTEMPT " + i + ": Enter the your number: ");
                      int n = Convert.ToInt32(Console.ReadLine());
                      if (n == x)
                      {
                            Console.WriteLine("Congrats! You have guessed the number correctly");
                            bGuessedCorrectly = true;
                            break;
                      }
                      int diff = (int)(Math.Abs(x - n));
                      bool bMoveHigher = false;
                      if(x > n)
                            bMoveHigher = true;
                      if(diff >= 50)
                      {
                            if (bMoveHigher == false)
                                  Console.WriteLine("Your guess is VERY HIGH");
                            else
                                  Console.WriteLine("Your guess is VERY LOW");
                      }
                      else if (diff >= 30)
                      {
                            if (bMoveHigher == false)
                                  Console.WriteLine("Your guess is HIGH");
                            else
                                  Console.WriteLine("Your guess is LOW");
                      }
                      else if (diff >= 15)
                      {
                            if (bMoveHigher == false)
                                  Console.WriteLine("Your guess is MODERATELY HIGH");
                            else
                                  Console.WriteLine("Your guess is MODERATELY LOW");
                      }
                      else
                      {
                            if (bMoveHigher == false)
                                  Console.WriteLine("Your guess is SOMEWHAT HIGH");
                            else
                                  Console.WriteLine("Your guess is SOMEWHAT LOW");
                      }
                }
                if (bGuessedCorrectly == false)
                {
                      Console.WriteLine("Unfortunately you did not guess it correctly. The correct number is: " + x);
                }
    Console.ReadLine();
        }
    }
}





Guess the Number

Monday 22 April 2013

Configuration File Maker

using System;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;

namespace yournamepace
{
    class Program
    {
        static void Main(string[] args)
        {
            // get config file from runtime args
            // or if none provided, request config
            // via console
            setConfigFileAtRuntime(args);

            // Rest of your console app
        }
   

    protected static void setConfigFileAtRuntime(string[] args)
    {
        string runtimeconfigfile;

        if (args.Length == 0)
        {
            Console.WriteLine("Please specify a config file:");
            Console.Write("> "); // prompt
            runtimeconfigfile = Console.ReadLine();
        }
        else
        {
            runtimeconfigfile = args[0];
        }

        // Specify config settings at runtime.
        System.Configuration.Configuration config
    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.File = runtimeconfigfile;
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");
    }
}
}
Click Me(Configruration_file_maker.cs)

convert number to words in c#

using System;
class Program
{
    static void Main()
    {
    Console.Clear();
        string input;
        int number;
        bool isValid;
        bool isUK = false;
        Console.WriteLine("\nEnter '0' to quit the program at any time\n");
        while (true)
        {
            Console.Write("\nUse UK numbering y/n : ");
            input = Console.ReadLine();
            if (!(input.ToLower() == "y" || input.ToLower() == "n"))
                Console.WriteLine("\n  Must be 'y' or 'n', please try again\n");
            else
            {
                if (input.ToLower() == "y") isUK = true;
                Console.WriteLine("\n");
                break;
            }
        }
        do
        {
            Console.Write("Enter integer : ");
            input = Console.ReadLine();
            isValid = int.TryParse(input, out number);
            if (!isValid)
                Console.WriteLine("\n  Not an integer, please try again\n");
            else
                Console.WriteLine("\n  {0}\n", NumberToText(number, isUK));
        }
        while (!(isValid && number == 0));
        Console.WriteLine("\nProgram ended");
    }
    public static string NumberToText(int number, bool isUK)
    {
        if (number == 0) return "Zero";
        string and = isUK ? "and " : ""; // deals with UK or US numbering
        if (number == -2147483648) return "Minus Two Billion One Hundred " + and +
        "Forty Seven Million Four Hundred " + and + "Eighty Three Thousand " +
        "Six Hundred " + and + "Forty Eight";
        int[] num = new int[4];
        int first = 0;
        int u, h, t;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (number < 0)
        {
            sb.Append("Minus ");
            number = -number;
        }
        string[] words0 = {"", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine "};
        string[] words1 = {"Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "};
        string[] words2 = {"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "};
        string[] words3 = { "Thousand ", "Million ", "Billion " };
        num[0] = number % 1000;           // units
        num[1] = number / 1000;
        num[2] = number / 1000000;
        num[1] = num[1] - 1000 * num[2];  // thousands
        num[3] = number / 1000000000;     // billions
        num[2] = num[2] - 1000 * num[3];  // millions
        for (int i = 3; i > 0; i--)
        {
            if (num[i] != 0)
            {
                first = i;
                break;
            }
        }
        for (int i = first; i >= 0; i--)
        {
            if (num[i] == 0) continue;
            u = num[i] % 10;              // ones
            t = num[i] / 10;
            h = num[i] / 100;             // hundreds
            t = t - 10 * h;               // tens
            if (h > 0) sb.Append(words0[h] + "Hundred ");
            if (u > 0 || t > 0)
            {
                if (h > 0 || i < first) sb.Append(and);
                if (t == 0)
                    sb.Append(words0[u]);
                else if (t == 1)
                    sb.Append(words1[u]);
                else
                    sb.Append(words2[t - 2] + words0[u]);
            }
            if (i != 0) sb.Append(words3[i - 1]);
        }
        return sb.ToString().TrimEnd();
Console.ReadLine();
}
}
Click Me(num_to_word.cs)

Sunday 17 March 2013

Print Simple "Hello World" In C# Language

using System;

class MyClass
{
      public static void Main()
      {
          Console.WriteLine("Hello World");
      }
}Click Me For Download Hello World Source Code