RSS

Category Archives: C# for Beginners

A place where I will post simple tutorials for those who are new to c#

When You Should Initialize Variables Conditionally

Here is an example of a variable you can initalize conditionally.

<pre>        public virtual T QueryString<T>(string name)
        {
            string queryParam = null;
            if (HttpContext.Current != null && HttpContext.Current.Request.QueryString[name] != null)
                queryParam = HttpContext.Current.Request.QueryString[name];

            if (!String.IsNullOrEmpty(queryParam))
                return CommonHelper.To<T>(queryParam);

            return default(T);
        }

now the reason you would want to intialize this conditonally is that no matter what the string is null unless
the if statements are met therefore assigning a value in the begining instead of in the else adds a step to the method that doesn’t have to be there. So do something more like this…

        public virtual T QueryString<T>(string name)
        {
            string queryParam;

            if (HttpContext.Current != null && HttpContext.Current.Request.QueryString[name] != null)
                queryParam = HttpContext.Current.Request.QueryString[name];
            else
                queryParam = null;

            if (!String.IsNullOrEmpty(queryParam))
                return CommonHelper.To<T>(queryParam);

            return default(T);
        }
 
Leave a comment

Posted by on April 18, 2012 in ASP.Net, C#, C# for Beginners

 

How Setting Up Web Config Transformation Files can Save you Time and Avoid Deployment Mistakes.

So let’s be honest, even if no one ever noticed because we caught it before the damage was done, We have all deployed a site with the developement connection string still in place. This and things like it happen when you manually set up your web config. Well heres the answer to things like that —

http://msdn.microsoft.com/en-us/library/dd465318.aspx

So what is Web Configuration Transformation, for those who don’t want to click yet I will explain. Transformation is a addon item to your web config file that allows you to declare items to be replaced based on the compilation type you set in your build type drop box at the top of your VS(Visusal Studio) IDE. So if I build in Release mode then the Web.Release.Config transformation file kicks in and replaces the values I told it to, in most cases for me this deals with connection strings to databases and names/addresses for web services. This is handy because you can include it in the svn check out and everyone has it so no more pesky ooops I forgot to change my connections just do it once, maintain it, and bam you sir are good to go.

 
Leave a comment

Posted by on March 12, 2012 in ASP.Net, C#, C# for Beginners

 

Tags: , ,

find the diffrence between 2 DateTimes in C# (DateDiff for you T-SQL Buffs)

SO many times you need to get the amount of time between 2 dates or you need to validate that the range between DateTimes is not within or beyond a certain amount of seconds,minutes,hours,days,months, and/or years. In T-SQL you get this info with the DateDiff function in c# we don’t have a function persay but the datetime type does have a method you can use to get it here is an example of the subtraction version.

//these are date time controls that we cast the values as date time
                et = (DateTime)EarliestCallDate.SelectedDate;
                lt = (DateTime)LatestCallDate.DbSelectedDate;
// now lets get the diffrence in days
            if (et > lt)
            {
                error.Text = "Earliest Call Date Cannot Be Less Than Latest Call Date.";
                return;
            }
            else if (lt.Subtract(et).Days > 1) // right here it is
            {
                error.Text = "Earliest Date and Latest Date must be in the same day";
            }

As you can see it is pretty simple the Return Type of lt.Subtract(et).Days is TimeSpan.Days. Well hopefully this helps someone until next time I post don’t let your code have a meltdown.

 
Leave a comment

Posted by on March 9, 2012 in C#, C# for Beginners

 

Tags: ,

My Default Helper Class

Just wanted to post what I have as my default helper class it is small just 2 methods but I use it in almost every project I do. the first one gets your connection string and the other executes a sql sommand that returns a table.

just fill in the catchs with your own error logging/handeling if you wish to do it or just leave it be and return null( I don’t recommend this but you can) and well there you go. use your helper class for any common code snippet you use over and over instead of writing the same thing all the time.

public class Helpers
    {
        /// <summary>
        /// Returns the current connection string
        /// </summary>
        /// <returns></returns>
        public SqlConnection getConnection()
        {
            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
            return Con;
        }

        /// <summary>
        /// Returns a DataTable, based on the command passed
        /// </summary>
        /// <param name="cmd">
        /// the SqlCommand object we wish to execute
        /// </param>
        /// <returns>
        /// a DataTable populated with the data 
        /// specified in the SqlCommand object
        /// </returns>
        /// <remarks></remarks>
        public DataTable GetDataTable(SqlCommand cmd)
        {
            try
            {
                // create a new data adapter based on the specified query.
                using (SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd })
                {
                    // create a new DataTable
                    DataTable dtGet = new DataTable();
                    //fill the DataTable
                    da.Fill(dtGet);
                    //return the DataTable
                    return dtGet;
                }
            }
            catch (SqlException ex)
            {
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }

        }
    }
 
Leave a comment

Posted by on March 9, 2012 in C#, C# for Beginners