Howto open ("/dev/urandom") on Windows0 Reacties

Just copy-paste2 might save you some time. rand_s is pretty safe on Windows since it uses RtlGenRandom(), but you’ll have to define _CRT_RAND_S first before

Assuming that the cpp somewhere in the class has: m_fd = open("/dev/urandom", O_RDONLY);

Original code: (thanks jacketzhong)

sds CRedLock::GetUniqueLockId()

{

unsigned char buffer[20];

if (_read(m_fd, buffer, sizeof(buffer)) == sizeof(buffer)) {

//获取20byte的随机数据

sds s; s = sdsempty();

for (int i = 0; i < 20; i++)

{

s = sdscatprintf(s, "%02X", bufferIdea); } return s;

}

else

{

//读取失败 printf("Error: GetUniqueLockId %d\n", __LINE__); }

return NULL;

}

Windows CPP compatible:

note: rand_s is not an ANSI standard.

sds CRedLock::GetUniqueLockId()
{
    //获取20byte的随机数据
    auto retVal = sdsempty();
    auto max = 20 / sizeof(unsigned int);
    for (int i = 0; i < max; i++)
    {
        unsigned int number;
        if (rand_s(&number) == 0)
        {           
            retVal = sdscatprintf(retVal, "%08X", number);           
        }
    }
    return retVal;
}

How to parse and read web.Config or app.Config in C++/on Windows0 Reacties

Just a tiny gem, which not often would be required but it can save you some time. It also demonstrates the power of the IXmlReader in unmanaged code. Because, as far I am aware of, the processing time a .config file measuring it with TickCount always is 0 ms (too small to measure). Microsoft has optimized the XML Reader implementation for fast forward reading, and it also does not allocate strings in memory, it just passes the pointer to the unicode strings (either key or value). In line with that, you might appreciate :) why I attach to the BSTR key to find as well.

What this class does, it reads the   section and puts the key value pairs in a ‘named value collection’ item.

Note 1: I am a big fan of CComBSTR when the final client still understands COM/automation. That is the reason I did not use CString in this class. In addition, the CComBSTR class has been boosted by me, to optimize reallocation of existing memory. But you can use the default MS implementation as well. So, you can change CSimpleMap to CSimpleMap if you wish.

Note 2: The .config file is cached but it is parsed again if the filewritetime of the .config file was changed.

config.h header.

#include
#include
#pragma once


using namespace ATL;

class ConfigurationManager
{
private:
    static const int DELAYTICKS = 1000;
    std::map _map;
    time_t _ftLastCheck;
    CComPtr _xmlReader;
    CComPtr _malloc;
    HRESULT CheckTimeOut();
    //ansi version!
    CComBSTR _szFilePath;
   
    void Init();

public:
    ConfigurationManager();
    ConfigurationManager(const BSTR configFile);
    std::wstring& AppSettings(const std::wstring key, PCWSTR defaultValue = NULL);
    BSTR AppSettings(const BSTR key, PCWSTR defaultValue = NULL);
    time_t GetFileTime();
    ~ConfigurationManager();
};

 

Implementation:


#include
#include
#include "config.h"
#pragma comment(lib, "xmllite.lib")


