You are hereProgramming & Web Design / .Net / C#


C#

warning: Creating default object from empty value in /home/hagrinad/public_html/modules/taxonomy/taxonomy.pages.inc on line 33.

C#

Visual Studio 2010 Conditional Breakpoints with Strings

By hagrin - Posted on 24 December 2011

Here's a really simple tip that isn't exactly readily obvious to novice .Net programmers. You can check out my post on conditional breakpoints in Visual Studio 2005 for a more in-depth explanation as to what a conditional breakpoint is and why you would want to set one.

However, something I didn't cover was "what if I want to have a conditional breakpoint when a string variable is a certain value?". Seems simple enough but if you try something like strVariable = "something" or strVariable == "something", neither will work. So exactly how do you evaluate a string in a conditional breakpoint?

Simply do strVariable.Equals("something"). Intellisense even works!

Happy debugging!

C#.Net - Get Remote Computer Uptime

By hagrin - Posted on 15 June 2011

Recently, at one of my jobs, the company's virtual servers were experiencing random, unnoticed reboots that would occur so quickly that their monitoring software, ManageEngine's OpManager (which does an extremely pitiful job at reporting correct uptimes by the way), wouldn't even send out a down alert. Admins were only being notified when they logged onto the box and actually saw a reboot reason message box.

Therefore, to supplement OpManager, we wanted a script/page that gave an overview of all the servers and their uptimes/last reboot. I came up with the following code which will query on a single machine -

using System.Management;

...

ManagementScope scope = new ManagementScope("\\\\COMPUTERNAME\\root\\cimv2");
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
// Display the remote computer information
// http://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx - list of available attributes
Console.WriteLine("Uptime : {0}", m["LastBootUpTime"]);
Console.WriteLine("Computer Name : {0}", m["csname"]);
}
queryCollection.Dispose();
this.Close();

You can easily put the machines you want to query in a database or an array and run this code through a loop to query the uptimes of all your machines in an organization. You can also clean up the formatting of the LastBootUptime to be more readable, but that's up to the developer.

Hope this code snippet helps someone manage their networks.

Exception from HRESULT: 0x800A03EC - Excel, .Net, SQL and Windows Server 2008

By hagrin - Posted on 16 March 2009

For the last 5 days, I have been encountering an error when trying to automate the creation of an Excel document through a scheduled SQL Server job. The error I was receiving was -

Exception from HRESULT: 0x800A03EC

Let's take a step back. The same code I had written worked on my development machine, worked on other target servers while scheduled as SQL jobs, but the code would not work on the following target server -

  • Windows Server 2008 Standard
  • 64-bit platform
  • SQL Server 2005
  • Excel/Office 2007 Professional

After adding some StackTrace code to my program, I was able to determine that the EXE was failing on the Microsoft.Office.Interop.Excel.WorkbookClass.SaveAs line. After trying multiple iterations of the SaveAs command (a quick Google search provided some potential solutions), I continued to get the same 0x800A03EC error code. I went down the road of thinking it was a problem with my 32-bit development environment and had our Sysadmin build me a 64-bit virtual machine for me to compile my application; however, this also yielded the same error. I made sure that the Excel assemblies on the development environment and the target machine were the same version. On the target server, I went to dcomcnfg, selected the Microsoft Excel Application entry and made sure it was using the "interactive user" and still no luck. I made sure that, for testing only, all the SQL services ran under my domain admin account to account for SQL security differences and still nothing.

At this point I decided that I was spinning my wheels and I would call Microsoft and use one of my MSDN support cases.

After speaking to several departments, I finally reached the Office department who tried to help. After explaining my issue quite a few times over and over, I finally got the response I had dreaded - it can't be done that way. Ugh. I had feared I would get this response after reading that using Open XML to create Office documents was the recommended approach and that using the Office COM references was no longer supported (if it ever was) and Windows 2008 has additional security that prevents the old approach from working properly. Well, I guess that explains why it wasn't working.

So where do I go from here? Even though Microsoft support couldn't provide me with sample code or a link to some code, I was able to find this knowledge base article detailing how to to create Excel files using Open XML. Hopefully, this approach will work on my target server environment.

Convert .Net Code to HTML

By hagrin - Posted on 03 May 2007

When you're writing a development related blog, you're eventually (hopefully) going to write some code snippets that you want to share with your readers. However, in order to get the most out of that code snippet, you should make it easy to read and color coded so that potential users can quickly read through your code and evaluate its worth.

That's where CopySourceAsHTML will solve all your problems. CSAH is a plug-in that integrates directly into your Visual Studio IDE environment and allows you to highlight code, right click and choose "Copy As HTML". The tool is freeware and performs exceptionally - if you maintain a .Net developer blog, I would suggest installing this add-on.

C#.Net - How to Unlock a Domain Account in Active Directory

By hagrin - Posted on 09 February 2007

How to Unlock a Domain Account in Active Directory utilizing C# .Net - (note: you must have Domain Admin privledges to execute this code successfully and you must import the System.DirectoryServices namespace):

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.DirectoryServices;

...

private void btnDisableUser_Click(object sender, System.EventArgs e)
{
string strUserName = "InsertUserNameHere";
DirectoryEntry usr = new DirectoryEntry("LDAP://dc=InsertDomainHere, dc=COM");
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(SAMAccountName=" + strUserName + ")";
searcher.CacheResults = false;
SearchResult result = searcher.FindOne();
usr = result.GetDirectoryEntry();
usr.Properties["LockOutTime"].Value = 0x0000;
usr.CommitChanges();
}

C#.Net - How to Disable a Domain Account in Active Directory

By hagrin - Posted on 09 February 2007

How to Disable a Domain Account in Active Directory utilizing C# .Net - (note: you must have Domain Admin privledges to execute this code successfully and you must import the System.DirectoryServices namespace):

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.DirectoryServices;

...

private void btnDisableUser_Click(object sender, System.EventArgs e)
{
string strUserName = "InsertUserNameHere";
DirectoryEntry usr = new DirectoryEntry("LDAP://dc=InsertDomainHere, dc=COM");
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(SAMAccountName=" + strUserName + ")";
searcher.CacheResults = false;
SearchResult result = searcher.FindOne();
usr = result.GetDirectoryEntry();
usr.Properties["userAccountControl"].Value = 0x0002;
usr.CommitChanges();
}

C# .Net Coding Samples

By hagrin - Posted on 30 January 2007

Below are code samples utilizing C# .Net. If you have any questions, comments or corrections on any code sample, please email me at "hagrin at gmail dot com" (email written out to avoid email harvesters) and I'll try and get back to all user inquiries as soon as possible. Thank you and hopefully this code will prove to be helpful.

Disable a Domain Account in Active Directory
Unlock a Domain Account in Active Directory