Solved: “Could not load file or assembly ‘Microsoft.SqlServer.Management.Sdk. The system cannot find the file specified”

You may run into the error below while doing development in Visual Studio:

Could not load file or assembly ‘Microsoft.SqlServer.Management.Sdk.Sfc, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91′ or one of its dependencies. The system cannot find the file specified.

Solution

You are missing SQL Server libraries that connects Visual Studio to SQL Server database. In order to fix this issue, download and install these two packages from the following URL.

  • SharedManagementObjects.msi
  • DB2OLEDBV5_x64.msi

Download: www.microsoft.com/en-us/download/details.aspx?id=35580

Note: The URL above is for SQL Server 2012. Download libraries for the version you use if it is not 2012 version.

How to fetch data from Active Directory from your .NET application?

By using System.DirectoryServices namespace, you can easily send LDAP queries to your Active Directory and return attribute values.

Make sure that LDAP port is open between your machine and the Active Directory server (Default port is 389 and Global Catalog query port is 3268. You may use another port if it is specified in your DirectoryEntry method)

string displayName = "";
string username = "AD username";

DirectoryEntry oDirectoryEntry = new DirectoryEntry("LDAP://AD-server");
DirectorySearcher oDirectorySearcher=new DirectorySearcher(oDirectoryEntry);

SearchResult oSearchResult = null;

try
{
   oDirectorySearcher.Filter = "(&(objectClass=user)(sAMAccountName=" +username+ ")) ";
   oSearchResult = oDirectorySearcher.FindOne();

   if (oSearchResult != null && oSearchResult.Properties.Contains("displayName"))
   {
      displayName = oSearchResult.Properties["displayName"][0].ToString();
   }
}
catch (Exception ex)
{
   // Error handling
}

References

How to fetch last logon date and last successful password set date from Active Directory using .NET?

Active Directory stores users’ last logon dates in lastLogon attribute and last successful password set dates in pwdLastSet attribute. You may think that it’s as easy as running an LDAP query to get these values. Unfortunately, it’s not that simple.

Background

If you check these values in ADSI Edit tool, you will see a well formatted timestamp. However, if you double click it, you will see a long integer. This is the value your .NET code will receive through an LDAP query. Active Directory returns dates as Int64 data type.

Solution

In order to convert Active Directory’s Int64 timestamps to .NET’s DateTime format, use the following code line.

DateTime lastLogon = DateTime.FromFileTime((long)oSearchResult.Properties["lastLogon"][0]);