Error con JavaScriptSerializer de JSON. La longitud de la cadena supera el valor establecido en la propiedad maxJsonLength

Error generado por .NET

Error durante la serialización o deserialización mediante JavaScriptSerializer de JSON. La longitud de la cadena supera el valor establecido en la propiedad maxJsonLength.

Se intento con (-no funcionó)

<system.web.extensions>
   <scripting>
      <webServices>
          <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
   </scripting>
</system.web.extensions>

Funcionó, asignado el valor en tiempo de ejecución, no se usó lo anterior:

List<Colaborador_BE> listaColaborador=oColaborador_SD.Listar(pColaborador_BE);
 var serializer=new System.Web.Script.Serialization.JavaScriptSerializer();
 serializer.MaxJsonLength=500000000;

var json = Json(listaColaborador, JsonRequestBehavior.AllowGet);
 json.MaxJsonLength = 500000000;
 return json;

 

Preparar web.config para html5 y css3

Ref: http://madskristensen.net/post/prepare-webconfig-for-html5-and-css3

 

HTML5 and CSS3 introduces some new file types that enables us to create even better websites. We are now able to embed video, audio and custom fonts natively to any web page. Some of these file types are relatively new and not supported by the IIS web server by default. It’s file types like .m4v, .webm and .woff.

When a request is made to the IIS for these unsupported file types, we are met with the following error message:

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The problem is that the IIS doesn’t know how to serve these new files unless we tell it how. This can be easily done in the web.config’s <system.webServer> section by adding the following snippet:

<staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
    <mimeMap fileExtension=".m4v" mimeType="video/m4v" />
    <mimeMap fileExtension=".ogg" mimeType="video/ogg" />
    <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
    <mimeMap fileExtension=".webm" mimeType="video/webm" />

    <mimeMap fileExtension=".oga" mimeType="audio/ogg" />
    <mimeMap fileExtension=".spx" mimeType="audio/ogg" />

    <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    <mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />

    <remove fileExtension=".eot" />
    <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
    <mimeMap fileExtension=".otf" mimeType="font/otf" />
    <mimeMap fileExtension=".woff" mimeType="font/x-woff" />
</staticContent>

The above snippet includes support for most video, audio and font file types used by HTML5 and CSS3

Identificar Caracteres escondidos en una consulta SQL

