Thursday, September 5, 2013

C#: SEMAPHORE - Run a number of threads at a time

 Here we have 10 scripts and we want to run 3 scripts only at at time.

public partial class Semaphore
{
 static SemaphoreSlim _sem = new SemaphoreSlim(3);
 string scriptMonitoring = string.Empty;

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
    for (int i = 1; i <= 10; i++)
    {
     new Thread(Enter).Start(i);
    }
 }

 void Enter(object id)
 {
  scriptMonitoring += String.Format("\nScript {0} wants to crawl.", id);
  _sem.Wait();
  scriptMonitoring += String.Format("\nScript {0} is now crawling.", id);
  Thread.Sleep(1000 * (int) id);
  scriptMonitoring += String.Format("\nScript {0} has stopped crawling.", id);
  _sem.Release();
 }
}

-----
Script 1 wants to crawl.
Script 1 is now crawling.
Script 2 wants to crawl.
Script 2 is now crawling.
Script 3 wants to crawl.
Script 3 is now crawling.
Script 4 wants to crawl.
Script 5 wants to crawl.
Script 6 wants to crawl.
Script 7 wants to crawl.
Script 9 wants to crawl.
Script 8 wants to crawl.
Script 10 wants to crawl.
Script 1 has stopped crawling.
Script 4 is now crawling.
Script 2 has stopped crawling.
Script 5 is now crawling.
Script 3 has stopped crawling.
Script 6 is now crawling.
Script 4 has stopped crawling.
Script 7 is now crawling.
Script 5 has stopped crawling.
Script 9 is now crawling.
Script 6 has stopped crawling.
Script 8 is now crawling.
Script 7 has stopped crawling.
Script 10 is now crawling.
Script 8 has stopped crawling.
Script 10 has stopped crawling.
Script 9 has stopped crawling.

Tuesday, September 3, 2013

Thread Locking

When sharing data between threads using static fields, chances are that the unique fields will be accessed/evaluated twice. Using an exclusive lock fixes this.

    class Program
    {
        static bool done;
        static readonly object locker = new object();

        static void Main(string[] args)
        {
            new Thread(Go).Start();
            Go();
        }

        static void Go()
        {
            lock (locker)
            {
                if (!done)
                {
                    Console.WriteLine("Completed."); //this must be accessed once
                    done = true;
                }
            }
            Console.ReadKey();
        }
    }

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));

Basic Student Enrollment Program

This program can;
1. add a student
2. edit a student
3. delete a student
4. display all students
Coding style is still a mess but I might need some codes here for future use.

[index.php]

<HTML><TITLE>STUDENT RECORD</TITLE>
<BODY>
<DIV ALIGN='center'>
    <H3>Login Page</H3>
    <FORM METHOD='POST' ACTION='validate.php'>
    <TABLE>
        <TR>
            <TD>Id Number:</TD>
            <TD><input type="text" name="IdNumber" size='2'></TD>
        </TR>
        <TR>
            <TD>Password:</TD>
            <TD><input type="password" name="Password"></TD>
        </TR>
    </TABLE>   
    <input type="submit" value="Sign In">
    </FORM>
</DIV>
</BODY>
</HTML>


[config.php]
<?php
    $db_user = "root"// mysql username to access the database with.
    $db_pass = "crawl"// mysql password to access the database with.
    $server = "localhost"// server to connect to.
   
    $database = "crawler_attendance"// the name of the database.
    $table = "students";    // the table that this script will set up and use.

    $link = mysql_connect($server, $db_user, $db_pass);
    mysql_select_db($database,$link);
?>


[validate.php]
<?php
    session_start();
   
    include("config.php"); //including config.php in our file
    $id_num = $_POST["IdNumber"]; //Storing username in $username variable.
    $password = $_POST["Password"]; //Storing password in $password variable.
   
    $query = "select id, firstname, lastname, rank from $table where id = '".$_POST['IdNumber']."'
          and password = '".$_POST['Password']."';";
   
    $execqry = mysql_query($query);
    $getValue = mysql_fetch_array($execqry); //place query result in an array?

    $num_rows = mysql_num_rows($execqry);

    if ($num_rows <= 0) {
        include("index.php");
        echo "Sorry, incorrect credentials entered.";
        echo "Try again";
        exit;
    } else {
        $id_firstname;
        $firstname = $getValue['firstname'];
        $rank = $getValue['rank'];
            $_SESSION['firstname']= $id_firstname;
        if($rank == 'administrator')
        {
            header("Location: addAccount.php");
            header("Location: editAccount.php");
            header("Location: deleteAccount.php");
            header("Location: showAll.php");
            header("Location: accountpage.php");
        }
        else
        {
            header("Location: studentpage.php");
        }
    }

