How To Add Or Change XML Encoding With .NET

Last time I wrote about comparing XML strings in .NET, and continuing that theme I’d like to discuss another handy XML trick.  As the last article pointed out, not all XML strings are created equal.  In fact, sometimes they are missing the necessary XML version and encoding information, like in the following sample XML:

<SampleXML>
    <SampleField1>Testing</SampleField1>
    <SampleField2 value="test value" />
    <SampleField3 type="int">456</SampleField3>
</SampleXML>

Notice anything missing?   Yes, the declaration information is not at the start of the XML string.  Declaration information like in the below example:

<?xml version="1.0" encoding="utf-8"?>

Continue reading

How to Compare XML Strings Using .NET

So you want to compare two XML strings together to see if they are equal. Obviously, it would be easy to just compare the two strings using a regular string equality comparison and call it a day. However, what if the XML strings looked like the following:

<SampleXML>
    <SampleField1>Testing</SampleField1>
    <SampleField2 value="test value" />
    <SampleField3 type="int">456</SampleField3>
</SampleXML>
<SampleXML>
        <SampleField1>Testing</SampleField1>
    <SampleField2     value="test value" />
        <SampleField3 type="int">456</SampleField3></SampleXML>

All of the nodes, attributes and values are the same, but the formatting is way off. Obviously, a string equality comparison between these two would return false. Is there anything that can be done about this? Not to fear, .NET provides a pretty simple solution. Continue reading

How to: Get Image Page Count in .NET C#

How to get image page count in .NET C#

private int GetTotalpages(string filePath)
{
int pageCount = 0;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (Image temp = Image.FromStream(fs))
{
pageCount = temp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
}
}

return pageCount;
}

KyoungSu Do
Software Developer
ImageSource, Inc.

Creating Case Insensitive Dictionaries In .NET

For millennia, mankind has looked to the stars and wondered, “How can I create a generic Dictionary in .NET that allows me use case insensitive strings as keys?” Well today that age old question will be answered with this neat trick.

Simply put, all you need to do is add a StringComparer object when constructing a generic Dictionary that uses a string key, and make sure to use on of the IgnoreCase StringComparers that are offered. Below is some sample code to illustrate just how easy this is.

// Create a generic dictionary with a string comparer that ignores case sensitivity.
//
// This includes the following:
//  - CurrentCultureIgnoreCase
//  - InvariantCultureIgnoreCase
//  - OrdinalIgnoreCase
Dictionary<string, string> stringMap = 
     new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
stringMap.Add("Test Key", "Some value");

// Now try to access or change the corresponding value with the key.
// The case of the key string no longer matters.
stringMap["test key"] = "This will work";
stringMap["TEST KEY"] = "And also this";
stringMap["tEsT kEy"] = "And this as well";
stringMap["tEST kEY"] = "And finally this";

// This can be done with any dictionary that uses a string as the key
Dictionary<string, int> numberMap = 
     new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
numberMap.Add("Test Key", 0);

// Same deal here, you can use any case to get or set the values in the map
numberMap["test key"] = 1;
numberMap["TEST KEY"] = 2;
numberMap["tEsT kEy"] = 3;
numberMap["tEST kEY"] = 4;

And that’s all there is to it.  I hope you enjoy and find this useful.

Richard Franzen
Developer
ImageSource, Inc.

Executing Retry Logic in C#

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)

Continue reading

HashSet .Net 3.5

The C# HashSet<T> data structure was introduced in the .NET Framework 3.5.
It is a very powerful data structure with no duplicate values. It comes with a bunch of built-in set functions. It inherits the ICollection interface, so the elements inside a HashSet can only be accessed through an enumerator.

Continue reading