Sunday, September 21, 2014

How to use Enum, Properties and string compare

using System;
using System.Collections.Generic;

namespace Workshop
{
    public enum Grades
    {
        Fail,
        Pass,
        FirstClass,
        Distinction
    }
    //class variable or members
    public class Student
    {
        //Define simple properties
        public string Name { get; set; }
        public int TotalMarks { get; set; }
        public string Course { get; set; }
        //read only complex property
        public Grades PassingGrades
        {
            get
            {
                if (TotalMarks >= 80)
                    return Grades.Distinction;
                else if (TotalMarks >= 60)
                    return Grades.FirstClass;
                else if (TotalMarks >= 50)
                    return Grades.Pass;
                else
                    return Grades.Fail;
            }
        }
       
        //Definte complex properties
    }
    class Program
    {
        static void Main(string[] args)
        {
            //prepare few student objects
            Student st1 = new Student();
            st1.Name = "Adrian";
            st1.Course = "EWS";
            st1.TotalMarks = 80;
            Student st2 = new Student();
            st2.Name = "Ross";
            st2.Course = "AA";
            st2.TotalMarks = 60;
            //simple collection of Student objects
            List allStudents = new List();
            allStudents.Add(st1);
            allStudents.Add(st2);
            //now print grades of all EWS student
            foreach (var st in allStudents)
            {
                //string compare
                if (st.Course.Equals("EWS"))
                {
                    //this is how we use enum
                    Console.WriteLine(st.Name  + " " + st.PassingGrades);
                }
            }

            //now print AA studets
            //this is simple java like loop
            for (int i = 0; i < allStudents.Count; i++)
            {
                //string compare in differnt way
                if (allStudents[i].Course == "AA")
                {
                    //use enum to print
                    Console.WriteLine(allStudents[i].Name + " " + allStudents[i].PassingGrades);
                }
            }
            Console.Read();
        }
    }
}

Friday, January 31, 2014

C# Currency Converter using Google API

//A very simple currency converter using google API.
private decimal GoogleCurrencyConverter(string fromCurrency, string toCurrency)
    {
        WebClient web = new WebClient();

        string url = string.Format("https://www.google.com/finance/converter?a=1&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper());

        string response = web.DownloadString(url);

        Regex regex = new Regex("(\\d*.\\d*)");
        var r = regex.Match(response);

        return Convert.ToDecimal(r.Groups[1].Value);
    }