Dispose in .NET

March 13, 2017 Leave a comment

Recently we were working on merging PDFs on our web site where we ran into a strange problem. The user could run the merged reports once but upon the second time the server would get a “File Locked” error. Here’s the original code:

public static string CreateMergedPdf(string targetPdf, List<string> pdfFiles)
{
    using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
    {
       Document pdfDoc = new Document(PageSize.LETTER);
       PdfCopy pdf = new PdfCopy(pdfDoc, stream);
       pdfDoc.Open();

       foreach (string file in pdfFiles)
       {
          pdf.AddDocument(new PdfReader(file));
       }

       if (pdfDoc != null)
       {
          pdfDoc.Close();
       }
    }

    return targetPdf;
}

Seems simple enough but we obviously aren’t cleaning up our work as the files are still locked.  After searching for all places where we were referencing disposable objects. We finally came up with this:

public string CreateMergedPdf(string targetPdf, List<string> pdfFiles)
{
   using (var stream = new FileStream(targetPdf, FileMode.Create))
   {
      using (var pdfDoc = new Document(PageSize.LETTER))
      {
         using (var pdf = new PdfCopy(pdfDoc, stream))
         {
            pdf.Open();
            pdfDoc.Open();
            foreach (var file in pdfFiles)
            {
               var reader = new PdfReader(file);
               pdf.AddDocument(reader);
               reader.Dispose();
            }
            pdf.Close();
         }
         pdfDoc.Close();
       }
       stream.Close();
   }

   return targetPdf;
}

 

The lessons learned were clear by the end, you must close and dispose when you are able. Another thing to note was the

pdf.AddDocument(new PdfReader(file));

was from an example, causing us to waste time looking for the last remnant of the locking situation.

Advertisements
Categories: Code Tags: , , ,

LinqPad – Get Disk Information

April 30, 2015 Leave a comment

Getting hardware information can sometimes be hard when writing in .NET, the Framework keeps many of the deails away from the developer.  One day I needed to know if a drive letter existed and what type of drive it was.  I found many ways to do this but the one I liked the best is extremely simple from a code perspective:

Assemblies:
System.Management
System.Management.Instrumentation

var drive = "C";
var disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
disk.Get();
disk.Dump();
Categories: Code Tags: , , ,

LinqPad – Enum to String

April 28, 2015 Leave a comment

Converting an enum item to s string in C# is pretty simple, but we had a situation where the enum was not what we wanted to display to the user on the web.  Looking around I found several examples of how to get the displayed version to be more user-friendly.  Here is an example:

public enum SysModeType
{
 Student,
 Admin,
 Preceptor,
 Undefined
}

We wanted to show “Administrator” on the web site but internally we were using “Admin”. We could do a search and replace for all Admin entries but there were other implications to the enum question in my mind. What if I wanted to display “Student Teacher” or “Intern/Unpaid” or any other combination of things that are not compatible with C# syntax.  I came up with several solutions and then went once step forward to test the performance of each.  The link is what worked and what didn’t.  I leave it to you to decide which one works for you.

LinqPad File: Utility – Enum to string.linq

Categories: Code Tags: , ,

LinqPad – Active Directory User Groups

April 21, 2015 Leave a comment

The other day I needed to know the Active Directory groups a user had assigned.  Not being an operations person, I couldn’t go and use the tools on the server.  I decided there must be an easy way to get this done.  After a bit of searching, I came up with this LinqPad script using some assemblies Microsoft provided.

Assemblies:
System.DirectoryServices
System.DirectoryServices.ActiveDirectory
System.DirectoryServices.AccountManagement
System.DirectoryServices.Protocols

string username = 'hlord'; 
string domain = 'MyDomain'; 

var domainGroups = new List<string>(); 
var domainContext = new PrincipalContext(ContextType.Domain, domain); 
var user = UserPrincipal.FindByIdentity(domainContext, username); 
var authGroups = user.GetAuthorizationGroups();
authGroups.All(g => {
		if (!string.IsNullOrEmpty(g.Name) && !domainGroups.Contains(g.Name))
			domainGroups.Add(g.Name);
		return true;
	});

domainGroups.Sort();
domainGroups.Dump();

LinqPad File: LDAP – User Groups.linq

Categories: Code Tags: , , ,

.NET Compiled in Debug? How do you know?

November 19, 2014 Leave a comment

Recently I had a need to find out if the build was in Debug mode. Our build process produced debug code in production, causing all kinds of issues so I went out into the web to find a way of determining if an assembly (or executable) was created in debug.  It was much harder than I initially thought to get this information.

The article posted at The Black Box of .NET had the answer I was looking for.