ConfigurationManager::ConfigurationManager(const BSTR configFile) throw()
{
    _szFilePath = configFile;
    time(&_ftLastCheck);
    Init();
}
ConfigurationManager::ConfigurationManager() throw()
{   
    time(&_ftLastCheck);
    _szFilePath.Attach(GetModulePath());   
    if (!_szFilePath.IsEmpty())
    {       
        _szFilePath.Append(L".config");
       
        Init();
    }   
}
void ConfigurationManager::Init() throw()
{
    if (!_szFilePath.IsEmpty())
    {
        HRESULT hr = CoGetMalloc(1, &_malloc);
        hr = CreateXmlReader(IID_IXmlReader, (void**)&_xmlReader, _malloc);
        if (FAILED(hr))
        {
   
        }
    }
}
time_t ConfigurationManager::GetFileTime() throw()
{   
    struct stat stResult;
    CComBSTR ansi(_szFilePath);
    ansi.Attach(ansi.ToByteString());
    ::stat((char*)ansi.m_str, &stResult);        // get the attributes of afile.txt
   
    return stResult.st_mtime;
}
BSTR ConfigurationManager::AppSettings(const BSTR key, PCWSTR defaultValue) throw()
{
   
    HRESULT hr = CheckTimeOut();
    if (FAILED(hr))
    {
      
        return NULL;
    }
    CComBSTR find;
    find.Attach(key);
   
    auto found = _map.find(find);
    find.Detach();
       if (found != _map.end())
    {
        return found->second.Copy();
    }
    else if (defaultValue != NULL)
    {
        return ::SysAllocString(defaultValue);
    }
    return NULL;
   
}
ConfigurationManager::~ConfigurationManager() throw()
{
    _map.clear();
    _xmlReader.Release();
    _malloc.Release();
    _szFilePath.Empty();
}
HRESULT ConfigurationManager::CheckTimeOut() throw()
{
   
    auto curT = GetFileTime();
   
    PCWSTR pwzValue;
    auto memResult = ::difftime(curT, _ftLastCheck);
    if (memResult != 0.0F)
    {
        DWORD start = ::GetTickCount();
   
        HRESULT hr = S_OK;
       
        CComPtr pStream;
        CComPtr _readerInput;
       
        hr = ::SHCreateStreamOnFileEx(_szFilePath, STGM_READ | STGM_SHARE_DENY_NONE, FILE_ATTRIBUTE_NORMAL, FALSE,NULL, &pStream);

        if (SUCCEEDED(hr))
        {
            hr = ::CreateXmlReaderInputWithEncodingCodePage(pStream, _malloc, CP_UTF8, TRUE, NULL, &_readerInput);           
            hr = _xmlReader->SetProperty(XmlReaderProperty_DtdProcessing, DtdProcessing_Prohibit);   
            hr = _xmlReader->SetInput(_readerInput);
        }   
        else
        {
            return hr;
        }
       
        XmlNodeType nodeType = XmlNodeType::XmlNodeType_None;
        UINT lenValue;
        PCWSTR key;
        bool startCollecting  = false;
        while (S_OK == _xmlReader->Read(&nodeType) && hr == S_OK)
        {
            switch(nodeType) {
            case XmlNodeType::XmlNodeType_EndElement:
               
                //hr = pReader->GetDepth(&dept);
                hr = _xmlReader->GetLocalName(&pwzValue, NULL);
                if (startCollecting && lstrcmpW(pwzValue, L"appSettings") == 0)
                {
                    //break loop
                    hr = S_FALSE;
                }
                break;
            case XmlNodeType::XmlNodeType_Element:
                {
                    // get element name such as option in

                        hr = _xmlReader->MoveToAttributeByName(L"configSource", NULL);
                        if (hr == S_OK)
                        {
                            hr = _xmlReader->GetValue(&pwzValue, NULL);
                            
                                              
                            if (::PathIsRelativeW(pwzValue) == TRUE)
                            {
                                //TODO: call back to do a Server.MapPath
                                _szFilePath.Attach(FileStripFile(_szFilePath));                               
                                _szFilePath.Append(L'\\');
                                _szFilePath.Append(pwzValue);
                            }
                            else
                            {
                                _szFilePath = pwzValue;
                            }
                            _readerInput.Release();
                            pStream.Release();
                            return CheckTimeOut(); //recursion                           
                        }
                        hr = S_OK;//reset otherwise loop stops
                    }                   
                    else if (startCollecting && lstrcmpW(pwzValue, L"add") == 0)
                    {
                       
                        hr = _xmlReader->MoveToAttributeByName(L"key", NULL);
                        if (hr == S_OK)
                        {
                            hr = _xmlReader->GetValue(&pwzValue, &lenValue);
                            //key.Append( pwzValue, lenValue);
                            key = pwzValue;

                            //ATLTRACE(L"found key %s %d\r\n", pwzValue, lenValue);
                            hr = _xmlReader->MoveToAttributeByName(L"value", NULL);
                            if (hr == S_OK)
                            {
                                _xmlReader->GetValue(&pwzValue, NULL);
                                _map.insert(std::pair(key, pwzValue));
                            }
                        }
                    }                   
                }
                break;
            }
        }
        if (SUCCEEDED(hr)) _ftLastCheck = curT;
        if (_xmlReader != NULL)
        {
            _xmlReader->SetInput(NULL);
        }
    
        return S_FALSE;
       
    }

    return S_OK;
   
};

