Tuesday, March 31, 2009

C# Classwork - The RichTextBox/Text Editor

This is a very basic text editor, rendered using the RichTextBox control.




The designing (drag and drop) should be easy, the list of code for each text controls are given below.


1) New (clears textbox)

richTextBox.Clear();


2) Open

OpenFileDialog openFile1 = new OpenFileDialog();
openFile1.ShowDialog();

richTextBox.LoadFile(openFile1.FileName, RichTextBoxStreamType.PlainText);


3) Save


richTextBox.SaveFile("C:\\DENIS.TXT", RichTextBoxStreamType.PlainText);


4) Save As


SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.ShowDialog();
saveFile1.DefaultExt = "*.txt";

richTextBox.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);


5) WordWrap


if (richTextBox.WordWrap == true)
richTextBox.WordWrap = false;
else
richTextBox.WordWrap = true;


6) Font


FontDialog fontDialog1 = new FontDialog();
fontDialog1.ShowDialog();

richTextBox.Font = fontDialog1.Font;


7) Color


ColorDialog colorDialog1 = new ColorDialog();
colorDialog1.ShowDialog();

richTextBox.ForeColor = colorDialog1.Color;


8) Undo, Cut, Copy, Paste


private void undoToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox.Undo();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox.Paste();
}


9) Number of Characters


MessageBox.Show("Number of Characters : " + richTextBox.Text.Length);


10) Number of Words


int iWords = 1;
for (int i = 0; i < richTextBox.Text.Length; i++)
{
if (richTextBox.Text[i].ToString() == " ")
iWords++;
}

MessageBox.Show("Number of words: " + iWords);



11) Number of Paragraphs



int iParagraph = 1;

for (int i = 0; i < richTextBox.Text.Length; i++)
{
if (richTextBox.Text[i].ToString() == "\n")
iParagraph++;
}

MessageBox.Show("Number of Paragraphs: " + iParagraph);


PS: Sorry for late input guys, I am now working freelance in the city :)

Friday, March 27, 2009

Monetary System - Version 2 - Using arrays & for loops - the proper way

Misa devised a brillant way to use arrays, loops and the TableLayoutPanel control to tackle the problem stated in the previous entry (version 1).  


But first, let's understand one important design concept, the TableLayoutPanel control.
We are used to display informations using labels, but we also found out the limitations of this control. With labels, it is very difficult to predict the display of the string or text being output. For example, a label might contain multiple lines of text (we might use '\n' for new lines, or '\t' for tabs).

With TableLayoutPanel, the organisation of any controls including labels, is made easier.
The TableLayoutPanel is just a series of rows and columns, analogous to a table.

One of the main advantage of using the TableLayoutPanel is that you can refer to each control in  a cell, just like an array. An array of controls, found in the Table. We will use that concept in this code.


For example, you might want to contain a list of Coins you have, and the number of coins, each represented on a different row, with separate columns for each category. You can do it with labels only, but the best design solution is to use the TableLayoutPanel with labels.

 

In this scenario, Coins are on the top row, whereas the numbers are below the respective coins, bottom row.  We create the table TableLayoutPanel1.


In design view, the table is set as follows, with 4 normal labels, one in each cell.

Now the nice part. You can actually refer to the labels in an 'array-like' fashion. For example, 

TableLayoutPanel1.Controls[0] will refer to label2.
TableLayoutPanel1.Controls[1] will refer to label3.
TableLayoutPanel1.Controls[2] will refer to label4.
TableLayoutPanel1.Controls[3] will refer to label5.
So this is why we should be using arrays and loops in this question. 
This is the end of the explanation on why we should use the TableLayoutPanel control. 


This is the final code for the home work.

   1:  int[] coins = { 50, 20, 10, 5 };
   2:  int[] numbers = { 0, 0, 0, 0 };
   3:  int iAmount = int.Parse(txtAmount.Text);
   4:  int iCoinsNum = 0;  //stores the number of coins used
   5:   
   6:  iAmount %= 100; //Get the 2 last digits
   7:   
   8:  for (int i = 0; i < coins.Length; i++)
   9:  {
  10:      numbers[i] = iAmount / coins[i];    //gets the number of particular coin in amount
  11:      iAmount = iAmount % coins[i];       //gets the remainder
  12:      tableLayoutPanel1.Controls[i].Text = coins[i] + " cent \n" + numbers[i];
  13:      //display the coins value and amount, in each label per column in the TableLayoutPanel
  14:      iCoinsNum += numbers[i];            //accumulates the amount of coins
  15:  }
  16:   
  17:  if (iCoinsNum == 0) //check if any coin was required
  18:  {
  19:      btnReset_Click(sender, e);
  20:      lblCoinsNum.Text = "No coins required.";
  21:  }
  22:  else
  23:  {
  24:      lblCoinsNum.Text = "" + iCoinsNum + " coins required.";
  25:  }