CREATE FUNCTION dbo.ShowWhiteSpace (@str varchar(8000))
RETURNS varchar(8000)
AS
BEGIN
     DECLARE @ShowWhiteSpace varchar(8000);
     SET @ShowWhiteSpace = @str
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(32), '[?]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(13), '[CR]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(10), '[LF]')
     SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(9),  '[TAB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(1),  '[SOH]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(2),  '[STX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(3),  '[ETX]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(4),  '[EOT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(5),  '[ENQ]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(6),  '[ACK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(7),  '[BEL]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(8),  '[BS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(11), '[VT]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(12), '[FF]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(14), '[SO]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(15), '[SI]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(16), '[DLE]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(17), '[DC1]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(18), '[DC2]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(19), '[DC3]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(20), '[DC4]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(21), '[NAK]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(22), '[SYN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(23), '[ETB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(24), '[CAN]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(25), '[EM]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(26), '[SUB]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(27), '[ESC]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(28), '[FS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(29), '[GS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(30), '[RS]')
--   SET @ShowWhiteSpace = REPLACE( @ShowWhiteSpace, CHAR(31), '[US]')
     RETURN(@ShowWhiteSpace)
END
SELECT dbo.ShowWhiteSpace(myfield) from mytable

 

Eliminar caracteres conflictivos xml en una cadena

CASO: USANDO closedxml para generar un excel, la ejecucion se caia porque indicaba que habia un caracter erroneo en la estructura xml.

Para solucionarlo se usó la siguiente funcion

public static string RemoveTroublesomeCharacters(string inString)
{
    if (inString == null) return null;

    StringBuilder newString = new StringBuilder();
    char ch;

    for (int i = 0; i < inString.Length; i++)
    {

        ch = inString[i];
        // remove any characters outside the valid UTF-8 range as well as all control characters
        // except tabs and new lines
        //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')
        //if using .NET version prior to 4, use above logic
        if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4
        {
            newString.Append(ch);
        }
    }
    return newString.ToString();

}

Los datos antes de asignarse a las celdas de excel, si «filtraban» por medio de esta funcion. Con este proceso se puedo generar el archivo esperado.

Leer archivos JSON en aplicaciones .NET

Add .json file in asp.net web.config file

Para poder leer archivos .json desde visual studio agregar lo siguiente al archivo de configuracion de la aplicacion

 <system.webServer>
 <staticContent>
 <mimeMap fileExtension=".json" mimeType="application/json"/>
 </staticContent>
 </system.webServer>

 

Response End en Update Panel

Se tenia un boton que generaba un archivo txt segun items seleccionados en una grilla. La grilla estaba dentro de un update panel.

Para generar el archivo, se generaba en memoria y luego se volcaba a un txt finalizando en response.end()

El response.end(), es incompatible con las llamadas asincronas por lo que el <asp:AsyncPostBackTrigger ControlID=»ImgBtnDescargar» EventName=»Click» /> no funciona.

Para que se realice la accion de generar el archivo se tuvo que cambiar  <asp:PostBackTrigger ControlID=»ImgBtnDescargar» />, sin embargo se generaba y descargaba el archivo pero no se actualizaba la grilla.

 

Al final se ha optado por generar el archivo en una ruta del servidor y redirigir la aplicacion a una nueva pagina que descarga el archivo.

 

private string GenerarArchivo()
{
string NombreArchivo = System.IO.Path.GetRandomFileName();
string NombreGenerado = "CargaSUNAT_" + DateTime.Now.ToString("yyyyMMdd");

System.IO.MemoryStream stream=new System.IO.MemoryStream();
//System.IO.StreamWriter SW = new System.IO.StreamWriter(stream);
System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("txtGenerados/" + NombreGenerado + ".txt"));

BLLDocument _BllDocument = new BLLDocument();

foreach (GridViewRow fila in this.gvDocumentosBaja.Rows)
{
DataKey dkey = gvDocumentosBaja.DataKeys[fila.RowIndex];
int IdCorrelativo = int.Parse(dkey[0].ToString());
CheckBox chkSeleccionado = (CheckBox)fila.Cells[0].FindControl("chkselbaja");
if (chkSeleccionado.Checked)
{
BEDocument _documento = _BllDocument.DocumentoTXT(IdCorrelativo);
string [] numeroDoc=_documento.NumberDocument.Split('-');
SW.WriteLine(_documento.ClientRUC + "|" + _documento.DateDocument.ToString("yyyyMMdd") + "|" + _documento.TipoDocumentoDescripcion +
"|" + numeroDoc[0] + "|" + numeroDoc[1] + "|" + _documento.DateDocument.ToString("yyyyMMdd") + "|" + _documento.MensajeBaja);

BEMethExResultInfo resultado = _BllDocument.RegistraTXTGenerado(IdCorrelativo, _SessionVariable.BEUser.Name);

}
}

SW.Close();

return NombreGenerado;
}

 

 protected void ImgBtnDescargar_Click(object sender, ImageClickEventArgs e)
        {
            string NombreGenerado=GenerarArchivo();
            //Response.Redirect("GenerarTXT.aspx");

            if (chkverTodos.Checked)
                CargarGrilla("1");
            else
                CargarGrilla("0");
            
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AbrirDescarga", string.Format("window.open('Descargas.aspx?Fileid={0}');",NombreGenerado), true); 
        }

 

    public partial class Descargas : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["Fileid"] != null)
                {
                    string nombrearchivo = Request.QueryString["Fileid"].ToString();

                    System.IO.FileStream fs = null;
                    fs = System.IO.File.Open(Server.MapPath("txtGenerados/" + nombrearchivo + ".txt"), System.IO.FileMode.Open);
                    byte[] txtbyte = new byte[fs.Length];
                    fs.Read(txtbyte, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    Response.AddHeader("Content-disposition", "attachment; filename=" + nombrearchivo + ".txt");
                    Response.ContentType = "application/octet-stream";
                    Response.BinaryWrite(txtbyte);
                    Response.End();
                }

            }
        }
    }

Autenticacion Windows en ASP NET

The default authentication mechanism built into ASP.NET Web Pages site templates is Forms Authentication via the SimpleMembershipProvider, which is designed to enable authentication of users against a database. This requires the user to know their user name and password, and to enter those whenever they want to log in to access restricted areas within a site. If you are using the ASP.NET Web Pages framework to build an Intranet site that will be hosted within your own corporate network (i.e. client machines and web server are in the same domain), you can use Integrated Windows Authentication instead which simplifies authentication dramatically.

Integrated Windows Authentication is the preferred approach to authentication whenever users are part of the same Windows domain as the server. Users are authenticated against an existing identity store such as Active Directory, and their credentials are not transmistted across the Internet. In addition, users are provided with a seamless experience, as they only need to log in to Windows, and their browser and IIS take care of managing authentication from then on. There are a number of alternatives to Integrated Windows Authentication: Basic, Digest and Client Certificate, but only Integrated Windows Authentication provides strong authentication without the hassle of managing client certificates. It is therefore the recommended option.

Configuring Integrated Windows Authentication is quite straightforward, but there are a number of steps that need to be followed. The first step is to change the web.config file to specify that Windows Authentication is to be used for the site:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="EnableSimpleMembership" value="false" />
    </appSettings>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Windows" />

    </system.web>
</configuration>

There are three items to note: first, an appSettings entry is added to turn off SimpleMembership, which relies on Forms Authentication. Then, within the system.web node, the authentication mode is set to Windows.