How to read a HTML page from a remote site using VBA/.NET into a Htmlocument0 Reacties

 

There are a lot of ways to read and parse HTML, the better tricks, don’t use IE itself, since this will deliver automation errors and waste memory.

I’m for 99% of my time into .NET programming, but still, one of my hobbies use an Access 2013 database and thus, a VBA codebase, yummy! And to get powerfeatures, I compiled a tlb to have interfaces like IPersistStreamInit, IStream etc. (it’s called odl compiling and requires  MkTypLib.EXE, not midl.exe!)

Now here is a neat way to fetch/get a plain HTML text and load it into a HTMLDocument without any dependency on IE automation. You’re a smart non-lazy programmer (right?) so you get the idea for C# as well since you need IPersistStreamInit there as well. It’s COM interop, dude!

Public Function HttpGet(ByRef url As String) As mshtml.HTMLDocument
    Dim xmlHttp As MSXML2.ServerXMLHTTP60
    Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP")
    xmlHttp.Open "GET", url, False
    xmlHttp.send
   'set return value
    Set HttpGet = New HTMLDocument
    Dim stream As adodb.stream
    Set stream = CreateObject("ADODB.Stream")
    Dim istrea As IPersistStreamInit
   
   'get interface IPersistStreamInit from HTMLDocument
    Set istrea = HttpGet
   
   'write the muke using a binary array (bytes)
    stream.Type = adTypeBinary
    stream.Open
    stream.write xmlHttp.responseBody
   'reset stream
    stream.position = 0
    'load the muke into the HTMLDocument
    istrea.Load stream

    Dim s As Single
    s = Timer

   'fake body onload ready
    Do Until Timer - s > 10 Or HttpGet.ReadyState = "complete"
        DoEvents        
    Loop

End Function

Fill a dropdownlist using the current UICulture in (ASP.NET)0 Reacties

Just for educational purpose (as for myself as well :) ) I post this code.

Using this, a programmer can use a good practise, that is to use the culture information which is built in, into .NET instead of making that data him/herself.

based upon the following element in web.Config, the list will fill using the correct number of monthnames. It also keeps track of calendars, that have 13 months in some cultures.

<globalization uiCulture="nl-nl"/>

using System;

using System.Collections.Generic;

using System.Web;

using System.Linq;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Threading;

using System.Globalization;

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        int monthNumber = 0;

        CultureInfo ci = Thread.CurrentThread.CurrentUICulture;

        var myMonthnames = ci.DateTimeFormat.MonthNames

            .Take(ci.Calendar.GetMonthsInYear(DateTime.Today.Year)).Select(p => new { monthNo = ++monthNumber, monthName = p });

        ddlMonthnames.DataTextField = "monthName";

        ddlMonthnames.DataValueField = "monthNo";

        ddlMonthnames.DataSource = myMonthnames;

        ddlMonthnames.DataBind();

    }

}

<select name="ddlMonthnames" id="ddlMonthnames">

<option value="1">januarioption>

<option value="2">februarioption>

<option value="3">maartoption>

<option value="4">apriloption>

<option value="5">meioption>

<option value="6">junioption>

<option value="7">julioption>

<option value="8">augustusoption>

<option value="9">septemberoption>

<option value="10">oktoberoption>

<option value="11">novemberoption>

<option value="12">decemberoption>

select>

HOWTO: [DotNet] Convert a DateTime structure to a Rfc822 mime conform string?0 Reacties

If you have to deal with MIME you'll have to interpret date information.

