Please post your helpful functions (C# or VB.Net)

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
28,051
Reaction score
17,805
I'm fairly newish to C#(About 3 months) and I'm trying to put together a list of functions for every day use. Please post the ones you guys/girls find helpful and use often, either pre-defined or ones you've created. I'll start

I use this function to populate a DataTable.

Code:
        public DataTable GetRecords(String sql)
        {

            String myConnString = ConfigurationManager.ConnectionStrings["Connection"].ToString();
            SqlConnection myConnection = new SqlConnection(myConnString);
            SqlCommand myCommand = new SqlCommand();

            myCommand.CommandType = CommandType.Text;
            myCommand.Connection = myConnection;
            myCommand.CommandText = sql;

            try
            {

                myConnection.Open();
                DataTable tbl = new DataTable();
                SqlDataAdapter sqlDataReader = new SqlDataAdapter();

                sqlDataReader.SelectCommand = myCommand;
                sqlDataReader.Fill(tbl);

                return tbl;
            }

            catch (Exception ex)
            {

                throw ex;

            }

            finally
            {

                myConnection.Close();

            }

        }

USE

Code:
string sql = "SELECT * From tblPersons WHERE User_ID = '12345'";
DataTable tbl = new DataTable();
tbl = GetRecords(sql);
 
Convert it to an extension method to make it more elegant.
 
i'm not going to comment on your data access.
i will say you should rewrite that in 2 lines, simply going

Code:
string sql = "SELECT * From tblPersons WHERE User_ID = '12345'";
DataTable tbl = GetRecords(sql);

@sem i was also thinking about extensions, but its a bit weird taking in an empty data table and then returning another datatable? unless its a string extension...

change the method signature to this :

Code:
 public static DataTable GetRecords(this String sql)

Code:
string sql = "SELECT * From tblPersons WHERE User_ID = '12345'";
DataTable tbl = sql.GetRecords();
 
Last edited:
(can't help it)
beer is there a reason you're working with datatables and stuff directly?
are you doing web or windows forms stuff?

I'm not sure about the first question. It's a windows forms project. I'm basically using the datatable to build an xml manifest. Here is a basic example.

Code:
  try

            {

                myConnection.Open();
                SqlDataReader sqlDataReader = myCommand.ExecuteReader();


                if (sqlDataReader.HasRows)

                {

                    while (sqlDataReader.Read())

                    {

            string xml;

            xml = "<report>";
            xml = xml + "<reporting_person>";
            xml = xml + "<first_name>" + tbl.Rows[0]["FirstName"].ToString().Trim() +"</first_name>";
            xml = xml + "<last_name>" + tbl.Rows[0]["Surname"].ToString().Trim() + "</last_name>";
            xml = xml + "</reporting_person>";
            xml = xml + "</report>";

                     }
                   
                }

                return "";

            }
            

            catch (Exception ex)
            {


                throw ex;
              
            }
            finally
            {

                
                myConnection.Close();
            }
 
Last edited:
Here's some I once used in a web project I was doing:

Code:
    public static class StringExtentions
    {
        /// <summary>
        /// Taken from: http://stackoverflow.com/questions/7567689/how-to-limit-the-description-text-to-100-150-words-using-razor
        /// </summary>
        /// <param name="text"></param>
        /// <param name="chopLength"></param>
        /// <param name="postfix"></param>
        /// <returns></returns>
        public static string Chop(this string text, int chopLength, string postfix = "...")
        {
            text = text.RemoveHtmlElements();
            text = text.Replace(Environment.NewLine, string.Empty);
            if (text == null || text.Length < chopLength)
            {
                return text;
            }
            else 
            {
                return text.Substring(0, chopLength - postfix.Length) + postfix;
            }
        }

        /// <summary>
        /// Adapted from http://www.c-sharpcorner.com/Blogs/3532/remove-html-tags-from-string-in-C-Sharp.aspx
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string RemoveHtmlElements(this string text)
        {
            Regex tags = new System.Text.RegularExpressions.Regex("<[^>]*>");
            Regex characters = new System.Text.RegularExpressions.Regex("&[^;]*;");
            
            // replace all matches with empty string
            text = tags.Replace(text, string.Empty);
            text = characters.Replace(text, string.Empty);

            return text;
        }

        /// <summary>
        /// Adapted from http://www.ehsanghanbari.com/Post/20/how-to-create-urlslug-in-aspnet-mvc
        /// </summary>
        /// <param name="title"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string GenerateSlug(this string title, int maxLength = 100)
        {
            string str = title.ToLower();
            str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
            str = Regex.Replace(str, @"[\s-]+", " ").Trim();
            str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim();
            str = Regex.Replace(str, @"\s", "-");
            return str;
        }
    }
 
Here's one I needed to get a DateTime to UnixTimestap:
Code:
    public static class DateTimeHelper
    {
        /// <summary>
        /// Adapted from http://stackoverflow.com/questions/17632584/how-to-get-the-unix-timestamp-in-c-sharp
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Int32 ConvertToUnixTimestamp(DateTime value)
        {
            Int32 unixTimestamp = (Int32)(value.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            return unixTimestamp;
        }
    }
 
beer dude (i'm about to get way off topic)
lets think about that method right there.

you obviously need to build some sort of xml abomination and you need to populate this from the db.
in order for that to happen you need the following :

#1 load the rows from the db (with whatever that entails)
#2 take those rows, build the xml structure and return it

now single responsibility principle (SRP) kind of means we should handle those seperately and maybe have 2 methods and possibly (probably) even more.

method 1 should return a bunch of rows from the DB, preferably in some sort of class collection like a list or something.
method 2 should worry about turning that list of stuff into the xml you're looking for.

so i would define a class person.
i would have a loadPeople method that returns a List<People>
i would have a generateXMLFromPeople method that takes in this list and returns the xml.

a good sort of general rule is that you make each method do only one thing. thats it.
the more methods you have the better. some people even say try not to have a method longer than 7 statements. how weird is that. its just a guideline to get you always thinking about whether or not you're doing too much.

also you shouldn't be mixing in your "db" data layer stuff with your "business logic" stuff. you should sort of be creating these layers of seperation between them. thats why im kinda surprised you're using data tables and a sql connection right there in your code next to the xml stuff. first off because its a really old way of working with your db's that bypasses objects entirely (and object oriented programming kicks ass 99% of the time) and also because its sitting right in the middle of everything else.

even building actual strings of sql to do queries is kind of old school. if you're really into sql and all the performance you can get from it there are still tools and solutions you can use to make it a lot more elegant, things like massive or dapper or other micro orm's.

this might be a good fit for your current solution and maybe i'm reading it wrong, but either way i'd maybe have a glance over these links just in case.

http://en.wikipedia.org/wiki/Single_responsibility_principle
http://programmers.stackexchange.co...thods-shouldnt-contain-more-than-7-statements
http://codebork.com/2011/02/02/revisiting-solid-principles-srp-methods.html
http://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET
 
Last edited:
Why aren't you disposing of that command object?

Also, doesn't that SQLAdapter implement IDisposable?

Sorry but please don't encourage anyone to use that.
 
Last edited:
beer dude (i'm about to get way off topic)
lets think about that method right there.

you obviously need to build some sort of xml abomination and you need to populate this from the db.
in order for that to happen you need the following :

#1 load the rows from the db (with whatever that entails)
#2 take those rows, build the xml structure and return it

now single responsibility principle (SRP) kind of means we should handle those seperately and maybe have 2 methods and possibly (probably) even more.

method 1 should return a bunch of rows from the DB, preferably in some sort of class collection like a list or something.
method 2 should worry about turning that list of stuff into the xml you're looking for.

so i would define a class person.
i would have a loadPeople method that returns a List<People>
i would have a generateXMLFromPeople method that takes in this list and returns the xml.

a good sort of general rule is that you make each method do only one thing. thats it.
the more methods you have the better. some people even say try not to have a method longer than 7 statements. how weird is that. its just a guideline to get you always thinking about whether or not you're doing too much.

also you shouldn't be mixing in your "db" data layer stuff with your "business logic" stuff. you should sort of be creating these layers of seperation between them. thats why im kinda surprised you're using data tables and a sql connection right there in your code next to the xml stuff. first off because its a really old way of working with your db's that bypasses objects entirely (and object oriented programming kicks ass 99% of the time) and also because its sitting right in the middle of everything else.

even building actual strings of sql to do queries is kind of old school. if you're really into sql and all the performance you can get from it there are still tools and solutions you can use to make it a lot more elegant, things like massive or dapper or other micro orm's.

this might be a good fit for your current solution and maybe i'm reading it wrong, but either way i'd maybe have a glance over these links just in case.

http://en.wikipedia.org/wiki/Single_responsibility_principle
http://programmers.stackexchange.co...thods-shouldnt-contain-more-than-7-statements
http://codebork.com/2011/02/02/revisiting-solid-principles-srp-methods.html
http://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

I do like that Three Layer architecture. Data, Business and Presentation. It makes a lot of sense. I don't have time to change the project over at the moment but that's something I'll implement with another up and coming project.
 
beer dude (i'm about to get way off topic)
lets think about that method right there.

you obviously need to build some sort of xml abomination and you need to populate this from the db.
in order for that to happen you need the following :

#1 load the rows from the db (with whatever that entails)
#2 take those rows, build the xml structure and return it

now single responsibility principle (SRP) kind of means we should handle those seperately and maybe have 2 methods and possibly (probably) even more.

method 1 should return a bunch of rows from the DB, preferably in some sort of class collection like a list or something.
method 2 should worry about turning that list of stuff into the xml you're looking for.

so i would define a class person.
i would have a loadPeople method that returns a List<People>
i would have a generateXMLFromPeople method that takes in this list and returns the xml.

a good sort of general rule is that you make each method do only one thing. thats it.
the more methods you have the better. some people even say try not to have a method longer than 7 statements. how weird is that. its just a guideline to get you always thinking about whether or not you're doing too much.

also you shouldn't be mixing in your "db" data layer stuff with your "business logic" stuff. you should sort of be creating these layers of seperation between them. thats why im kinda surprised you're using data tables and a sql connection right there in your code next to the xml stuff. first off because its a really old way of working with your db's that bypasses objects entirely (and object oriented programming kicks ass 99% of the time) and also because its sitting right in the middle of everything else.

even building actual strings of sql to do queries is kind of old school. if you're really into sql and all the performance you can get from it there are still tools and solutions you can use to make it a lot more elegant, things like massive or dapper or other micro orm's.

this might be a good fit for your current solution and maybe i'm reading it wrong, but either way i'd maybe have a glance over these links just in case.

http://en.wikipedia.org/wiki/Single_responsibility_principle
http://programmers.stackexchange.co...thods-shouldnt-contain-more-than-7-statements
http://codebork.com/2011/02/02/revisiting-solid-principles-srp-methods.html
http://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET

good advise.

What I have been doing lately with guys here, to stop them writing spaghetti code, besides frequent code reviews), is to force implement TDD (I have done a complete u-turn on this, TDD is indeed awesome :) ). Try testing code like that, and you will quickly realize you need to refactor it out into manageable chunks.

TDD is part of their KPI.
 
:D tdd dude. tdd.

my new job involves a lot of code reviews and stuff.
i've seen button clicks with literally 100's of lines (1200 is my record so far) and one of first things i did when trying to get people to refactor was have them turn away, let me introduce a random exception and then let them guess what the error was based on the stacktrace.

apprently its easier when the callstack is
buttonClick => generateForm => handleLogic => loadRows => callDB => getConnectionString (exception thrown)

rather than just a buttonClick (exception thrown)
 
I'm not sure about the first question. It's a windows forms project. I'm basically using the datatable to build an xml manifest. Here is a basic example.
/snip

Here's some advice along the same lines. Use an lightweight ORM (also look at ORM lite from servicestack V3), to load up your objects.

Then create a projection of those data objects into the object that will hold all the xml properties. Make the projection class serialize-able. See linky

That way, you don't need to write the serialization to XML since .Net gives it to you for free.
 
Should I get myself a book on Entity Framework?
 
I think a book on assisted suicide would be more informative.

That is a bit harsh...

Beerisgood, may I suggest that you go back to the drawing board and start reading up about good software development practices before writing another line of code.

The code you have written here really isn't suitable for a professional production environment. You show a severe lack of understanding of what it takes to write decent code.

You cannot handcraft XML like that. You need to dispose of unmanaged resources. You need to understand what an immutable object is and why you use a string builder instead od using string concatenation.

Please remove that first post of yours because if anyone does a search engine search and comes up with that as a viable result and copies it you are just going to make real software developers lives that much more difficult when they inevitably have to rewrite it.
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X