The next step is to ensure that your web server is set up to manage Windows Authentication for the site. To do this, you need to explicitly disable anonymous access (which allows anyone to access the site withoiut havng to authenticate) and enable Windows Authentication. WebMatrix doesn’t offer any GUI management tools for IIS Express, so you need to locate the applicationhost.config file (typically located in C:\Users\<your_username>\Documents\IISExpress\config). Having done that, navigate all the way to the bottom where you should find the closing </configuration> tag. Add the following, where «Windows Auth» is the name of your site:

	<location path="Windows Auth">
        <system.webServer>
            <security>
                <authentication>
                    <anonymousAuthentication enabled="false" />
                    <windowsAuthentication enabled="true" />
                </authentication>
            </security>
        </system.webServer>
    </location>
</configuration> <-- left in to help with positioning -->

Visual Studio Express for Web does provide a visual means to manage these settings: you can configure them with two clicks in the site properties:

Windows Authentication

There is an alternative way to disable anonymous access to the site, and that is to add the following to your web.config file within the system.web node:

<authorization>
    <deny users="?"/>
</authorization>

When you deploy the site to the full version of IIS, you can use the standard IIS administrative tools to manage configuration. First, you need to ensure that Windows Authentication is enabled for the web server. You can do this by going to Control Panel » Programs and Features, and then clicking Turn Windows features on or off (left hand side). Locate Internet Information Services and then drill down to Security and ensure that Windows Authentication is checked.

Windows Auth in IIS

Once you have created the site in IIS, go to Feature View and click Authentication:

Windows Authentication in IIS

Make sure that the options are the same as you set in IIS Express: Anonymous Authentication should be disabled, and Windows Authentication enabled.

Windwos Authentication IIS

Working with users and roles

Users are logged in automatically and their identity is stored in the Identity property of the User object. The User object is an instance of the IPrincipal interface. The underlying type is the WindowsPrinciple class. You can get the name of the user from User.Identity.Name. The value returned from this is in the form DomainName\UserName or MachineName\UserName. For example, if I have a Windows login for a domain called CONTOSO01, the value returned by User.Identity.Name might be CONTOSO01\mikebrind.

Some parts of the Intranet might only be accessible to members of certain Windows groups (roles) such as Administrator or Sales. In order to determine whether the current user belongs to a specific group, you use the User.IsInRole method:

@if(User.IsInRole(@"BUILTIN\Administrators") || User.IsInRole(@"DOMAIN\Sales")){
    <div>Is an administrator or sales person</div>
}

You can also use an override of the IsInRole method that takes a WindowsBuiltInRole enumeration, although you have to cast the User object to a WindowsPrincipal to use this option:

@using System.Security.Principal;
@{
    var user = (WindowsPrincipal)User;
    if(user.IsInRole(WindowsBuiltInRole.Administrator)){
        //user is an administrator
    }
}

Note that you also need to add a using directive to reference the System.Security.Principal namespace. Enumerations are good, in that Intellisense offers code completion and compile time checking, but you can’t use this approach to test for membership of custom groups that you have created such as the Sales one illustrated earlier.

You can’t do very much with groups or roles when using Windows Authentication. However, you can activate theWindowsTokenRoleProvider if you do need to make use of its limited features. To do this, add the following to your web.config within the system.web node:

<roleManager enabled="true" defaultProvider="WindowsProvider">
    <providers>
        <clear />
        <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
    </providers>
</roleManager>

The first thing to point out is that if you enable this feature, you can no longer use the WindowsBuiltInRole enumeration option with the User.IsInRole method because the underlying type for User has now become a RolePrincipal type, which cannot be converted to WindowsPrincipal. You can continue to use the User.IsInRole method that accepts a string, or you can use the Roles.IsUserInRole(string, string) method, that takes the user name and the role to check against. The only other meaningful method exposed by the WindowsTokenRoleProvider is the GetRolesForUser method which returns an array of roles:

@foreach(var role in Roles.GetRolesForUser()){
    <div>User belongs to @role</div>
}

Unless you actually need to use this method, there seems little point in activating the RoleManager for your intranet site.

Active Directory con C#

Table of Contents

Introduction

When it comes to programmatically accessing Microsoft’s Active Directory a lot of people seem to have quite a difficult time tying all the pieces together to accomplish exactly what they want to. There are so many technologies available for communicating with LDAP that many programmers end up with a mix between COM+ ADSI calls and .NET class calls mixed into their code. ADSI code is so difficult to understand and follow that the creator of that code usually owns it for the entirety of it’s lifecycle since no one else wants to support it.

This article attempts to tie together the most commonly used elements involved in Active Directory Management in the simplest, most clean manner possible. I interact with Active Directory in nearly all of my applications (web & forms) and I have had to solve a lot of integration issues for many customers. When I was starting out with this technology I had a lot of growing pains so this is an attempt to help those programmers who may have a need to interact with the Directory but do not want to have to become experts in the issue. However, certain rudimentary knowledge and concepts are required in order to utilize the code. You must be familiar with such terms as: distinguishedName, ldap paths, fully qualified domain names, object attributes (single string & multi-string), and general knowledge of ldap schemas.

Background