Some programmers argue, that the DotNet framework, should support the RFc822 date format out of the box.
Others say,  'no, you need not, because RFC1123  has already been implemented which goes as "Sun, 04 Dec 2005 20:57:57 GMT" for instance'.

I do not agree with this completely. First because sometimes, you might want to be able to detect the timezone difference between clients. If you have a GMT notation, you have the correct worldtime in sync, but you won't see a difference.

Second, if the RFC or API recommends a RFC822 it is a error to assume that the runtime or their runtime, automatically will deal with rfc1123 as well (it is in many situations).

So here is a way to format your string into rfc822. I did not pack it into a handy class or something. Just use the idea. You could make it detect and accept rfc822 and rfc1123 as well!

    // the (UTC) suffix  is optional. You can leave it out.

    DateTime dt = DateTime.Now;

    string Rfc822DateTime = dt.ToString(@"ddd, dd MMM yyyy HH:mm:ss zzzz (\U\T\C)", System.Globalization.DateTimeFormatInfo.InvariantInfo);

    // remove the time separator in the timezone because zzzz will produce +01:00 for instance

    Rfc822DateTime = Rfc822DateTime.Remove(Rfc822DateTime.LastIndexOf(':'), 1);

 

    // for the sake of completeness I want to state that formatting as an RFc1123 string is as simple as formatting using a predefined mask that is .ToString("r").

    // and do not forget the ToUniversalTime() method or otherwise, the time string is still a local time!

    string rfc1123DateTime = dt.ToUniversalTime().ToString("r"); 

 

    // and convert the rfc822 formatted date back 

    if (Rfc822DateTime.EndsWith("(UTC)"))

        Rfc822DateTime = Rfc822DateTime.Substring(0, Rfc822DateTime.Length - 6);

 

    DateTime rfc822Parse = DateTime.ParseExact(Rfc822DateTime, @"ddd, dd MMM yyyy HH:mm:ss zzzz", System.Globalization.DateTimeFormatInfo.InvariantInfo);

    // rfc822Parse equals e.g.: "Mon, 15 May 2006 08:31:40 GMT"

    // rfc1123DateTime equals eg.: "Mon, 15 May 2006 10:31:40 +0200"

   

    // converting from string to datetime also requires us to convert from UTC to Local manually

    DateTime rfc1123Parse = DateTime.ParseExact(rfc1123DateTime, "r", System.Globalization.DateTimeFormatInfo.InvariantInfo).ToLocalTime();

    if (rfc822Parse != rfc1123Parse)

        throw new FormatException("rfc822Parse and rfc1123Parse should be equal!");

HOWTO: [DotNet] marshale a managed string array for Interop0 Reacties

Normally if you have defined a struct in C# which is for a Win32 call, you might tend to copy-paste it from C++, and then modify LPWSTR to string and add attributes (etc),
like this:

struct myStruct
{
   [MarshalAs(UnmanagedType.LPWstr)}
   public string blah; //ok
   [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.LPWStr)]   
    public string[] stringarray;
}

Let's concentrate on the array definition. The original array was defined like LPWSTR* stringarray;  this is an array of pointers to zero-terminated strings.

Now you thought, that a few attributes, would be sufficient to support your interop?

[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr)]   
public string[] stringarray;

but the .NET framework, won't support you here. It is not able to create an unmanaged array of 'some type' on structs (this however, is working for parameter definitions) and to pass it to your unmanaged API.

And if you wonder what UnmanagedType.ByValArray, UnmanagedType.LPWStr  really does; it creates a pointer to a contigous block of zero terminated strings. It would not create an array of stringpointers. So now you know, why interop is an art, not a science :)

At last, I wrote an easy wrapper. It returns an IntPtr which is a just pointer to our first element to an array of string pointers :)

You should assign this class as a member variable on your own class. If you use this class inside a member function, your unmanaged memory might be cleaned when the function goes out of scope.
PS: Please send back the improved code, if you decide to use it (at your own risk of course). It might be improved, to pack managed structures as well, using C# generics.

Sample:

class myClass()

{   private packLPArray packit;      

