Developping for the translation industry RSS 2.0



 Thursday, 29 July 2010

Here is a simple way to get a specific character count (for example, count the number of occurences of the character ‘0’) and the word count of a varchar string using T-SQL.

-- Count the number of specific characters, in this case, ‘0’

Declare @value varchar(100)

Set @value = 'SQL Server 2000, SQL Server 2005, SQL Server 2008'

Select Len(@value) - Len(Replace(@value, '0', ''))

 

-- Count the number of words

DECLARE @String VARCHAR(100)

SELECT @String = 'SQL Server 2005 Stan test code'

SELECT LEN(@String) - LEN(REPLACE(@String, ' ', '')) + 1

 

As you see this is quite straightforward, the script simply substract the length of the string minus the character searched from the full length of the string, giving as a result the character count. The script counting words is simply counting the space characters.

 

Other posts:

How to remove multiple whitespaces from a string with SQL Server 2005

How to generate random numbers with a SQL query

How to remove leading zeros from the results of an SQL Query

How to Find The List Of Unused Tables Since The Last SQL Server Restart

Which performs better: ISNULL or COALESCE

Thursday, 29 July 2010 08:58:32 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Wednesday, 24 February 2010

The SQL Server functions ISNULL and COALESCE seem to occupy the same space in terms of functionality. The only difference is that ISNULL is restricted to only two parameters, while COALESCE can take any number of parameters. So why ever use ISNULL?

First of all, the simple answer for why to prefer ISNULL over COALESCE when given the choice is that ISNULL tends to produce query plans that are more efficient than COALESCE's. Examine the query plans for the two queries given below to see the difference:

SELECT a.au_id, 
       Isnull
((SELECT price
               FROM   titles
               WHERE  title_id = ta.title_id),0)
FROM   authors a
       JOIN titleauthor ta
         ON a.au_id = ta.au_id

————————————

SELECT a.au_id, 
       Coalesce((SELECT price
                 FROM   titles
                 WHERE  title_id = ta.title_id),0)
FROM   authors a
       JOIN titleauthor ta
         ON a.au_id = ta.au_id

The first query uses one less nested loop in it’s execution plan than the second, resulting in a lower overall cost. Note that I would never recommend writing queries that nest subqueries within functions. This example was only intended to show you the difference between the two generated execution plans, not to recommend a certain T-SQL coding style.

The other bit that most people don't know about ISNULL and COALESCE is that the return data type for ISNULL is guaranteed to be the same as the data type of the first parameter. However, the return data type of COALESCE is determined by data type precedence rules (see the Books Online topic "Data Type Precedence"). Therefore, the following queries will produce two different outputs:

DECLARE  @Example CHAR(2)
SET @Example = NULL

SELECT Isnull(@Example,'abcde'),
       Coalesce(@Example,'abcde')

In this example, the first expression using ISNULL will return 'ab', which is the declared datatype of the first parameter, a char(2). The second expression using COALESCE will return the highest precedence data type, which is the longer string 'abcde.'

To summarize:

  • When you only need to coalesce two arguments, use ISNULL instead because it performs better.
  • When using COALESCE, you may want to use explicit casting to ensure you get a consistent return data type.

Other posts:

5 ways to generate random numbers with a T-SQL query

How to remove leading zeros from the results of an SQL Query

How to get the list of object modifications in SQL Server

How to use derived tables to boost SQL performance

Good Joke on SQL Injection

Wednesday, 24 February 2010 10:15:13 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Tuesday, 09 February 2010

Here is a quick and easy way to remove multiple whitespaces from a string, leaving only one space character between tokens.

CREATE FUNCTION dbo.CleanString
               (@string VARCHAR
(50))
RETURNS VARCHAR
(50)
AS
  BEGIN
    SET @string = Ltrim
(Rtrim(@string))
    
    WHILE Charindex
('  ',@string) > 1
      SET @string = Replace
(@string,'  ',' ')
    
    RETURN @string
  END

 

Other Posts:

How to generate random numbers with a T-SQL query

How to insert a file in an image column in SQL Server 2005

How to track the growth of your SQL Server database

SQL Server indexing best practices and guidelines

How to remove leading zeros from the results of an SQL Query