There is a great collection of sample code available on MSDN’s website for the v1.1System.DirectoryServices assembly but there seems to be a void when it comes to the new functionality available in the v2.0 System.DirectoryServices.ActiveDirectory assembly. Since this article’s original publishing, Generics have gained widespread acceptance and I encourage anyone borrowing from this resource to replace the archaic ArrayList collections with List<T> or appropriate generic collections.

Points of Concern

In order to communicate with Active Directory one must take into account network security, business rules, and technological constraints. If you’re using Active Directory code from an ASP.NET page you must ensure that the code has the appropriate level of permission to access and interact with the directory. For development purposes or proof of concept you can enable impersonation at the ASP.NET level (in web.config) and the IIS level and if the IIS server and the directory domain controller reside on the same machine this will work. However, if these entities are not co-located on the same server (as they never are in production) you can wrap the code around an impersonation class (such as the Zeta Impersonator which will execute the Directory calls under the token of the impersonated user. It’s strongly recommended that you do not do this for security reasons unless absolutely necessary.. The authorized method for granting the ASP.NET application permission to the directory is by way of either a privileged IIS Application Pool running under the identity of a service account or by way of a COM+ entity running under the identity of a service account.

If you plan on running this code from a desktop assembly then you’re going to want to ensure that your machine is attached to a domain and can communicate with that domain. The impersonation is not necessary if the user running the code has sufficient privileges on the domain.

Running Code in Batch Processes

It is also important to note that if you plan on running this code from an ASP.NET page in batch, ASP.NET will time out on you if you try to run batch processes from it’s primary thread. There are several things to consider in this scenario but be aware that for example, if you’re creating x number of accounts through an ASP.NET application (or performing any batch operation in general) that you must plan to use queues, a back-end scheduler, or some other mechanism outside the scope of the page itself to prevent timing out during your processes. As with any ASPNET design, it’s never a good idea to use ASPNET itself for anything but the «View» part of the solution. The best architecture would queue tasks into a SQL database or something to that effect and then a back-end windows service or similar application would pick up the tasking and perform the actual Directory operations.

This is typically how I engineer Active Directory management solutions for customers.

A Note on Method Parameters

You will notice that most of the methods require the same parameters. Rather than identify each time I will outline them now:

  • friendlyDomainName: the non qualified domain name (contoso – NOT contoso.com)
  • ldapDomain: the fully qualified domain such as contoso.com or dc=contoso,dc=com
  • objectPath: the fully qualified path to the object: CN=user, OU=USERS, DC=contoso, DC=com (same asobjectDn)
  • objectDn: the distinguishedName of the object: CN=group, OU=GROUPS, DC=contoso, DC=com
  • userDn: the distinguishedName of the user: CN=user, OU=USERS, DC=contoso, DC=com
  • groupDn: the distinguishedName of the group: CN=group,OU=GROUPS,DC=contoso,DC=com

A Note on System.DirectoryServices.DirectoryEntry

You’ll notice in all the samples that we’re binding directly to the directoryEntry and not specifying a server or credentials. If you do not want to use an impersonation class you can send credentials directly into theDirectoryEntry constructor. The impersonation class is helpful for those times when you want to use astatic method and don’t want to go through the trouble of creating a DirectoryContext object to hold these details. Likewise you may want to target a specific domain controller.

Target Specific Domain Controllers or Credentials

Everywhere in the code that you see: LDAP:// you can replace withLDAP://MyDomainControllerNameOrIpAddress as well as everywhere you see a DirectoryEntry class being constructed you can send in specific credentials as well. This is especially helpful if you need to work on an Active Directory for which your machine is not a member of it’s forest or domain or you want to target a DC to make the changes to.

//Rename an object and specify the domain controller and credentials directly


public static void Rename(string server,
    string userName, string password, string objectDn, string newName)
{
    DirectoryEntry child = new DirectoryEntry("LDAP://" + server + "/" + 
        objectDn, userName, password);
    child.Rename("CN=" + newName);
}

Managing local accounts with DirectoryEntry

It is important to note that you can execute some of these methods against a local machine as opposed to an Active Directory if needed by simply replacing the LDAP:// string with WinNT:// as demonstrated below

//create new local account

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + 
    Environment.MachineName);
DirectoryEntry newUser = localMachine.Children.Add("localuser", "user");
newUser.Invoke("SetPassword", new object[] { "3l!teP@$$w0RDz" });
newUser.CommitChanges();
Console.WriteLine(newUser.Guid.ToString());
localMachine.Close();
newUser.Close();

Managing local groups with DirectoryEntry

A few configuration changes need to be made to the code but it’s pretty straightforward. Below you can see an example of using DirectoryEntry to enumerate the members of the local «administrator» group.

DirectoryEntry localMachine = new DirectoryEntry
    ("WinNT://" + Environment.MachineName + ",Computer");
DirectoryEntry admGroup = localMachine.Children.Find
    ("administrators", "group");
object members = admGroup.Invoke("members", null);

foreach (object groupMember in (IEnumerable)members)
{
    DirectoryEntry member = new DirectoryEntry(groupMember);
    Console.WriteLine(member.Name);
}

Managing IIS with DirectoryEntry