Note: The order of the Coins array is important, as you want to divide the 50c coins first before moving to the 20c coins, and so on.


Screenshots of design and runtime application

Thursday, March 26, 2009

Monetary System - Can someone tell me why we should be using arrays for this?


Assume your monetary system only has the following coins: 50 cents, 20 cents, 10 cents,
and 5 cents. One dollar is equal to 100 cents.
Write a program to display the number and type of coins required to make up the amount
of money given by the user. The amount must be in cents, and must be an integer. Print
the number and type of coins required to make up the amount of money using the
smallest possible number of coins. The output lists types of coins only if at least one coin
of that is required.

Example:

If the input is 70
The output is:
2 coins required:
Fifty Cents Twenty Cents Ten Cents Five Cents
1 1 0 0
If the input is a multiple of 100 cents
The output is:
No coins required

If the input is 170
The output is:
2 coins required:
Fifty Cents Twenty Cents Ten Cents Five Cents
1 1 0 0


I have been pondering on this question for a long time, not because it is difficult. I was trying to figure out how arrays can make my life easier, but I couldn't find the answer. Anyone has an idea?

The first version I made (version 1) does not use arrays at all. Check the screenshot below:

Code Discussion
The main points to be addressed in C# in this question are:
  1. We need to get the TENS and UNITS from the value entered by the user. For example, we need to extract '87' from '187', or '6' from '106'.
  2. We need to keep count of 50's, 20's, 10's and 5's.
  3. Display a summary of the number of coins required.

We need to get the TENS and UNITS from the value entered by the user. For example, we need to extract '87' from '187', or '6' from '106'.
The logic is straight-forward. You need to check the number of digits in the string. We make use of the Length() method.
For example, if the length of the string is 2, it means that the value entered may look like "99", which does not need any validation.
However, "1024" needs to be addressed. The length for this string is 4. We need the last two elements. I used the Substring() function to perform the appropriate string manipulation.

iVal (int) will store the tens and units from the value entered by the user.
sVal (string) will store the text value entered by the user.
iLengthAmount is the length of the string value entered by the user.
e.g. int iLengthAmount = txtValueEnteredByUserBox.Length;


if (iLengthAmount > 2)
{
iLengthAmount = iLengthAmount - 2;
iVal = int.Parse(sVal.Substring(iLengthAmount, 2));//Discard Hundreds,
keeping Units and Tens

}


Note: I will continue on this post at a later time in the evening.

Update: 27/03
Misa, thanks for the solution in your comment. Your proposed solution is awesome and I think that is what is required from us by Allan. You definitely made it simpler. I will discontinue on this post, and create a new entry for this question. If anyone needs the complete code or wants to know more about this code algorithm/logic, just post a message.

Wednesday, March 25, 2009

Using CSS to create navigation buttons/bar/dropdowns

As per Misa's request, the link below shows how you can use CSS to create navigation buttons and dropdowns. I found this site to be very educational and very rich in terms of content and creativity.

http://www.cssplay.co.uk/

Have Your Say!

If you are copying-pasting, the file organisation is as follows:
  1. .myHTML.html
  2. .mysay.css
  3. /images/bg.png
  4. /images/textbg.gif


HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="yoursay.css" />
<title>Have your Say!</title>
</head>
<body>
<div id="wrapper">
<div id="formcontrols">
<form action="" method="post">
Name
<br/>
<input type="text" name="myname" size="30" id="eachcontrol" />
<br/><br/>
Email
<br/>
<input type="text" name="myemail" size="30" id="eachcontrol" />
<br/><br/>

http://
<br/>
<input type="text" name="myhttp" size="30" id="eachcontrol" />
<br/><br/>


Comments
<br/>
<textarea name="myComments" rows="2" cols="23" id="eachcontrol" >
</textarea>
<br/><br/>

<input type="button" name="preview" value="PREVIEW" class=
"previewbtn"
/>
<br/><br/>

Remember details?<br/>
<input type="checkbox" name="chkremember" />
<br/><br/>
</form>
</div>
<div id="myColumn">
<h3>HAVE YOUR SAY</h3>
<div id="content">
<p>Feel free top publish your thoughts but please be judicious
when communicating I am.</p>
<p>Gravatars are enabled. Go get yourself one.</p>
<p>All the cool kids use Textile.</p>
<p>Email address is required but will not be posted or
distributed.</p>
</div>
</div>
</div>
</body>

