Archive

Posts Tagged ‘C#’

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: , , ,

ASP.NET Code: Register Script in Head Section

January 27, 2010 4 comments

Registering a client-side script in ASP.NET is normally done with the Page.RegisterClientScript or Page.RegisterClientScriptInclude.  Both of these add the appropriate script reference into the resulting body of the HTML.  However there are times when it is nice to have the script added to the head section of the page.  I have written two extension methods to accomplish the task using the same naming convention as the Microsoft provided functions.

        /// <summary>
        /// Registers the client script include in the head section.  If the
        /// same ID is sent, the source file is replaced with the new one.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="id">The control ID to make sure there aren't two
        /// registered under the same ID</param>
        /// <param name="src">The file name.</param>
        public static void RegisterHeadClientScriptInclude(this Page page, string id, string src)
        {
            HtmlGenericControl si = null;
            foreach (Control c in page.Header.Controls)
            {
                if (c.ID != id) continue;
                si = (HtmlGenericControl) c;
                break;
            }
            if (si == null)
            {
                si = new HtmlGenericControl { ID = id, TagName = "script" };
                si.Attributes.Add("type", "text/javascript");
                si.Attributes.Add("src", src);
            }
            else
            {
                si.Attributes["src"] = src;
            }
            page.Header.Controls.Add(si);
        }

        /// <summary>
        /// Registers the client script code block in the head section of the page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="id">The id.</param>
        /// <param name="code">The code.</param>
        public static void RegisterHeadClientScriptBlock(this Page page, string id, string code)
        {
            HtmlGenericControl si = null;
            foreach (Control c in page.Header.Controls)
            {
                if (c.ID != id) continue;
                si = (HtmlGenericControl)c;
                break;
            }
            if (si == null)
            {
                si = new HtmlGenericControl { ID = id, TagName = "script" };
                si.Attributes.Add("type", "text/javascript");
            }
            si.InnerText = code;
            page.Header.Controls.Add(si);
        }

Please comment if you find it interesting or crap, I would like to know either way.

Categories: Code Tags: ,