Categories: Code Tags: , , ,

.NET 4 – Tuple instead of out parameters

April 6, 2012 Leave a comment

.NET 4 introduced a tuple class which can be very useful.

Wikipedia defines a Tuple as “… a tuple is an ordered list of elements.”

MSDN defines a Tuple as “A tuple is a data structure that has a specific number and sequence of elements.”

You may be asking right now, “What am I supposed to do with that?”  I hope to give you a good idea by the time you are done reading this post.  I will provide a few examples of why, when and how to use them.  Let’s get to it.

One of my pet peeves is output parameters also known as ByRef in VB.  I know there many reasons to use them but the default seems to be where you need to return more than one value from a function.  Consider the following:

string outParameter1, outParameter2;
var v = OutParameterFunction("Test", out outParameter1, out outParameter2);
Console.WriteLine("return value: {0} :: out parameters: {1}, {2}", v, outParameter1, outParameter2);

public static int OutParameterFunction(string inParameter, out string outParameter1, out string outParameter2)
{
     var retValue = 0;
     outParameter1 = null;

     if (!string.IsNullOrEmpty(inParameter))
     {
         outParameter1 = inParameter;
         outParameter2 = "Kewl";
         retValue = 1;
     }
     else outParameter2 = "NOT Kewl";

     return retValue;
}

Simply put there are two values being returned with one of them being the integer value and the other being the output string parameter.

It would be easy to circumvent issue by creating a class to hold the multiple values and return the class.  What happens when you have a bunch of permutations of data, you could end up having dozens of container classes therefore increasing the cost of maintenance.

Another option would be to use an array of object.  Although it can be done, it has a huge performance impact and

The tuple option can be like this:

var t = TupleFunction("Test");
Console.WriteLine("return value: {0} :: {1}", t.Item1, t.Item2, t.Item3);

public static Tuple<int, string, string> TupleFunction(string inParameter)
{
var retInt = 0;
var retString1 = string.Empty;
string retString2;

     if (!string.IsNullOrEmpty(inParameter))
{
retString1 = inParameter;
retString2 = "Kewl";
retInt = 1;
}
else retString2 = "NOT Kewl";

     return Tuple.Create(retInt, retString1, retString2);
}

The code performs the same overall function but does not rely on output parameters.  You may look at the source as the same length and seems to hide the vales inside of a strange object.  The caller of the Tuple function does not have to create a container variable except for the return value.  Consider the situation where the call needs to be extended to return a third value, or a forth?  The tuple can be extended with more values and the caller can deal with the longer return set or not as the caller’s choice (if you like var) because the actual call is not determined at run time but at compile time.

There are some drawbacks to tuples:

  1. You can’t change the values once placed into a tuple.
  2. Unlike list types, you can’t iterate through the values.

I hope this helps.

Categories: Code Tags: ,

Windows: Wired vs Wireless

March 5, 2012 Leave a comment

This morning I started up my work laptop after placing gently yet firmly into the docking station and saw my connection to the network was with the wireless network.  Something inside of me thought, “The docking station has a wired connection, why not use it versus a wireless connection?”.  Now that I have considered it for more than a few minutes, I am a little upset about the wireless preference when a perfectly good wired connection exists.

Armed with a sense of righteous empowerment and a little noodle power, I think I have come up with a sure fire way for WIndows to chose the right connection given a set of scenarios.  Here goes:

  1. Speed advantage– If one is faster than another then go with the fastest
    • Pros – the fastest will result in the best experience for the user.
    • Cons – How often does the measurement need to take place?  Do we warn the user when switching in case they are streaming or connected via VPN or any form of connection where the adapter and the data flow matters?
    • Net – I don’t see this as a viable option when it comes to configuration because the cons are too many and too hard to interpret.
  2. All network connections– Have no preference and use them all at once
    • Pros – Amazing throughput for applications that can use more than one connection at a time.
    • Cons – Incredibly complex implementation.  If wired and wireless are pointing to the same network there would be no advantage to the multiple connection points.  Possible application issues for apps that require a specific MAC or IP.
    • Net – Too many potential issues but if it could be done, the result could be amazing.
  3. Use wired as primary then wireless as a secondary or allow the user to select a preference
    • Pros – Simple and predictable; wired is usually better for speed and throughput; user preferential order for overrides; the functionality for wireless already exists
    • Cons – The user needs to know which is faster; the user may get confused if too many networks are available
    • Net – Easiest for Windows to support because half of the functionality exists

I don’t think making the third option work would be too hard and third parties may be able to get the other options working.  This request will be made to the Microsoft support network but I am interested in getting your feedback.

Categories: Code, Hardware