?>

[studentpage.php]

<?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='right'><a href="index.php">logout</a></DIV>
    <DIV ALIGN='center'>
    <?php
        echo "Welcome $firstname.";
    ?>
    <H3>Always WEAR your school id properly.</H3>
    <p>Study hard.<p>
    </DIV>

</BODY>
</HTML>

[accountpage.php]

<?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='center'>
    <?php
        echo "Welcome $firstname.";
    ?>
        
    <TABLE>
    <TR>
        <td><a href="addAccount.php">Add an account</a></td>
        <td><a href="editAccount.php">Edit an account</a></td>
        <td><a href="deleteAccount.php">Delete an account</a></td>
        <td><a href="showAll.php">Show all accounts</a></td>
        <td><DIV ALIGN='right'><a href="index.php">logout</a></DIV><td>
    </TR>
    <H3>STUDENT RECORD</H3>
    </DIV>
    </TABLE>
</BODY>
</HTML>


[addAccount.php]

<?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='center'>
    <?php echo "Welcome $firstname."; ?>
   
    <TABLE>
    <TR>
        <td><B>Add an account</B></td>
        <td><a href="editAccount.php">Edit an account</a></td>
        <td><a href="deleteAccount.php">Delete an account</a></td>
        <td><a href="showAll.php">Show all accounts</a></td>
        <td><DIV ALIGN='right'><a href="index.php">logout</a></DIV><td>
    </TR>
    <H3>STUDENT RECORD</H3>
    </DIV>
    </TABLE>
   
    <FORM METHOD='POST' ACTION='addAccount_backend.php'>
   
    <H1>REGISTRATION FORM</H1>
    <TABLE>
        <TR>
            <TD>Firstname:</TD>
            <TD><input type="text" name="Firstname"></TD>
        </TR>
        <TR>
            <TD>Lastname:</TD>
            <TD><input type="text" name="Lastname"></TD>
        </TR>
       
        <TR>
            <TD>Position:</TD>
            <TD>
                <select name="Position">
                  <option value="user">User</option>
                  <option value="supervisor">Supervisor</option>
                </select>
            </TD>
        </TR>
       
        <TR>
            <TD>Password:</TD>
            <TD><input type="password" name="Password"></TD>
        </TR>
       
        <TR>
            <TD></TD>
            <TD><DIV ALIGN='right'><input type="submit" value="Save"></DIV></TD>
        </TR>
    </TABLE>   
    </FORM>
</BODY>
</HTML>

[addAccount_backend.php]
 <?php
    session_start();
    include("config.php");

    $Firstname = $_POST["Firstname"];
    $Lastname = $_POST["Lastname"];
    $Position = $_POST["Position"];
    $Password = $_POST["Password"];

$query = "INSERT INTO students(password, firstname, lastname, rank)
        VALUES    ('$Password', '$Firstname', '$Lastname', '$Position')";

$execqry = mysql_query($query);
include("accountpage.php");
echo "Account successfully added.";
?>

[editAccount.php]
 
<?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='center'>
    <?php echo "Welcome $firstname."; ?>
   
    <TABLE>
    <TR>
        <td><a href="addAccount.php">Add an account</a></td>
        <td><B>Edit an account</B></td>
        <td><a href="deleteAccount.php">Delete an account</a></td>
        <td><a href="showAll.php">Show all accounts</a></td>
        <td><DIV ALIGN='right'><a href="index.php">logout</a></DIV><td>
    </TR>
    <H3>STUDENT RECORD</H3>
    </DIV>
    </TABLE>
    <FORM METHOD='POST' ACTION='editAccount_backend01.php'>
        <H1>UPDATE A STUDENT INFO</H1>
        <TABLE>
            <TR>
            <TD>Enter ID:</TD>
            <TD><input type="text" name="Id" size='1'><input type="submit" value="Show"></TD>
            </TR>
        </TABLE>
    </FORM>
</BODY>
</HTML>

[editAccount_backend01.php]
<?php
session_start();
include("config.php");

$Id = $_POST["Id"];

$query = "SELECT `id`, `firstname`, `lastname`, `rank`
      FROM `students`
      WHERE `rank` != 'administrator'
      AND `is_active` = 1
      AND `id` = $Id";

$Firstname = '';
$Lastname = '';
$Rank = '';
    
$execqry = mysql_query($query);
include("editAccount.php");
echo "<table border='1'>
       <tr>
       <th>Id</th>
       <th>Firstname</th>
       <th>Lastname</th>
       <th>Rank</th>
      </tr>";
    while($row = mysql_fetch_array($execqry))
    {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['firstname'] . "</td>";
        echo "<td>" . $row['lastname'] . "</td>";
        echo "<td>" . $row['rank'] . "</td>";
        echo "</tr>";
        $Firstname = $row['firstname'];
        $Lastname = $row['lastname'];
        $Rank = $row['rank'];
    }
