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...

Thursday, November 10, 2011

Converting string to literal

Recently I need it to solve the issue how to convert string to literal. My demands were simple. I get string value from somewhere (SharePoint list) then I needed to convert this string to literal. It is really simple to do it by @ sign, but this doesn't work when you obtain value from some source.
For better understanding here is example:
This works fine:
        string sValue = @"This is \nexample."; 
and this doesn't :
        static class MyClass
        {
            public static string myString = "This is \nexample.";   
        }


        static void Main(string[] args)
        {
            string myString = @MyClass.myString;
            Console.WriteLine(myString);
            Console.WriteLine("Press Enter to continue...");
            Console.ReadLine();
        }


If you don't know what @ is for, lets have look here.

After all searching and trying I finally found solution on stockOverflow:
Here is the link and here is the code snippet:

static string ToLiteral(string input)
    {
        var writer = new StringWriter();
        CSharpCodeProvider provider = new CSharpCodeProvider();
        provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
        return writer.GetStringBuilder().ToString();
    }
I have to thank Hallgrim for this code 'cause it really saved me :)

Wednesday, November 9, 2011

List of colors

Sometimes is needed to customize page programmatically. In that case the list of colors with names, codes and examples would be helpful I guess :)
This web contains them and helped me:
http://web.njit.edu/~kevin/rgb.txt.html

LINQ and System.NullReferenceException

LINQ is very useful, but it was also cause of my problems. I think almost everybody already have seen this exception: System.NullReferenceException: Object reference not set to an instance of an object. You can google it and I think you would find many useful information :) But it was not useful for me at all. I was stuck for some hours with this error message.
The reason was simple. Before some months ago I created application with connect to database and I was using LINQ to querying. I made some simple query like this:

var query =  from table in sql08.minussevenshorts
                    where table.DATUM == yesterday
                    group table by table.order into g
                    select new
                    {
                        FirstColum = g.Key,
                        CountOfOrders = (g.Sum(p => p.MONEY) / g.Sum(p => p.STUFFS)),
                    };
everything works fine so I was satisfied at the moment. But after some months the error occurred and I didn't know reason at all. I checked my source code and database was only place where could be a problem. As I thought this really was cause of error because if you look at CountOfOrders column, there is not any condition which prevent before dividing by zero. When I was programming application I didn't even expecting that g.Sum(p => p.STUFFS) could return zero but data was changed when time goes by. I added simple condition and everything works fine now. Here it is:
CountOfOrders = (g.Sum(p => p.STUFFS) == 0 ? 0 : g.Sum(p => p.MONEY) / g.Sum(p => p.STUFFS)),

So this really was lesson for me. You should not trust that data will be same as you are expecting it. So check it all the time ;) I think if you need to make more counting operations, it is better to make your own class and work with raw data from database. But I am not sure what would be faster if you need just ordinary counting operations as I showed above. I think in that case is better to count inside querying.
I hope that maybe it would help somebody :)

Flip (swap) table according to custom column

Sometimes is need it to flip table in data set, but all functions I found just swap rows with columns. For example like this:
Original table
Swapped table
As you can see columns are rows now but there is first row added (this is what the function I found did). So if you want to have table like this:
You can delete first row and change ordering others rows or you can use this function :) :
public DataSet flipDataSet(DataSet dataSet, string columnToXName, bool showColumnX)
        {
            DataSet ds = new DataSet();
            DataTable table = new DataTable();
            //Loop through all tables in dataset
            //if flipping all tables is not needed the table should be specify
            foreach (DataTable dt in dataSet.Tables)
            {
                //creating a new columns
                for (int i = 0; i <= dt.Rows.Count; i++)
                {
                    if (i != 0)
                        table.Columns.Add(dt.Rows[i - 1][columnToXName].ToString());
                    else
                        table.Columns.Add(columnToXName);
                }
                //filling columns
                DataRow r;
                for (int k = 0; k < dt.Columns.Count; k++)
                {

                    if (k != dt.Columns.IndexOf(columnToXName))
                    {
                        r = table.NewRow();
                        r[0] = dt.Columns[k].ToString();
                        for (int j = 1; j <= dt.Rows.Count; j++)
                            r[j] = dt.Rows[j - 1][k];
                        table.Rows.Add(r);
                    }
                }
            }
            if (!showColumnX)
                table.Columns.Remove(columnToXName);

            ds.Tables.Add(table);
            return ds;
        }

Maybe it can safe some time to somebody ;)

Tuesday, November 8, 2011

Clean invalid characters

Sometimes you need to get rid off some unwanted characters. This function will help you to change them into something else.

public static string cleanInvalidCharacters(string text)
        {
            string newText = text;

            // remove invalid characters
            newText = newText .Replace(@"#", "_");
            newText = newText.Replace(@"%", "_");
            newText = newText.Replace(@"&", "_");
            newText = newText.Replace(@"*", "_");
            newText = newText.Replace(@":", "_");
            newText = newText.Replace(@"<", "_");
            newText = newText.Replace(@">", "_");
            newText = newText.Replace(@"?", "_");
            newText = newText.Replace(@"\", "_");
            newText = newText.Replace(@"/", "_");
            newText = newText.Replace(@"{", "_");
            newText = newText.Replace(@"}", "_");
            newText = newText.Replace(@"|", "_");
            newText = newText.Replace(@"~", "_");
            newText = newText.Replace(@"+", "_");
            newText = newText.Replace(@"-", "_");
            newText = newText.Replace(@",", "_");
            newText = newText.Replace(@"(", "_");
            newText = newText.Replace(@")", "_");
            newText = newText.Replace(@"[", "_");
            newText = newText.Replace(@"]", "_");
            newText = newText.Replace(@"=", "_");
            newText = newText.Replace(@";", "_");
            newText = newText.Replace(@"'", "_");
            newText = newText.Replace(@"@", "_");

            return newText ;
        }