Hammendorp.net

Blogging about SharePoint and other development

I always forget the outcome of the DateTime.Compare method; Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. Just a reminder to myself ;) The result of the next piece of code:

int result = DateTime.Compare(date1, date2)

result is less than zero : date1 is earlier than date2. 
 
result is zero : date1 is the same as date2.
 
result is greater than zero : date1 is later than date2.



Sometimes you need to copy one or more rows from a source datatable to another datatable. The importrow method can do this for you. It copies a DataRow into a DataTable, preserving any property settings, as well as original and current values. An important condition is that the destination datatable must be the same as the source datatable:

// copy the table definition from source to destination table
DataTable destinationTable = sourceTable.Clone();

In the destination table, you can now import rows:

foreach (DataRow dr in sourceTable)
{
   destinationTable.ImportRow(dr);
}



Alway nice to have, an overview of all stsadm commands: http://technet.microsoft.com/en-us/office/sharepointserver/cc948709.aspx


I was creating the same method over and over again to execute different stored procedures. Now I have created one general method which you can use for all stored procedures (with no result set). Off course it can be extended with, for example, the return of a datatable:

public void ExecuteStoredProcedure(string name, string[] parameters, object[] values)
{
    using (SqlConnection connection = new SqlConnection(ConnectionString))
   {
      connection.Open();

      try
      {
         SqlCommand command = new SqlCommand(name, connection);
         command.CommandType = CommandType.StoredProcedure;

         for (int i = 0; i < parameters.Length; i++)
         {
            command.Parameters.Add(new SqlParameter(parameters[i], values[i]));
         }
                   
         command.ExecuteNonQuery();
      }
      catch (Exception ex)
      {

      }
      finally
      {
         connection.Close();
       }
   }
}



Jun
09

SQL bulk insert

by BasHammendorp | Tags: ,

If you want to insert a complete DataTable at once, you can use SqlBulkCopy:

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
   using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
   {
      bulkCopy.DestinationTableName = "myNewTable";
      bulkCopy.WriteToServer(dt);
   }
}

It's easy as that!



If you want to create and fill an Excel sheet with c#, you can do this by using Microsoft.Office.Interop.Excel. The smart thing to do is to fill an array with all you values and copy those values in a new excel sheet at once. This i much faster then filling the excel sheet line by line.

// create the excel objects
Application application = new Application();
Workbook workbook = (Workbook)(application.Workbooks.Add(Missing.Value));
Worksheet worksheet = (Worksheet)workbook.ActiveSheet;

// init the values for the array; rows is a variable for the number of rows and columns ... duh
string[,] values = new string[rows, columns];
int rowCount = 0; // use the rowcount to select the array position

// add the first line in the array
values[rowCount, 0] = "Firstname";
values[rowCount, 1] = "Lastname";
values[rowCount, 2] = "Country";
                                
// loop through the data assuming you have a datarow with values and fill the array; all values in the datarow are strings
foreach (DataRow dr in dataRows)
{
                    rowCount++;
                    values[rowCount, 0] = dr["Firstname"].ToString();
                    values[rowCount, 1] = dr["Lastname"].ToString();
                    values[rowCount, 2] = dr["Country"].ToString();
}

// fill the values of the array in the excel worksheet; with get_Range you provide the range in the excel workbook
worksheet.get_Range("A1", "C" + values.Length.ToString()).Value2 = values;
                
// you can also format the first line in the excel
worksheet.get_Range("A1", "C1").Font.Bold = true;

application.Visible = true;
application.UserControl = true;

// save and close the workbook; excelFileLocation is the full path to the excel file
workbook.SaveAs(excelFileLocation, XlFileFormat.xlXMLSpreadsheet,
                            Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange,
                            Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

workbook.Close(false, Missing.Value, false);

// close the application
application.Quit();



It's alway nice to have an example of readinga textfile. This example also works fine with extra large files > 1 GB.

// open the file; fileLocation can be something like c:\temp\myfile.txt
using (StreamReader sr = new StreamReader(fileLocation))
{
 // check if there is a new line
        while (sr.Peek() >= 0)
        {
         // read line
                line = sr.ReadLine();

  // do your thing
 }
}



Bas Hammendorp

I am Bas Hammendorp, working as SharePoint developer at PGGM Zeist

Month List

Sign in