.NET 101
Introduction
.NET is basically an interface for a single programming language. MSIL, However languages can be written to be compliant with MSIL and thus usable with the .NET framework. Thus StringBuilders are available whether you are coding in C#, VB.NET or whatever other languages.
Using System
Most Basic Project setup
Windows
Apps
Web
Apps
Console
Apps
Hello World
File,
New Project, Windows App, save to c:projects
File,
Saveas, Form1.cs to net101.cs
Properties,
text, ‘Hello World’
Using System.Text
String / StringBuilder
Strings are immutable (non appendable) thus very inefficient when there are multiple changes to the value.
My habit I’ve tried to develop is anytime I am using += more than once or twice I use a StringBuilder.
Had one program which was parsing, rebuilding and databasing text files that went from 8 hours to 20 seconds from simply switching from string to StringBuilder.
StringBuilder is like stringbuffer in Java
string
strHello =
"Hello World 111 \n";
strHello += "Hello World 222
\n";
StringBuilder
sbHello = new
StringBuilder(); //use intelisense to show you must
add system.text first.
sbHello.Append("Hello World
333 \n");
sbHello.Append("Hello World
444 \n");
label1.Text = strHello + sbHello.ToString();
Array / ArrayList
I think ArrayList is just simpler. Useful methods and Dynamic Resizing
:Add method so you don’t have to keep track of last index.
:Remove/ RemoveAt / RemoveRange Method
:Sort
Also properties: Count
ArrayList is like a vector in java or redim / preserve (but it does the work)
string[] strStringArrayEx = new String[5];
ArrayList
alArrayListEx = new
ArrayList();
strStringArrayEx[1]
= "red";
alArrayListEx.Add("RED");
strStringArrayEx[2]
= "blue";
alArrayListEx.Add("BLUE");
foreach(string test in strStringArrayEx)
{
sbHello.Append(test + " ");
}
sbHello.Append("\n");
foreach(string test in alArrayListEx)
{
sbHello.Append(test);
}
Using System.Web
Web Controls (except Data grid) and Data
Binding
All controls are Server Controls when dropped off the toolbox. This means they are very useful, unless you want to do some client side processing to avoid trips to the server. If this is your desire then you need to use handbuild HTML clientside controls.
All Controls inherit from Control Class (Buttons including regular/radio/checkboxes inherit from ButtonClass which inherits from Control Class.
Basi,c most commonly used Control Class Properites.
Anchor (Anchors when window resized), BackColor, Dock(Docks to edges of window), Enabled, ForeColor, Height, Left, Name, Parent, Right, TabIndex, TabStop, Tag(a spot to store additional data associated with the control, Often used to hold valid or not), Top, Visible, Width
Labels
We
already did, ok change BackColor, FontSize in properties and in code.
label2.BackColor = "Color.Red";
label2.Font.Italic = true; (doesn’t work not
‘settable’)
TextBox
Visually
change ID, Text, Word Wrap etc..
Warning if you use Multiline = True, then it changes when it renders from an HTML TextBox to a HTML TextArea which changes some of the available events.Specifically maxlength property is inaccessible
1 Server Side control can represent multiple types of HTML objects
If you want to control the length, you must use a javascript functions that catches the keystrokes. To add a clientside event to a server control you must add it into the C# code.
txtDescription.Attributes.Add( "OnKeyUp","checklen()");
--Switch
to Web Apps
Rename
webfrom to netwebform.aspx
‘Set as Start
Page’.
Buttons / ImageButtons / Link Buttons
A link button looks just like a plain old link, but can have server side events
RadioButtons
Add
radiobuttonlist change id to rblExample
Save copied
code from before
ArrayList alArrayListEx = new ArrayList();
alArrayListEx.Add("RED");
alArrayListEx.Add("BLUE");
Add new code
rblExample.DataSource =
sbHello;
rblExample.DataBind();
ComboBox / DropDowns
Change
id to ddlExample
Note
AutoPostBack, Items
ddlExample.DataSource =
alArrayListEx;
ddlExample.DataBind();
go
back and note out DataBinds and add
Page.DataBind();
**DataBind must be in !Page.IsPostBack if later
events to avoid rebinding everything which clears your values that you think
you have.
Here is a list of some of the other controls that we won’t be going over today, but are available.
ListBox, ListView, GroupBox/Panel, RichTextBox, StatusBar, ImageList, TabControl, Validators, Calendar
(Functions)
Move
above code into function
arrayStuff();
private void arrayStuff()
{}
Using System.IO
StreamReader
The Base class is the StreamReader, but the functionality of the TextReader and XMLReader are remarkably similar, just obviously for Text and XML.
Must add System.Text for string builder
Add function call funcReadFile()
Create new folder in c drive called ‘data’
Create text file and save in new folder
1||Red||E
2||Blue||W
3||Green||E
private
void funcReadFile()
{
StringBuilder
sbFile = new
StringBuilder();
string strTemp;
TextReader
tr = new
StreamReader("C:\\\\testing.txt");
while (tr.Peek()>-1) //if line exists
{
strTemp
= tr.ReadLine();
strTemp
= strTemp.Replace("E", "East");
sbFile.Append(strTemp + "\r\n");
}
tr.Close();
TextWriter
tw = new
StreamWriter("C:\\\\data\\testing2.txt");
tw.Write (sbFile.ToString());
tw.Close();
}
Using System.XML
Xpath is like a folder system
10 Second intro to Xpath
/ represents absolute path, // relative path, * wildcard, //@ for attributes, [1], selects first , count( ) returns count, starts-with ( )..
<?xml version='1.0'
encoding='ISO-8859-1'?>
<catalog>
<cd
country='USA'>
<title>Empire
Burlesque</title>
<artist>Bob
Dylan</artist>
<price>10.90</price>
</cd>
<cd
country='UK'>
<title>Hide
your heart</title>
<artist>Bonnie
Tyler</artist>
<price>9.90</price>
</cd>
<cd
country='USA'>
<title>Greatest
Hits</title>
<artist>Dolly
Parton</artist>
<price>9.90</price>
</cd>
</catalog>
private void funcXML()
{
string strXML = "<?xml
version='1.0' encoding='ISO-8859-1'?><catalog><cd
country='USA'><title>Empire Burlesque</title><artist>Bob
Dylan</artist><price>10.90</price></cd><cd
country='UK'><title>Hide your heart</title><artist>Bonnie
Tyler</artist><price>9.90</price></cd><cd country='USA'><title>Greatest
Hits</title><artist>Dolly Parton</artist>
<price>9.90</price></cd></catalog>";
StringBuilder
sbXML = new
StringBuilder();
XmlDocument
oDoc = new
XmlDocument();
oDoc.LoadXml(strXML);
//how we would normally do it.
oDoc.Load("c://filename");
XmlNodeList
oNodes = oDoc.SelectNodes("//cd/artist");
// XmlNodeList oNodes =
oDoc.SelectNodes("/catalog/cd[price=10.90]/price");
// XmlNodeList
oNodes = oDoc.SelectNodes("//cd[starts-with(artist,'Bo')]");
// XmlNodeList
oNodes = oDoc.SelectNodes("//cd[@country='UK']/artist");
for(int i=0;i<oNodes.Count;i++)
{
sbXML.Append(oNodes.Item(i).OuterXml + " -<br> " );
}
lblXML.Text = sbXML.ToString();
}
1.************************************************************************
State / Request /
QueryString
Very Similar to ASP
String s =
Request.QueryString["Name"];
Getting an item
passed through can be grabbed in C# or Javascript. The most common way is to
grab in C#
vVariable = Request["Variable "]
then get in
javascript alert(‘<%=vVariable%>’)
or you could get directly in javascript
In order to hold
a value through multiple postbacks putting an variable in to “ViewState” is
often the simplest way to go.
public string vLayerName
{
get
{
return (string)ViewState["vLayerName"];
}
set
{
ViewState["vLayerName"] =
value;
}
in Classic ASP all form values are cleared on submit. In ASP.NET, all form values are maintained in viewstate.
Automatic state management is a feature that enables server controls to re-populate their values on a round trip without requiring you to write any code, but with a price
Viewstate can be controlled at four levels--the machine level, the application level, the page level and the control level
Application level state can be controlled through global.asax
Session Level state can be controlled using Session[“anyvarname”]
Debugging
Debugger
Set
breakpoint on strScraped = webScraper\
Show
step into / step over /step out
Show
Watch for variable strTemp inside funcReadFile
Trace
Add Trace.Write(strTemp) as last line inside tr.Peek loop
Add Trace=true to html page
Other
option is to change web config to…
<configuration> <system.web> <trace enabled="true"/> </system.web> </configuration> and look at this page…
http://localhost/myapplication/trace.axd
Response
Old School – add in right after …strTemp.Replace(“W”….
if(strTemp.IndexOf("West")>-1)
{
Response.Write("we made it
here");
Response.End();
}
Framework
Project
More Complex Project Setup
The best architecture for multiple developer .NET projects is utilizing SourceSafe.
On a server you have the original copy of the Project. Whenever you work on the project you check it out and work locally on your machine. (The whole project is running on your machine, not just the file. – Thus you must ‘Get Latest Version’ of the entire project regularly to ensure you have updated code for the pages that you are not checking out.) Then when you are done you check it back in which movse it back to the Server. You can then do a build on this Server to update this server. This server can be your Live Server, in which case you are done….or for an extra layer of comfort, this can be your Dev machine. The Live Server is just like any other machine/user who checks never checks out stuff. Because you can do a ‘Get Latest Version’ of only a few files or do a ‘Get Latest Version’ of the whole project you can very safely update small sections of your website.
One more hint : Don’t start page names with numbers – Confuses C#
References/ Web References (add web.mail to windows form)
Other
Copy Project
You must use this to move a project, copy and paste in Windows Explorer doesn’t work.
If you are not using SourceSafe this is the simplest way to move files back and forth. However there is no project management. You simply overwrite the Live Server.
Bulk Comment/Uncomment
Go to Definition / Reference…
Region Blocks
# region Mail and IO functions / # endregion
Format – Align lefts, Make same size, snap to grid
+= works in c# and vb.
Only significant bug so far: Properties window disappears.
Using System.Net
HttpWebResponse
Must first add label named
lblScraper
string strScraped;
strScraped = webScraper();
lblScraper.Text
= strScraped;
private string webScraper()
{
string strURL = "http://www.cuppcondo.com/code";
HttpWebRequest
HttpWReq = (HttpWebRequest)WebRequest.Create(strURL);
HttpWebResponse
HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
string stringResult;
using (StreamReader sR =
new StreamReader(HttpWResp.GetResponseStream()))
{
stringResult
= sR.ReadToEnd();
sR.Close();
}// Insert code that uses the response object.
HttpWResp.Close();
return stringResult;
}
cast( )
create new page/ change ‘set as start page’
Using System.Data
/ System.Data.SqlClient
Data Access
ADO.NET is very similar looking at first glance to ADO but very different the more your find.
Both use the connection and command object, and the recordset is relatively similar to the dataset object. That said…
SqlClient is faster than OldDb for SqlServer.
Connection object – very similar to the ADO connection. 99% (I haven’t found the 1% yet) of connection strings work for ADO.NET
The command object is similar but with enhancements. The command object is exposes the Reader object which cannot be directly instantiated. Thus the only way to utilize is through the Reader’s Methods
ExecuteNonQuery (Returns nothing),
ExecuteScalar (returns a single string)
ExecuteReader (a forward-only, read-only DataSet) is through the Command object.
ExecuteXMLReader which returns an XML document
A dataset is a disconnected set of data and can represent tables or multiple tables. It is usually built through the dataAdapter’s object fill method.
Start
– create new table tblTest in enterprise manager
Columnname
= tblTestID, data type =
uniqueidentifier, is rowGUid yes
tblTestName
= varchar, tblTestCol2 = varchar
add
in 4 rows, abc, def, ghi, jkl execute to get guids, 111 for each row in col2
Select
“select * from table where field = 1”
//string vConnStr1 =
ConfigurationSettings.AppSettings.Get("dbUPAA");
//SqlConnection vConn1 = new SqlConnection(vConnStr1);
ArrayList al =
new ArrayList();
StringBuilder
sbTest = new
StringBuilder();
SqlConnection
myConnection;
myConnection
= new
SqlConnection("server=database;database=petrowebtest;uid=zz;pwd=zzz");
myConnection.Open();
string strInsert = "1234";
string vSql = "INSERT INTO tblTest(tblTestName) VALUES ('"
+ strInsert + "')";
SqlCommand
InsertCommand = new
SqlCommand(vSql,myConnection);
InsertCommand.ExecuteNonQuery();
vSql = "SELECT * FROM
tblTest " ;
SqlCommand
vCommand = new
SqlCommand(vSql, myConnection);
SqlDataReader
vDr;
vDr = vCommand.ExecuteReader();
// while
(vDr.Read())
// {
// sbTest.Append(vDr["tblTestName"]
+ " ");
// }
lblFirstSql.Text = sbTest.ToString();
if(!Page.IsPostBack)
{
dgExample.DataSource = vDr;
dgExample.DataBind();
vDr.Close();
//for later
//SqlDataReader vDr2;
//vDr2
= vCommand.ExecuteReader();
//dlExample.DataSource = vDr2;
//dlExample.DataBind();
//vDr2.Close();
}
2.***************************************************************
SqlConnection myConnection;
myConnection
= new
SqlConnection("server=database;database=petrowebtest;uid=zz;pwd=zzz");
myConnection.Open();
string vSql2 = "INSERT INTO tblTest(tblTestName) VALUES (@sName)";
SqlCommand
InsertCommand2 = new
SqlCommand(vSql2,myConnection);
SqlParameter
paramItemDesc = new
SqlParameter("@sName", SqlDbType.VarChar);
paramItemDesc.Value = sqlItem;
InsertCommand2.Parameters.Add(paramItemDesc);
InsertCommand2.ExecuteNonQuery();
myConnection.Close();
// Stored
Procedure
SqlCommand
spCommand = new
SqlCommand();
spCommand.Connection =
myConnection;
spCommand.CommandText = "spTblTest";
spCommand.CommandType =
CommandType.StoredProcedure;
SqlParameter
spParam = new
SqlParameter("@sName", SqlDbType.VarChar);
spParam.Value = "blank1";
spCommand.Parameters.Add(spParam);
SqlDataReader
vDr;
vDr = spCommand.ExecuteReader();
// SqlDataAdapter
da = new SqlDataAdapter();
// da.SelectCommand
= spCommand;
// da.TableMappings.Add("Table","zz");
// DataSet
ds = new DataSet();
// da.Fill(ds);
//
dgExample.DataSource = vDr;
dgExample.DataBind();
Controls
DropDown/Radio etc…
DataGrid
DataList
Repeater
Data Grid
Note
out while loop
dgExample.DataSource
= vDr;
dgExample.DataBind();
mess with datagrid properties.
AutoGenerateColumns, alternatingitems/bgcolor,
header style etc…
Autogenerate does one simple thing – creates
a bound column for each field.
**DataBind must be in !Page.IsPostBack if
later events to avoid rebinding everything which clears your values that you
think you have.
AutoGenerateColumns vs. Bound Columns
I went out and
bought Transact SQL when I started working with .NET. Because auto generated
columns are so much simpler. So far 80% of the time I’ve thought I needed to do
Bound Columns I’ve been able to achieve the same in SQL utilizing stuff like
substring/case/datepart/etc…
Change
autogenerate columns to false and add HTML code
<Columns>
<asp:BoundColumn
DataField="tblTestName"></asp:BoundColumn>
<asp:BoundColumn
DataField="tblTestCol2">
<ItemStyle
BackColor="Red"></ItemStyle>
</asp:BoundColumn>
</Columns>
Rerun and show that we lost stuff (headers etc… )This is why I like to do things in SQL…
TemplateColumns – Use for special formatting (some can be done with bound columns) ie. Combine fields (can be done in Sql) add in string text (can be done in SQL) add in whole table inside of a column.
<asp:TemplateColumn >
<ItemTemplate><%#
DataBinder.Eval(Container.DataItem, "tblTestName")%> --- <%#
DataBinder.Eval(Container.DataItem, "tblTestCol2")%>
</ItemTemplate>
</asp:TemplateColumn>
Formatting for datagrid, BackColor, Font, CellPadding, CellSpacing, Wdth, Horizontal Align.
Styles – HeaderStyle, FooterSytle, ItemStyle, AlternatingItemStyle
It is possible to specify these bound columns programmatically, but it’s ugly and ton’s of code.
Formatting for bound columns, HeaderText, FooterText, HeaderStyle/FooterStyle/ItemStyle, DataFormatString
DataList
Slightly faster than DataGrid, but requires hand building of columns. And not quite as flexible in formatting
Add
in design view new datalist and change id to dlExample
Add
in HMTL
<asp:DataList id="dlExample"
style="Z-INDEX: 104; LEFT: 524px; POSITION: absolute; TOP: 150px"
runat="server" Height="61" Width="233">
<ItemTemplate>Item
Template Example</ItemTemplate>
<ItemTemplate>
<%#
DataBinder.Eval(Container.DataItem, "tblTestName")%>
---
<%#
DataBinder.Eval(Container.DataItem, "tblTestCol2")%>
</ItemTemplate>
</asp:DataList>
Add second dataareader to is not postback section
if(!Page.IsPostBack)
{
dgExample.DataSource = vDr;
dgExample.DataBind();
vDr.Close();
SqlDataReader
vDr2;
vDr2
= vCommand.ExecuteReader();
dlExample.DataSource
= vDr2;
dlExample.DataBind();
vDr2.Close();
}
More Data
DataSet
Disconnected like Recordset, but can hold multiple Tables.
DataAdapter
Used to populate DataSet
Stored Procedure
Parameters
Use to properly input Text field data into databases.
More DataGrid
Paging and Sorting
OnEditCommand, OnItemCommand
if(!Page.IsPostBack)
{
BindGridNow();
}
public void
DataGrid1_SelectedIndexChanged(object sender,
DataGridCommandEventArgs e)
{
strLaunchURL
= "true";
string strEndURL = e.Item.Cells[2].Text;
strURL = "http://www.cuppcondo.com/"
+ strEndURL;
//Response.Write("<script>top.returnValue='"
+ e.Item.Cells[1].Text + "'</script>");
}
public void dg_Edit(object sender, DataGridCommandEventArgs e)
{
dgExample.EditItemIndex = e.Item.ItemIndex;
this.BindGridNow( );
//this.DataBind( );
}
public void BindGridNow()
{
SqlConnection
myConnection;
myConnection
= new
SqlConnection("server=database;database=petrowebtest;uid=zz;pwd=zzz");
myConnection.Open();
//Binding to Datagrid from Dataset
string strSql = "select tblTestName as Name, tblTestCol2 as 'Column
2' from tblTest";
DataSet
dsLayers = new
DataSet();
SqlDataAdapter
daLayers = new SqlDataAdapter(strSql,myConnection);
daLayers.Fill(dsLayers);
dgExample.DataSource =
dsLayers;
dgExample.DataBind();
}
<script language=javascript>
<!--
if
('<%=strLaunchURL%>' == "true")
{
window.open('<%=strURL%>');
}
//-->
</script>
<form
id="FirstDaySql2" method="post"
runat="server">
<asp:DataGrid
id="dgExample" AutoGenerateColumns="False"
style="Z-INDEX: 101; LEFT: 183px; POSITION: absolute; TOP: 141px"
OnEditCommand="dg_Edit"
OnItemCommand="DataGrid1_SelectedIndexChanged"
runat="server">
<Columns>
<asp:ButtonColumn
ButtonType="PushButton" Text="testurl"
HeaderText="Details"></asp:ButtonColumn>
<asp:EditCommandColumn
EditText="edit"
CancelText="cance"></asp:EditCommandColumn>
<asp:BoundColumn
DataField="Name"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
3.*****************************************************************
Using
System.ServiceProcess
WebServices
Server
Create Web
Service Project Net101Service
Unnote Webmethod
code as directed
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
Client
Create
new file in our Webforms
Net101Web/ClientService.aspx
Add
web reference http://localhost/Net101Service/Service1.asmx
Add
Code
localhost.Service1 webServ = new localhost.Service1();
webServ.Url = "http://localhost/Net101Service/Service1.asmx";
Click
on URL and should see Tab “Service 1 Web Service”
Click
HelloWorld and Invoke and you should see XML run.
Feel
free to change Namespace to something like….
[WebService(Namespace="http://machineName/Copy_of_MaptesterService")]
change
Service1.asmx code to
[WebMethod]
public string
HelloWorld(string a)
{
return
"I updated database with " + a ;
}
add
lblService to ClientService
add
code to ClientService
lblService.Text = webServ.HelloWorld("bbb");
You
must build Service1 and updateReference on clientService
If
you add public class clsName : System.Web.Services.WebService
Then
you can access application, session, user and content objects
You
can also call webservcies synchronously or asynchronously
[WebService(Namespace="http://sql3srvr/Copy_of_MaptesterService")]
public class
Service1 : System.Web.Services.WebService
{
[WebMethod]
public void WSWriteToMaptester(string
sSql)
{
SqlConnection
myConnection = new
SqlConnection("server=database;database=petroweb;uid=zz;pwd=zzz");
myConnection.Open();
SqlCommand cmd = new SqlCommand(sSql.ToString(),
myConnection);
cmd.ExecuteNonQuery();
myConnection.Close();
}
}
localhost.Service1 RS1 = new localhost.Service1();
Class1 clsWrite = new Class1();
clsWrite.RS1.Url = "http://216.87.66.ZZZ/newMaptesterService/Service1.asmx";
strInsertSQL = "INSERT INTO maptester2(timedate,) VALUES ('"
+ str + "')";
clsWrite.RS1.WSWriteToMaptester(strInsertSQL);
4.******************************************
Event Handling
Server Side
DataGrid
– Auto
Most
Common double click button/control and eventfunction automatically build,
simply add event code
Label1.text = TextBox1.Text.ToString()
AutoCreation of this code
In web form designer
generated code…oninit
this.Button1.Click += new System.EventHandler(this.Button1_Click);
In class delclarations
protected System.Web.UI.WebControls.Button Button1;
private void Button1_Click(object sender, System.EventArgs
e)
{ }
To color row based on output
public void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
//not
header or footer rows..
if (e.Item.ItemType
== ListItemType.Item
|| e.Item.ItemType ==
ListItemType.AlternatingItem)
{
if (DataBinder.Eval(e.Item.DataItem,"Completion_Date","{0}") != "")
{
//((TableCell)e.Item.FindControl("tblCellStatus")).CssClass
= "tdNotRunning";
e.Item.BackColor = Color.Tan;
}
}
}
change Boolean to show x
string vmap = DataBinder.Eval(e.Item.DataItem, "map_failed", "{0}");
if(vmap == "1")
((Label) e.Item.FindControl("labelMapDown")).Text = "X";
!Postback…
AutoPostback Controls Non-Auto Postback Controls
Button Checkbox (list)
DataGrid Listbox
Image RadioButton(list)
Link DropDownList
DataList TextBox
Client Side
Javascript
sLoader = "javascript:window.close();";
Function Loader() { <% = sLoader %>//window.returnValue
= '<% =sLoader %>' // alert(" in sloader zoomgoto.aspx " + '<% = sLoader %>')
}
<BODY
onload="javascript:Loader()">
Client and Server
Do normal Server
and add to code behind
txtItemDes.Attributes.Add( "OnKeyUp","checklen()");
then add script code something like this
function checklen()
{ x =
document.recordUpdate.txtItemDes.value.length;
if (x >= 490)
{ alert("The maximum character length
for this field is 500 characters."); }
}
5.*******************************************************
Go to Definition Go to Reference
Start pages with numbers – dashes
Format align lefts, etc..
Wincv.exe – in c:\program files\microsoft visual studio .NET\FrameworkSDK\Bin
To deal with AppSettings
WebConfig or MachineConfig
<add key = “sqldata” value =”server=zeus;database=dbname;uid=sa;pwd=zzz;”/>
in aspx page
str Conn = ConfigurationSettings.AppSettings[“sqldata”];
In global.asax, or Machine.config, web.config you can setup things like
Custom errors, httpruntime maxrequestlength=”4096”, pages enableviewstate=”true”
Trace enabled=”true”
Other
Inheritance
C# public class Foo : Bar {
VB Public Class Foo : Inherits Bar
A few Other C# objects worth remembering
Convert
Math
DateTime
int
intstartDays = Convert.ToInt16(txtNumDays.Text);
decmyData5perc = Math.Round(decmyData5perc *
100, 2);
DateTime
dtToday =
DateTime.Now;
DateTime dtLast = dtToday.AddDays(intDays);
string strLast = dtLast.ToShortDateString();
switch (FirstName) {
case
"John" :
...
break;
case
"Paul" :
...
break;
case
"Ringo" :
...
break;
default:
...
break;
while
/ do
foreach
try/ Catch
try {
// Code
that throws exceptions
} catch(OverflowException e) {
// Catch a specific exception
} catch(Exception e) {
// Catch the generic exceptions
} finally {
// Execute some cleanup code
}
Practice Exercise for them to do.
Code for Practice 1
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
namespace Net101Web
{
/// <summary>
/// Summary description for
Practice1.
/// </summary>
public class
Practice1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnGo;
protected System.Web.UI.WebControls.Label lblError;
protected System.Web.UI.WebControls.DataGrid dgClasses;
protected System.Web.UI.WebControls.DropDownList ddlDate;
protected System.Web.UI.WebControls.RadioButtonList rblClasses;
private void
Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
// 1. Create 3 strings –Math, Physics, English
// 2. Use StringBuilder to create another sbClass
– History
// 3. Combine into a single string strAll;
// 4. Create string array strArrClasses and split
strAll into it.
// 5. Create RadioButtonList rblClasses and bind
alClasses to it.
// 6. Add button btnGo and grab selected radio
rblClasses.SelectedItem.ToString();
// 7. Insert new row into Database with
// 8. Create a DataGrid dgClasses
// 9. Get Datareader from table tblTest where tblTestName is in our previous arrayList and
bind to dgClasses
// 10. Format Header (fix names in SQL) and make every
other row grey and the header row black with white lettering.
//
// 11. Extra for fast kids, add a dropdownlist above
radio buttons called ddlDate
// 12. Create a string array with max of 3 ;s
// 13. Assign index 0 today’s date (hint: DateTime
object) – index 1 Tomorrow’s date, index 2 Yesterday’s date.
// 14. Bind array to ddl and when Go is clicked add
this item as second Column.
if(!Page.IsPostBack)
{
string strE = "English";
string strM = "Math";
string strP = "Physics";
StringBuilder
sbClass = new
StringBuilder();
sbClass.Append("History");
string strAll =
strE + "," +
strM + ","
+ strP + "," + sbClass.ToString();
string[] strArrClasses;
strArrClasses
= strAll.Split(',');
rblClasses.DataSource =
strArrClasses;
rblClasses.DataBind();
string[] strArrDate =
new string[3];
strArrDate[0]
= DateTime.Now.ToShortDateString();
strArrDate[1]
= DateTime.Now.AddDays(1).ToShortDateString();
strArrDate[2]
= DateTime.Now.AddDays(-1).ToShortDateString();
ddlDate.DataSource =
strArrDate;
ddlDate.DataBind();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form
Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for
Designer support - do not modify
/// the contents of this
method with the code editor.
/// </summary>
private void
InitializeComponent()
{
this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void
btnGo_Click(object sender, System.EventArgs e)
{
string strClass =
rblClasses.SelectedItem.ToString();
string strDate =
ddlDate.SelectedItem.ToString();
//lblError.Text = strTest;
SqlConnection
myConnection;
myConnection
= new
SqlConnection("server=database;database=petrowebtest;uid=zz;pwd=zzz");
myConnection.Open();
string vSql = "INSERT INTO tblTest(tblTestName,tblTestCol2) VALUES
('" + strClass + "','" + strDate + "')";
SqlCommand
InsertCommand = new
SqlCommand(vSql,myConnection);
InsertCommand.ExecuteNonQuery();
string strSql = "select tblTestName as Name, tblTestCol2 as 'Column
2' from tblTest";
SqlCommand
SelectCommand = new
SqlCommand(strSql,myConnection);
SqlDataReader
drSelect = SelectCommand.ExecuteReader();
dgClasses.Visible = true;
dgClasses.DataSource =
drSelect;
dgClasses.DataBind();
}
}
}
System.Web.Mail
SMTP Mail (Additionally
Try-Catch )
string strWorked = funcMail();
lblMail.Text = strWorked;
private string
funcMail()
{
try
{
StringBuilder
sbBody = new
StringBuilder();
sbBody.Append(" This is the
Body ");
MailMessage
nmMessage = new
MailMessage();
nmMessage.To = "ccupp@petroweb.com";
nmMessage.From = "ccupp@petroweb.com";
nmMessage.Subject = "How does this look....";
nmMessage.Body = sbBody.ToString();
nmMessage.BodyFormat =
MailFormat.Html;
SmtpMail.SmtpServer = "MailBox2";
SmtpMail.Send(nmMessage);
return "true";
}
catch(Exception ex)
{
return ex.ToString();
}
}
Questions!!!
label2.Font.Italic = true; (doesn’t work
not ‘settable’)
Radiobuttonlist for windows apps / Group box
“\r\n for label in xml section….
Title not working for XML section
No source safe?
Common database
Summary Time
Introduction
Talk about .NET
MSIL / CLR
Talk about String/StringBuilder/ Arrays/ ArrayList
Go over controls except Datagrid
Have them do exercise up to Data
System.IO
System.XML
QueryString
Debugging
Framework
System.Net
Data Access
Data Grid
Data List
Have them finish exercise
Depending on time, more datagrid/data access…