      void myMemberfunction()
      {   // ... do your dangerous, endeavourish :) interop thing here
            packit = new packLPArray(new string[] {"element1", "element2", "blah"});
            mystruct.stringarray = packit.arrayPtr;
      }

}

 

///

packs an array of strings (type = string[]) to unmanaged memory
/// also works for 64-bit environments
///

public sealed class  packLPArray
{
    private IntPtr taskAlloc;

    private readonly int _length;

    private IntPtr[] _strings;

    public packLPArray(string[] theArray)

    {   int sizeIntPtr = IntPtr.Size;

        int neededSize = 0;

        if (theArray != null)

        {

            this._length = theArray.Length;

            this._strings = new IntPtr[this._length];

           // System.Diagnostics.Debugger.Break();

            neededSize = this._length * sizeIntPtr;

            this.taskAlloc = Marshal.AllocCoTaskMem(neededSize);           

            for (int cx = this._length - 1; cx >= 0; cx--)
            {   this._strings[cx] = Marshal.StringToCoTaskMemUni(theArray[cx]);
                Marshal.WriteIntPtr(this.taskAlloc, cx * sizeIntPtr, this._strings[cx]);

            }

        }

    }

    ///

    /// retrieves array length

    ///

    public int Length

    {

        get { return _length; }

    }

    public IntPtr arrayPtr

    {

        get { return this.taskAlloc; }

 

    }

    ~packLPArray() // clean up the rub

    {

        if (taskAlloc != IntPtr.Zero)

        {

            Marshal.FreeCoTaskMem(this.taskAlloc);

            int cx = this._length;

            while(cx-- != 0)

                Marshal.FreeCoTaskMem(this._strings[cx]);

        }

    } 

}

yummi! A new namespace! Let's have a look at ComTypes (NET 2.0)0 Reacties


I just had some COM interop work, and decided to use STGMEDIUM and
FORMATETC.
These structs, are necessary for many CLIPboard operations. But what draws my attention?
the MSDN says this:

typedef struct tagSTGMEDIUM

{

    DWORD tymed;

    [switch_type(DWORD), switch_is((DWORD) tymed)]

    union {

        [case(TYMED_GDI)]      HBITMAP        hBitmap;

        [case(TYMED_MFPICT)]   HMETAFILEPICT  hMetaFilePict;

        [case(TYMED_ENHMF)]    HENHMETAFILE   hEnhMetaFile;

        [case(TYMED_HGLOBAL)]  HGLOBAL        hGlobal;

        [case(TYMED_FILE)]     LPWSTR         lpszFileName;

        [case(TYMED_ISTREAM)]  IStream        *pstm;

        [case(TYMED_ISTORAGE)] IStorage       *pstg;

        [default] ;

    };

    [unique] IUnknown *pUnkForRelease;

}STGMEDIUM;

typedef STGMEDIUM *LPSTGMEDIUM;
As we all know, a union, in C++ is just a keyword which makes it's member variables start all at the same memory location. In a .NET struct, we can have the same result by using the following atribute: [StructLayout(LayoutKind.Explicit)]
For each structure member,. you now can specify an offset.
Our dear developers, decided for us, that we should not have that luxury of difficult choices having a struct with explicit layout, but let's not complain about this for now...
There is something -more- seriously wrong.

Have a look at the built in interop defintion (in the .NET 2.0 framework!)
(namespace System.Runtime.InteropServices.ComTypes)
public struct STGMEDIUM
{
public object pUnkForRelease;
public TYMED tymed;
public IntPtr unionmember;
}
 
After some crashes, I found that the definition, contains the correct members  at the wrong location!

As you can see, this defintion, is wrong and should be
public struct STGMEDIUM
{

public TYMED tymed;
public IntPtr unionmember;
public object pUnkForRelease;
}
 
A similar problem exists with FORMATETC. I'll not bother you with the details, but let's just post the correct defition. Next time, if you need these structs, don't use the one from the .NET 2.0 interop layer...