In addition to managing local & directory services accounts, the versatile DirectoryEntry object can manage other network providers as well, such as IIS. Below is an example of how you can use DirectoryEntry to provision a new virtual directory in IIS.

//Create New Virtual Directory in IIS with DirectoryEntry()


string wwwroot = "c:\\Inetpub\\wwwroot";
string virtualDirectoryName = "myNewApp";
string sitepath = "IIS://localhost/W3SVC/1/ROOT";

DirectoryEntry vRoot = new DirectoryEntry(sitepath);
DirectoryWntry vDir = vRoot.Children.Add(virtualDirectoryName, 
                            "IIsWebVirtualDir");
vDir.CommitChanges();

vDir.Properties["Path"].Value = wwwroot + "\\" + virtualDirectoryName;
vDir.Properties["DefaultDoc"].Value = "Default.aspx";
vDir.Properties["DirBrowseFlags"].Value = 2147483648;
vDir.Commitchanges();
vRoot.CommitChanges();

Active Directory Code

The code below is broken apart logically into usage categories. Again, this is not intended to be a complete library, just the code that I use on a daily basis.

Active Directory Management

//These methods require these imports

//You must add a references in your project as well

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

Translate the Friendly Domain Name to Fully Qualified Domain

public static string FriendlyDomainToLdapDomain(string friendlyDomainName)
{
    string ldapPath = null;
    try
    {
        DirectoryContext objContext = new DirectoryContext(
            DirectoryContextType.Domain, friendlyDomainName);
        Domain objDomain = Domain.GetDomain(objContext);
        ldapPath = objDomain.Name;
    }
    catch (DirectoryServicesCOMException e)
    {
        ldapPath = e.Message.ToString();
    }
    return ldapPath;
}

Enumerate Domains in the Current Forest

public static ArrayList EnumerateDomains()
{
    ArrayList alDomains = new ArrayList();
    Forest currentForest = Forest.GetCurrentForest();
    DomainCollection myDomains = currentForest.Domains;

    foreach (Domain objDomain in myDomains)
    {
        alDomains.Add(objDomain.Name);
    }
    return alDomains;
}

Enumerate Global Catalogs in the Current Forest

public static ArrayList EnumerateDomains()
{
    ArrayList alGCs = new ArrayList();
    Forest currentForest = Forest.GetCurrentForest();
    foreach (GlobalCatalog gc in currentForest.GlobalCatalogs)
    {
        alGCs.Add(gc.Name);
    }
    return alGCs;
}

Enumerate Domain Controllers in a Domain

public static ArrayList EnumerateDomainControllers()
{
    ArrayList alDcs = new ArrayList();
    Domain domain = Domain.GetCurrentDomain();
    foreach (DomainController dc in domain.DomainControllers)
    {
        alDcs.Add(dc.Name);
    }
    return alDcs;
}

Create a Trust Relationship

public void CreateTrust(string sourceForestName, string targetForestName)
{
    Forest sourceForest = Forest.GetForest(new DirectoryContext(
        DirectoryContextType.Forest, sourceForestName));

    Forest targetForest = Forest.GetForest(new DirectoryContext(
        DirectoryContextType.Forest, targetForestName));

    // create an inbound forest trust

    sourceForest.CreateTrustRelationship(targetForest,
        TrustDirection.Outbound);
}

Delete a Trust Relationship

public void DeleteTrust(string sourceForestName, string targetForestName)
{
    Forest sourceForest = Forest.GetForest(new DirectoryContext(
        DirectoryContextType.Forest, sourceForestName));

    Forest targetForest = Forest.GetForest(new DirectoryContext(
        DirectoryContextType.Forest, targetForestName));

    // delete forest trust

    sourceForest.DeleteTrustRelationship(targetForest);
}

Enumerate Objects in an OU

The parameter OuDn is the Organizational Unit distinguishedName such asOU=Users,dc=myDomain,dc=com

public ArrayList EnumerateOU(string OuDn)
{
    ArrayList alObjects = new ArrayList();
    try
    {
        DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + OuDn);
        foreach (DirectoryEntry child in directoryObject.Children)
        {
            string childPath = child.Path.ToString();
            alObjects.Add(childPath.Remove(0,7)); 
                //remove the LDAP prefix from the path

            child.Close();
            child.Dispose();
        }
        directoryObject.Close();
        directoryObject.Dispose();
    }
    catch (DirectoryServicesCOMException e)
    {
        Console.WriteLine("An Error Occurred: " + e.Message.ToString());
    }
    return alObjects;
}

Enumerate Directory Entry Settings

One of the nice things about the 2.0 classes is the ability to get and set a configuration object for yourdirectoryEntry objects.