Tuesday, 09 February 2010 13:24:17 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Wednesday, 03 February 2010

The sys.objects system table offers you some information on the last modifications made on any database object. As a quick example, the following script queries for the list of user tables modified since the start of this year.

DECLARE  @date  AS DATETIME
SET @date = '2010-01-01'

SELECT   name, 
         type_desc,
         create_date,
         modify_date
FROM     sys.objects
WHERE    TYPE = 'U'
         AND modify_date >= @date
ORDER BY modify_date

Now this knowledge can help you manage your SQL Servers more easily. You could, for example, create a script that runs every night and send you within an email the list of objects modified the last day.

The list of available types to filter your search are:

AF Aggregate function (CLR)
C CHECK constraint
D DEFAULT (constraint or stand-alone)
F FOREIGN KEY constraint
FN SQL scalar function
FS Assembly (CLR) scalar-function
FT Assembly (CLR) table-valued function
IF SQL inline table-valued function
IT Internal table
P SQL Stored Procedure
PC Assembly (CLR) stored-procedure
PG Plan guide
PK PRIMARY KEY constraint
R Rule (old-style, stand-alone)
RF Replication-filter-procedure
S System base table
SN Synonym
SQ Service queue
TA Assembly (CLR) DML trigger
TF SQL table-valued-function
TR SQL DML trigger
TT Table type
U Table (user-defined)
UQ UNIQUE constraint
V View
X Extended stored procedure

 

Other posts:

How to: Find The List Of Unused Tables Since The Last SQL Server Restart

Differences between temporary tables and table variables

Using derived tables to boost SQL performance

How to track the growth of your database

Wednesday, 03 February 2010 11:00:54 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Monday, 01 February 2010

This script will return a list of user tables in the database, along with the last time a SELECT was executed against them (including any views that include data from that table). This can be used to determine if a table is not in use anymore.

Statistics are reset when the SQL Server sevice is restarted, so this query will only return activity since that time. Also, just because there's no activity doesn't mean it's safe to remove an object - some tables may only be used during monthly or annual processes, and so they wouldn't show any activity except during those brief intervals.

WITH lastactivity(objectid,lastaction)
     AS (SELECT object_id      AS tablename,
                last_user_seek AS lastaction
         FROM   sys.dm_db_index_usage_stats u
         WHERE  database_id = Db_id
(Db_name())
         UNION
         SELECT object_id      AS tablename,
                last_user_scan AS lastaction
         FROM   sys.dm_db_index_usage_stats u
         WHERE  database_id = Db_id
(Db_name())
         UNION
         SELECT object_id        AS tablename,
                last_user_lookup AS lastaction
         FROM   sys.dm_db_index_usage_stats u
         WHERE  database_id = Db_id
(Db_name()))
SELECT   Object_name
(so.object_id) AS tablename,
         Max
(la.lastaction)        AS lastselect
FROM     sys.objects so
         LEFT JOIN lastactivity la
           ON so.object_id = la.objectid
WHERE    so.TYPE = 'U'
         AND so.object_id > 100
GROUP BY Object_name
(so.object_id)
ORDER BY Object_name
(so.object_id)

 

Other posts:

How to generate random numbers within a T-SQL query

SQL Server SPACE function

SQL Injection humor

Differences between temporary tables and table variables

How to track the growth of your database

How to get the total number of rows in a database

Using derived tables to boost SQL performance

Monday, 01 February 2010 10:36:17 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Monday, 11 January 2010

A little quicky post on the SQL Server SPACE function. The SPACE function returns a string that consists of a specified number of spaces.

The following command will generate 10 space characters:

SELECT SPACE(10)

The use of SPACE() function is demonstrated very clearly in BOL:

USE AdventureWorks;
GO
SELECT RTRIM(LastName) + ',' + SPACE(2) + LTRIM(FirstName)
FROM Person.Contact
ORDER BY LastName, FirstName;
GO

A very useful little function.

 

Others posts:

How to generate random numbers within a T-SQL query

How to remove leading zeros within an SQL query

Some tips to enhance your SQL Server security

The T-SQL LoginProperty function in SQL Server 2005

Monday, 11 January 2010 09:42:00 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Friday, 20 November 2009

