Tuesday, September 3, 2013

Simple SQL

public static DataTable GetAddressFromDB()
{
    string MyConString = "server=192.168.2.213;database=hotel;Username=root;Password=crawl;";
    MySqlConnection conn = new MySqlConnection(MyConString);

    MySqlCommand command = conn.CreateCommand();

    string dbQuery = String.Format(@"SELECT
                    suburb_city_id as SuburbCityId,
                    LOWER(TRIM(suburb_city_name)) as SuburbCityName,
                    LOWER(TRIM(main_country_state.state_name)) as StateName,
                    LOWER(TRIM(main_country.country_name)) as CountryName
                    FROM main_suburb_city
                    LEFT JOIN main_country_state
                      ON main_country_state.state_id = main_suburb_city.state_id
                    LEFT JOIN main_country
                      ON main_country.country_id = main_suburb_city.country_id
                    ORDER BY main_suburb_city.suburb_city_name;");

    MySqlCommand cmd = new MySqlCommand(dbQuery, conn);

    MySqlDataAdapter adapter = new MySqlDataAdapter();
    adapter.SelectCommand = cmd;

    DataTable dt = new DataTable();
    adapter.Fill(dt);

    conn.Close();

    return dt;
}

Two Types of LinQ Syntax

class LinQ
{
  int[] numbers = { 5, 10, 8, 3, 6, 12};


 
  //METHOD SYNTAX   
  IEnumerable<int> numQuery = numbers.Where(n => (n%2==0)).OrderBy(n==>n);  

 
  //QUERY SYNTAX   
  IEnumerable<int> numQuery = from n in numbers               
                  where n%2 == 0
                  order by n
                  select n;
}

WPF: Basic Thread

using System.Windows.Threading;
using System.Threading;

private void btnPlay01_Click(object sender, RoutedEventArgs e)
{
    ThreadStart start1 = new ThreadStart(Thread1);
    Thread t1 = new Thread(start1);
    t1.Start();
}

public void Thread1()
{
    int x = 0;
    do
    {
      x++;
      Thread.Sleep(100);
      Dispatcher.Invoke(DispatcherPriority.Send, new Action(delegate
      {
        lbl01.Content = String.Format("Thread 1 running: {0}", x);
      }));
    }while (x < 50);
}

Wednesday, July 31, 2013

C#: IComparer vs IComparable

In sorting a list of objects, I encountered these interfaces(IComparer and IComparable). These two interfaces define the logic for sorting.



using System.Collections.Generic;

class CompareByAge : IComparer<Employee>
{
    public int Compare(Employee a, Employee b)
    {
        if(a.Age > b.Age) return 1;
        else if(a.Age < b.Age) return -1;
        else return 0;
    }
}
Employees.Sort(new CompareByAge()); //sorts employees based on their age in ascending order


class Location : IComparable<Location>
{
    private
int population;
    private string country;
   
    public
int Population
    {
        get { return population; }
        set { population = value; }
    }
   
    public string Country
    {
        get { return country; }
        set { country = value; }
    }
   
    public Location()
    {
        population = 0;
        country = 0;
    }
   
    public
int CompareTo(Location other)
    {
        if(this.Population == other.Population) return this.Country.CompareTo(other.Country);
        else return other.Population.CompareTo(this.Population);
    }
}
Locations.Sort(); //sorts countries based on population in ascending order. for same population, they are sorted by their country names

Wednesday, July 24, 2013

C#: using Delegates

     Now I want to code in a not-so-noob way.  People have been talking about 'delegates' and I'm like, 'Hey, I don't wanna feel left out.'  For starters, I have to settle on this simple understanding that a delegate is used to reference a method.

     A simple example;

namespace Delegate
{
    public delegate int DelegateMethod(int x, int y);
   
    public static void Main()
    {
        DelegateMethod addMethod = new DelegateMethod(Calculator.Add);
        int resultAdd = addMethod(10, 15);
    }
   
    public class Calculator
    {
        public static int Add(int x, int y)
        {
            return x + y;
        }
    }
}

Tuesday, July 23, 2013

C# SQLParameters

Always use parameters. This allows one to safely inject the right data. 

public int AddUser(Logic.Employee details)
{
   
int lastId = 0;
    string MyConString = "server=localhost;database=crawler_attendance;Username=root;Password=crawl;";
    MySqlConnection conn = new MySqlConnection(MyConString);

    try
    {
   
string dbQuery = string.Empty;
    dbQuery = String.Format(@"INSERT INTO employeeTEST(username,firstname,lastname,company)
                  VALUES(@username,@firstname,@lastname,@company)");

    MySqlCommand cmd = new MySqlCommand(dbQuery, conn);
    cmd.Parameters.AddWithValue("@username", details.userName);
    cmd.Parameters.AddWithValue("@firstname", details.firstName);
    cmd.Parameters.AddWithValue("@lastname", details.lastName);
    cmd.Parameters.AddWithValue("@company", details.company);
    conn.Open();
    cmd.ExecuteNonQuery();

    cmd.Parameters.Add(new MySqlParameter("lastId", cmd.LastInsertedId));
    lastId = Convert.ToInt32(cmd.Parameters["@lastId"].Value);
    }
    catch (Exception e)
    {
    conn.Close();
    }
    finally
    {
    conn.Close();
    }

    return lastId;
}

Thursday, July 4, 2013

C#: Search for a specific object


 To get the object by its Id;

 


Data.Employee emp = BusinessLogic.AttendanceApp.Employees.ToList<Data.Employee>().Find(e => e.IdNumber.Equals(IdNumber));