echo "</table>";
?>
<HTML>
    <FORM METHOD='POST' NAME ="form2" ACTION='editAccount_backend02.php'>
    <TABLE>
        <INPUT type="hidden" name="Id" value="<?php echo "$Id"?>">
        <TR>
            <TD>Firstname:</TD>
            <TD><INPUT TYPE = "TEXT" NAME="Firstname" VALUE ="<?php echo "$Firstname"?>"></TD>
        </TR>
      
        <TR>
            <TD>Lastname:</TD>
            <TD><INPUT TYPE= "TEXT" NAME="Lastname" VALUE="<?php echo "$Lastname"?>"></TD>
        </TR>
      
        <TR>
            <TD>Position:</TD>
            <TD><SELECT name="Position">
                  <option value="user">User</option>
                  <option value="supervisor">Supervisor</option>
            </SELECT></TD>
        </TR>
        <TR>
            <TD><DIV ALIGN='right'><input type="submit" value="Update"></DIV></TD>
        </TR>
    </TABLE>  
    </FORM>
</HTML>

[editAccount_backend02.php] 
<?php
    session_start();
    include("config.php");

    $Firstname = $_POST["Firstname"];
    $Lastname = $_POST["Lastname"];
    $Position = $_POST["Position"];
    $Password = $_POST["Password"];
    $Id = $_POST["Id"];

$query = "UPDATE `students`
      SET `firstname`= '$Firstname',
          `lastname` = '$Lastname',
          `rank` = '$Position'
      WHERE `id` = '$Id'";

$execqry = mysql_query($query);
include("accountpage.php");
echo "Account successfully updated.";
?>

[deleteAccount.php]

 <?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='center'>
    <?php echo "Welcome $firstname."; ?>
  
    <TABLE>
    <TR>
        <td><a href="addAccount.php">Add an account</a></td>
        <td><a href="editAccount.php">Edit an account</a></td>
        <td><B>Delete an account</B></td>
        <td><a href="showAll.php">Show all accounts</a></td>
        <td><DIV ALIGN='right'><a href="index.php">logout</a></DIV><td>
    </TR>
    <H3>STUDENT RECORD</H3>
    </DIV>
    </TABLE>
    <FORM METHOD='POST' ACTION='deleteAccount_backend.php'>
        <H1>REMOVE A STUDENT INFO</H1>
        <TABLE>
            <TR>
            <TD>Enter ID:</TD>
            <TD><input type="text" name="Id" size='1'><input type="submit" value="Delete"></TD>
            </TR>
        </TABLE>
    </FORM>
</BODY>
</HTML>

[deleteAccount_backend.php]
<?php
    session_start();
    include("config.php");

    $Id = $_POST["Id"];

$query = "UPDATE `students`
      SET `is_active` = '0'
      WHERE    `id` = '$Id'";

$execqry = mysql_query($query);
include("accountpage.php");
echo "Account successfully deleted.";
?>


[showAll.php]

<?php
    session_start();
    $firstname = $_SESSION['firstname'];
?>
<HTML>
<BODY>
    <DIV ALIGN='center'>
    <?php echo "Welcome $firstname."; ?>
   
    <TABLE>
    <TR>
        <td><a href="addAccount.php">Add an account</a></td>
        <td><a href="editAccount.php">Edit an account</a></td>
        <td><a href="deleteAccount.php">Delete an account</a></td>
        <td><B>Show all accounts</B></td>
        <td><DIV ALIGN='right'><a href="index.php">logout</a></DIV><td>
    </TR>
    <H3>STUDENT RECORD</H3>
    </DIV>
    </TABLE>
    <H1>LIST OF ALL REGISTERED STUDENTS</H1>

</BODY>
</HTML>
<?php
    include("showAll_backend.php");
?>


[showAll_backend.php]
<?php
session_start();
include("config.php");

$query = "SELECT `id` , `firstname` , `lastname` , `rank`
      FROM `students`
      WHERE `rank` != 'administrator'
      AND `is_active` = 1
      ORDER BY `id` ASC";

$execqry = mysql_query($query);


echo "<table border='1'>
       <tr>
       <th>Id</th>
       <th>Firstname</th>
       <th>Lastname</th>
       <th>Rank</th>
      </tr>";
    while($row = mysql_fetch_array($execqry))
    {
        echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['firstname'] . "</td>";
        echo "<td>" . $row['lastname'] . "</td>";
        echo "<td>" . $row['rank'] . "</td>";
        echo "</tr>";
    }
echo "</table>";
?>