Setting a User’s `manager` Property in DirectoryServices

I was trying to run some code earlier today to set a user's manager in ActiveDirectory using System.DirectoryServices, C#. I had code that did the following (actual code has a bunch of reusable methods for doing things like loading up UserPrincipal and DirectoryEntry objects, saving values, not hard coding key names etc - I am simplifying it here to get it all in one place):
using (var pc = new PrincipalContext(ContextType.Domain))
{
    // get the user's directory entry
    var up = UserPrincipal.FindByIdentity(pc, userName);
    var de = (DirectoryEntry)up.GetUnderlyingObject();
    
    // get manager directoryEntry
    var managerUp = UserPrincipal.FindByIdentify(pc, managerUserName);
    var managerDe = (DirectoryEntry)up.GetUnderlyingObject();
    
    // get the manager's distinguished name
    string managerDN = managerDe.Properties["distinguishedName"][0].ToString();

    // set the manager's distinguished name as the value for the `manager` property on the users DirectoryEntry and save
    de.Properties["manager"].Value = managerDN;
    de.CommitChanges();
}
However, when I ran this, I got a System.DirectoryServices.DirectoryServicesCOMException telling me:
A constraint violation occurred
Eventually, I was able to figure out the issue (leading to this post, which will hopefully help someone else out in the future): when setting the `manager` property of a DirectoryEntry, you should not set it to a string that includes the DistinguishedName of the manager. Rather, you want to retrieve the object returned by DirectoryServices for the DistinguishedName of the manager, and set that object value directory. So the end of the code excerpt should look like this:
    object managerDN = managerDe.Properties["distinguishedName"][0];

    // set the manager's distinguished name as the value for the `manager` property on the users DirectoryEntry and save
    de.Properties["manager"].Value = managerDN;
Once I changed it to use the object value of the Distinguished name, I was able to CommitChanges to Active Directory successfully.

MiniProfiler v3.0.10-beta1 Released

I have been a big fan of MiniProfiler since soon after its initial release, so soon after I joined Stack Exchange (2013-10), I made an effort to try to get involved with the development work. Lots of work had been completed already by Jarrod Dixon, Marc Gravell, Matt Jibson, Sam Saffron, Nick Craver and the other members of the team to get MiniProfiler to version 3, and this has been in use for a number of months already on the Stack Exchange sites (including Stack Overflow). A few items remained on the ToDo list before the new version could be released on nuget, and I volunteered to work on these. All of the remaining items have now been completed and a few minutes ago I pushed the new 3.0.10-beta release up to nuget.org. Note: if you are going to install the pre-release beta nugets, be sure to include "-pre" in your command: PM> Install-Package MiniProfiler -Pre

Release Notes:

  • First public nuget release of v3.0
  • Includes new nuget package updates:
  • CustomTiming replaces SqlTiming as the general timing storage. Sql is now just one case. More adaptable for different timing types.
  • Lots of bug fixing, performance enhancements
  • Move from the old location to here.
  • SqlServerStorage is rewritten to use different tables, corresponding to new CustomTiming approach. If you used SqlServerStorage in v2.0 this is a breaking change. In this case be sure to see the newtable creation script
  • Add MultiStorageProvider as new option for being able to designate multiple storage locations.
    • Will store in all listed, retrieve from the first possible location where there is a match
    • Implements IStorage so it can be set for the session using MiniProfiler.Settings.Storage, or for the individual request.
    • Set MiniProfiler.Current.Storage to any IStorage (including MultiStorageProvider) to customize the storage for any single request (example)
  • New nuget for Entity Framework 6. Initialize in with MiniProfilerEF6.Initialize();
  • Updated for newest versions of SqlCe and SqlLite
I also just updated the MiniProfiler.com site to include up to date information (based on the new release) on nugets and basic usage, and changed up the UI a tiny bit (now using Bootstrap). Issues and Pull Requests are welcome on GitHub, and any feedback is also welcome on the community site.

Gematria Class Library on GitHub

I just pushed the initial version of my first public GitHub repository: Gematria (Gematriya). Gematria is a .Net Class Library for calculating the Gematria value of strings of Hebrew text, or convert numbers into Hebrew Text.
Gematria or gimatria (Hebrew: גימטריא/גימטריה‎ gēmaṭriyā) is a traditional Jewish system of assigning numerical value to a word or phrase (Wikipedia)
You can learn more about Gematria in one of these sites (1, 2) This library exposes the following methods, all available through the static Calculator class:
  • GetGematriaValue
    • Calculates the gematria value for all Hebrew letters in the given string.
    • Ignores all characters that are not Hebrew letters.
  • GetNumericGematriaValue
    • Calculates the gematria value for a string that is intended to represent a number (example: a year in the Hebrew calendar or page in a Hebrew book).
    • This function expects that the given string will contain only one word, and will throw an error if more than one word is included
    • (this is because a string of Hebrew characters representing a number will never consist of multiple words).
    • Ignores non-Hebrew characters and punctuation in the given word.
  • ConvertToGematriaNumericString
    • Convert a number into its Gematria Numeric Representation
