.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.
Using System
Most Basic Project
setup
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.
Array
/ ArrayList
Array
List had Dynamic Resisizing
:Add method so you don’t have to keep
track of last index.
:Remove/ RemoveAt / RemoveRange Method
:Sort
Also properties: Count
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.
Basic, 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
.Text
is most commonly used Property
TextBox
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.
Buttons / ImageButtons / Link Buttons
RadioButtons
SelectedItem most commonly used property
ComboBox / DropDowns
SelectedItem most commonly used property
ListItem and ListItemCollection
are two key objects for interfacing with List Controls
**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
Using System.IO
StreamReader
The Base class is the StreamReader,
but the functionality of the TextReader and XMLReader are very similar.
Key code to remember: stringreaderExample.Peek()>-1
1||Red||E
2||Blue||W
3||Green||E
Using System.XML
Key code: SelectNodes
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 ( )..
Sample XML
<?xml version='1.0' encoding='ISO-8859-1'?>
<catalog>
<cd
country='
<title>Empire
Burlesque</title>
<artist>Bob
Dylan</artist>
<price>10.90</price>
</cd>
<cd
country='
<title>Hide
your heart</title>
<artist>Bonnie
Tyler</artist>
<price>9.90</price>
</cd>
<cd
country='
<title>Greatest
Hits</title>
<artist>Dolly
Parton</artist>
<price>9.90</price>
</cd>
</catalog>
State / Request / QueryString
Key code: 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%>’)
In order to hold a value through
multiple postbacks putting an
variable in to “ViewState” is often the simplest way
to go.
Application level state can be
controlled through global.asax
Session Level state can
be controlled using Session[“anyvarname”]
Debugging
Debugger
Trace
Trace.Write(strTemp)
Trace=true
Response
Can still use, but must
be perfect syntax
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 mouse 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
Design View Format –
Align lefts, Make same size, snap to grid
+= works
in c# and vb.
Using System.Net
HttpWebResponse
Key objects – HttpWebRequest,
HttpWebResponse.
Sample 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();
Using System.Data
/ System.Data.SqlClient
Data
Access
ADO.NET is very similar looking to
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
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.
More
Controls
DataGrid, DataList, Repeater
**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
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.
More Data
DataSet
Disconnected like Recordset, but can hold multiple Tables.
DataAdapter
Used to populate DataSet
Stored
Procedure
Command.CommandType = CommandType.StoredProcedure;
Command.ComandText = “spTblTest”;
Parameters
Use to properly input Text field
data into databases.
SqlParameter spParam = new SqlParameter("@sName",
SqlDbType.VarChar);
spParam.Value = "blank1";
spCommand.Parameters.Add(spParam);
Using System.ServiceProcess
WebServices
Create webservice
.asmx page using prewritten code
Create
call to it by adding web reference and
localhost.Service1 webServ = new localhost.Service1();
webServ.Url = "http://localhost/Net101Service/Service1.asmx";
You should be able to click on the url and see the available
services.
Event Handling
Server
Side
DataGrid
– Auto
Most Common double click
button/control and event function automatically build, simply add event code
Must utilize !Postback… in PageLoad
to avoid binding rebinding on events and losing your event args.
AutoPostback Controls Non-Auto Postback Controls
Button Checkbox
(list)
DataGrid Listbox
Image RadioButton(list)
Link DropDownList
DataList TextBox
Client
Side
Javascript
just like asp
To add javascript event to a server side control add the following
to code behind
txtItemDes.Attributes.Add( "OnKeyUp","checklen()");
A few Other C# objects worth
remembering
Convert
Math
DateTime
ListItem
/ ListItemCollection
Practice Exercise.