Retry Logic

Sometimes an exception isn’t just an exception. For example, SQL can have connection or timeout issues and file IO can have problems competing for file access. In these situations, sometimes it makes sense to try executing the code again rather than letting it completely error out. Below is some C# sample code for executing some simple retry logic.

for (int retryAttempt = 1; retryAttempt <= MAX_RETRY_ATTEMPTS; retryAttempt++)
{
     try
     {
          // Perform code execution here
          break;
     }
     catch (Exception ex)
     {
          // Perform any logging here

          if (retryAttempt < MAX_RETRY_ATTEMPTS)
          {
               Thread.Sleep(1000); // Sleep 1 second before retrying
          }
          else
          {
               throw;
          }
     }
}

As you can see, it’s pretty simple.  Execute the actual code logic within the try block, and perform any necessary exception logging within the catch block.
Richard Franzen
Sr. Developer
ImageSource, Inc.

How to Convert Office File to PDF File Format in C#

How to Convert Office file to pdf in C#.

These codes are used for Microsoft Office products with the Save As PDF add-in installed.

Note that You will need to add a reference to Microsoft.Office.Interop.(word,excel, or powerpoint)

<Word To PDF>

public string ConvertWordToPdf(string inputFile)
{
string outputFileName = “Desired Output File Path”;
Microsoft.Office.Interop.Word.ApplicationClasswordApp =
new rosoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document wordDoc = null;
object inputFileTemp = inputFile;

try
{
wordDoc = wordApp.Documents.Open(refinputFileTemp);
wordDoc.ExportAsFixedFormat(outputFileName, WdExportFormat.wdExportFormatPDF);
}
finally
{
if (wordDoc != null)
{
wordDoc.Close(WdSaveOptions.wdDoNotSaveChanges);
}
if (wordApp != null)
{
wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges);
wordApp = null;
}
}

return outputFileName;
}

<Excel To PDF>

public static string ConvertExcelToPdf(string inputFile)
{
string outputFileName = “DesireOutput File Path”;
Microsoft.Office.Interop.Excel.Application excelApp =
new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;
Workbook workbook = null;
Workbooks workbooks = null;
try
{
workbooks = excelApp.Workbooks;
workbook = workbooks.Open(inputFile);
workbook.ExportAsFixedFormatXlFixedFormatType.xlTypePDF,outputFileName,
XlFixedFormatQuality.xlQualityStandard, true, true, Type.Missing,Type.Missing, false,Type.Missing);
}
finally
{
if (workbook != null)
{
workbook.Close(XlSaveAction.xlDoNotSaveChanges);
while(Marshal.FinalReleaseComObject(workbook) != 0) { };
workbook = null;
}
if (workbooks != null)
{
workbooks.Close();
while(Marshal.FinalReleaseComObject(workbooks) != 0) { };
workbooks = null;
}
if(excelApp != null)
{
excelApp.Quit();
excelApp.Application.Quit();
while(Marshal.FinalReleaseComObject(excelApp) != 0) { };
excelApp = null;
}
}

return outputFileName;
}

<PowerPoint To PDF>

public static string ConvertPowerPointToPdf(string inputFile)
{
string outputFileName = “DesireOutput File Path”;
Microsoft.Office.Interop.PowerPoint.ApplicationClass powerPointApp =
new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
Presentation presentation = null;
Presentations presentations = null;
try
{
presentations = powerPointApp.Presentations;
presentation = presentations.Open(inputFile, MsoTriState.msoFalse,MsoTriState.msoFalse,
MsoTriState.msoFalse);

presentation.ExportAsFixedFormat(outputFileName, PpFixedFormatType.ppFixedFormatTypePDF,
PpFixedFormatIntent.ppFixedFormatIntentScreen, MsoTriState.msoFalse,
PpPrintHandoutOrder.ppPrintHandoutVerticalFirst,PpPrintOutputType.ppPrintOutputSlides,
MsoTriState.msoFalse,null,PpPrintRangeType.ppPrintAll, string.Empty, false, true, true, true, false,
Type.Missing);
}
finally
{
if (presentation != null)
{
presentation.Close();
Marshal.ReleaseComObject(presentation);
presentation = null;
}
if (powerPointApp != null)
{
powerPointApp.Quit();
Marshal.ReleaseComObject(powerPointApp);
powerPointApp = null;
}
}
return outputFileName;

}

Kyoungsu Do
Software Quality Engineer
ImageSource, Inc.

SQL Transactions in .NET

In my last blog post, I talked about performing SQL transactions as part of the SQL statement itself.  Now I want to talk about an alternative method for implementing SQL transactions within .NET code.  Basically, the SqlTransaction object can perform the function of grouping together the execution of multiple SQL statements within .NET code.

Below is an example of a SqlTransaction object in action:

 //Create and open a connection to the datase
 using (SqlConnection conn = new SqlConnection(connStr))
 {
      conn.Open();

      //Next, create a sql transaction using our current connection.
      using (SqlTransaction transact = conn.BeginTransaction())
      {
           try
           {
                //Execute the first sql command
                string sqlStr1 =
                    "INSERT INTO TestTable1 (Field1) values ('This is a sample value.')";
                using (SqlCommand cmd1 = new SqlCommand(sqlStr1, conn, transact))
                {
                     cmd1.ExecuteNonQuery();
                }

                //Execute the second sql command
                string sqlStr2 =
                     "INSERT INTO TestTable2 (Field1, Field2) values ('Performing a test insert', 'Into SQL')";
                using (SqlCommand cmd2 = new SqlCommand(sqlStr2, conn, transact))
                {
                     cmd2.ExecuteNonQuery();
                }

                //Execute the third sql command
                string sqlStr3 =
                     "INSERT INTO TestTable3 (Field1) values ('All of these inserts should be successful.')";
                using (SqlCommand cmd3 = new SqlCommand(sqlStr3, conn, transact))
                {
                     cmd3.ExecuteNonQuery();
                }

                //Finally, make sure to commit the transaction
                transact.Commit();
           }
           catch (Exception)
           {
                //If there is a sql exception, we need to back out the transaction
                transact.Rollback();
                throw;
           }
      }
  }

As you can see, the SqlTransaction object is created through a SqlConnection object’s BeginTransaction method.   It must be included with all of the SqlCommand objects for all of the commands to function as part of the same transaction.  The Commit method must be called on the SqlTransaction object in order to complete the transaction.  If there is an exception thrown, it must be caught and dealt with using the Rollback method in the SqlTransaction object.  I hope that helps with any future SQL coding.

 

Richard Franzen
Sr. Developer
ImageSource, Inc. 

Inline Code with XAML

One of the hidden tricks in XAML is that you can actually write inline code directly on the page instead of using the typical code-behind files.  Below is an example on how this works

image

 

And here is the running code

image

Follow

Get every new post delivered to your Inbox.