As explained in the links above, there are different systems that can be used for translating Hebrew letters into numeric equivalents. The Gematria library allows use of the following four methods:
  1. Absolute Value (מספר הכרחי):
    • Alef (א) through Tet (ט) are 1-9
    • Yud (י) through Tzadik (צ) are 10-90, increasing in increments of 10
    • Kuf (ק) through Tav (ת) are 100-400, increasing in increments of 100
    • The five final forms (sofiyot | סופיות) in the alphabet are given the equivalent values to their non-final analogs
    • This is the most standard method, used by default
  2. Absolute Alternate Value
    • The same as the Absolute Value, except that the Final Forms continue from 500-900
  3. Ordinal Value (מספר סידורי)
    • Alef starts at 1. Each following letter continues in sequence, with the final forms continuing the sequence (Tav = 22, Final Tzadik = 27)
  4. Reduced Value (מספר קטן)
    • Calculated the value of each letter using the absolute system, truncating all zeros
    • Leads to a sequence of values in order of letters: 1-9, 1-9, 1-9
The code is released under the MIT License

Could not load type ‘System.Web.Razor.Parser.SyntaxTree.CodeSpan’ from assembly ‘System.Web.Razor

I am working with an ASP.net MVC4 project with WebAPI, and upgraded/installed a number of nuget packages (and stupidly did not test after each one). When the dust settled, I tried to load an API page in my browser and got the following error message:

"Could not load type 'System.Web.Razor.Parser.SyntaxTree.CodeSpan' from assembly 'System.Web.Razor"

Eventually, I was able to resolve the error by removing the following from my web.config and app.config files:
<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <!-- Begin Remove -->
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
    </dependentAssembly>
    <!-- End Remove -->
  </assemblyBinding>
</runtime>
I would guess that one of the packages that I installed added this reference, which had a conflict with a different version of the same assembly in the GAC. In any event, it fixed the error (and did not cause any apparent new errors). Posting in case it may help you out with a similar error.

Force WebAPI to return JSON by Default for Html GET Requests

Currently, the default response type of for Web API requests is XML. By the time it comes out of beta, it will be the default (source - this is mentioned by Hanselman towards the end of the post). However, if you want to activate this right now, how should you do it? Two steps:
  1. Set a JSON formatter as the first Formatter in the Web API Config Formatters collection
  2. Set "text/html" as an accepted media type for this formatter
WebAPI includes a JSON Serializer by default: DataContractJsonSerializer. However, no one wants to use it, and for good reason: lots of issues with different types, slow performance, bad date formatting and more. Thankfully, WebAPI allows you to switch customize the data formatters used for different content types. Bloggers have recommended a number of different approaches. What seems to be the most promising is Henrik Nielsen's JsonNetFormatter (using Json.NET to handle the JSON serialization) combined with a fix for a DateTime serialization issue (Hanselman also implies that this will be the default in post-beta WebAPI). After you add the code for the JsonNetFormatter, you can set this up as the default Json data formatter by doing the following:
protected void Application_Start()
{
    ...

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
    serializerSettings.Converters.Add(new IsoDateTimeConverter());
    GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));

    ...
}
Once you have done this, any request that comes in to the API that asks for json (setting a header to accept content of type application/json, utilizing the facility in WebAPI for content negotiation) will receive Json content formatter using the JsonNetFormatter class. However, if you want to just test this out in your browser, you will still get XML content. This is because a plan request from your browser is for type text/html, which translates to xml in the Web API universe. Though the Json will be returned automatically if you explicitly request json content (or if you use a function that requests this content type, like the $.ajax function in jQuery), if you want to test out the json in your browser, you will be out of luck using the standard configuration. To get around this, you need to set the JsonNetFormatter to support the "text/html" media type. This will allow it to respond to requests made from the browser (and since the JsonNetFormatter is now the first Formatter in the Formatters collection, it will be used by default). You can do this as follows:
protected void Application_Start()
{
    ...

    JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
    serializerSettings.Converters.Add(new IsoDateTimeConverter());
    var jsonFormatter = new JsonNetFormatter(serializerSettings);
    jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    GlobalConfiguration.Configuration.Formatters.Insert(0, jsonFormatter);

    ...
}

Google Translating Search Queries on the Fly

The most popular post on this blog, by far, is Where Does Google Chrome Store User History, Profile and Bookmarks. I had the good luck to be the first person on the Internet to post an answer to this question (even before Google did so in their documentation), just a few days into the original Chrome Beta release. The vast majority of hits come from Google searches that include one or more of the following keywords: Chrome, History, Profile, Bookmarks, Cookies, Save. I mention this because I saw something very interesting in my site stats today. Someone got to this page by searching for "שמירת סימניות בכרום". This is Hebrew for "Save Bookmarks in Chrome". If you searched for this term in English you would see a link to my post on the subject somewhere in the range of the 5th-10th link. However, they searched in Hebrew, and even so, a link to this post showed up (number 8 in the results when I tried it). So they must be taking the Hebrew, and while they are processing results in Hebrew, the search algorithm also translates it on the fly, searches on the term translated into English, and integrates relevant English results into the result set. This is very cool, and in a world where the bulk of technical literature and answers to questions like this are in English, it is very smart. There is a good chance that someone searching for this in Hebrew will still find an answer in English to be useful. Looks like the Google Search team still has a few tricks up their collective sleeve.