Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, 23 December 2009

Symbolic constants vs Enumerated Types'

These constants are handy when cheking on the setter (as can use an int range)

    public const int APARTMENT = 1;
    public const int COMMERCIAL = 2;
    public const int HOME = 3;
 
    public int BuildingType
    {
        get { return buildingType; }
        set
        {
            if (value >= APARTMENT && value <= HOME)
                buildingType = value;
        }
    }
This keyword
public clsBuilding()
    {
        address = "Not closed yet";
    }
 
    public clsBuilding(string addr, decimal price, decimal payment, decimal tax, decimal insur, DateTime date, int type)
        : this() // good practise to call initial constructor first..second constructor will overwrite address = "Not closed yet"
    {
        if (addr.Equals("") == false)
            address = addr;
        purchasePrice = price;
        monthlyPayment = payment;
        taxes = tax;
        insurance = insur;
        datePurchased = date;
        buildingType = type;
    }
Base keyword
    public clsCommercial(string addr, decimal price, decimal payment,
                        decimal tax, decimal insur, DateTime date, int type) :
                        base(addr, price, payment, tax, insur, date, type)
    {
        buildingType = type;   // Commercial type from base
    }

this is calling the bases’ constructor.

can also call base methods from the derived (child) class.

Polymorphism

essentially this means we can send the same message to a group of different classes and each class will know how to respond correctly. eg

image

        lstMessages.Items.Add(myApt.RemoveSnow());
        lstMessages.Items.Add(myComm.RemoveSnow());
        lstMessages.Items.Add(myHome.RemoveSnow());

clsApt and clsComm have overridden methods and respond with different phone numbers.  clsHome doesn’t have a RemoveSnow method and responds as above.

Abstract Classes

To prevent instantiation of the base class ie if it makes no sense.

public abstract class clsDeciduous
{
 
Virtual and Override
The method may be overridden in a derived class.
 
    public virtual string RemoveSnow()
    {
        return whichType[buildingType] + ": No snow removal service available.";
    }

And in the derived class:

public override string RemoveSnow()
    {
        return "Commercial: Call Acme Snow Plowing: 803.234.5566";
    }

To prevent further inheritence use public sealed class.

| | # 

From msdn.

        // i is compiled as an int
        var i = 5;
 
        // s is compiled as a string
        var s = "Hello";
 
        // a is compiled as int[]
        var a = new[] { 0, 1, 2 };
 
        // person is compiled as an anonymous type
        var person = new { Name = "Terry", Age = 34 }; 
Anonymous types:
 
var v = new { Amount = 108, Message = "Hello" };

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type

| | # 

See: http://www.programgood.net/2009/10/20/TestDrivenDevelopmentInNETDALCh5.aspx

ADO.NET (ActiveX Data Objects) consists of two primary parts:

Data provider

These classes provide access to a data source, such as a Microsoft SQL Server.  Each data source has its own set of provider objects, but they each have a common set of utility classes:

  • Connection: Provides a connection used to communicate with the data source.
  • Command: Used to perform some action on the data source, such as reading, updating, or deleting relational data.
  • Parameter: Describes a single parameter to a command. A common example is a parameter to a stored procedure.
  • DataAdapter: A bridge used to transfer data between a Data source and a DataSet object (see below).
  • DataReader: Used to efficiently process a large list of results one record at a time. It allows records to be accessed in a read-only, forward-only mode, i.e., records have to be accessed in sequential order; they can neither be randomly accessed nor can a record which has been processed previously be accessed again.
DataSets

DataSet objects, a group of classes describing a simple in-memory relational database,

