RSS

Monthly Archives: February 2012

How to avoid If statements by using inline comparison with c#

So Another thing I see alot of especialy from jr devs is a if statment that changes the way you load a object based on on of the items being refrenced to load that object with data take the following example

DeliveryCompanyInfo.Columns.AddRange(new DataColumn[]
{
	new DataColumn("CompanyName"),
	new DataColumn("Name"),
	new DataColumn("Phone"),
	new DataColumn("Address1"),
	new DataColumn("Address2"),
	new DataColumn("City"),
	new DataColumn("State"),
	new DataColumn("Zip")
});
if (string.IsNullOrEmpty(txtToAddress2.Text))
{
       DeliveryCompanyInfo.Rows.Add(DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, " ", txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);
}
else
{
DeliveryCompanyInfo.Rows.Add(DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, txtToAddress2.Text, txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);
}</pre>

This is bad because it puts in a unneeded switch and adds complexity to maintenance instead do this

DeliveryCompanyInfo.Rows.Add( DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, (string.IsNullOrWhiteSpace(txtToAddress2.Text)) ? " " : txtToAddress2.Text , txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);

this does the change inline by doing a comparison that returns a bool and then inserting the proper value based on the result the basic function is like this

(Boolean) ? (TrueValue):(FalseValue)

pretty simple huh? so if you can use this and avoid if statements also you can use multiple comparisons using the || or && in the Boolean block.

 
Leave a comment

Posted by on February 29, 2012 in C#

 

If its important add it to a session

So, allot of time I see a variable that is the exact same used many times throughout a web page. This in itself is not a problem but actually very common when you work in a web environment with business web apps. The problem comes in when you constantly retrieve that value over and over instead of storing it in the session so lets say when i log in i go to a page that has me select the client company who’s data I wish to manipulate and then move on. This is a variable used in 5 pages and if i wish to change it i have to go and use a dropdown or some other control w/e it stays the same until I change it in a single master control.
This should be saved in a session variable I should not have to set it every time i load a new variable and I should only have to select a new company when I actually want to change my client company. So guys learn to do this you may not be a webdev but at least understand the basic concept.

example of saving a value

Session["testcompany"] = ddlCompany.SelectedValue;

example of saving a whole object

DataTable mycompany = new DataTable();

//fill the data table with you company info

Session["mycompany"] = mycompany;

now until the user terminates the session the information for the selected company and the actual company selected is saved.

 
Leave a comment

Posted by on February 29, 2012 in ASP.Net, C#

 

Tags: , ,

Using Sting.Format instead of building a string through manual concatenation

when you use concatenation to build a string instead of string format c# creates (a) extra String Object(s) so instead use this it is more efficent overall

instead of

cmd.CommandText = "SELECT * FROM addresses WHERE Zip LIKE '" + delZip.Trim() + "%'";

Do this

cmd.CommandText = String.Format("SELECT * FROM addresses WHERE Zip LIKE '{0}%'", delZip.Trim());

The code is more readable you have one string that is legible without all the breaks and pluses and the like. This allows me to read the string and then see what variables are being put into the placeholders (probably not the correct technical term but you get the point).

 
Leave a comment

Posted by on February 28, 2012 in C#

 

How to add multiple columns at once to a DataTable Object using C# and AddRange

So instead of creating 20 DataTable.Columns.Add statements use add range and use a array of columns and some copy pasta magic like the following

DeliveryCompanyInfo.Columns.AddRange(new DataColumn[]
{
new DataColumn("CompanyName"),
new DataColumn("Name"),
new DataColumn("Phone"),
new DataColumn("Address1"),
new DataColumn("Address2"),
new DataColumn("City"),
new DataColumn("State"),
new DataColumn("Zip"),

});

Work smarter not harder. If you have to define a table with more then 2 or three columns use this for maintainability, proper disposal, legibility, and productive use of time.

 
Leave a comment

Posted by on February 28, 2012 in C#

 

Adding multiple parameters all at once to a SqlCommand using AddRange

So rarely does a Stored Procedure take just one argument and well typing the same thing over and over and over can be a pain so what to do? use AddRange and create a array of sql command using simple syntax and copy pasta

 using (SqlCommand cmd = new SqlCommand() { CommandType = CommandType.StoredProcedure, Connection = connString, CommandText = "Exec Card_Add_Company" })
{
cmd.Parameters.AddRange(new SqlParameter[]
{
new SqlParameter("@Example",NewExampleInfo.Rows[0]["CompanyName"].ToString()),
new SqlParameter("@Example_Contact",NewExampleInfo.Rows[0]["Name"].ToString()),
new SqlParameter("",[ControlNameHere]),
new SqlParameter("",[ControlNameHere])
})

Using this then filling in the blanks can save you quite a bit of time and you get those 13-20 something variables out of the way in no time for me it was only nine so i made 9 SqlParameters in the add range statement and bam love is in the air. Make a custom snippet for this to use with intelisense and you are golden.

 
Leave a comment

Posted by on February 28, 2012 in C#, SQL