There are many ways to generate random numbers in SQL Server. Here are some scripts that will let you accomplish this.

Method 1 : Generate Random Numbers (Int) between Rang
---- Create the variables for the random number generation
DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT

---- This will create a random number between 1 and 999
SET @Lower = 1 ---- The lowest random number
SET @Upper = 999 ---- The highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random

Method 2 : Generate Random Float Numbers
SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )
+ (
DATEPART(ss, GETDATE()) * 1000 )
+
DATEPART(ms, GETDATE()) )


Method 3 : Random Numbers Quick Scripts

---- random float from 0 up to 20 - [0, 20)
SELECT 20*RAND()
-- random float from 10 up to 30 - [10, 30)
SELECT 10 + (30-10)*RAND()
--random integer BETWEEN 0
AND 20 - [0, 20]
SELECT CONVERT(INT, (20+1)*RAND())
----random integer BETWEEN 10
AND 30 - [10, 30]
SELECT 10 + CONVERT(INT, (30-10+1)*RAND())


Method 4 : Random Numbers (Float, Int) Tables Based with Time

DECLARE @t TABLE( randnum float )
DECLARE @cnt INT; SET @cnt = 0
WHILE @cnt <=10000
BEGIN
SET
@cnt = @cnt + 1
INSERT INTO @t
SELECT RAND( (DATEPART(mm, GETDATE()) * 100000 )
+ (
DATEPART(ss, GETDATE()) * 1000 )
+
DATEPART(ms, GETDATE()) )
END
SELECT
randnum, COUNT(*)
FROM @t
GROUP BY randnum


Method 5 : Random number on a per row basis

---- The distribution is pretty good however there are the occasional peaks.
---- If you want to change the range of values just change the 1000 to the maximum value you want.
---- Use this as the source of a report server report and chart the results to see the distribution
SELECT randomNumber, COUNT(1) countOfRandomNumber
FROM (
SELECT ABS(CAST(NEWID() AS binary(6)) %1000) + 1 randomNumber
FROM sysobjects) sample
GROUP BY randomNumber
ORDER BY randomNumber

 

Other posts :

How to convert dates in T-SQL

How to remove leading zeros within an SQL Query

How to insert a file in an image column in SQL Server 2005

 

Friday, 20 November 2009 10:21:08 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 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
 Wednesday, 12 November 2008

For my own reference, and yours, here's a complete overview of everything possible with a mailto link.

There are a couple of variables you can use in the queryString. As with any other URL, you use the ? to add the query parameters and the & to separate each parameter, which are in the form param=value

Here are the variables you can use in these mailto links:

mailto: to set the recipient, or recipients, separate with comma
cc to set the CC recipient(s)
bcc to set the BCC recipient(s)
subject to set the email subject, URL encode for longer sentences, so replace spaces with %20, etc.
body to set the body of the message, you can add entire sentences here, including line breaks. Line breaks should be converted to %0A.

Some mailto examples

Simple mailto link:

<a href="mailto:info@example.com">mail link</a>

mailto link with subject:

<a href="mailto:info@example.com?subject=email%20subject">mail link</a>

mailto link with multiple recipients:

<a href="mailto:info@example.com,email@example.com">mail link</a>

mailto link with a CC:

<a href="mailto:info@example.com?cc=email2@example.com">mail link</a>

mailto with message body already started:

<a href="mailto:info@example.com?body=these%20mailto%20links%20are%20cool">mail link</a>

mailto with 3 lines of message body:

<a href="mailto:info@example.com?body=these%20mailto%0Alinks%20are%0Acool">mail link</a>

mailto with 3 lines of message body and a BCC:

<a href="mailto:info@example.com?bcc=mail2@example.com&body=these%20mailto%0Alinks%20are%0Acool">mail link</a>

As you can see, you can add as many of these as you want and stack them on top of each other. On top of that, for the code to be valid HTML, you will have to replace every & with &amp;.

Happy mailing!

 

Other posts :

How To: Create an Outlook 2003 addin using VSTO SE and Visual Studio 2005

How to insert a file in an image column in SQL Server 2005

Tools for Web developers

Wednesday, 12 November 2008 13:45:47 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet
 Thursday, 16 October 2008