static void DirectoryEntryConfigurationSettings(string domainADsPath)
{
    // Bind to current domain

    DirectoryEntry entry = new DirectoryEntry(domainADsPath);
    DirectoryEntryConfiguration entryConfiguration = entry.Options;

    Console.WriteLine("Server: " + entryConfiguration.GetCurrentServerName());
    Console.WriteLine("Page Size: " + entryConfiguration.PageSize.ToString());
    Console.WriteLine("Password Encoding: " + 
        entryConfiguration.PasswordEncoding.ToString());
    Console.WriteLine("Password Port: " + 
        entryConfiguration.PasswordPort.ToString());
    Console.WriteLine("Referral: " + entryConfiguration.Referral.ToString());
    Console.WriteLine("Security Masks: " + 
        entryConfiguration.SecurityMasks.ToString());
    Console.WriteLine("Is Mutually Authenticated: " + 
        entryConfiguration.IsMutuallyAuthenticated().ToString());
    Console.WriteLine();
    Console.ReadLine();
}

Active Directory Objects

//These methods require these imports

//You must add a references in your project as well

using System.DirectoryServices;

Check for the Existence of an Object

This method does not need you to know the distinguishedName, you can concat strings or even guess a location and it will still run (and return false if not found).

public static bool Exists(string objectPath)
{
    bool found = false;
    if (DirectoryEntry.Exists("LDAP://" + objectPath))
    {
        found = true;
    }
    return found;
}

Move an Object from one Location to Another

It should be noted that the string newLocation should NOT include the CN= value of the object. The method will pull that from the objectLocation string for you. So object CN=group,OU=GROUPS,DC=contoso,DC=comis sent in as the objectLocation but the newLocation is something like:OU=NewOUParent,DC=contoso,DC=com. The method will take care of the CN=group.

public void Move(string objectLocation, string newLocation)
{
    //For brevity, removed existence checks

    DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + objectLocation);
    DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newLocation);
    string newName = eLocation.Name;
    eLocation.MoveTo(nLocation, newName);
    nLocation.Close();
    eLocation.Close();
}

Enumerate Multi-String Attribute Values of an Object

This method includes a recursive flag in case you want to recursively dig up properties of properties such as enumerating all the member values of a group and then getting each member group’s groups all the way up the tree.

public ArrayList AttributeValuesMultiString(string attributeName,
     string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}

Enumerate Single String Attribute Values of an Object

public string AttributeValuesSingleString
    (string attributeName, string objectDn)
{
    string strValue;
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    strValue = ent.Properties[attributeName].Value.ToString();
    ent.Close();
    ent.Dispose();
    return strValue;
}

Enumerate an Object’s Properties: The Ones with Values

public static ArrayList GetUsedAttributes(string objectDn)
{
    DirectoryEntry objRootDSE = new DirectoryEntry("LDAP://" + objectDn);
    ArrayList props = new ArrayList();

    foreach (string strAttrName in objRootDSE.Properties.PropertyNames)
    {
        props.Add(strAttrName);
    }
    return props;
}

Get an Object DistinguishedName: ADO.NET search (ADVANCED)

This method is the glue that ties all the methods together since most all the methods require the consumer to provide a distinguishedName. Wherever you put this code, you must ensure that you add these enumerations as well. This allows the consumers to specify the type of object to search for and whether they want thedistinguishedName returned or the objectGUID.

public enum objectClass
{
    user, group, computer
}
public enum returnType
{
 distinguishedName, ObjectGUID
}

A call to this class might look like:

myObjectReference.GetObjectDistinguishedName(objectClass.user, returnType.ObjectGUID,"john.q.public", "contoso.com")

public string GetObjectDistinguishedName(objectClass objectCls,
    returnType returnValue, string objectName, string LdapDomain)
{
    string distinguishedName = string.Empty;
    string connectionPrefix = "LDAP://" + LdapDomain;
    DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
    DirectorySearcher mySearcher = new DirectorySearcher(entry);

    switch (objectCls)
    {
        case objectClass.user:
            mySearcher.Filter = "(&(objectClass=user)
        (|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
            break;
        case objectClass.group:
            mySearcher.Filter = "(&(objectClass=group)
        (|(cn=" + objectName + ")(dn=" + objectName + ")))";
            break;
        case objectClass.computer:
            mySearcher.Filter = "(&(objectClass=computer)
            (|(cn=" + objectName + ")(dn=" + objectName + ")))";
            break;
    }
    SearchResult result = mySearcher.FindOne();

    if (result == null)
    {
        throw new NullReferenceException
        ("unable to locate the distinguishedName for the object " +
        objectName + " in the " + LdapDomain + " domain");
    }
    DirectoryEntry directoryObject = result.GetDirectoryEntry();
    if (returnValue.Equals(returnType.distinguishedName))
    {
        distinguishedName = "LDAP://" + directoryObject.Properties
            ["distinguishedName"].Value;
    }
    if (returnValue.Equals(returnType.ObjectGUID))
    {
        distinguishedName = directoryObject.Guid.ToString();
    }
    entry.Close();
    entry.Dispose();
    mySearcher.Dispose();
    return distinguishedName;
}

Convert distinguishedName to ObjectGUID

public string ConvertDNtoGUID(string objectDN)
{
    //Removed logic to check existence first

    DirectoryEntry directoryObject = new DirectoryEntry(objectDN);
    return directoryObject.Guid.ToString();
}

Convert an ObjectGUID to OctectString: The Native ObjectGUID