</html>




CSS

body
{
font-family:Verdana;
font-size:16px;
color:#ffffff;
margin:0 auto;

}

h3{
width:350px;
border-width: 0px 0px 3px 0px;
border-style:dashed;
font-size:30px;
padding:12px;
text-align:center;
background-color:orange;
margin:10px 0px 10px 0px;
padding:2px 2px 5px 2px;
}

#wrapper
{
margin:50px;
float:left;
background-image:url('images/bg.png');
background-repeat:repeat;
width:700px;
}

#formcontrols
{
width:280px;
float:left;
padding:10px;
}

#myColumn{
width:380px;
float:left;

}

#content{
margin-left:30px;
width:300px;
float:left;
}

#eachcontrol
{
background-image:url('images/textbg.gif');
background-repeat:repeat;
}

.previewbtn
{
border:3px solid;
border-color: #ffffff #000000 #000000 #ffffff;
color:#ffffff;
background-image:url('images/bg.png');
background-repeat:repeat;
padding:7px 20px 7px 20px;
}

Tuesday, March 24, 2009

Displaying the TAB escape character in a label

The '\t' character is a bit tricky. When you use the tab character, the compiler translates it to this squared character that we have all seen in class. This squared character is correctly interpreted, and displays perfectly in C# console. The only problem is that the tab character does not display properly in controls at form level.

Solution:
To display the escape character for '\t', I made use of the replace function.

private void button_Click(object sender, EventArgs e)
{
string s = "\tDenis\t";
s = s.Replace("\t", " ");
label1.Text = s.ToString();
}

Monday, March 23, 2009

Shanti C# -> Morse Code version2

Shanti gave me this as homework. It has basically the same specs as per the question discussed in the previous entry, except that the user should type in text (alphanumerics), and the text should be translated automatically to Morse code.

The specs I gathered are:

  1. Type text in the combo box, and Morse code of the text being typed should be displayed.
  2. I assume that she wants the translation to be dynamic (On key press). Another solution is to use some static textboxes and buttons, and on click of the button, the text is translated to morse code. But, sounds to easy :), so I'll try the dynamic one.
The final product looks as follows:



Actually, I am using the same code from the previous Morse version 1 code (Declare and Initialise string arrays. Also populate the combo and the list boxes, and associate both boxes with the indices (Note: we don't say 'indexes') of the respective arrays. Refer to previous post on how to do it.) .

Below is the procedure to get this to work, considering the fact that this is an enhancement to Morse version 1.


Let's try to figure out how this should work.
We want the program to detect any input from the user, and translate the input text to Morse.
The input text is entered in the combo box, and a label will be used (see picture, right hand side of dialogbox) to display the Morse code.

  1. We deduce that the changes are made in the Event cmbText_KeyDown.
  2. In this event, we need to capture the text being entered by the user.
  3. We want to compare the text entered, CHARACTER BY CHARACTER, with the values in the combobox.
  4. What if the user enters lowercase alphabets? Remember that the array that contains them are all in uppercase. We will need to do the comparison with uppercases only.

The code is as follows:

private void cmbText_KeyDown(object sender, KeyEventArgs
e)
{
string sLabel = "";
string sTextEntered = cmbText.Text.ToUpper();//Convert
the text entered by user to uppercases, and put it in
the sTextEntered string


for (int i = 0; i < sTextEntered.Length; i++)//We
need to loop for all characters, one by one, entered by
the user
{
myChar = sTextEntered[i];//myChar is a char
variable, declared in the class section as being a
global variable. It contains the character in
string at position [i]


for (int j = 0; j < sMorse.Length; j++) //We
make use of a nested for loop, using j as counter,
because we need to compare each character entered
in the combo with all the elements present in the
alphanumerics array (0-9, A...Z)
{
if (myChar == char.Parse(sText[j]))//if
the character in the textbox matches the character
in the alphanumeric array, we have a catch

{
sLabel += sMorse[j] + " ";//on
catch, we put the corresponding Morse code to
another string sLabel

break;//When we have a catch, we
do not want to continue the for loop, so we
break/exit to save time

}
}
}
lblMorse.Text = sLabel;//We put the resulting
Morse into the label. Done!

}

Shanti C# -> Morse Code

Same coding as in previous entry (English Spanish Translator):

Declaring and initialising the variables:
string[] sText = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2",
"3", "4", "5", "6", "7", "8", "9", "0" };
string[] sMorse = {". -","- . . .
","- . - .","- . . ",".",". . - .","- - .",". . . .",". . ",". - - -","- . -",".
- . .","- -","- .","- - -",". - - .","- - . -",". - . ",". . .","-",". . - ",".
. . -",". - -","- . . -","- . - -","- - . .",". - - - -",". . - - -",". . . -
-",". . . . -",". . . . .","- . . . .","- - . . .","- - - . .","- - - - .","- -
- - -"};


On form load,

for (int i = 0; i < sMorse.Length;
i++)
{
cmbText.Items.Add(sText[i]);
lisMorse.Items.Add(sMorse[i]);
}


Making both controls dependent on user-choice:
private void cmbText_SelectedIndexChanged(object sender, EventArgs
e)
{
int iIndex = cmbText.SelectedIndex;
lisMorse.Text =
sMorse[iIndex];
}

private void lisMorse_SelectedIndexChanged(object sender, EventArgs
e)
{
int iIndex = lisMorse.SelectedIndex;
cmbText.Text =
sText[iIndex];
}


Enjoy!

Shanti C# -> English - Spanish Translator

In the class definition, you might want to declare and initialise the two global string variables

string[] sEng = {"arm","body","ear","eye","face","foot/feet","finger","hair","hand","head","leg","mouth","neck",
"nose","stomach","tooth/teeth"};
string[] sSpan = {"brazo","cuerpo","oreja","ojo","cara","pie/s","dedo","pelo","mano","cabeza","pierna","boca",
"cuello","nariz","est\u00F3mago","diente/s"};



Note the character in orange, which is the unicode that represents the spanish character.



Now, we bind the arrays to the controls (I use a combo box and a list box).

for (int i = 0; i < sEng.Length; i++)
{
cmbEng.Items.Add(sEng[i]);
lisSpan.Items.Add(sSpan[i]);
}

for (int i = 0; i < sMorse.Length; i++)
{
cmbText.Items.Add(sText[i]);
lisMorse.Items.Add(sMorse[i]);
}


Finally, we put the coding behind the index selection of the combobox and listbox respectively, so that when you click on an english term, the spanish translation is offered, and vice-versa:

private void cmbEng_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = cmbEng.SelectedIndex;
lisSpan.Text =
sSpan[iIndex];
}

private void lisSpan_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = lisSpan.SelectedIndex;
cmbEng.Text = sEng[iIndex];
}



That's it, compile, run and learn Spanish :)

Friday, March 20, 2009

CSS - My two cents' worth

CSS Basics

1) How to use CSS?
You can use CSS in 3 ways:
  1. Using inline CSS means that you use your styling elements within the tags in the HTML. You will use the <style> tag to do so.
    e.g.
    <body style="background-color:blue; font-weight:bold">


  2. Using internal CSS means that you define all your styling elements for each tag you are using in the <head> section.
    e.g.

    <style type="text/css">
    <!--
    h1 { font-family:Times serif; color: #f00000; }
    -->
    </style>
  3. External Style Sheets: using a file with extension .CSS that will contain all the styling elements that you would normally put in the head section. This improves readability of your code and helps achieving separation of content from form/design.

2) How to use external CSS?
<head>
<link type=”text/css” rel=”stylesheet” href=”mystyle.css”>
</head>

3) How to use Classes?
Say for example, you want all your paragraphs <p> to be black, except for one paragraph that would be red.
The solution is to use a class, that will be applied for only this particular paragraph.
e.g.

p.warning {color: red;}

<p class="warning">This is red. </p>

Note: You can also create classes that will apply to any tag (generic classes).
e.g.
.mycolor{color: red;}

<p class=”mycolor”>A red body text.</p>

<h1 class=”mycolor”>A red headline.</h1>

4) What are IDs? What is the difference between IDs and Classes?
The ID selectors and generic classes are very similar, except for the fact the an ID is supposed to be used only once.
e.g.
#myID{color:green;font-size:10px}

<p id="myID">my green paragraph</p>
5) What if I want one paragraph to be in red, and one sentence of that paragraph in bold?
Well, we could use the <bold> tag which will contain the sentence, but it is not XHTML compliant and the bold tag is deprecated.
The solution is to use the <span> tag.
e.g.

.myBold{font-weight:bold}

<p>This paragraph has the browser default formatting, but <span class="myBold"> this sentence is bold, without making any change to the paragraph selector.</span> This sentence is back to browser default formatting for a paragraph tag. </p>

Using DIVs

Divs tags are used to separate contents in blocks, or more specifically, divides sections in the html file (content).

When you have your contents divided in a number of divs, you can apply whatever fancy styles to your divs for formatting, presentation, design etc (CSS).

