.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