Developping for the translation industry RSS 2.0



 Wednesday, 10 June 2009

This C# snippet lets you enumerate all the domain controllers in the current Active Directory Domain.

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

public static ArrayList GetDomainControllerNames()
{

ArrayList domainControllerList = new ArrayList();
Domain currentDomain = Domain.GetCurrentDomain();
foreach (DomainController dc in currentDomain.DomainControllers)
{

domainControllerList .Add(dc.Name);

}
return domainControllerList ;

}

Other relevant posts:

How To: Create User Accounts in Active Directory using C#

How to enumerate the Domains in the current Forest in C#

How To: Use Active Directory To Authenticate Users

Wednesday, 10 June 2009 13:07:53 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | Code Snippet

This C# snippet lets you enumerate all the domains present in the current Active Directory Forest.

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

public static ArrayList GetDomainNames()
{

ArrayList domainList = new ArrayList();
Forest currentForest = Forest.GetCurrentForest();
DomainCollection myDomains = currentForest.Domains;
foreach (Domain domainItem in myDomains)
{

domainList.Add(domainItem.Name);

}

return domainList;

}

Other relevant posts:

How To: Create User Accounts in Active Directory using C#

How To: set NTFS Permissions using C#

How To: Use Active Directory To Authenticate Users

Wednesday, 10 June 2009 12:57:23 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | Code Snippet
 Friday, 20 March 2009

This function creates a new user Account in your active directory domain:

public string CreateUserAccount(string ldapPath, string userName, string password)
{
    try
    {
        string connectionPrefix = "LDAP://" + ldapPath;

        DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix);
        DirectoryEntry newUser = dirEntry.Children.Add(
"CN=" + userName, "user");

        newUser.Properties["samAccountName"].Value = userName;
        newUser.CommitChanges();

        newUser.Invoke("SetPassword", new object[] { password });
        newUser.CommitChanges();

        dirEntry.Close();
        newUser.Close();
    }
    catch (System.DirectoryServices.DirectoryServicesCOMException E)
    {
        //…
    }
}
 

Related posts :

How To: Use Active Directory To Authenticate Users

How To: set NTFS Permissions using C#

How to enumerate the Domain Controllers in the current Domain in C#

Friday, 20 March 2009 13:11:31 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | Code Snippet
 Wednesday, 17 December 2008

This method tries to stop the service (and waits until it's stopped) then it begins to start the service (and waits until the service is running). The specified timeout is used for both operations together.

First, you need to add a using directive to System.ServiceProcess.

using System.ServiceProcess;

This is the method to restart the service:

public static void RestartService(string serviceName, int timeoutMilliseconds)
{
    ServiceController service =
new ServiceController(serviceName);
    try
    {
        int millisec1 = Environment.TickCount;
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

        // count the rest of the timeout
        int millisec2 = Environment.TickCount;
        timeout =
TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    }
    catch
    {
        // ...
    }
}

Wednesday, 17 December 2008 15:22:24 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | Code Snippet
 Tuesday, 06 May 2008

This code example sets the permission to create files and update them in a folder for a particular user but doesn’t propagate these permissions to the subfolders.

 

using System.Security.AccessControl;

 

System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(folder);

DirectorySecurity folderSecurity = folderInfo.GetAccessControl();

 

FileSystemAccessRule rule =

      new FileSystemAccessRule(

      "Domain\\username",

      FileSystemRights.ReadAndExecute |

        FileSystemRights.AppendData |

        FileSystemRights.CreateFiles |

        FileSystemRights.Write,

      InheritanceFlags.ObjectInherit,

      PropagationFlags.None,

      AccessControlType.Allow);

 

folderSecurity.AddAccessRule(rule);

folderInfo.SetAccessControl(folderSecurity);

Tuesday, 06 May 2008 17:52:15 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C# | Code Snippet
 Wednesday, 19 December 2007

Jeff Atwood recently posted on the topic of sorting strings in a more natural order that the default string sorting gives us.  His main point is, when we’re dealing with numbers, a simple alphabetic sorting doesn’t cut it.

So. just for fun, here’s my little C# 2.0 Implementation of a more human-friendly sorter.

 

public class FriendlySorter<T> : IComparer<T>

{

    public int Compare(T x, T y)

    {

        if (x == null || y == null) return 0;

        if (x.ToString() == y.ToString()) return 0;

 

        string[] left = Regex.Split(x.ToString(), "([0-9]+)");

        string[] right = Regex.Split(y.ToString(), "([0-9]+)");

 

        int index = 0;

 

        while (true)

        {

            while (left[index] == right[index]) index++;

 

            if (left.Length == index && right.Length == index) return 0;

            if (left.Length <= index) return -1;

            if (right.Length <= index) return 1;

 

            try

            {

                return (int.Parse(left[index]) - int.Parse(right[index]));

            }

            catch

            {

                int CompareResult = String.Compare(left[index], right[index]);

                if (CompareResult != 0) return CompareResult;

            }

 

            index++;

        }

    }

}

 

The following code :

List<string> list = new List<string>();

 

list.Add("Track 1 : abc");

list.Add("Track 2 : abc");

list.Add("Track 10 : abc");

list.Add("Track 5 : abc");

list.Add("Track 11 : abc");

list.Add("Track 22 : abc");

list.Add("Track 9 : abc");

 

list.Sort(new FriendlySorter<string>());

 

Will produce the results :

Sshot-4

For small sets the performance is Ok.  But when dealing with a larger amount of data (1000+ items), the sorting performance drops a lot (I currently have 5 seconds to sort 1000 random elements).  I will probably try to enhance it in the future and update this post.

Happy holidays !

Tags:
Wednesday, 19 December 2007 18:42:12 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C# | Code Snippet
 Wednesday, 10 October 2007

It’s a shame how many applications, even popular ones, have huge security gaps regarding passwords.  The most recent case to hit the news was Reddit but this is only the tip of the iceberg.  How many internals applications out there uses plain text password.  A whole lot!  You probably did it at some point, and so do I.  But the object of this post is not to rant and whine about that situation.  I just want to show those who don’t know about it how easy it is to integrate Windows Active Directory authentication to your application.  So now, if you read this my blog, no more excuses to have that “password” field in your database.

First you need to add a reference in your project to System.DirectoryServices

Here is the code, I will catch you up on the other side.

try

String Username = "username";

String domainAndUsername = "domain\\username";

String Password = "password";

 

DirectoryEntry entry = new DirectoryEntry("", domainAndUsername, Password);

DirectorySearcher search = new DirectorySearcher(entry);

 

search.Filter = "(SAMAccountName=" + Username + ")";

 

// search.FindOne() will throw an exception if there is a bad username/password combination provided

SearchResult result = search.FindOne();

 

// User is authenticated

catch 

    throw new System.Security.SecurityException("Access denied.");

End Try

Pretty straightforward isn’t it?  Obviously, you need to change the first lines with the user’s input but other than that, it’s all that’s needed for a basic username/password authentication using Active Directory.  You can copy this code and use it in your application and see for yourself.  If you want more information on what you can get from Active Directory, there is a good article on the different name attributes here.  You can also go to the homepage of System.DirectoryService on MSDN here.

I want to add that I’m not an Active Directory expert.  If a reader see something wrong with this code, please let me know and I’ll update it right away!

Other Posts:

How to create user accounts in active directory using C#

Wednesday, 10 October 2007 10:59:42 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C# | Code Snippet

Navigation
Advertisement
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Stanislas Biron
Sign In
Statistics
Total Posts: 135
This Year: 0
This Month: 0
This Week: 0
Comments: 1
All Content © 2017, Stanislas Biron