Below are the CSS tag styles (tested and optimised on IE 7 only, but works fine in Firefox/Safari)
Just add it in an external css file, and link to it in your html using the <link> tag in the <head> section.

Note: I added a Header (H3) in the HTML file for HTML and CSS in the boxes to the right, so that the whole line is gray.

html{
font-family:"Times New Roman";
color:black;
margin: 0 auto; /* Centred Page */
width:800px;
margin-left:100px;
font-size:14px;
}
#heading{
font-size:20px;
font-weight:bold;
margin:10px 0px 0px 0px;
}

#navigation,#footer{
color:orange;
text-transform:uppercase;
font-weight:bold;
margin:0px 10px 0px 0px;
}

#content{
width:790px;
}

#text{
float:left;
width:500px;
}

#summary{
float:left;
width:250px;
}

#html,#css{
width:300px;
border:thin;
border-style:solid;
border-color:gray;
margin: 0px 20px 10px 20px;
}


h3{
background:gray;
font-size:14px;
color:white;
}

.cssgraybackground{
background:gray;
}
a{
color:orange;
}
ul{
margin-left:0px;
margin-top:30px;
margin-bottom:30px;
margin-right:10px;
}

li{
list-style-type:none;
display:inline;
border-style:solid;
border-color:white gray white white;
border-width:2px;
margin: 0px 0px 0px 0px;
}

Postcode Finder - Using ListBox and Textbox


The specs of this program are as follows:
  • one string array that will contain the names of suburbs
  • one int array that will contain the list of postcode
  • one listbox, one dropdown
First things first, we need to create the two arrays. We might want to declare and initialise both of them in the class section as we want both arrays to have visibility (I prefer the term Scope) throughout the whole program.

string[] sSuburb = { "Ashfield", "Balmain", "Circular Quay", "Newtown", "Petersham", "Redfern" };
string[] sPostcode = { "2131", "2041", "2000", "2042", "2049", "2016" };


Now, we need to bind the suburb and postcode arrays to the dropdown and the listbox respectively. We might want add them one by one, but as Allan said, when you see ARRAYS, YOU USE FOR LOOPS :D

As a consequence, the for loop as shown below will loop from i=0 because any array whatsoever starts with element 0.
The condition for this loop is that it should not exceed the length of the array, hence we use the array property Array.Length.
We use the control.Items.Add because we want them to be added dynamically (at runtime, not at design time). We can use only one for loop to populate both controls:

for (int i = 0; i < sSuburb.Length; i++)
{
cboSuburb.Items.Add(sSuburb[i]);
lisPostCode.Items.Add(sPostcode[i]);
}

Done! Now, we try to make the the association between suburb name and postcode. Let's say, we want to make the postcode in the listbox to change when we choose any suburb from the dropdown.
We need to make the change in suburb dropdown because the dropdown change will trigger the change in the listbox, yes?

private void cboSuburb_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = cboSuburb.SelectedIndex;
//change list
lisPostCode.Text = sPostcode[iIndex];
}

The iIndex variable will just store the index of the suburb that is changed. You could also write the following, by omitting the iIndex variable:

lisPostCode.Text = sPostcode[cboSuburb.SelectedIndex];


but it affects readability, so we try to avoid this.


We do the same for the listbox, as follows:

private void lisPostCode_SelectedIndexChanged(object sender, EventArgs e)
{
int iIndex = lisPostCode.SelectedIndex;
//change list
cboSuburb.Text = sSuburb[iIndex];
}


Click Build, run and enjoy. Easy right? :D

Thursday, March 19, 2009

Hello World!

Hello there Cert IV Students (IT Programming)!

I've just set up this blog today 19 March 2009 [23 38] so that we can relax in our own comfort at home with a cup of coffee and discuss about anything related to our TAFE course (Cert IV IT Programming), or anything really...

Topics might include
  • Classwork related(C#, HTML, XHTML, CSS, and even how to create a blog or how to use diigo)
  • Homework - Let's discuss the possible solutions to any particular problem and the different algorithms or ways to tackle them (one problem --> many solutions)
  • Websites worth mentioning
  • the weather, good plans, outings etc
and are non-exhaustive.

I will also post weekly solutions to the classes, so check the website regularly, or add it to your CSS feed on diigo, or click FOLLOW ME link on the right hand side of this page.

As from today, I will update the solutions on the blog. If you have any questions, please do ask. Do not be shy. Everyone can give their own views on this blog. You are ENCOURAGED to do so.

Let's make this place an extra knowledge hub that will complement our classes!