[StructLayout(LayoutKind.Sequential)]
public struct FORMATETC
{
   public short cfFormat;
   public IntPtr ptd;
   [
MarshalAs(UnmanagedType.U4)]
   public DVASPECT dwAspect; 
   public int lindex;
   [
MarshalAs(UnmanagedType.U4)]
   public TYMED tymed;
};

A C# implementation of DsCrackNames for a NameTranslate class, what about unsafe code? (update)0 Reacties

Have you ever tried to pinvoke a function, that returns a pointer to an array of structs? There's you can easily marshale them using safe C# code but if the code was not written already and you can't simply copy-paste that :), I promise to you, that you'll have to do a lot more work to get it done. unsafe code might be a quicker solution.

You could use unsafe code in the following situations:

a) You are not writing code or utilities, that might or will run in restricted environments, such as with an ISP environment. And ISPs (eg.) should not allow .NET to run third-party code that needs full-trust policies.
b) You have knowledge about pointers using C++
c) Your program will not be completely 'type safe', this is what some evangelists say, however, I don't see a flawless windows or webfarm if only everything were typesafe :).

Therefore, I propagate, that the biggest part, if not all, of your code, is type-safe. If some tiny utilities, are tested well and in favor of speed and power and possibilities, need to be type-unsafe, just go on.

If conditions have been considered, make your decision. Eventually stop reading now and wait for other postings :).

Such a candidate to be marked as unsafe, would be DsCrackNames, for the COM/automation world, it would be clever to instantiate the NameTranslate class which has an IDispatch interface (good for scripting as well).
Since ít's my hobby, to avoid easy solutions :) I wrote a unique (for the moment, I did not find another on the internet) wrapper for DsCrackNames which run nearly identical its earlier automation friend.

Let's have a look at the MSDN definition of this function.:
DWORD DsCrackNames(
  HANDLE hDS
,
  DS_NAME_FLAGS flags
,
  DS_NAME_FORMAT formatOffered
,
  DS_NAME_FORMAT formatDesired
,
  DWORD cNames
,
  LPCTSTR* rpNames
,
  PDS_NAME_RESULT* ppResult

);

Wow! this promises a lot of troubles, since PDS_NAME_RESULT is a pointer to a structure which contains an array of pointers to another sequential struct.

MSDN definition:
typedef struct
{
  DWORD cItems;
  PDS_NAME_RESULT_ITEM rItems;
} DS_NAME_RESULT,
*PDS_NAME_RESULT;

And here's the struct  rItems refers to...

typedef struct {
DWORD status;
LPTSTR pDomain;
LPTSTR pName;

} DS_NAME_RESULT_ITEM,
*PDS_NAME_RESULT_ITEM;


I do challence you, to write a 'safe' equivalent to it, I tried it, and believe me, the .NET framework does its stinking best to tell you that your attributes are not valid.

Of course, we understand that it simply is not possible  unless you jump to a MC++ solution or you use the definition from www.pinvoke.net which is requires a lot tricky code (no offense to anybody)... .

You cannot use attributes on the structure, and pass the stuff in one single call to the platform invoke and have the net framework do the actual marshaling for you.  You should create some looping work using Marshal.ReadInt32 (..) if you go for the 'safe' code solution .

I want to stress the point that safe platform invokes are not necessarily safer! They can leak memory as hell sorry, as well.

I've tried to use the [MarshalAs] attribute, but a having interop fill an array of IntPtrs inside a struct is not supported by the IL environment. Yes, you can try something like

struct DS_NAME_RESULT
{
        int cItems;
        IntPtr firstItem; //will work only if you crack one item or if you use Marshal.ReadInt32 etc code seen at pinvoke.net
}

Or try this... But now you have a managed array of IntPtr and that won't work as well.

struct DS_NAME_RESULT
{
        int cItems;
        IntPtr[] pDS_NAME_RESULT_ITEM; //won't be marshaled since the framework cannot create and marshale this array on the fly
}

and DS_NAME_RESULT ITEM would be like:

struct DS_NAME_RESULT_ITEM
{
public int status;
  [MarshalAs(UnmanagedType.LPWstr)]
public string pDomain;
  [MarshalAs(UnmanagedType.LPWstr)]
public string pName;
} ;