As a DBA, you may want to know the evolution, in time, of your databases size. To do so, you just need to execute the following script, after having changed ‘databaseName’ with your database’s name.  This script won’t look for the actual database size but for the backup size, which is a very good indicator. It’s good to note that only full backups are logged in this table, so, if you have a full backup every night and 4 differential scattered through the day, only the full backup will be logged.

        Select backup_start_date, SizeInMegs=floor(backup_size/1024000)
        from msdb..backupset
        where database_name = 'DatabaseName' and type = 'd'

        order by backup_start_date asc

 

Other interesting SQL posts :

SQL Server indexing best practices and guidelines

How to insert a file in an image column in SQL Server 2005

How to remove leading zeros within an SQL query


Other popular posts

How To: Create an Outlook 2003 addin using VSTO SE and Visual Studio 2005

Thursday, 16 October 2008 09:00:37 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Wednesday, 30 July 2008

A common thing you may want to do when dealing with transactions involving various documents and files is insert them into you SQL Server database.  The following code snippet let you load a file from the disk and insert it into your database.

INSERT INTO myTable (documentData)
SELECT * FROM
OPENROWSET(BULK N'c:\myDocument.doc', SINGLE_BLOB) as dt

Note that you need to name the select statement (here, I named it “dt”) or you will get this error message:

Server: Msg 491, Level 16, State 1, Line 3
A correlation name must be specified for the bulk rowset in the from clause.


Wednesday, 30 July 2008 12:38:15 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Thursday, 10 July 2008

Using SQL Server 2005 new function ROW_NUMBER() makes this really easy.

All you have to do is to add the function ROW_NUMBER, with the OVER() clause as such :

SELECT ROW_NUMBER() 
        OVER (ORDER BY EmployeeName) AS Row, 
    EmployeeId, EmployeeName, Salary 
FROM Employees
The OVER clause needs an “order by” parameter to know how to sort the rows for proper numbering.
 
Thursday, 10 July 2008 15:58:08 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL

There is a very simple script to accomplish this and this can be really helpful for generating stats on a week-by-week basis:

SELECT DATEADD(wk, DATEDIFF(wk, 0, GetDate()), 0)

Replace GetDate with a datetime column and you could generate, for example, a sales report, week-by-week.

Thursday, 10 July 2008 12:25:54 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Wednesday, 02 July 2008

This isn’t necessary a critical part of a DBA’s job but, at times, it can be useful to have an idea of how many rows are in your databases.

The simplest way to get it is with this query:

select sum(rowcnt) from sysobjects, sysindexes
where sysindexes.id = sysobjects.id and sysindexes.indid in (0, 1) and sysobjects.xtype = 'u'

This will get you the sum of rows in the entire database, for users objects only.  If you want the table-by-table breakdown, you can simply add the name of the object in the query:

select sysobjects.name, sysindexes.rowcnt from sysobjects, sysindexes
where sysindexes.id = sysobjects.id and sysindexes.indid in (0, 1) and sysobjects.xtype = 'u'
order by sysobjects.name

Wednesday, 02 July 2008 09:43:51 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 Monday, 26 May 2008

The LTRIM function in T-SQL only removes whitespaces. But, in some instances, you need to do more complex trimming. The trick is to use the PATINDEX function in conjunction with the STUFF function.  PATINDEX will return the index of the first occurence of a specified pattern.  In my example below, PATINDEX will return the index of the first non-zero character.  STUFF takes 4 parameters:

– the affected column

– the the starting point of the deletion

– the length of the deletion

– a string to insert at the deletion point

So the code below will delete all characters, starting at the first, and finishing before the first non-zero character.  Why not use SUBSTRING instead?  Because STUFF is a little more robust than SUBSTING and will not raise an error on you if the PATINDEX returns -1.

SELECT STUFF(myColumn, 1, PATINDEX('%[^0]%', myColumn) - 1, SPACE(0)) FROM mytable

Also, if you happen to have a column of type float and you want to get the values without the leading zeros (for example, 0.75 would become .75), you simply need to cast your column as varchar and you’re set.


Monday, 26 May 2008 16:49:50 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Code Snippet | SQL
 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