C#
WebForms
TextBoxes
You can restrict length using maxlength
property unless you set property textmode=multiline then the textbox is output in HTML as a textarea for which there is no maxlength
property. Instead just created javascript function
called from the textbox called ontextchanged; to
access a javascript function from a server control
you must input this code in the c#
if(!Page.IsPostBack)
{
txtDescription.Attributes.Add( "OnKeyUp","checklen()");
}
DropDownList
Properties
Properties like visible in Design
Properties Manager is Capatalized Visible = False;
But in c# code false is
lowercase
Application
Application.DoEvents(); // processes previous
instructions (like changing a label to In Process….)
Arrays
string[]
myStrings = new string[3];
string[] Words =
strOriginalValue.Split('.');
(In C# you cannot split on a string only a char-so only a
single character, you can do a replace on a string and change it to a char(like
a |))
Array List
ArrayList arrList = new ArrayList(50);
arrList.Add("http://www.hub.slb.com/Docs/NSA_TZ_Data_Sales/lafourche.pdf");
arrList.Count
to
bind to DropDownList
ddlProjectName.DataSource=alProj;
to get back out
for(int i2=0;i2<alBad.Count;i2++)
{
string
tester =
alBad[2].ToString();
twB.Write (alBad[i2].ToString()+
"\r\n");
}
Date
Current Date/Time - DateTime.Now.ToString()
Current Date - DateTime.Now.ToShortDateString();
DateTime dtstr =
DateTime.Now;
TimeSpan diff = dtstr.Subtract(fiFile.CreationTime);
dttmCompare2
= Convert.ToDateTime(myDataReader5["timedate"].ToString());
tmspCompare
= dttmCompare.Subtract(dttmCompare2);
intDiff
= tmspCompare.TotalMinutes;
if
(intDiff > 5)
Database
Access
using System.Data.SqlClient;
SqlConnection myConnection;
string strSqlConnect
= "server=database;database=mms_data;uid=sa;pwd=19wazee";
myConnection
= new SqlConnection(strSqlConnect);
myConnection.Open();
SqlCommand myCommandddl2;
string
sql = " select * from tablename";
myCommandddl2 = new SqlCommand(sql,myConnection);
SqlDataReader
myDataReaderddl3 = myCommandddl2.ExecuteReader();
while
(!myDataReaderddl3.Read())
{
deleteString
=myDataReaderddl3["plan_ctrl_num"].ToString();
}
-----------------------------------------------------------
string
selectSql2 = "SELECT
count(*) FROM maptester” SqlCommand myCommand2;
myCommand2 = new SqlCommand(selectSql2,myConnection);
string
myData2 = myCommand2.ExecuteScalar().ToString();
----------------------------------------------------------
myConnection.Open();
strSql =
"update TblRequestTopFive
set RequestSubmitted = '1' where requestClientName
= '" + sName
+ "'";
SqlCommand comCommand2 = new SqlCommand(strSql,myConnection);
comCommand2.ExecuteNonQuery();
------------------------------------------------------------
DataGrid
private void
DataGrid4_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs
e)
{
// In Recent Results Turn rows
red if the map is down.
if
(e.Item.ItemType == ListItemType.AlternatingItem
|| e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.EditItem || e.Item.ItemType == ListItemType.SelectedItem)
{
string
vworked = DataBinder.Eval(e.Item.DataItem,
"worked", "{0}");
if(vworked == "NO")
((Label)
e.Item.FindControl("Label7")).BackColor = Color.Red;
Event Handling
Make sure bind is in !postback or else event handler won’t work.
Exception Handling
Try
{}
catch(Exception vE)
{
string vExceptMsg;
vExceptMsg
= vE.ToString();
}
private class cException
: System.Exception
{
private string
m_Message = "";
public cException(string message)
{
m_Message = message;
}
public override
string ToString()
{
return m_Message;
}
}
Email
using System.Web.Mail;
string sTo =
"ccupp@petroweb.com";
string sFrom
= "ccupp@petroweb.com";
string sSubject
= "The C# Map
program failed somewhere ";
string sBody
= "The C# Map
program failed somewhere " + vStatusMsg;
SmtpMail.SmtpServer = "MailBox2";
SmtpMail.Send(sFrom,sTo,sSubject,sBody);
Or
MailMessage nmMessage
= new MailMessage();
nmMessage.To
= "ccupp@petroweb.com,
pwalsh@petroweb.com";
nmMessage.From
= "pwalsh@petroweb.com";
nmMessage.Subject
= "How does
this look... petroWEB map.";
nmMessage.Body
= sbBody.ToString();
nmMessage.BodyFormat = MailFormat.Html;
SmtpMail.SmtpServer
= "MailBox2";
SmtpMail.Send(nmMessage);
Switch
switch(myChoice)
{
case
"A":
Console.WriteLine("You wish to add an
address.");
break;
default:
Console.WriteLine("{0}
is not a valid choice", myChoice);
break;
}
ForEach
string[]
names = {"Cheryl", "Joe", "Matt",
"Robert"};
foreach (string person in names)
{
Console.WriteLine("{0} ", person);
}
XML
using System.Xml;
//Instanciate an XMLDocument object
XmlDocument doc = new XmlDocument();
//Load the doc (parses at the same time apparently)
doc.Load(reader);Selectnodes()
XmlDocument doc = ReadXMLFromString(strRequest);
XmlNodeList nodes = doc.GetElementsByTagName("ENVELOPE");
File Objects
using System.IO;
DirectoryInfo()
FileInfo()
foreach(FileInfo fiFile
in dirDirect.GetFiles())
{
for(z=0;z<arrFileList.Count;z++)
{
fiFile.MoveTo(strNewPath + arrFileList[z]);
}
}
TextReader tr =
new StreamReader(fileloc +
filenm);
while (tr.Peek()>-1)
//if line exists
{
sLine =
tr.ReadLine();
}
//close the stream
tr.Close();
TextWriter tw = new StreamWriter("../../testing.txt");
tw.Write (sb.ToString());
tw.Close();
WebRequest vReq = null;
WebResponse vResult = null;
StreamReader vStreamReader = null;
Stream
vReceiveStream = null;
Encoding
vEncoding = Encoding.GetEncoding("UTF-8");
vReq =
WebRequest.Create(strURL);
vReq.Method = "GET";
vResult =
vReq.GetResponse();
vReceiveStream = vResult.GetResponseStream();
vStreamReader = new StreamReader(vReceiveStream, vEncoding);
strAxlResponse = vStreamReader.ReadToEnd();
vResult.Close();
vStreamReader.Close();
String
– StringBuilder
string bodytext = "",
line;
StringBuilder noString =
new StringBuilder();
noString.Append( "No
List \r\n");
sb.AppendFormat("L,\"{0}\",\"{1}\",{2}\r\n", sName.Trim(), sName.Trim(), namecount);
References
Must add references if not available (ie. System.Web.Mail for Console apps)
Just right click add reference
For web references for WebServices.
Regular Expressions
string[] arCols = Regex.Split(sLineBig,"<td");
if(Regex.IsMatch(arCols[y],"table"))
split – regex can split on a
string where string can only do it on a char
This is important for parsing HTML
HttpWebRequest – HttpWebResponse
//simpler
way
string strURL
= "http://www2.petroweb.com/UpaaLogin.aspx?ReturnUrl=%2fDefault.aspx";
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(strURL);
/HttpWebRequest
HttpWReq = (HttpWebRequest)WebRequest.Create("http://www.cuppcondo.com");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
string
stringResult2;
using
(StreamReader sR2 = new StreamReader(HttpWResp.GetResponseStream()))
{
stringResult2 = sR2.ReadToEnd();
sR2.Close();
}// Insert code that uses the
response object.
HttpWResp.Close();
stringResult2 +="";
if(stringResult2.IndexOf("password")>0)
//
end of simple….
HttpWebRequest httprequest;
HttpWebResponse httpresponse;
Uri responseUri
= null, requestUri;
StreamReader bodyreader;
requestUri = new Uri(arrList[x].ToString());
//create the web request.
httprequest = (HttpWebRequest) WebRequest.Create(requestUri);
//fill in the properties of the request. All properties
//are optional
//allow auto redirects from redirect headers
httprequest.AllowAutoRedirect=true;
//maximum of 10 auto redirects
httprequest.MaximumAutomaticRedirections=10;
//use the GET method
httprequest.Method="GET";
//use HTTP/1.0
httprequest.ProtocolVersion=new Version(1,0);
//30 second timeout for request
httprequest.Timeout=(int) new TimeSpan(0,0,20).TotalMilliseconds;
//give the crawler a name.
httprequest.UserAgent="Mozilla/3.0
(compatible; My Browser/1.0)";
//retrieve the response from the requestUri.
httpresponse = (HttpWebResponse) httprequest.GetResponse();
//remember the url
that responded because it may not
//be the same as the input url because of the autoredirect
//property setting above.
responseUri = httpresponse.ResponseUri;
//get the body stream of the requested page.
responsestream = httpresponse.GetResponseStream();
if (responsestream
!= null)
{
//read the stream and build it into a string
//representing the body of the web page.
bodyreader = new StreamReader(responsestream);
//loop the body, reading line by line
while((line=bodyreader.ReadLine())!=null)
{
bodytext+=line+"\r\n";
}
//close the body stream
bodyreader.Close();
//cleanup
bodyreader = null;
}
//close response which cleans up the socket used to
//retrieve the page.
httpresponse.Close();
//cleanup
httpresponse = null;
httprequest = null;
WebServices
private
localhost.Service1 RS;
localhost.Service1 RS1 = new localhost.Service1();
RS1.Url = "http://216.87.66.115/newMaptesterService/Service1.asmx";
RS1.WriteToMaptester(strInsertSQL);