Let's see how easy you could write the solution set the 'unsafe'  attribute in spite of how disastrous this might sound.

Unsafe only allows for easy interop with unmaged IL code, this is a facto default with MC++, where you easily can use all those .h files, (windows.h, winbase.h etc) without having to retype all your DllImport statements or without having to copy them from http://www.pinvoke.net which often has untested declares. I could have use MC++ as well, but if you want to expose the assembly for reusage, you'll start to redefine all those Win32 enums and constants anyway. We have to learn to live with the border between managed and unmanged code.

Our 'unsafe' CSharp code, looks very much like a C++ implementation. In addition, it offers some improvements over the IADsNameTranslate interface (that you derive from NameTranslate, with Guid("b1b272a3-3625-11d1-a3a4-00c04fb950dc").

Some remarks about my style of programming: I really don't like ansi or Win9x compatible code. Screw it! :), as you can see, my declares favor Windows 2000 and higher. Also take in account, that this is not full proof & tested code.

Have fun using this code.

/* Copyright, Nierop Webconsultancy 2005 www.nieropwebconsult.nl

 * Use of this code, in your projects, is for your own risk.

 * If you modify the code, you send improvements back

 * If you copy the code, you won't remove the credits for the code

 */

using System;

using System.DirectoryServices;

using System.Runtime.InteropServices;

using System.DirectoryServices.ActiveDirectory;

using System.Data;

using System.ComponentModel;

 

 

namespace NameTranslate

{

    public enum ADS_NAME_INITTYPE_ENUM

    {

        ///

        /// Initializes a NameTranslate object by setting the domain that the object binds to.

        ///

        ADS_NAME_INITTYPE_DOMAIN = 1,

        ///

        /// Initializes a NameTranslate object by setting the server that the object binds to.

        ///

        ADS_NAME_INITTYPE_SERVER = 2,

        ///

        /// Initializes a NameTranslate object by locating the global catalog that the object binds to

        ///

        ADS_NAME_INITTYPE_GC = 3

    } ;

   

    public enum DS_NAME_FORMAT

    {

        DS_UNKNOWN_NAME = 0,

        DS_FQDN_1779_NAME = 1,

        DS_NT4_ACCOUNT_NAME = 2,

        DS_DISPLAY_NAME = 3,

        DS_UNIQUE_ID_NAME = 6,

        DS_CANONICAL_NAME = 7,

        DS_USER_PRINCIPAL_NAME = 8,

        DS_CANONICAL_NAME_EX = 9,

        DS_SERVICE_PRINCIPAL_NAME = 10,

        DS_SID_OR_SID_HISTORY_NAME = 11,

        DS_DNS_DOMAIN_NAME = 12

    } ;

 

    enum DS_NAME_FLAGS

    {

        ///

        /// Indicates that there are no associated flags

        ///

        DS_NAME_NO_FLAGS = 0x0,

        ///

        /// Performs a syntactical mapping at the client without transferring over the network.

        /// The only syntactic mapping supported is from DS_FQDN_1779_NAME to DS_CANONICAL_NAME or DS_CANONICAL_NAME_EX.

        /// DsCrackNames returns the DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING flag if a syntactical mapping is not possible.

        ///

        DS_NAME_FLAG_SYNTACTICAL = 0x1,

        ///

        /// Forces a trip to the domain controller for evaluation, even if the syntax could be cracked locally

        ///

        DS_NAME_FLAG_EVAL_AT_DC = 0x2,

        ///

        /// The call fails if the domain controller is not a global catalog server.

        ///

        DS_NAME_FLAG_GCVERIFY = 0x4,

        ///

        /// Enables cross forest trust referral.

        ///

        DS_NAME_FLAG_TRUST_REFERRAL = 0x8

    } ;

    public enum DS_NAME_ERROR

    {

        ///

        /// The conversion was successful.

        ///

        DS_NAME_NO_ERROR = 0,

        ///

        /// A generic processing error occurred.

        ///

        DS_NAME_ERROR_RESOLVING = 1,

        ///