How To Check DataRow Column To Correct Specified Cast Is Invalid



TODO:

Have you ever received a invalid cast exception, when checking the value of a column in a data row?

 

SOLUTION:

OrderNumber =  row.IsNull("ordernumber") ? "" : (string)row["ordernumber"];

 

NOTES:

OrderNumber above is a string, and row is a row in a DataTable

How To Merge / Join Two Typed Lists



TODO:

Have you ever wanted to combine 2 typed lists in C#?

 

SOLUTION:

 

string data = "test,test2,test3";
string data2 = "test4;test5;test6";

List<string> list1 = data.Split(',').ToList<string>();
List<string> list2 = data2.Split(';').ToList<string>();
list1 = list1.Union(list2).ToList();

 

 

NOTES:

The example above is one that I use when I want to allow a comma or semi-colon delimited list.  For instance in my config file, people sometimes use a comma to seperate email addresses, and other times they use a semi-colon.  This will split the data one both, and join the 2 lists.

How To Read Entire Text File



TODO:

Have you ever wanted to read the contents of a text file in C#?

 

SOLUTION:

string filedata = "";
string inFileName = "C:\\test.txt";

using (StreamReader sr = new StreamReader(inFileName))
{
     filedata = sr.ReadToEnd();
}

 

NOTES:

There are no notes on this topic.

How To Convert An Excel Spreadsheet To A DataSet



TODO:

Have you ever wanted to convert an Excel SpreadSheet to a DataSet?

 

SOLUTION:

public bool ConvertXLSToDataset(ref DataSet InDataSet, string InFileName, bool ProcessAllSheets)
{
    DataSet currentSheetDS = null;
    DataTable spreadsheets = null;

    string TableName = "";
    try
    {
        InDataSet = new DataSet();
        string ConnectionString = String.Format("Data Source={0};HDR=true", InFileName);

        //now see if it has an xlsx extension
        if (InFileName.ToLower().Contains(".xlsx"))
            ConnectionString = String.Format("{0};Format=xlsx", ConnectionString);

        //get the connection stuff
        using (ExcelConnection excelConnection = new ExcelConnection(ConnectionString))
        {
            excelConnection.Open();

            spreadsheets = excelConnection.GetExcelSchemaTable(ExcelConnection.ExcelClientSchemaType.Tables);

            //make sure we have rows
            if (spreadsheets.Rows != null)
            {
                foreach (DataRow datarow in spreadsheets.Rows)
                {
                    currentSheetDS = new DataSet();
                    TableName = datarow["TABLE_NAME"].ToString();

                    //Create an ExcelCommand to specify from which spreadsheets inside of the workbook to query data
                    using (ExcelCommand excelCommand = new ExcelCommand(TableName, excelConnection))
                    {
                        excelCommand.CommandType = CommandType.TableDirect; //It is always TableDirect

                        //Create an ExceldataAdapter to retrieve data into the DataSet
                        using (ExcelDataAdapter loDataAdapter = new ExcelDataAdapter(excelCommand))
                        {
                            //Get data
                            loDataAdapter.Fill(currentSheetDS);
                            InDataSet.Merge(currentSheetDS);
                        }
                    }//using

                    //if we are not processing all sheets, then break out so we do the first
                    if (!ProcessAllSheets)
                        break;
                }//foreach
            }//if
        }//using

        return true;
    }
    catch (Exception x)
    {
        return false;
    }
}//method

 

NOTES:

You will need the VM.xPort.ExcelClient dll.  You can buy it here.

How To Convert A SqlDataReader To A DataTable Using C#



TODO:

Have you ever wanted to convert a SqlDataReader to a DataTable in C#?

 

SOLUTION:

 

DataTable datatable = null;
string ErrorMessage = "";

try
{
     using (SqlConnection myConnection = new SqlConnection(ConnectionString))
     {
           using (SqlCommand cmd = new SqlCommand("some sql here", myConnection))
           {
                 myConnection.Open();
                 using (SqlDataReader reader = cmd.ExecuteReader())
                 {
                       datatable = new DataTable();
                       datatable.Load(reader);
                 }
           }
      }
}
catch (Exception ex)
{
     ErrorMessage = ex.Message;
}

 

NOTES:

There are no notes on this topic.

How To Convert List<T> To A Comma Separated String



TODO:

Have you ever wanted to convert a List<string> to a comma delimited string?

 

SOLUTION:

List<string> list = new List<string>();

list.Add("blah");
list.Add("blah1");
list.Add("blah2");
list.Add("blah3");

string result = String.Join(",", list.ToArray());

 

NOTES:

There are no notes on this topic.

Properties Marked As Obsolete() Are Not Serialized



TODO:

Have you ever marked a property as Obsolete(), and noticed that it is empty whe DeSerialzie occurs.

 

SOLUTION:

It appears that Obsolete() is the same as XmlIgnore().  I found this article interesting in explaining why this happens: connect.microsoft.com

 

NOTES:

There are no notes on this topic.

How To Check @@ERROR to Determine If An Error Occurred In A Stored Procedure



TODO:

Have you ever wanted to check to see if an update or other error occurred in your stored procedure.  To do so check the @@ERROR variable, if it is 0, then no errors occurred.

 

SOLUTION:

IF @@ERROR = 0
BEGIN
     --return the id of the row inserted
     SELECT @@ROWCOUNT As RowsAffected
END
ELSE
BEGIN
     SELECT -1 As RowsAffected
END

 

NOTES:

In the example above, I did not care about the error code, which is why i chose to return -1 in the ELSE.

How To Test If A PDF Is Valid



TODO:  

Have you ever wanted to test that a PDF was actually a valid PDF?

 

SOLUTION:

try
{
      reader = new PdfReader("mypdf.pdf");
}
catch (iTextSharp.text.exceptions.InvalidPdfException ex)
{
     //do some stuff here, like move to an error folder maybe?                           
}

 

NOTES:

You can download iTextSharp from SourceForge.net

How To Import A Key Using GnuPG



TODO:

Have you ever wanted to install a key into your keyring using GnuPG?

 

SOLUTION:

gpg --import "fullpath to file"

 

NOTES:

There are no notes on this topic