public static string ConvertGuidToOctectString(string objectGuid)
{
    System.Guid guid = new Guid(objectGuid);
    byte[] byteGuid = guid.ToByteArray();
    string queryGuid = "";
    foreach (byte b in byteGuid)
    {
        queryGuid += @"\" + b.ToString("x2");
    }
    return queryGuid;
}

Search by ObjectGUID or convert ObjectGUID to distinguishedName

public static string ConvertGuidToDn(string GUID)
{
      DirectoryEntry ent = new DirectoryEntry();
      String ADGuid = ent.NativeGuid;
      DirectoryEntry x = new DirectoryEntry("LDAP://{GUID=" + ADGuid + ">"); 
          //change the { to <>

      return x.Path.Remove(0,7); //remove the LDAP prefix from the path

}

Publish Network Shares in Active Directory

 //Example

 private void init()
{
    CreateShareEntry("OU=HOME,dc=baileysoft,dc=com",
        "Music", @"\\192.168.2.1\Music", "mp3 Server Share");
    Console.ReadLine();
}

//Actual Method

public void CreateShareEntry(string ldapPath,
    string shareName, string shareUncPath, string shareDescription)
{
    string oGUID = string.Empty;
    string connectionPrefix = "LDAP://" + ldapPath;
    DirectoryEntry directoryObject = new DirectoryEntry(connectionPrefix);
    DirectoryEntry networkShare = directoryObject.Children.Add("CN=" + 
        shareName, "volume");
    networkShare.Properties["uNCName"].Value = shareUncPath;
    networkShare.Properties["Description"].Value = shareDescription;
    networkShare.CommitChanges();

    directoryObject.Close();
    networkShare.Close();
}

Create a New Security Group

Note: by default if no GroupType property is set, the group is created as a domain security group.

public void Create(string ouPath, string name)
{
    if (!DirectoryEntry.Exists("LDAP://CN=" + name + "," + ouPath))
    {
        try
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
            DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
            group.Properties["sAmAccountName"].Value = name;
            group.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
    }
    else { Console.WriteLine(path + " already exists"); }
}

Delete a group

public void Delete(string ouPath, string groupPath)
{
    if (DirectoryEntry.Exists("LDAP://" + groupPath))
    {
        try
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
            DirectoryEntry group = new DirectoryEntry("LDAP://" + groupPath);
            entry.Children.Remove(group);
            group.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
    }
    else
    { 
        Console.WriteLine(path + " doesn't exist"); 
    }
}

Active Directory Users Tasks

//These methods require these imports

//You must add a references in your project as well

using System.DirectoryServices;

Authenticate a User Against the Directory

Per John Storer, thanks for sharing.

private bool Authenticate(string userName,
    string password, string domain)
{
    bool authentic = false;
    try
    {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain,
            userName, password);
        object nativeObject = entry.NativeObject;
        authentic = true;
    }
    catch (DirectoryServicesCOMException) { }
    return authentic;
}

Add User to Group

public void AddToGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Add(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}

Remove User from Group

public void RemoveUserFromGroup(string userDn, string groupDn)
{
    try
    {
        DirectoryEntry dirEntry = new DirectoryEntry("LDAP://" + groupDn);
        dirEntry.Properties["member"].Remove(userDn);
        dirEntry.CommitChanges();
        dirEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //doSomething with E.Message.ToString();

    }
}

Get User Group Memberships of the Logged in User from ASP.NET

public ArrayList Groups()
{
    ArrayList groups = new ArrayList();
    foreach (System.Security.Principal.IdentityReference group in
        System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
    {
        groups.Add(group.Translate(typeof
            (System.Security.Principal.NTAccount)).ToString());
    }
    return groups;
}

Get User Group Memberships

This method requires that you have the AttributeValuesMultiString method earlier in the article included in your class.

public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", userDn,
        groupMemberships, recursive);
}

Create User Account

public string CreateUserAccount(string ldapPath, string userName, 
    string userPassword)
{
    try
    {
        string oGUID = string.Empty;
        string connectionPrefix = "LDAP://" + ldapPath;
        DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
        DirectoryEntry newUser = dirEntry.Children.Add
            ("CN=" + userName, "user");
        newUser.Properties["samAccountName"].Value = userName;
        newUser.CommitChanges();
        oGUID = newUser.Guid.ToString();

        newUser.Invoke("SetPassword", new object[] { userPassword });
        newUser.CommitChanges();
        dirEntry.Close();
        newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingwith --> E.Message.ToString();

    }
    return oGUID;
}

Dealing with User Passwords

There are some specifics to understand when dealing with user passwords and boundaries around passwords such as forcing a user to change their password on the next logon, denying the user the right to change their own passwords, setting passwords to never expire, to when to expire, and these tasks can be accomplished usingUserAccountControl flags that are demonstrated in the proceeding sections. Please refer to this great MSDN article: Managing User Passwords for examples and documentation regarding these features. (thanks to Daniel Ocean for identifying this resource)

//Add this to the create account method

int val = (int)newUser.Properties["userAccountControl"].Value; 
     //newUser is DirectoryEntry object

