Wednesday, October 23, 2013

Simple SQL connection

Hi everyone,
In a case you need to create fast and simple SQL connection and get some data from it, there is a nice solution for you :) I won't discuss whether it is appropriate approach or not. This is just about to get your data in fast way without hassling about connection strings or web. configs. So please keep that in mind when you use it ;)

string Server = "<yourServer.com>";
string DB = "<yourDatabaseName>";
string connectionString = "Data Source=" + Server + ";Initial Catalog=" + DB + ";user id=<username>;password=<userPassword>";
DataTable dataTable = new DataTable();

using (SqlConnection conn = new SqlConnection(connectionString))
{
    //Open connection
    conn.Open();

     //Set SQLCommand
     using (SqlCommand cmd = new SqlCommand(<YourSQLcommand>, conn))
                    {
                        using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
                        {
                            //Use SQL Command
                            sqlDataAdapter.SelectCommand = cmd;
                            try
                            {
                                //Fill DataTable
                                sqlDataAdapter.Fill(dataTable);
                            }
                            catch (Exception ex)
                            {
                                <handle errors here>
                            }
                        }
                    }
}
This is it.. hope it helps ;)

Tuesday, January 29, 2013

How to remove diacritic

Hi,
I guess that everyone whom comes from Czech or Slovakia or at least works there needs remove diacritics time to time. Actually there is quite easy solution for this:

// using System.Globalization
public static string RemoveDiacritics(string s) {
    s = s.Normalize(NormalizationForm.FormD);
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.Length; i++) {
        if (CharUnicodeInfo.GetUnicodeCategory(s[i]) != UnicodeCategory.NonSpacingMark) sb.Append(s[i]);
    }

    return sb.ToString();
}


I won't describe the solution here 'cause you can find the original source here http://www.aspnet.cz/articles/92-jak-spolehlive-odstranit-v-net-z-retezce-diakritiku
It's in Czech, but all things are easily to find on the MSDN.

happy codding...