  • A DataSet object represents a schema (either an entire database or a subset of one). It can contain tables and relationships between those tables.
    • A DataTable object represents a single table in the database. It has a name, rows, and columns.
      • A DataView object overlays a DataTable and sorts the data (much like an SQL "order by" clause) and filters the records (much like an SQL "where" clause) if a filter is set. An in-memory index is used to facilitate these operations. All DataTables have a default filter, while any number of additional DataViews can be defined, reducing interaction with the underlying database and thus improving performance.
        • A DataColumn represents a column of the table, including its name and type.
        • A DataRow object represents a single row in the table; it allows reading and updating of values in that row, likewise retrieving any rows that are related to it through a primary-key foreign-key relationship.

OLE-DB is a replacement for ODBC.

image

When adding in a reference (a COM – Component Object Model).. I had to restart VS to get Resharper/VS to recognize and give me intellisense.

The reference was an ADOX reference – ADO ext 2.8 for DDL and Security.  We have to use this as the OLE DB features do not give create new database functionality.

int index;
        string newDB;
        string dbName = txtDatabaseName.Text;
        try
        {
            if (dbName.Length == 0)
                return;
            index = dbName.LastIndexOf('.');
            if (index == -1) // no secondary filename
            {
                dbName += ".mdb";
            }
            string pathName = Application.StartupPath.ToString();
            string combinedName = Path.Combine(pathName, dbName);
            ADOX.CatalogClass myCat = new ADOX.CatalogClass();
            newDB = CONNECTSTRING + combinedName + ";" + CONNECTSTRINGPART2;
            myCat.Create(newDB);
            myCat = null;
        }
CreateDatabase_website

image

Good bit of functionality, if you double click on an element in the list, it deletes it.

void lstFieldsToAdd_DoubleClick(object sender, EventArgs e)
    {
        ListView.SelectedIndexCollection indexes = lstFieldsToAdd.SelectedIndices;
 
        foreach (int index in indexes)
        {
            lstFieldsToAdd.Items[index].Remove();
        }
    }

Writing to the database he uses a class in clsDB called ProcessCommand

However to read data he does this from a form object.  So only using the clsDB to get the connection string.

OleDbConnection myDB = new OleDbConnection();
OleDbDataReader myReader;
OleDbCommand myCommand;
clsDB myData = new clsDB("Friend");
 
try
{
    myDB.ConnectionString = myData.getConnectString + dbName;
    myDB.Open();
    if (txtLastName.Text.Length != 0)
        sql = "SELECT * FROM Friend WHERE LastName = '" +
              txtLastName.Text + "'";
    else
        sql = "SELECT * FROM Friend WHERE ID = " + txtRecordID.Text;
  
    ClearFields();
 
    myCommand = new OleDbCommand(sql, myDB);
    myReader = myCommand.ExecuteReader();
    if (myReader.Read() == true)
    {
        record = (int)myReader[0];
        txtRecordID.Text = record.ToString();

image

Querying and DataGrid

image

Changing properties on the grid, such as docking to allow window resizing, colour schemes, formatting of cells.

Double click on the database table automatically runs the execute query.  User can drag column headers around, and sort each column.  User can add/edit/del data (code not implemented in this example).

image

LINQ

image

var query = from p in numbers // the linq query
                    where p > lo && p < hi
                    select p;
        foreach (var val in query) // display results
        {
            lstOutput.Items.Add(val.ToString());
        }

image

This is an interesting construct, using anonymous types.  What this is actually saying

var friends = new[]
                      {
                          new {name = "Tom", state = "IN"},
                          new {name = "Alice", state = "VA"},
                          new {name = "Tammy", state = "IN"},
                          new {name = "Ann", state = "KY"},
                      };

 

var query = from p in friends
                        where p.state == txtLow.Text
                        select p;
 
            foreach (var val in query)
            {
                lstOutput.Items.Add(val.name.ToString() + ", " + val.state.ToString());
            }
| | # 
# Wednesday, 09 December 2009

 

beginning

This book looked interesting as it seemed to be written by someone with a lot of experience teaching.  Sometimes it is great to go back to basics, as there is always something new to learn, and I was so right!  Here are my notes, source code, screenshots.

Chapter 1 – Getting Started

setting up the IDE.. VS2008 Express.   And installing the MSDN library.. 2GB download here: http://www.microsoft.com/downloads/details.aspx?FamilyID=7BBE5EDA-5062-4EBB-83C7-D3C5FF92A373&displaylang=en

Also a tool to take msdn into a chm help file: http://www.codeplex.com/packagethis

Chapter 2 - Understanding Objects

Class eg Person.. a template used to describe an object
  properties..that describe the object
  methods.. or actions that we associate with the object

Object eg the Person Object for Jack

naming convention
  cls - class
  txt - textbob
  btn - button

  good for selecting in the ide

making a blank project
putting in references for winform:

System, System.Drawing, System.Windows.Forms

putting in bootstrapper
change output to winform and tell which startup object asdf

using System;
using System.Windows.Forms;

public class frmMain : Form
{
    #region Windows code
    private void InitializeComponent()
    {
    }
    #endregion

    public frmMain()
    {
        InitializeComponent();
    }

    public static void Main()
    {
        frmMain main = new frmMain();
        Application.Run(main);
    }

}

3d on labels cool
making a default enter button (acceptbutton)
ctrl x and ctrl d shortcut keys with the ampersand on Text
True Type vs non fonts.. good to make things line up properly.

**screenshot mailing label program

**source code here too … c:\code\oopbook

screen

 

Part II – Understand C# Syntax

Chapter 3 – Understanding Data Types

Integer Division
.Focus property when coming back from an error
Int.TryParse method to see if it really is an integer
.Visible proerty of a textbox

Floating Point
AcceptButton
StartPosition - CenterScreen

int
float - 32 bit.. F,f
double - 64 bit... this is the usual one.. D,d
Decimal - 128bit (28 digit precision)..  M,m

eg int i = 0.5M

**insert source code  c:\code\oopbook\ch3IntegerDivision\

screen1

Also Fahrehiegh converter:

** put in source code link… c:\code\oopbook\ch3TempConvert

screen2

Interesting here was the use of consts…

how a division takes up more cycles, so better not to do 5/9 but to put in the decimal equivalent.  The out.. focus when  coming back from an error.  And unhiding the results box when it needs to be.

bool flag;
        double operand1;
        double answer;
        const double FIVENINTHS = 0.55555555;
        const double ZEROFAHRENHEIGHT = 32;

        flag = double.TryParse(txtOperand1.Text, out operand1);
        if (flag == false)
        {
            MessageBox.Show("Enter a whole number", "Input Error");
            txtOperand1.Focus();
            return;
        }

        answer = FIVENINTHS *(operand1 - ZEROFAHRENHEIGHT);

        txtResult.Text = operand1.ToString() + " degressF "  + " equals " + answer.ToString() + " degreesC";
        txtResult.Visible = true;

Ch4 – Understanding C# Statements

operand   eg 10
operator eg +, -, *, /, % these are binary operators
  unary
  binary
  ternary

expression
  one or more operands and their associated operator

statements
  one or more expressions terminated by a semicolon.

lvalue - location value.. memory address
rvalue - register value..actual value

eg int i
this is defining a variable to be at address 900,000 ie lvalue
i = 10
this is declaring a variable to have an rvalue of 10

if narly bug, hardcode data into the textboxes to make it easy!
10 / 6

avoid magic numbers
use const

Ch5 - Reference Data Types

If you're not going to manipulate data with Maths, store it as a string.

intellisense (expect in Resharper which is clearer)
  hand is a property
  diamond is a method

Pass by reference vs Pass by Value

Ctrl spacebar to give help on methods/props near current selection.

**insert source…c:\code\oopbook\ch5StringTester

screen3

Escape characters eg string message = “this is a \\ backlash, and this is a quote \””;

String literals eg string message = @”Go the the c:\program files\ directory and”;

DateTime reference Objects

**upload source code** c:\code\oopbook\ch5DateTime

screen4

Interesting code here is:

txtLongDate.Text = myTime.ToString("D");

Starting the app (everything gets populated automatically without having to press Test)

public frmMain()
{
    // 2) place all the label, textbox and button objects in correct positions on the form and set their properties
    InitializeComponent(); 
    UpdateTimeInfo();  // 3) set the properties of the objects just created
}

public static void Main()
{
    // 1) start here then this goes to constructor now everything is in memory ready to go
    frmMain main = new frmMain(); 
    Application.Run(main);  // 4) run the app
    MessageBox.Show("hello"); // 5) this would only be displayed when Close() is called.
}

Ch6 – Making Decisions In Code

20% of a programs time is spent in initial development

80% of a programs time is spent in testing, debugging, and maintenance

flag = int.TryParse(txtOperand1.Text, out operand1);

don’t need to initialise operand1 to any value.. int operand1 is fine.

**upload code ** c:\code\oopbook\ch6OddOrEven

screen5

Interesting here is the .Clear method after the check.

MessageBox.Show("Enter a whole number", "Input Error");
        txtOperand1.Clear();
        txtOperand1.Focus();
        return;

Brackets Style:

K&R (Kernighan and Ritchie… 1978 book on C)

if (x == 2) {

//do something

}

Other style:

if (x == 2)

{

  //do something

}

or

if (x == 2)

  // do something

the danger of the above is it’s easier to make a mistake like:

if (x == 2);  // notice the semicolon!

  //do something

Nested If Statements / Cascading if statements

Switch

statements are better

switch (expression1)

{

case 1:

// do stuff here

break;

case 2:

// do other stuff

break;

default:

// do the default stuff.

break;

}

Ch7 Statement Repetition Using Loops

screen1

for (i = start; i <= end; i++)
{
    // {0, 5} first argument and right-justify it in a field of five characters
    // {1,20} second argument and right-justify in a field of twenty characters
    buff = string.Format("{0, 5}{1, 20}", i, i*i);
    lstOutput.Items.Add(buff);
}

for loops – ideally suited for counting operations

while loops are good for searching for a particular value in a set

screen6

bucket = 1;
        for (int i = num; i > 1; i--)
        {
            bucket *= i;
        }

Don’t need to do the last factorial as it multiplies by 1, so leave i > 1.

Keyboard shortcut – F7 to view designer / view code

 

screen7

Notice the currency here:

buff = string.Format("{0,4}, {1,15:C}", i, assetIsWorth);
lblResults.Items.Add(buff);

http://www.programgood.net/2009/12/14/ParameterPassingInCValueAndReferenceTypes.aspx
| | #