newUser.Properties["userAccountControl"].Value = val | 0x80000; 
    //ADS_UF_TRUSTED_FOR_DELEGATION

All UserAccountControl flags

CONST   HEX
-------------------------------
        SCRIPT 0x0001
        ACCOUNTDISABLE 0x0002
        HOMEDIR_REQUIRED 0x0008
        LOCKOUT 0x0010
        PASSWD_NOTREQD 0x0020
        PASSWD_CANT_CHANGE 0x0040
        ENCRYPTED_TEXT_PWD_ALLOWED 0x0080
        TEMP_DUPLICATE_ACCOUNT 0x0100
        NORMAL_ACCOUNT 0x0200
        INTERDOMAIN_TRUST_ACCOUNT 0x0800
        WORKSTATION_TRUST_ACCOUNT 0x1000
        SERVER_TRUST_ACCOUNT 0x2000
        DONT_EXPIRE_PASSWORD 0x10000
        MNS_LOGON_ACCOUNT 0x20000
        SMARTCARD_REQUIRED 0x40000
        TRUSTED_FOR_DELEGATION 0x80000
        NOT_DELEGATED 0x100000
        USE_DES_KEY_ONLY 0x200000
        DONT_REQ_PREAUTH 0x400000
        PASSWORD_EXPIRED 0x800000
        TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000

Enable a User Account

public void Enable(string userDn)
{
    try
    {
        DirectoryEntry user = new DirectoryEntry(userDn);
        int val = (int)user.Properties["userAccountControl"].Value;
        user.Properties["userAccountControl"].Value = val & ~0x2; 
            //ADS_UF_NORMAL_ACCOUNT;

        user.CommitChanges();
        user.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();

    }
}

Disable a User Account

public void Disable(string userDn)
{
    try
    {
        DirectoryEntry user = new DirectoryEntry(userDn);
        int val = (int)user.Properties["userAccountControl"].Value;
        user.Properties["userAccountControl"].Value = val | 0x2; 
             //ADS_UF_ACCOUNTDISABLE;

        user.CommitChanges();
        user.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();

    }
}

Unlock a User Account

public void Unlock(string userDn)
{
    try
    {
        DirectoryEntry uEntry = new DirectoryEntry(userDn);
        uEntry.Properties["LockOutTime"].Value = 0; //unlock account

        uEntry.CommitChanges(); //may not be needed but adding it anyways

        uEntry.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //DoSomethingWith --> E.Message.ToString();

    }
}

Alternate Lock/Unlock Account

It’s hard to find code to lock an account. Here is my code to lock or unlock an account. dEntry is class variable already set to a user account. Shared by dextrous1.

/// <span class="code-SummaryComment"><summary></span>
/// Gets or sets a value indicating if the user account is locked out
/// <span class="code-SummaryComment"></summary></span>
public bool IsLocked
{
    get { return Convert.ToBoolean(dEntry.InvokeGet("IsAccountLocked")); }
    set { dEntry.InvokeSet("IsAccountLocked", value); }
}

Reset a User Password

public void ResetPassword(string userDn, string password)
{
    DirectoryEntry uEntry = new DirectoryEntry(userDn);
    uEntry.Invoke("SetPassword", new object[] { password });
    uEntry.Properties["LockOutTime"].Value = 0; //unlock account

    uEntry.Close();
}

Rename an Object

public static void Rename(string objectDn, string newName)
{
    DirectoryEntry child = new DirectoryEntry("LDAP://" + objectDn);
   child.Rename("CN=" + newName);
}

Conclusion

I would have liked to include a sample project but my professional code is so tightly integrated with customer proprietary code that it was not feasible at this time.

UPDATE

If you would like to see an extremely simple implementation of some of this code check out theDirectoryServicesBrowserDialog I posted some time ago. This should demonstrate to those of you who are having trouble adding the proper references or having other difficulties.

I hope this helps out all those programmers that were like me and had to get up to speed really quickly and lost countless hours studying the System.DirectoryServices assembly trying to dig up answers on how to do AD tasks.

If you have some additional segments of code that are small but efficient that you’d like to include send them to me and I’ll add them to this document.

History

  • Originally submitted – 22 March 2007
  • Added GetUsedAttributes() method – 24 March 2007
  • Added EnumerateOU() method – 25 March 2007
  • Added CreateShareEntry() – 27 March 2007
  • Added CommitChanged() call in UnlockUserAccount()
  • Cleaned up article, added a few new methods – 03 Apr 2007
  • Added note on DirectoryEntry – 04 Apr 2007
  • Added note on working with local accounts – 12 Apr 2007
  • Added code for creating/deleting groups – 20 Apr 2007
  • Added John Storer’s code for authenticating users against the directory
  • Added UserAccountControl flags section – 06 Jun 2007
  • Added Managing IIS with DirectoryEntry() section – 12 Jun 2007
  • Created table of contents – 09 Jul 2007
  • Added Dealing with User Passwords Section – 21 May 2008
  • Added Alternate Lock/Unlock Account by dextrous1 – 21 May 2008