using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Vanara.Extensions;
using Vanara.InteropServices;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace Vanara.PInvoke
{
/// Platform invokable enumerated types, constants and functions from ntdsapi.h
public static partial class NTDSApi
{
private const uint NO_ERROR = 0;
///
/// The SyncUpdateProc function is an application-defined function that handles update messages passed from the
/// DsReplicaSyncAll function. SyncUpdateProc is a placeholder for the application-defined callback function name.
///
///
/// Pointer to application-defined data passed in the pCallbackData parameter of the DsReplicaSyncAll function.
///
///
/// Pointer to a DS_REPSYNCALL_UPDATE structure that describes the event in the DsReplicaSyncAll function that caused
/// the SyncUpdateProc callback function to be called.
///
///
/// Execution of the DsReplicaSyncAll function pauses when it calls the SyncUpdateProc callback function. If
/// SyncUpdateProc returns TRUE, execution of DsReplicaSyncAll resumes. Otherwise, the DsReplicaSyncAll
/// function terminates.
///
// BOOL SyncUpdateProc( LPVOID pData, PDS_REPSYNCALL_UPDATE pUpdate ); https://msdn.microsoft.com/en-us/library/ms677968(v=vs.85).aspx
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
[PInvokeData("ntdsapi.h", MSDNShortId = "ms677968")]
// [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SyncUpdateProc(IntPtr pData, PDS_REPSYNCALL_UPDATE pUpdate);
[return: MarshalAs(UnmanagedType.Bool)]
public delegate bool SyncUpdateProc(IntPtr pData, ref DS_REPSYNCALL_UPDATE pUpdate);
/// Identifies the task that the KCC should execute.
[PInvokeData("ntdsapi.h", MSDNShortId = "2a83ffcb-1ebd-4024-a186-9c079896f4e1")]
public enum DS_KCC_TASKID
{
/// Update topology.
DS_KCC_TASKID_UPDATE_TOPOLOGY = 0
}
///
/// Defines the errors returned by the status member of the structure. These are potential errors
/// that may be encountered while a name is converted by the function.
///
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676061")]
public enum DS_NAME_ERROR
{
/// The conversion was successful.
DS_NAME_NO_ERROR = 0,
/// A generic processing error occurred.
DS_NAME_ERROR_RESOLVING = 1,
/// The name cannot be found or the caller does not have permission to access the name.
DS_NAME_ERROR_NOT_FOUND = 2,
///
/// The input name is mapped to more than one output name or the desired format did not have a single, unique value for the
/// object found.
///
DS_NAME_ERROR_NOT_UNIQUE = 3,
///
/// The input name was found, but the associated output format cannot be found. This can occur if the object does not have all
/// the required attributes.
///
DS_NAME_ERROR_NO_MAPPING = 4,
///
/// Unable to resolve entire name, but was able to determine in which domain object resides. The caller is expected to retry the
/// call at a domain controller for the specified domain. The entire name cannot be resolved, but the domain that the object
/// resides in could be determined. The pDomain member of the DS_NAME_RESULT_ITEM contains valid data when this error is specified.
///
DS_NAME_ERROR_DOMAIN_ONLY = 5,
/// A syntactical mapping cannot be performed on the client without transmitting over the network.
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6,
/// The name is from an external trusted forest.
DS_NAME_ERROR_TRUST_REFERRAL = 7
}
///
/// Used to define how the name syntax will be cracked. These flags are used by the function.
///
[Flags]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676062")]
public 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. returns the DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING flag if a syntactical
/// mapping is not possible.
///
DS_NAME_FLAG_SYNTACTICAL_ONLY = 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
}
///
/// Provides formats to use for input and output names for the function.
///
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676245")]
public enum DS_NAME_FORMAT
{
///
/// Indicates the name is using an unknown name type. This format can impact performance because it forces the server to attempt
/// to match all possible formats. Only use this value if the input format is unknown.
///
DS_UNKNOWN_NAME = 0,
///
/// Indicates that the fully qualified distinguished name is used. For example: CN = someone, OU = Users, DC = Engineering, DC =
/// Fabrikam, DC = Com
///
DS_FQDN_1779_NAME = 1,
///
/// Indicates a Windows NT 4.0 account name. For example: Engineering\someone The domain-only version includes two trailing
/// backslashes (\\).
///
DS_NT4_ACCOUNT_NAME = 2,
///
/// Indicates a user-friendly display name, for example, Jeff Smith. The display name is not necessarily the same as relative
/// distinguished name (RDN).
///
DS_DISPLAY_NAME = 3,
/// Indicates a GUID string that the IIDFromString function returns. For example: {4fa050f0-f561-11cf-bdd9-00aa003a77b6}
DS_UNIQUE_ID_NAME = 6,
///
/// Indicates a complete canonical name. For example: engineering.fabrikam.com/software/someone The domain-only version includes
/// a trailing forward slash (/).
///
DS_CANONICAL_NAME = 7,
/// Indicates that it is using the user principal name (UPN). For example: someone@engineering.fabrikam.com
DS_USER_PRINCIPAL_NAME = 8,
///
/// This element is the same as DS_CANONICAL_NAME except that the rightmost forward slash (/) is replaced with a newline
/// character (\n), even in a domain-only case. For example: engineering.fabrikam.com/software\nsomeone
///
DS_CANONICAL_NAME_EX = 9,
/// Indicates it is using a generalized service principal name. For example: www/www.fabrikam.com@fabrikam.com
DS_SERVICE_PRINCIPAL_NAME = 10,
///
/// Indicates a Security Identifier (SID) for the object. This can be either the current SID or a SID from the object SID
/// history. The SID string can use either the standard string representation of a SID, or one of the string constants defined in
/// Sddl.h. For more information about converting a binary SID into a SID string, see SID Strings. The following is an example of
/// a SID string: S-1-5-21-397955417-626881126-188441444-501
///
DS_SID_OR_SID_HISTORY_NAME = 11,
/// Not supported by the Directory Service (DS) APIs.
DS_DNS_DOMAIN_NAME = 12,
///
/// This causes DsCrackNames to return the distinguished names of all naming contexts in the current forest. The formatDesired
/// parameter is ignored. cNames must be at least one and all strings in rpNames must have a length greater than zero characters.
/// The contents of the rpNames strings is ignored.
///
DS_LIST_NCS = unchecked((int)0xfffffff6)
}
///
///
/// The DS_REPL_INFO_TYPE enumeration is used with the DsReplicaGetInfo and DsReplicaGetInfo2 functions to specify the type of
/// replication data to retrieve.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ne-ntdsapi-_ds_repl_info_type typedef enum _DS_REPL_INFO_TYPE {
// DS_REPL_INFO_NEIGHBORS, DS_REPL_INFO_CURSORS_FOR_NC, DS_REPL_INFO_METADATA_FOR_OBJ, DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES,
// DS_REPL_INFO_KCC_DSA_LINK_FAILURES, DS_REPL_INFO_PENDING_OPS, DS_REPL_INFO_METADATA_FOR_ATTR_VALUE, DS_REPL_INFO_CURSORS_2_FOR_NC,
// DS_REPL_INFO_CURSORS_3_FOR_NC, DS_REPL_INFO_METADATA_2_FOR_OBJ, DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE,
// DS_REPL_INFO_METADATA_EXT_FOR_ATTR_VALUE, DS_REPL_INFO_TYPE_MAX } DS_REPL_INFO_TYPE;
[PInvokeData("ntdsapi.h", MSDNShortId = "88d8a164-2192-4e73-a190-aa5b5dbb1101")]
public enum DS_REPL_INFO_TYPE
{
///
/// Requests replication state data for naming context and source server pairs. Returns a pointer to a DS_REPL_NEIGHBORS structure.
///
[CorrespondingType(typeof(DS_REPL_NEIGHBORS), CorrespondingAction.Get)]
DS_REPL_INFO_NEIGHBORS,
///
/// Requests replication state data with respect to all replicas of a given naming context. Returns a pointer to a
/// DS_REPL_CURSORS structure.
///
[CorrespondingType(typeof(DS_REPL_CURSORS), CorrespondingAction.Get)]
DS_REPL_INFO_CURSORS_FOR_NC,
///
/// Requests replication state data for the attributes for the given object. Returns a pointer to a DS_REPL_OBJ_META_DATA structure.
///
[CorrespondingType(typeof(DS_REPL_OBJ_META_DATA), CorrespondingAction.Get)]
DS_REPL_INFO_METADATA_FOR_OBJ,
///
/// Requests replication state data with respect to connection failures between inbound replication partners. Returns a pointer
/// to a DS_REPL_KCC_DSA_FAILURES structure.
///
[CorrespondingType(typeof(DS_REPL_KCC_DSA_FAILURESW), CorrespondingAction.Get)]
DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES,
///
/// Requests replication state data with respect to link failures between inbound replication partners. Returns a pointer to a
/// DS_REPL_KCC_DSA_FAILURES structure.
///
[CorrespondingType(typeof(DS_REPL_KCC_DSA_FAILURESW), CorrespondingAction.Get)]
DS_REPL_INFO_KCC_DSA_LINK_FAILURES,
///
/// Requests the replication tasks currently executing or queued to execute. Returns a pointer to a DS_REPL_PENDING_OPS structure.
///
[CorrespondingType(typeof(DS_REPL_PENDING_OPSW), CorrespondingAction.Get)]
DS_REPL_INFO_PENDING_OPS,
///
/// Requests replication state data for a specific attribute for the given object. Returns a pointer to a
/// DS_REPL_ATTR_VALUE_META_DATA structure.
///
[CorrespondingType(typeof(DS_REPL_ATTR_VALUE_META_DATA), CorrespondingAction.Get)]
DS_REPL_INFO_METADATA_FOR_ATTR_VALUE,
///
/// Requests replication state data with respect to all replicas of a given naming context. Returns a pointer to a
/// DS_REPL_CURSORS_2 structure.
///
[CorrespondingType(typeof(DS_REPL_CURSORS_2), CorrespondingAction.Get)]
DS_REPL_INFO_CURSORS_2_FOR_NC,
///
/// Requests replication state data with respect to all replicas of a given naming context. Returns a pointer to a
/// DS_REPL_CURSORS_3 structure.
///
[CorrespondingType(typeof(DS_REPL_CURSORS_3W), CorrespondingAction.Get)]
DS_REPL_INFO_CURSORS_3_FOR_NC,
///
/// Requests replication state data for the attributes for the given object. Returns a pointer to a DS_REPL_OBJ_META_DATA_2 structure.
///
[CorrespondingType(typeof(DS_REPL_OBJ_META_DATA_2), CorrespondingAction.Get)]
DS_REPL_INFO_METADATA_2_FOR_OBJ,
///
/// Requests replication state data for a specific attribute for the given object. Returns a pointer to a
/// DS_REPL_ATTR_VALUE_META_DATA_2 structure.
///
[CorrespondingType(typeof(DS_REPL_ATTR_VALUE_META_DATA_2), CorrespondingAction.Get)]
DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE,
///
/// Requests replication state data for a specific attribute for the given object. Returns a pointer to a
/// DS_REPL_ATTR_VALUE_META_DATA_EXT structure.
///
[CorrespondingType(typeof(DS_REPL_ATTR_VALUE_META_DATA_EXT), CorrespondingAction.Get)]
DS_REPL_INFO_METADATA_EXT_FOR_ATTR_VALUE,
}
///
///
/// The DS_REPL_OP_TYPE enumeration type is used to indicate the type of replication operation that a given entry in the
/// replication queue represents.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ne-ntdsapi-_ds_repl_op_type typedef enum _DS_REPL_OP_TYPE {
// DS_REPL_OP_TYPE_SYNC, DS_REPL_OP_TYPE_ADD, DS_REPL_OP_TYPE_DELETE, DS_REPL_OP_TYPE_MODIFY, DS_REPL_OP_TYPE_UPDATE_REFS } DS_REPL_OP_TYPE;
[PInvokeData("ntdsapi.h", MSDNShortId = "81d9f464-90f4-405c-b014-0a61f5a5b816")]
public enum DS_REPL_OP_TYPE
{
/// Indicates an inbound replication over an existing replication agreement from a direct replication partner.
DS_REPL_OP_TYPE_SYNC,
/// Indicates the addition of a replication agreement for a new direct replication partner.
DS_REPL_OP_TYPE_ADD,
/// Indicates the removal of a replication agreement for an existing direct replication partner.
DS_REPL_OP_TYPE_DELETE,
/// Indicates the modification of a replication agreement for an existing direct replication partner.
DS_REPL_OP_TYPE_MODIFY,
/// Indicates the addition, deletion, or update of outbound change notification data for a direct replication partner.
DS_REPL_OP_TYPE_UPDATE_REFS,
}
///
///
/// The DS_REPSYNCALL_ERROR enumeration is used with the DS_REPSYNCALL_ERRINFO structure to indicate where in the replication
/// process an error occurred.
///
///
// https://webcache.googleusercontent.com/search?q=cache:ryUMFaJus6sJ:https://docs.microsoft.com/is-is/windows/desktop/api/Ntdsapi/ne-ntdsapi-ds_repsyncall_error+&cd=1&hl=en&ct=clnk&gl=us
// typedef enum DS_REPSYNCALL_ERROR { DS_REPSYNCALL_WIN32_ERROR_CONTACTING_SERVER , DS_REPSYNCALL_WIN32_ERROR_REPLICATING ,
// DS_REPSYNCALL_SERVER_UNREACHABLE } ;
[PInvokeData("ntdsapi.h", MSDNShortId = "9c020046-ab52-4676-931e-12ce176e93fb")]
public enum DS_REPSYNCALL_ERROR
{
/// The server referred to by the pszSvrId member of the DS_REPSYNCALL_ERRINFO structure cannot be contacted.
DS_REPSYNCALL_WIN32_ERROR_CONTACTING_SERVER,
///
/// An error occurred during replication of the server identified by the pszSvrId member of the DS_REPSYNCALL_ERRINFO structure.
///
DS_REPSYNCALL_WIN32_ERROR_REPLICATING,
/// The server identified by the pszSvrId member of the DS_REPSYNCALL_ERRINFO structure cannot be contacted.
DS_REPSYNCALL_SERVER_UNREACHABLE,
}
///
///
/// The DS_REPSYNCALL_EVENT enumeration is used with the DS_REPSYNCALL_UPDATE structure to define which event the
/// DS_REPSYNCALL_UPDATE structure represents.
///
///
// https://webcache.googleusercontent.com/search?q=cache:NyB4AWln394J:https://docs.microsoft.com/en-us/windows/desktop/api/Ntdsapi/ne-ntdsapi-ds_repsyncall_event+&cd=1&hl=en&ct=clnk&gl=us
// typedef enum DS_REPSYNCALL_EVENT { DS_REPSYNCALL_EVENT_ERROR , DS_REPSYNCALL_EVENT_SYNC_STARTED ,
// DS_REPSYNCALL_EVENT_SYNC_COMPLETED , DS_REPSYNCALL_EVENT_FINISHED } ;
[PInvokeData("ntdsapi.h", MSDNShortId = "a732a906-0e26-45f6-b89c-58f2277057ba")]
public enum DS_REPSYNCALL_EVENT
{
/// An error occurred. Error data is stored in the pErrInfo member of the DS_REPSYNCALL_UPDATE structure.
DS_REPSYNCALL_EVENT_ERROR,
///
/// Synchronization of two servers has started. Both the pErrInfo and pSync members of the DS_REPSYNCALL_UPDATE structure are NULL.
///
DS_REPSYNCALL_EVENT_SYNC_STARTED,
///
/// Synchronization of two servers has just finished. The servers involved in the synchronization are identified by the pSync
/// member of the DS_REPSYNCALL_UPDATE structure. The pErrInfo member of the DS_REPSYNCALL_UPDATE structure is NULL.
///
DS_REPSYNCALL_EVENT_SYNC_COMPLETED,
///
/// Execution of DsReplicaSyncAll is complete. Both the pErrInfo and pSync members of the DS_REPSYNCALL_UPDATE structure are
/// NULL. The return value of the callback function is ignored.
///
DS_REPSYNCALL_EVENT_FINISHED,
}
///
/// The DS_SPN_NAME_TYPE enumeration is used by the DsGetSPN function to identify the format for composing SPNs.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ne-ntdsapi-ds_spn_name_type typedef enum DS_SPN_NAME_TYPE {
// DS_SPN_DNS_HOST , DS_SPN_DN_HOST , DS_SPN_NB_HOST , DS_SPN_DOMAIN , DS_SPN_NB_DOMAIN , DS_SPN_SERVICE } ;
[PInvokeData("ntdsapi.h", MSDNShortId = "7aab22a6-1fe1-4127-97d3-54287d770790")]
public enum DS_SPN_NAME_TYPE
{
/// The SPN format for the distinguished name service of the host-based service, which provides services identified with its host computer. This SPN uses the following format:
/// jeffsmith.fabrikam.com
DS_SPN_DNS_HOST,
/// The SPN format for the distinguished name of the host-based service, which provides services identified with its host computer. This SPN uses the following format:
/// cn=jeffsmith,ou=computers,dc=fabrikam,dc=com
DS_SPN_DN_HOST,
/// The SPN format for the NetBIOS service of the host-based service, which provides services identified with its host computer. This SPN uses the following format:
/// jeffsmith-nec
DS_SPN_NB_HOST,
/// The SPN format for a replicable service that provides services to the specified domain. This SPN uses the following format:
/// fabrikam.com
DS_SPN_DOMAIN,
/// The SPN format for a replicable service that provides services to the specified NetBIOS domain. This SPN uses the following format:
/// fabrikam
DS_SPN_NB_DOMAIN,
/// The SPN format for a specified service. This SPN uses the following formats, depending on which service is used:
/// cn=anRpcService,cn=RPC Services,cn=system,dc=fabrikam,dc=com
/// cn=aWsService,cn=Winsock Services,cn=system,dc=fabrikam,dc=com
DS_SPN_SERVICE
}
///
///
/// The DS_SPN_WRITE_OP enumeration identifies the type of write operation that should be performed by the DsWriteAccountSpn function.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ne-ntdsapi-ds_spn_write_op typedef enum DS_SPN_WRITE_OP {
// DS_SPN_ADD_SPN_OP , DS_SPN_REPLACE_SPN_OP , DS_SPN_DELETE_SPN_OP } ;
[PInvokeData("ntdsapi.h", MSDNShortId = "8367bdaf-3d8d-46b3-9d03-b9753e8e5a1a")]
public enum DS_SPN_WRITE_OP
{
/// Adds the specified service principal names (SPNs) to the object identified by the pszAccount parameter in DsWriteAccountSpn.
DS_SPN_ADD_SPN_OP,
///
/// Removes all SPNs currently registered on the account identified by the pszAccount parameter in DsWriteAccountSpn and replaces
/// them with the SPNs specified by the rpszSpn parameter in DsWriteAccountSpn.
///
DS_SPN_REPLACE_SPN_OP,
/// Deletes the specified SPNs from the object identified by the pszAccount parameter in DsWriteAccountSpn.
DS_SPN_DELETE_SPN_OP,
}
/// Flags for DsBindWithSpnEx and DsBindByInstance
[PInvokeData("ntdsapi.h", MSDNShortId = "52a5761d-5244-4bc9-8c09-fd08f10a9fff")]
[Flags]
public enum DsBindFlags
{
///
///
/// Causes the bind to use the delegate impersonation level. This enables operations that require delegation, such as
/// DsAddSidHistory, to succeed. Specifying this flag also causes DsBindWithSpnEx to operate similar to DsBindWithSpn.
///
///
/// If this flag is not specified, the bind will use the impersonate impersonation level. For more information about
/// impersonation levels, see Impersonation Levels.
///
///
/// Most operations do not require the delegate impersonation level; this flag should only be specified if it is required.
/// Binding to a rogue server with the delegate impersonation level enables the rogue server to connect to a non-rogue server
/// with your credentials and perform unintended operations.
///
///
NTDSAPI_BIND_ALLOW_DELEGATION = 0x00000001,
///
/// With AD/AM, a single machine, could have multiple "AD's" on a single server. Since DsBindXxxx() will not pick an AD/AM
/// instance without an instance specifier ( ":389" ), it can be difficult (well impossible) to determine from just a server
/// name, what the instance annotation or instance guid is. This option will take a server name and find the first available AD
/// or AD/AM instance. WARNING: The results could be non- deterministic on a server w/ multiple instances.
///
NTDSAPI_BIND_FIND_BINDING = 0x00000002,
///
/// Active Directory Lightweight Directory Services: If this flag is specified, DsBindWithSpnEx requires Kerberos authentication
/// to be used. If Kerberos authentication cannot be established, DsBindWithSpnEx will not attempt to authenticate with any other mechanism.
///
NTDSAPI_BIND_FORCE_KERBEROS = 0x00000004,
}
/// Contains a set of flags that modify the function behavior.
[PInvokeData("ntdsapi.h", MSDNShortId = "2a83ffcb-1ebd-4024-a186-9c079896f4e1")]
[Flags]
public enum DsKCCFlags
{
/// The task is queued and then the function returns without waiting for the task to complete.
DS_KCC_FLAG_ASYNC_OP = (1 << 0),
/// The task will not be added to the queue if another queued task will run soon.
DS_KCC_FLAG_DAMPED = (1 << 1),
}
/// Passes additional data to be used to process the request.
[PInvokeData("ntdsapi.h", MSDNShortId = "33bd1b61-b9ed-479f-a128-fb7ddbb5e9af")]
[Flags]
public enum DsReplicaAddOptions
{
/// Performs this operation asynchronously.
DS_REPADD_ASYNCHRONOUS_OPERATION = 0x00000001,
/// Creates a writable replica; otherwise, the replica is read-only.
DS_REPADD_WRITEABLE = 0x00000002,
/// Synchronizes the NC from this source when the DSA is started.
DS_REPADD_INITIAL = 0x00000004,
/// Synchronizes the NC from this source periodically, as defined in pSchedule.
DS_REPADD_PERIODIC = 0x00000008,
///
/// Synchronizes from the source DSA using the Intersite Messaging Service (IMS) transport, for example, by SMTP, rather than
/// using the native directory service RPC.
///
DS_REPADD_INTERSITE_MESSAGING = 0x00000010,
/// Does not replicate the NC. Instead, save enough state data such that it may be replicated later.
DS_REPADD_ASYNCHRONOUS_REPLICA = 0x00000020,
///
/// Disables notification-based synchronization for the NC from this source. This is expected to be a temporary state. Use
/// DS_REPADD_NEVER_NOTIFY to permanently disable synchronization.
///
DS_REPADD_DISABLE_NOTIFICATION = 0x00000040,
/// Disables periodic synchronization for the NC from this source.
DS_REPADD_DISABLE_PERIODIC = 0x00000080,
///
/// Uses compression when replicating. This saves network bandwidth at the expense of CPU overhead at both the source and
/// destination servers.
///
DS_REPADD_USE_COMPRESSION = 0x00000100,
///
///
/// Disables change notifications from this source. When this flag is set, the source does not notify the destination when
/// changes occur. This is recommended for all intersite replication that may occur over WAN links.
///
/// This is expected to be a permanent state; use DS_REPADD_DISABLE_NOTIFICATION to temporarily disable notifications.
///
DS_REPADD_NEVER_NOTIFY = 0x00000200,
/// Undocumented.
DS_REPADD_TWO_WAY = 0x00000400,
/// Undocumented.
DS_REPADD_CRITICAL = 0x00000800,
/// Undocumented.
DS_REPADD_SELECT_SECRETS = 0x00001000,
/// Undocumented.
DS_REPADD_NONGC_RO_REPLICA = 0x01000000,
}
/// Passes additional data used to process the request.
[PInvokeData("ntdsapi.h", MSDNShortId = "68c767c4-bbb6-477b-8ffb-94f3ae235375")]
[Flags]
public enum DsReplicaDelOptions
{
/// Performs this operation asynchronously.
DS_REPDEL_ASYNCHRONOUS_OPERATION = 0x00000001,
/// Signifies that the replica deleted can be written to.
DS_REPDEL_WRITEABLE = 0x00000002,
/// Signifies the replica is mail-based rather than synchronized using native directory service RPC.
DS_REPDEL_INTERSITE_MESSAGING = 0x00000004,
///
/// Ignores any error generated from contacting the source to instruct it to remove this NC from its list of servers to which it replicates.
///
DS_REPDEL_IGNORE_ERRORS = 0x00000008,
///
/// Does not contact the source to tell it to remove this NC from its list of servers to which it replicates. If this flag is not
/// set and the link is based in RPC, the source is contacted.
///
DS_REPDEL_LOCAL_ONLY = 0x00000010,
/// Deletes all the objects in the NC. This option is valid only for read-only NCs with no source.
DS_REPDEL_NO_SOURCE = 0x00000020,
/// Allows deletion of a read-only replica even if it sources other read-only replicas.
DS_REPDEL_REF_OK = 0x00000040,
}
/// Contains a set of flags that modify the behavior of the function.
[PInvokeData("ntdsapi.h", MSDNShortId = "5735d91d-1b7d-4dc6-b6c6-61ba38ebe50d")]
[Flags]
public enum DsReplInfoFlags
{
/// No flags are set.
DS_REPL_INFO_FLAG_NONE = 0,
///
/// Causes the attribute metadata to account for metadata on the attribute's linked values. The resulting vector represents
/// changes for all attributes. This modified vector is useful for clients that expect all attributes and metadata to be included
/// in the attribute metadata vector.
///
DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS = 0x00000001,
}
/// Specifies what fields should be modified. At least one field must be specified in ModifyFields.
[PInvokeData("ntdsapi.h", MSDNShortId = "aad20527-1211-41bc-b0e9-02e4ab28ae2e")]
[Flags]
public enum DsReplModFieldFlags
{
/// Updates the flags associated with the replica.
DS_REPMOD_UPDATE_FLAGS = 0x00000001,
/// Updates the address associated with the referenced server.
DS_REPMOD_UPDATE_INSTANCE = 0x00000002,
/// Updates the address associated with the referenced server.
DS_REPMOD_UPDATE_ADDRESS = DS_REPMOD_UPDATE_INSTANCE,
/// Updates the periodic replication schedule associated with the replica.
DS_REPMOD_UPDATE_SCHEDULE = 0x00000004,
/// Not used. Specifying updates of result values is not currently supported. Result values default to 0.
DS_REPMOD_UPDATE_RESULT = 0x00000008,
/// Updates the transport associated with the replica.
DS_REPMOD_UPDATE_TRANSPORT = 0x00000010,
}
/// Passes additional data used to process the request.
[PInvokeData("ntdsapi.h", MSDNShortId = "aad20527-1211-41bc-b0e9-02e4ab28ae2e")]
public enum DsReplModOptions
{
/// Performs this operation asynchronously.
DS_REPMOD_ASYNCHRONOUS_OPERATION = 0x00000001,
/// Indicates that the replica being modified can be written to.
DS_REPMOD_WRITEABLE = 0x00000002
}
/// Contains a set of flags that specify attributes and options for the replication data.
[PInvokeData("ntdsapi.h", MSDNShortId = "acab74f4-5739-4310-895b-081062c0360b")]
[Flags]
public enum DsReplNeighborFlags
{
///
/// The local copy of the naming context is writable.
///
DS_REPL_NBR_WRITEABLE = 0x10,
///
///
/// Replication of this naming context from this source is attempted when the destination server is booted. This normally only
/// applies to intra-site neighbors.
///
///
DS_REPL_NBR_SYNC_ON_STARTUP = 0x20,
///
///
/// Perform replication on a schedule. This flag is normally set unless the schedule for this naming context/source is "never",
/// that is, the empty schedule.
///
///
DS_REPL_NBR_DO_SCHEDULED_SYNCS = 0x40,
///
///
/// Perform replication indirectly through the Inter-Site Messaging Service. This flag is set only when replicating over SMTP.
/// This flag is not set when replicating over inter-site RPC/IP.
///
///
DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT = 0x80,
///
///
/// If set, indicates that when inbound replication is complete, the destination server must tell the source server to
/// synchronize in the reverse direction. This feature is used in dial-up scenarios where only one of the two servers can
/// initiate a dial-up connection. For example, this option would be used in a corporate headquarters and branch office, where
/// the branch office connects to the corporate headquarters over the Internet by means of a dial-up ISP connection.
///
///
DS_REPL_NBR_TWO_WAY_SYNC = 0x200,
///
///
/// This neighbor is in a state where it returns parent objects before children objects. It goes into this state after it
/// receives a child object before its parent.
///
///
DS_REPL_NBR_RETURN_OBJECT_PARENTS = 0x800,
///
///
/// The destination server is performing a full synchronization from the source server. Full synchronizations do not use vectors
/// that create updates (DS_REPL_CURSORS) for filtering updates. Full synchronizations are not used as a part of the normal
/// replication protocol.
///
///
DS_REPL_NBR_FULL_SYNC_IN_PROGRESS = 0x10000,
///
///
/// The last packet from the source indicated a modification of an object that the destination server has not yet created. The
/// next packet to be requested instructs the source server to put all attributes of the modified object into the packet.
///
///
DS_REPL_NBR_FULL_SYNC_NEXT_PACKET = 0x20000,
///
/// A synchronization has never been successfully completed from this source.
///
DS_REPL_NBR_NEVER_SYNCED = 0x200000,
///
///
/// The replication engine has temporarily stopped processing this neighbor in order to service another higher-priority neighbor,
/// either for this partition or for another partition. The replication engine will resume processing this neighbor after the
/// higher-priority work is completed.
///
///
DS_REPL_NBR_PREEMPTED = 0x1000000,
///
///
/// This neighbor is set to disable notification-based synchronizations. Within a site, domain controllers synchronize with each
/// other based on notifications when changes occur. This setting prevents this neighbor from performing syncs that are triggered
/// by notifications. The neighbor will still do synchronizations based on its schedule, or in response to manually requested synchronizations.
///
///
DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS = 0x4000000,
///
///
/// This neighbor is set to not perform synchronizations based on its schedule. The only way this neighbor will perform
/// synchronizations is in response to change notifications or to manually requested synchronizations.
///
///
DS_REPL_NBR_DISABLE_SCHEDULED_SYNC = 0x8000000,
///
///
/// Changes received from this source are to be compressed. This is normally set if, and only if, the source server is in a
/// different site.
///
///
DS_REPL_NBR_COMPRESS_CHANGES = 0x10000000,
///
///
/// No change notifications should be received from this source. Normally set if, and only if, the source server is in a
/// different site.
///
///
DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS = 0x20000000,
///
///
/// This neighbor is in a state where it is rebuilding the contents of this replica because of a change in the partial attribute set.
///
///
DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET = 0x40000000,
}
/// Passes additional data used to process the request.
[PInvokeData("ntdsapi.h", MSDNShortId = "2608adde-4f18-4048-a96f-d736ff09cd4b")]
[Flags]
public enum DsReplSyncAllFlags
{
/// This option has no effect.
DS_REPSYNCALL_NO_OPTIONS = 0x00000000,
///
/// Generates a fatal error if any server cannot be contacted or if any server is unreachable due to a disconnected or broken topology.
///
DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE = 0x00000001,
/// Disables transitive replication. Synchronization is performed only with adjacent servers.
DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY = 0x00000002,
/// In the event of a non-fatal error, returns server distinguished names (DN) instead of their GUID DNS names.
DS_REPSYNCALL_ID_SERVERS_BY_DN = 0x00000004,
///
/// Disables all synchronization. The topology is still analyzed, and unavailable or unreachable servers are still identified.
///
DS_REPSYNCALL_DO_NOT_SYNC = 0x00000008,
///
/// Assumes that all servers are responding. This speeds operation of the DsReplicaSyncAll function, but if some servers are not
/// responding, some transitive replications may be blocked.
///
DS_REPSYNCALL_SKIP_INITIAL_CHECK = 0x00000010,
///
/// Pushes changes from the home server out to all partners using transitive replication. This reverses the direction of
/// replication, and the order of execution of the replication sets from the usual "pulling" mode of execution.
///
DS_REPSYNCALL_PUSH_CHANGES_OUTWARD = 0x00000020,
///
/// Synchronizes across site boundaries. By default, DsReplicaSyncAll attempts to synchronize only with DCs in the same site as
/// the home system. Set this flag to attempt to synchronize with all DCs in the enterprise forest. However, the DCs can be
/// synchronized only if connected by a synchronous (RPC) transport.
///
DS_REPSYNCALL_CROSS_SITE_BOUNDARIES = 0x00000040,
}
/// These flag values are used both as input to DsReplicaSync and as output from DsReplicaGetInfo, PENDING_OPS, DS_REPL_OPW.ulOptions
[PInvokeData("ntdsapi.h", MSDNShortId = "20c7f96d-f298-4321-a6f5-910c25e418db")]
[Flags]
public enum DsReplSyncOptions
{
///
/// Performs this operation asynchronously.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista and Windows Server 2003: Required when using DS_REPSYNC_ALL_SOURCES.
///
///
DS_REPSYNC_ASYNCHRONOUS_OPERATION = 0x00000001,
/// Replica is writable. Otherwise, it is read-only.
DS_REPSYNC_WRITEABLE = 0x00000002,
/// Indicates this operation is a periodic synchronization request as scheduled by the administrator.
DS_REPSYNC_PERIODIC = 0x00000004,
/// Synchronizes using an ISM.
DS_REPSYNC_INTERSITE_MESSAGING = 0x00000008,
/// Synchronizes starting from the first Update Sequence Number (USN).
DS_REPSYNC_FULL = 0x00000020,
/// Indicates this operation is a notification of an update marked urgent.
DS_REPSYNC_URGENT = 0x00000040,
/// Does not discard this synchronization request, even if a similar synchronization is pending.
DS_REPSYNC_NO_DISCARD = 0x00000080,
/// Synchronizes even if the link is currently disabled.
DS_REPSYNC_FORCE = 0x00000100,
///
/// Causes the source directory system agent (DSA) to verify that the local DSA is present in the source replicates-to list. If
/// not, the local DSA is added. This ensures that the source sends change notifications.
///
DS_REPSYNC_ADD_REFERENCE = 0x00000200,
/// A sync from this source has never completed (e.g., a new source).
DS_REPSYNC_NEVER_COMPLETED = 0x00000400,
/// When this sync is complete, requests a sync in the opposite direction.
DS_REPSYNC_TWO_WAY = 0x00000800,
/// Do not request change notifications from this source.
DS_REPSYNC_NEVER_NOTIFY = 0x00001000,
/// Sync the NC from this source when the DSA is started.
DS_REPSYNC_INITIAL = 0x00002000,
///
/// Use compression when replicating. Saves message size (e.g., network bandwidth) at the expense of extra CPU overhead at both
/// the source and destination servers.
///
DS_REPSYNC_USE_COMPRESSION = 0x00004000,
/// Sync was abandoned for lack of updates (W2K, W2K3)
DS_REPSYNC_ABANDONED = 0x00008000,
/// Special secret processing
DS_REPSYNC_SELECT_SECRETS = 0x00008000,
/// Initial sync in progress
DS_REPSYNC_INITIAL_IN_PROGRESS = 0x00010000,
/// Partial Attribute Set sync in progress
DS_REPSYNC_PARTIAL_ATTRIBUTE_SET = 0x00020000,
/// Sync is being retried
DS_REPSYNC_REQUEUE = 0x00040000,
/// Sync is a notification request from a source
DS_REPSYNC_NOTIFICATION = 0x00080000,
/// Sync is a special form which requests to establish contact now and do the rest of the sync later
DS_REPSYNC_ASYNCHRONOUS_REPLICA = 0x00100000,
/// Request critical objects only
DS_REPSYNC_CRITICAL = 0x00200000,
/// A full synchronization is in progress
DS_REPSYNC_FULL_IN_PROGRESS = 0x00400000,
/// Synchronization request was previously preempted
DS_REPSYNC_PREEMPTED = 0x00800000,
/// Non GC readonly replica
DS_REPSYNC_NONGC_RO_REPLICA = 0x01000000,
}
/// Contains a set of flags that provide additional data used to process the request.
[PInvokeData("ntdsapi.h", MSDNShortId = "158c7e73-0e6c-4b71-a87f-2f60f3db91cb")]
[Flags]
public enum DsReplUpdateOptions
{
/// The operation is performed asynchronously.
DS_REPUPD_ASYNCHRONOUS_OPERATION = 0x00000001,
/// The reference to the replica added or removed is writable. Otherwise, it is read-only.
DS_REPUPD_WRITEABLE = 0x00000002,
/// A reference to the destination is added to the source server.
DS_REPUPD_ADD_REFERENCE = 0x00000004,
/// A reference to the destination is removed from the source server.
DS_REPUPD_DELETE_REFERENCE = 0x00000008,
/// Use GCSPN while notifying replica partner
DS_REPUPD_REFERENCE_GCSPN = 0x00000010,
}
/// Contains a set of flags that modify the behavior of the function.
[PInvokeData("ntdsapi.h", MSDNShortId = "d0e139dc-6aaf-47e1-a76f-4e84f17aa7c6")]
[Flags]
public enum DsReplVerifyOptions
{
/// Do not delete objects in response to this function.
DS_EXIST_ADVISORY_MODE = 0x1,
}
/// Indicates the type of GUID mapped by DsMapSchemaGuids.
[PInvokeData("ntdsapi.h")]
public enum DsSchemaGuidType
{
/// The GUID cannot be found in the directory service schema.
DS_SCHEMA_GUID_NOT_FOUND = 0,
/// The GUID identifies a property.
DS_SCHEMA_GUID_ATTR = 1,
/// The GUID identifies a property set.
DS_SCHEMA_GUID_ATTR_SET = 2,
/// The GUID identifies a type of object.
DS_SCHEMA_GUID_CLASS = 3,
/// The GUID identifies an extended access right.
DS_SCHEMA_GUID_CONTROL_RIGHT = 4,
}
/// Defines the type of schedule data that is contained in the structure.
[PInvokeData("schedule.h", MSDNShortId = "5453927e-306e-4442-a855-916005dc8e3b")]
public enum ScheduleType
{
///
///
/// The schedule contains a set of intervals. The Offset member contains the offset to an array of bytes with
/// SCHEDULE_DATA_ENTRIES elements. Each byte in the array represents an hour of the week. The first hour is 00:00 on
/// Sunday morning GMT.
///
///
/// Each bit of the lower four bits of each byte represents a 15 minute block within the hour that the source is available for
/// replication. The following list lists the binary values and describes each bit of the lower four bits of the hour value.
///
///
///
/// Binary value
/// Description
///
/// -
/// 1000
/// The source is available for replication from 0 to 14 minutes after the hour.
///
/// -
/// 0100
/// The source is available for replication from 15 to 29 minutes after the hour.
///
/// -
/// 0010
/// The source is available for replication from 30 to 44 minutes after the hour.
///
/// -
/// 0001
/// The source is available for replication from 45 to 59 minutes after the hour.
///
///
///
/// These bits can be combined to create multiple 15 minute blocks that the source is available. For example, a binary value of
/// 0111 indicates that the source is available from 0 to 44 minutes after the hour.
///
/// The upper fours bits of each byte are not used.
///
SCHEDULE_INTERVAL = 0,
/// Not supported.
SCHEDULE_BANDWIDTH = 1,
/// Not supported.
SCHEDULE_PRIORITY = 2,
}
///
///
/// The DsAddSidHistory function retrieves the primary account security identifier (SID) of a security principal from one
/// domain and adds it to the sIDHistory attribute of a security principal in another domain in a different forest. When the
/// source domain is in Windows 2000 native mode, this function also retrieves the sIDHistory values of the source principal
/// and adds them to the destination principal sIDHistory.
///
///
/// The DsAddSidHistory function performs a security-sensitive function by adding the primary account SID of an existing
/// security principal to the sIDHistory of a principal in a domain in a different forest, effectively granting to the latter
/// access to all resources accessible to the former. For more information about the use and security implications of this function,
/// see Using DsAddSidHistory.
///
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Reserved for future use. Set to NULL.
/// Pointer to a null-terminated string that specifies the name of the domain to query for the SID of SrcPrincipal.
///
/// If the source domain runs on Windows Server operating systems, SrcDomain can be either a domain name system (DNS) name, for
/// example, fabrikam.com, or a flat NetBIOS, for example, Fabrikam, name. DNS names should be used when possible.
///
/// Pointer to a null-terminated string that specifies the name of a security principal, user or group, in the source domain. This
/// name is a domain-relative Security Account Manager (SAM) name, for example: evacorets.
///
/// Pointer to a null-terminated string that specifies the name of the primary domain controller (PDC) Emulator in the source domain
/// to use for secure retrieval of the source principal SID and audit generation.
///
/// If this parameter is NULL, DSBindWithCred will select the primary domain controller.
/// SrcDomainController can be either a DNS name or a flat NetBIOS name. DNS names should be used when possible.
///
/// Contains an identity handle that represents the identity and credentials of a user with administrative rights in the source
/// domain. To obtain this handle, call DsMakePasswordCredentials. This user must be a member of either the Administrators or the
/// Domain Administrators group. If this call is made from a remote computer to the destination DC, then both the remote computer and
/// the destination DC must support 128-bit encryption to privacy-protect the credentials. If 128-bit encryption is unavailable and
/// SrcDomainCreds are provided, then the call must be made on the destination DC.
///
/// If this parameter is NULL, the credentials of the caller are used for access to the source domain.
/// Pointer to a null-terminated string that specifies the name of the destination domain in which DstPrincipal resides. This name
/// can either be a DNS name, for example, fabrikam.com, or a NetBIOS name, for example, Fabrikam. The destination domain must run
/// Windows 2000 native mode.
/// Pointer to a null-terminated string that specifies the name of a security principal, user or group, in the destination domain.
/// This domain-relative SAM name identifies the principal whose sIDHistory attribute is updated with the SID of the SrcPrincipal.
/// Returns a Win32 error codes including the following.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsaddsidhistorya NTDSAPI DWORD DsAddSidHistoryA( HANDLE
// hDS, DWORD Flags, LPCSTR SrcDomain, LPCSTR SrcPrincipal, LPCSTR SrcDomainController, RPC_AUTH_IDENTITY_HANDLE SrcDomainCreds,
// LPCSTR DstDomain, LPCSTR DstPrincipal );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "36ef8734-717a-4c3a-a839-6591d85c9734")]
public static extern Win32Error DsAddSidHistory(SafeDsHandle hDS, uint Flags, string SrcDomain, string SrcPrincipal, string SrcDomainController, SafeAuthIdentityHandle SrcDomainCreds,
string DstDomain, string DstPrincipal);
///
/// The DsBind function binds to a domain controller.DsBind uses the default process credentials to bind to the domain controller. To
/// specify alternate credentials, use the DsBindWithCred function.
///
/// Pointer to a null-terminated string that contains the name of the domain controller to bind to. This name can be the name of the
/// domain controller or the fully qualified DNS name of the domain controller. Either name type can, optionally, be preceded by two
/// backslash characters. All of the following examples represent correctly formatted domain controller names:
/// - "FAB-DC-01"
- "\\FAB-DC-01"
- "FAB-DC-01.fabrikam.com"
- "\\FAB-DC-01.fabrikam.com"
This parameter can be NULL. For more information, see Remarks.
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind to. This parameter can be
/// NULL. For more information, see Remarks.
/// Address of a HANDLE value that receives the binding handle. To close this handle, pass it to the DsUnBind function.
///
/// Returns ERROR_SUCCESS if successful or a Windows or RPC error code otherwise.
///
///
/// The behavior of the DsBind function is determined by the contents of the DomainControllerName and DnsDomainName parameters. The
/// following list describes the behavior of this function based on the contents of these parameters.
/// DomainControllerNameDnsDomainNameDescription- NULLNULLDsBind will attempt to bind to a global catalog server in the forest of the local computer.
- (value)NULLDsBind will attempt to bind to the domain controller specified by the DomainControllerName parameter.
- NULL(value)DsBind will attempt to bind to any domain controller in the domain specified by DnsDomainName parameter.
- (value)(value)
/// The DomainControllerName parameter takes precedence. DsBind will attempt to bind to the domain controller specified by the
/// DomainControllerName parameter.
///
///
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto, SetLastError = true)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675931")]
public static extern Win32Error DsBind([Optional] string DomainControllerName, [Optional] string DnsDomainName, out SafeDsHandle phDS);
///
/// The DsBindByInstance function explicitly binds to any AD LDS or Active Directory instance.
///
/// Pointer to a null-terminated string that specifies the name of the instance. This parameter is required to bind to an AD LDS
/// instance. If this parameter is NULL when binding to an Active Directory instance, then the DnsDomainName parameter must
/// contain a value. If this parameter and the DnsDomainName parameter are both NULL, the function fails with the return value
/// ERROR_INVALID_PARAMETER (87).
///
/// Pointer to a null-terminated string that specifies the port number of the AD LDS instance or NULL when binding to an
/// Active Directory instance. For example, "389".
///
///
/// If this parameter is NULL when binding by domain to an Active Directory instance, then the DnsDomainName parameter must be
/// specified. If this parameter is NULL when binding to an AD LDS instance, then the InstanceGuid parameter must be specified.
///
/// Pointer to a GUID value that contains the GUID of the AD LDS instance. The GUID value is the
/// objectGUID property of the nTDSDSA object of the instance. If this parameter is NULL when binding to an AD
/// LDS instance, the Annotation parameter must be specified.
/// Pointer to a null-terminated string that specifies the DNS name of the domain when binding to an Active Directory instance by
/// domain. Set this parameter to NULL to bind to an Active Directory instance by server or to an AD LDS instance.
/// Handle to the credentials used to start the RPC session. Use the DsMakePasswordCredentials function to create a structure
/// suitable for AuthIdentity.
/// Pointer to a null-terminated string that specifies the Service Principal Name to assign to the client. Passing NULL in
/// ServicePrincipalName is equivalent to a call to the DsBindWithCred function.
///
/// Contains a set of flags that define the behavior of this function. This parameter can contain zero or a combination of one or
/// more of the following values.
///
/// NTDSAPI_BIND_ALLOW_DELEGATION (1)
///
/// Causes the bind to use the delegate impersonation level. This enables operations that require delegation, such as
/// DsAddSidHistory, to succeed. Specifying this flag also causes DsBindWithSpnEx to operate similar to DsBindWithSpn.
///
///
/// If this flag is not specified, the bind will use the impersonate impersonation level. For more information about impersonation
/// levels, see Impersonation Levels.
///
///
/// Most operations do not require the delegate impersonation level; this flag should only be specified if it is required. Binding to
/// a rogue server with the delegate impersonation level enables the rogue server to connect to a non-rogue server with your
/// credentials and perform unintended operations.
///
/// NTDSAPI_BIND_FORCE_KERBEROS (4)
///
/// Active Directory Lightweight Directory Services: If this flag is specified, DsBindWithSpnEx requires Kerberos
/// authentication to be used. If Kerberos authentication cannot be established, DsBindWithSpnEx will not attempt to
/// authenticate with any other mechanism.
///
/// Address of a HANDLE value that receives the bind handle. To close this handle, call DsUnBind.
///
/// Returns NO_ERROR if successful or an RPC or Win32 error otherwise. Possible error codes include those listed in the
/// following list.
///
///
/// The following list lists the required parameter values for binding to an instance.
///
///
/// Instance
/// ServerName
/// Annotation
/// InstanceGuid
/// DnsDomainName
///
/// -
/// Active Directory by server
/// Server Name
/// NULL
/// NULL
/// NULL
///
/// -
/// Active Directory by domain
/// NULL
/// NULL
/// NULL
/// DNS domain name
///
/// -
/// AD LDS by port
/// DNS Name of the computer with the AD LDS installation.
/// Port Number
/// NULL
/// NULL
///
/// -
/// AD LDS by GUID
/// DNS Name of the computer with the AD LDS installation.
/// NULL
/// Instance GUID
/// NULL
///
///
///
/// Note For improved performance when binding to an AD LDS instance on a computer with several instances of AD LDS, bind by
/// the Instance GUID instead of the port number.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindbyinstancea NTDSAPI_POSTXP DWORD DsBindByInstanceA(
// LPCSTR ServerName, LPCSTR Annotation, GUID *InstanceGuid, LPCSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, LPCSTR
// ServicePrincipalName, DWORD BindFlags, HANDLE *phDS );
[PInvokeData("ntdsapi.h", MSDNShortId = "65302ddc-2bc0-4d80-b028-e268859be227")]
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto, EntryPoint = "DsBindByInstance", SetLastError = false, ThrowOnUnmappableChar = true), SuppressUnmanagedCodeSecurity]
public static extern Win32Error DsBindByInstance([Optional] string ServerName, [Optional] string Annotation, in Guid InstanceGuid, [Optional] string DnsDomainName,
SafeAuthIdentityHandle AuthIdentity, [Optional] string ServicePrincipalName, [Optional] DsBindFlags BindFlags, out SafeDsHandle phDS);
///
/// The DsBindByInstance function explicitly binds to any AD LDS or Active Directory instance.
///
/// Pointer to a null-terminated string that specifies the name of the instance. This parameter is required to bind to an AD LDS
/// instance. If this parameter is NULL when binding to an Active Directory instance, then the DnsDomainName parameter must
/// contain a value. If this parameter and the DnsDomainName parameter are both NULL, the function fails with the return value
/// ERROR_INVALID_PARAMETER (87).
///
/// Pointer to a null-terminated string that specifies the port number of the AD LDS instance or NULL when binding to an
/// Active Directory instance. For example, "389".
///
///
/// If this parameter is NULL when binding by domain to an Active Directory instance, then the DnsDomainName parameter must be
/// specified. If this parameter is NULL when binding to an AD LDS instance, then the InstanceGuid parameter must be specified.
///
/// Pointer to a GUID value that contains the GUID of the AD LDS instance. The GUID value is the
/// objectGUID property of the nTDSDSA object of the instance. If this parameter is NULL when binding to an AD
/// LDS instance, the Annotation parameter must be specified.
/// Pointer to a null-terminated string that specifies the DNS name of the domain when binding to an Active Directory instance by
/// domain. Set this parameter to NULL to bind to an Active Directory instance by server or to an AD LDS instance.
/// Handle to the credentials used to start the RPC session. Use the DsMakePasswordCredentials function to create a structure
/// suitable for AuthIdentity.
/// Pointer to a null-terminated string that specifies the Service Principal Name to assign to the client. Passing NULL in
/// ServicePrincipalName is equivalent to a call to the DsBindWithCred function.
///
/// Contains a set of flags that define the behavior of this function. This parameter can contain zero or a combination of one or
/// more of the following values.
///
/// NTDSAPI_BIND_ALLOW_DELEGATION (1)
///
/// Causes the bind to use the delegate impersonation level. This enables operations that require delegation, such as
/// DsAddSidHistory, to succeed. Specifying this flag also causes DsBindWithSpnEx to operate similar to DsBindWithSpn.
///
///
/// If this flag is not specified, the bind will use the impersonate impersonation level. For more information about impersonation
/// levels, see Impersonation Levels.
///
///
/// Most operations do not require the delegate impersonation level; this flag should only be specified if it is required. Binding to
/// a rogue server with the delegate impersonation level enables the rogue server to connect to a non-rogue server with your
/// credentials and perform unintended operations.
///
/// NTDSAPI_BIND_FORCE_KERBEROS (4)
///
/// Active Directory Lightweight Directory Services: If this flag is specified, DsBindWithSpnEx requires Kerberos
/// authentication to be used. If Kerberos authentication cannot be established, DsBindWithSpnEx will not attempt to
/// authenticate with any other mechanism.
///
/// Address of a HANDLE value that receives the bind handle. To close this handle, call DsUnBind.
///
/// Returns NO_ERROR if successful or an RPC or Win32 error otherwise. Possible error codes include those listed in the
/// following list.
///
///
/// The following list lists the required parameter values for binding to an instance.
///
///
/// Instance
/// ServerName
/// Annotation
/// InstanceGuid
/// DnsDomainName
///
/// -
/// Active Directory by server
/// Server Name
/// NULL
/// NULL
/// NULL
///
/// -
/// Active Directory by domain
/// NULL
/// NULL
/// NULL
/// DNS domain name
///
/// -
/// AD LDS by port
/// DNS Name of the computer with the AD LDS installation.
/// Port Number
/// NULL
/// NULL
///
/// -
/// AD LDS by GUID
/// DNS Name of the computer with the AD LDS installation.
/// NULL
/// Instance GUID
/// NULL
///
///
///
/// Note For improved performance when binding to an AD LDS instance on a computer with several instances of AD LDS, bind by
/// the Instance GUID instead of the port number.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindbyinstancea NTDSAPI_POSTXP DWORD DsBindByInstanceA(
// LPCSTR ServerName, LPCSTR Annotation, GUID *InstanceGuid, LPCSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, LPCSTR
// ServicePrincipalName, DWORD BindFlags, HANDLE *phDS );
[PInvokeData("ntdsapi.h", MSDNShortId = "65302ddc-2bc0-4d80-b028-e268859be227")]
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto, EntryPoint = "DsBindByInstance", SetLastError = false, ThrowOnUnmappableChar = true), SuppressUnmanagedCodeSecurity]
public static extern Win32Error DsBindByInstance([Optional] string ServerName, [Optional] string Annotation, [Optional] IntPtr InstanceGuid, [Optional] string DnsDomainName,
SafeAuthIdentityHandle AuthIdentity, [Optional] string ServicePrincipalName, [Optional] DsBindFlags BindFlags, out SafeDsHandle phDS);
///
/// The DsBindingSetTimeout function sets the timeout value that is honored by all RPC calls that use the specified binding
/// handle. RPC calls that required more time than the timeout value are canceled.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Contains the new timeout value, in seconds.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error code otherwise. The following is a possible error code.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindingsettimeout NTDSAPI_POSTXP DWORD
// DsBindingSetTimeout( HANDLE hDS, ULONG cTimeoutSecs );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true)]
[PInvokeData("ntdsapi.h", MSDNShortId = "abdaae89-fba3-4949-92a9-acd62898ec24")]
public static extern Win32Error DsBindingSetTimeout(SafeDsHandle hDS, uint cTimeoutSecs);
///
/// The DsBindToISTG function binds to the computer that holds the Inter-Site Topology Generator (ISTG) role in the domain of
/// the local computer.
///
/// Pointer to a null-terminated string that contains the site name used when binding. If this parameter is NULL, the site of
/// the nearest domain controller is used.
/// Address of a HANDLE value that receives the bind handle. To close this handle, call DsUnBind.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error code otherwise. The following are possible error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindtoistga NTDSAPI_POSTXP DWORD DsBindToISTGA( LPCSTR
// SiteName, HANDLE *phDS );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "bd53124c-8578-495d-b540-d4b4c09297c3")]
public static extern Win32Error DsBindToISTG([Optional] string SiteName, out SafeDsHandle phDS);
///
/// The DsBindWithCred function binds to a domain controller using the specified credentials.
///
/// Pointer to a null-terminated string that contains the name of the domain controller to bind to. This name can be the name of the
/// domain controller or the fully qualified DNS name of the domain controller. Either name type can, optionally, be preceded by two
/// backslash characters. All of the following examples represent correctly formatted domain controller names:
/// - "FAB-DC-01"
- "\\FAB-DC-01"
- "FAB-DC-01.fabrikam.com"
- "\\FAB-DC-01.fabrikam.com"
This parameter can be NULL. For more information, see Remarks.
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind to. This parameter can be
/// NULL. For more information, see Remarks.
/// Contains an RPC_AUTH_IDENTITY_HANDLE value that represents the credentials to be used for the bind. The DsMakePasswordCredentials
/// function is used to obtain this value. If this parameter is NULL, the credentials of the calling thread are used.
/// DsUnBind must be called before freeing this handle with the DsFreePasswordCredentials function.
/// Address of a HANDLE value that receives the binding handle. To close this handle, pass it to the DsUnBind function.
///
/// Returns ERROR_SUCCESS if successful or a Windows or RPC error code otherwise.
///
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto, SetLastError = true)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675961")]
public static extern Win32Error DsBindWithCred([Optional] string DomainControllerName, [Optional] string DnsDomainName, SafeAuthIdentityHandle AuthIdentity, out SafeDsHandle phDS);
///
///
/// The DsBindWithSpn function binds to a domain controller using the specified credentials and a specific service principal
/// name (SPN) for mutual authentication.
///
///
/// This function is provided for where complete control is required for mutual authentication. Do not use this function if you
/// expect DsBind to find a server for you, because SPNs are computer-specific, and it is unlikely that the SPN you provide will
/// match the server that DsBind finds for you. Providing a NULL ServicePrincipalName argument results in behavior that
/// is identical to DsBindWithCred.
///
///
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind to. For more information,
/// see the DomainControllerName description in the DsBind topic.
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind to. For more information,
/// see the DnsDomainName description in the DsBind topic.
/// Contains an RPC_AUTH_IDENTITY_HANDLE value that represents the credentials to be used for the bind. The
///
/// DsMakePasswordCredentialsfunction is used to obtain this value. If this parameter is NULL, the credentials of the calling
/// thread are used.
///
/// DsUnBind must be called before freeing this handle with the DsFreePasswordCredentials function.
/// Pointer to a null-terminated string that specifies the Service Principal Name to assign to the client. Passing NULL in
/// ServicePrincipalName is equivalent to a call to the DsBindWithCred function.
/// Address of a HANDLE value that receives the binding handle. To close this handle, pass it to the DsUnBind function.
///
/// Returns ERROR_SUCCESS if successful or a Windows or RPC error code otherwise. The following are the most common error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindwithspnw NTDSAPI DWORD DsBindWithSpnW( LPCWSTR
// DomainControllerName, LPCWSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, LPCWSTR ServicePrincipalName, HANDLE *phDS );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "9a149654-fd94-4b0c-b712-07fb827bef2f")]
public static extern Win32Error DsBindWithSpn([Optional] string DomainControllerName, [Optional] string DnsDomainName, SafeAuthIdentityHandle AuthIdentity, [Optional] string ServicePrincipalName, out SafeDsHandle phDS);
///
///
/// The DsBindWithSpnEx function binds to a domain controller using the specified credentials and a specific service principal
/// name (SPN) for mutual authentication. This function is similar to the DsBindWithSpn function except this function allows more
/// binding options with the BindFlags parameter.
///
///
/// This function is provided where complete control is required over mutual authentication. Do not use this function if you expect
/// DsBind to find a server for you, because SPNs are computer-specific, and it is unlikely that the SPN you provide will match the
/// server that DsBind finds for you. Providing a NULL ServicePrincipalName argument results in behavior that is
/// identical to DsBindWithCred.
///
///
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind. For more information, see
/// the DomainControllerName description in the DsBind topic.
/// Pointer to a null-terminated string that contains the fully qualified DNS name of the domain to bind. For more information, see
/// the DnsDomainName description in the DsBind topic.
/// Contains an RPC_AUTH_IDENTITY_HANDLE value that represents the credentials to be used for the bind. The
///
/// DsMakePasswordCredentialsfunction is used to obtain this value. If this parameter is NULL, the credentials of the calling
/// thread are used.
///
/// DsUnBind must be called before freeing this handle with the DsFreePasswordCredentials function.
/// Pointer to a null-terminated string that specifies the Service Principal Name to assign to the client. Passing NULL in
/// ServicePrincipalName is equivalent to a call to the DsBindWithCred function.
///
/// Contains a set of flags that define the behavior of this function. This parameter can contain zero or a combination of the values
/// listed in the following list.
///
/// NTDSAPI_BIND_ALLOW_DELEGATION (1)
///
/// Causes the bind to use the delegate impersonation level. This allows operations that require delegation, such as DsAddSidHistory,
/// to succeed. Specifying this flag also causes DsBindWithSpnEx to operate like DsBindWithSpn.
///
///
/// If this flag is not specified, the bind will use the impersonate impersonation level. For more information, see Impersonation Levels.
///
///
/// Most operations do not require the delegate impersonation level, so this flag should only be specified if absolutely required.
/// Binding to a rogue server with the delegate impersonation level will allow the rogue server to connect to a non-rogue server with
/// your credentials and perform unintended operations.
///
/// NTDSAPI_BIND_FIND_BINDING (2)
/// Reserved.
/// NTDSAPI_BIND_FORCE_KERBEROS (4)
///
/// Active Directory Lightweight Directory Services: If this flag is specified, DsBindWithSpnEx forces Kerberos
/// authentication to be used. If Kerberos authentication cannot be established, DsBindWithSpnEx will not attempt to
/// authenticate with any other method.
///
/// Address of a HANDLE value that receives the binding handle. To close this handle, pass it to the DsUnBind function.
///
/// Returns ERROR_SUCCESS if successful or a Windows or RPC error code otherwise. The following list lists common error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsbindwithspnexw NTDSAPI_POSTXP DWORD DsBindWithSpnExW(
// LPCWSTR DomainControllerName, LPCWSTR DnsDomainName, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, LPCWSTR ServicePrincipalName, DWORD
// BindFlags, HANDLE *phDS );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "52a5761d-5244-4bc9-8c09-fd08f10a9fff")]
public static extern Win32Error DsBindWithSpnEx([Optional] string DomainControllerName, [Optional] string DnsDomainName, SafeAuthIdentityHandle AuthIdentity, [Optional] string ServicePrincipalName,
DsBindFlags BindFlags, out SafeDsHandle phDS);
///
/// The DsClientMakeSpnForTargetServer function constructs a service principal name (SPN) that identifies a specific server to
/// use for authentication.
///
/// Pointer to a null-terminated string that contains the class of the service as defined by the service. This can be any string
/// unique to the service.
///
/// Pointer to a null-terminated string that contains the distinguished name service (DNS) host name. This can either be a fully
/// qualified name or an IP address in the Internet standard format.
///
///
/// Use of an IP address for ServiceName is not recommended because this can create a security issue. Before the SPN is constructed,
/// the IP address must be translated to a computer name through DNS name resolution. It is possible for the DNS name resolution to
/// be spoofed, replacing the intended computer name with an unauthorized computer name.
///
/// Pointer to a DWORD value that, on entry, contains the size of the pszSpn buffer, in characters. On output, this parameter
/// receives the number of characters copied to the pszSpn buffer, including the terminating NULL.
/// Pointer to a string buffer that receives the SPN.
/// This function returns standard Windows error codes.
///
/// When using this function, supply the service class and part of a DNS host name.
///
/// This function is a simplified version of the DsMakeSpn function. The ServiceName is made canonical by resolving through DNS.
///
/// GUID-based DNS names are not supported. When constructed, the simplified SPN is as follows:
/// The instance name portion (second position) is always set to default. The port and referrer fields are not used.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsclientmakespnfortargetserverw NTDSAPI DWORD
// DsClientMakeSpnForTargetServerW( LPCWSTR ServiceClass, LPCWSTR ServiceName, DWORD *pcSpnLength, LPWSTR pszSpn );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "d205e7cc-4879-41a4-baa7-75e7dd177cd0")]
public static extern Win32Error DsClientMakeSpnForTargetServer(string ServiceClass, string ServiceName, ref uint pcSpnLength, StringBuilder pszSpn);
///
/// The DsCrackNames function converts an array of directory service object names from one format to another. Name conversion enables
/// client applications to map between the multiple names used to identify various directory service objects. For example, user
/// objects can be identified by SAM account names (Domain\UserName), user principal name (UserName@Domain.com), or distinguished
/// name. This function uses many handles and memory allocations that can be unwieldy. It is recommended to use the
/// method instead.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function. If flags contains
/// DS_NAME_FLAG_SYNTACTICAL_ONLY, hDS can be NULL.
/// Contains one or more of the DS_NAME_FLAGS values used to determine how the name syntax will be cracked.
/// Contains one of the DS_NAME_FORMAT values that identifies the format of the input names.
/// Contains one of the DS_NAME_FORMAT values that identifies the format of the output names. The DS_SID_OR_SID_HISTORY_NAME value is
/// not supported.
/// Contains the number of elements in the rpNames array.
/// Pointer to an array of pointers to null-terminated strings that contain names to be converted.
/// Pointer to a PDS_NAME_RESULT value that receives a DS_NAME_RESULT structure that contains the converted names. The caller must
/// free this memory, when it is no longer required, by calling DsFreeNameResult.
///
/// Returns a Win32 error value, an RPC error value, or one of the following.
///
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto, SetLastError = true)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675970")]
public static extern Win32Error DsCrackNames(SafeDsHandle hSafeDs, DS_NAME_FLAGS flags, DS_NAME_FORMAT formatOffered, DS_NAME_FORMAT formatDesired, uint cNames,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPTStr, SizeParamIndex = 4)] string[] rpNames, out SafeDsNameResult ppResult);
/// A wrapper function for the DsCrackNames OS call
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function. If flags contains
/// DS_NAME_FLAG_SYNTACTICAL_ONLY, hDS can be NULL.
/// The names to be converted.
/// Contains one of the DS_NAME_FORMAT values that identifies the format of the output names. The DS_SID_OR_SID_HISTORY_NAME value is
/// not supported.
/// Contains one of the DS_NAME_FORMAT values that identifies the format of the input names.
/// Contains one or m ore of the DS_NAME_FLAGS values used to determine how the name syntax will be cracked.
/// The crack results.
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675970")]
public static DS_NAME_RESULT_ITEM[] DsCrackNames(SafeDsHandle hSafeDs, string[] names,
DS_NAME_FORMAT formatDesired = DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME,
DS_NAME_FORMAT formatOffered = DS_NAME_FORMAT.DS_UNKNOWN_NAME,
DS_NAME_FLAGS flags = DS_NAME_FLAGS.DS_NAME_NO_FLAGS)
{
DsCrackNames(hSafeDs, flags, formatOffered, formatDesired, (uint)(names?.Length ?? 0), names, out var pResult).ThrowIfFailed();
return pResult.Items;
}
///
/// The DsFreeDomainControllerInfo function frees memory that is allocated by DsGetDomainControllerInfo for data about the
/// domain controllers in a domain.
///
///
/// Indicates what version of the DS_DOMAIN_CONTROLLER_INFO structure should be freed. This parameter can be one of the
/// following values.
///
/// 1
/// The function frees the structure that contains DS_DOMAIN_CONTROLLER_INFO_1 data.
/// 2
/// The function frees the structure that contains DS_DOMAIN_CONTROLLER_INFO_2 data.
/// Indicates the number of items in pInfo.
/// Pointer to an array of DS_DOMAIN_CONTROLLER_INFO structures to be freed.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsfreedomaincontrollerinfoa NTDSAPI VOID
// DsFreeDomainControllerInfoA( DWORD InfoLevel, DWORD cInfo, VOID *pInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "1b6d3136-91e2-4653-a4b0-ae2f66a6c5a2")]
public static extern void DsFreeDomainControllerInfo(uint InfoLevel, uint cInfo, DCInfoHandle pInfo);
///
/// The DsFreeNameResult function frees the memory held by a DS_NAME_RESULT structure. Use this function to free the memory allocated
/// by the DsCrackNames function.
///
/// Pointer to the DS_NAME_RESULT structure to be freed.
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675978")]
public static extern void DsFreeNameResult(IntPtr pResult);
///
/// Frees memory allocated for a credentials structure by the DsMakePasswordCredentials function.
///
/// Handle of the credential structure to be freed.
[DllImport(Lib.NTDSApi, ExactSpelling = true)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms675979")]
public static extern void DsFreePasswordCredentials(IntPtr AuthIdentity);
///
/// The DsFreeSchemaGuidMap function frees memory that the DsMapSchemaGuids function has allocated for a DS_SCHEMA_GUID_MAP structure.
///
/// Pointer to a DS_SCHEMA_GUID_MAP structure to deallocate.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsfreeschemaguidmapa NTDSAPI VOID DsFreeSchemaGuidMapA(
// PDS_SCHEMA_GUID_MAPA pGuidMap );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "54d6acb9-5602-4996-a483-08534143bc0a")]
public static extern void DsFreeSchemaGuidMap(IntPtr pGuidMap);
///
/// The DsFreeSpnArray function frees an array returned from the DsGetSpn function.
///
/// Specifies the number of elements contained in rpszSpn.
/// Pointer to an array returned from DsGetSpn.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsfreespnarraya void DsFreeSpnArrayA( DWORD cSpn, LPSTR
// *rpszSpn );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "1c229933-432d-4ded-be3b-3bd339a0abe4")]
public static extern void DsFreeSpnArray(uint cSpn, ref SpnArrayHandle rpszSpn);
///
/// The DsGetDomainControllerInfo function retrieves data about the domain controllers in a domain.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the domain name.
///
/// Contains a value that indicates the version of the DS_DOMAIN_CONTROLLER_INFO structure to return. This can be one of the
/// following values.
///
/// 1
/// The function provides the domain data in the DS_DOMAIN_CONTROLLER_INFO_1 structure format.
/// 2
/// The function provides the domain data in the DS_DOMAIN_CONTROLLER_INFO_2 structure format.
/// 3
/// The function provides the domain data in the DS_DOMAIN_CONTROLLER_INFO_3 structure format.
/// Pointer to a DWORD variable that receives the number of items returned in ppInfo array.
/// Pointer to a pointer variable that receives an array of DS_DOMAIN_CONTROLLER_INFO_* structures. The type of structures in
/// this array is defined by the InfoLevel parameter. The caller must free this array, when it is no longer required, by using the
/// DsFreeDomainControllerInfo function.
///
///
/// If the function returns domain controller data, the return value is ERROR_SUCCESS. If the caller does not have the
/// privileges to access the server objects, the return value is ERROR_SUCCESS, but the DS_DOMAIN_CONTROLLER_INFO
/// structures could be empty.
///
/// If the function fails, the return value can be one of the following error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsgetdomaincontrollerinfoa NTDSAPI DWORD
// DsGetDomainControllerInfoA( HANDLE hDs, LPCSTR DomainName, DWORD InfoLevel, DWORD *pcOut, VOID **ppInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "52db3b25-e6b0-4a0d-831b-89a203580cf1")]
public static extern Win32Error DsGetDomainControllerInfo(SafeDsHandle hDs, string DomainName, uint InfoLevel, out uint pcOut, out DCInfoHandle ppInfo);
///
/// The DsGetDomainControllerInfo function retrieves data about the domain controllers in a domain.
///
/// The type of the DS_DOMAIN_CONTROLLER_INFO_X structure to return.
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the domain name.
///
/// An array of returned by a call to the native DsGetDomainControllerInfo function.
///
/// Unable to determine level from requested type.
public static T[] DsGetDomainControllerInfo(SafeDsHandle hDs, string DomainName) where T : struct, IDsGetDCResult
{
uint level = 0, cout = 0;
DCInfoHandle h = default;
try
{
level = uint.Parse(typeof(T).Name.Substring(typeof(T).Name.LastIndexOf('_') + 1));
}
catch
{
throw new ArgumentException("Unable to determine level from requested type.");
}
try
{
DsGetDomainControllerInfo(hDs, DomainName, level, out cout, out h).ThrowIfFailed();
return h.ToIEnum(cout).ToArray();
}
finally
{
if (!h.IsNull)
DsFreeDomainControllerInfo(level, cout, h);
}
}
///
/// The DsGetSpn function constructs an array of one or more service principal names (SPNs). Each name in the array identifies
/// an instance of a service. These SPNs may be registered with the directory service (DS) using the DsWriteAccountSpn function.
///
/// Identifies the format of the SPNs to compose. The ServiceType parameter can have one of the following values.
/// DS_SPN_DNS_HOST, DS_SPN_DN_HOST, DS_SPN_NB_HOST
/// The SPNs have the following format.
/// The
/// ServiceName
/// parameter must be
/// NULL
/// . This is the SPN format for a host-based service, which provides services identified with its host computer. The
/// InstancePort
/// component is optional.
/// DS_SPN_DOMAIN, DS_SPN_NB_DOMAIN
/// The SPNs have the following format.
/// The
/// ServiceName
///
/// parameter must be the DNS name or DN of a domain. This format is used for a replicable service that provides services to the
/// specified domain.
///
/// DS_SPN_SERVICE
/// The SPNs have the following format.
/// The
/// ServiceName
///
/// parameter must be a canonical DN or DNS name that identifies an instance of the service. For example, it could be a DNS name of a
/// SRV record, or the distinguished name of the service connection point for this service instance.
///
/// Pointer to a constant null-terminated string that specifies the class of the service; for example, http. Generally, this can be
/// any string that is unique to the service.
/// Pointer to a constant null-terminated string that specifies the DNS name or distinguished name (DN) of the service. ServiceName
/// is not required for a host-based service. For more information, see the description of the ServiceType parameter for the possible
/// values of ServiceName.
/// Specifies the port number of the service instance. If this value is zero, the SPN does not include a port number.
/// Specifies the number of elements in the pInstanceNames and pInstancePorts arrays. If this value is zero, pInstanceNames must
/// point to an array of cInstanceNames strings, and pInstancePorts can be either NULL or a pointer to an array of
/// cInstanceNames port numbers. If this value is zero, DsGetSpn returns only one SPN in the prpszSpn array and pInstanceNames
/// and pInstancePorts are ignored.
/// Pointer to an array of null-terminated strings that specify extra instance names (not used for host names). This parameter is
/// ignored if cInstanceNames is zero. In that case, the InstanceName component of the SPN defaults to the fully qualified DNS name
/// of the local computer or the NetBIOS name if DS_SPN_NB_HOST or DS_SPN_NB_DOMAIN is specified.
/// Pointer to an array of extra instance ports. If this value is non- NULL, it must point to an array of cInstanceNames port
/// numbers. If this value is NULL, the SPNs do not include a port number. This parameter is ignored if cInstanceNames is zero.
/// Pointer to a variable that receives the number of SPNs contained in prpszSpn.
/// Pointer to a variable that receives a pointer to an array of SPNs. This array must be freed with DsFreeSpnArray.
///
/// If the function returns an array of SPNs, the return value is ERROR_SUCCESS.
/// If the function fails, the return value can be one of the following error codes.
///
///
///
/// To create SPNs for multiple instances of a replicated service running on multiple host computers
///
///
/// -
/// Set cInstanceNames to the number of instances.
///
/// -
/// Specify the names of the host computers in the pInstanceNames array.
///
///
///
/// To create SPNs for multiple instances of a service running on the same host computer
///
///
/// -
/// Set the cInstanceNames to the number of instances.
///
/// -
/// Set each entry in the pInstanceNames array to the DNS name of the host computer.
///
/// -
/// Use the pInstancePorts parameter to specify an array of unique port numbers for each instance to disambiguate the SPNs.
///
///
/// String parameters cannot include the forward slash (/), which is used to separate the components of the SPN.
///
/// An application with the appropriate privileges, which are usually those of a domain administrator, can call the DsWriteAccountSpn
/// function to register one or more SPNs on the user or computer account where the service is running. Clients can then use the SPNs
/// to authenticate the service.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsgetspna NTDSAPI DWORD DsGetSpnA( DS_SPN_NAME_TYPE
// ServiceType, LPCSTR ServiceClass, LPCSTR ServiceName, USHORT InstancePort, USHORT cInstanceNames, LPCSTR *pInstanceNames, const
// USHORT *pInstancePorts, DWORD *pcSpn, LPSTR **prpszSpn );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "cbd53850-9b05-4f74-ab07-30dcad583fc5")]
public static extern Win32Error DsGetSpn(DS_SPN_NAME_TYPE ServiceType, string ServiceClass, string ServiceName, ushort InstancePort, ushort cInstanceNames,
string[] pInstanceNames, ushort[] pInstancePorts, ref uint pcSpn, out SpnArrayHandle prpszSpn);
///
/// The DsInheritSecurityIdentity function appends the objectSid and sidHistory attributes of SrcPrincipal to
/// the sidHistory of DstPrincipal and then deletes SrcPrincipal, all in a single transaction. To ensure that this operation
/// is atomic, SrcPrincipal and DstPrincipal must be in the same domain and hDS must be bound to a domain controller that the correct
/// permissions within that domain.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Reserved for future use. Must be zero.
/// Pointer to a null-terminated string that specifies the name of a security principal (user or group) in the source domain. This
/// name is a domain-relative SAM name.
/// Pointer to a null-terminated string that specifies the name of a security principal (user or group) in the destination domain.
/// This domain-relative SAM name identifies the principal whose sidHistory attribute will be updated with the SID of SrcPrincipal.
/// Returns a system or RPC error code including the following.
///
///
/// With an operating system upgrade domain applications, which span both upgraded and non-upgraded domains, may have security
/// principals inside and outside the forest for the same logical entity at the same time.
///
///
/// When all upgraded domains have joined the same forest, DsInheritSecurityIdentity eliminates the duplicate objects while
/// ensuring that the remaining objects have all the security rights and privileges belonging to their respective deleted object.
///
/// A DsInheritSecurityIdentity implementation:
///
/// -
/// Verifies that SrcPrincipal and DstPrincipal are in the same domain.
///
/// -
/// Verifies that the domain is writable at the bind to the server.
///
/// -
/// Verifies that auditing is enabled for the domain.
///
/// -
/// Verifies that the caller is a member of the domain administrators for the domain.
///
/// -
/// Verifies that the domain is in the native mode.
///
/// -
///
/// Verifies that SrcPrincipal exists, that it is a security principal and has read its objectSid and sidHistory properties.
///
///
/// -
///
/// Verifies that DstPrincipal exists, that it is a security principal, and has read certain properties required for auditing and verification.
///
///
/// -
///
/// Deletes SrcPrincipal in the database only if the entire operation is committed at completion. This operation fails if the caller
/// does not have delete rights or if SrcPrincipal has children.
///
///
/// -
/// Fails the operation if the objectSid of SrcPrincipal or DstPrincipal is a well-known SID.
///
/// -
/// Adds the objectSid and the sidHistory (if present) of SrcPrincipal to the sidHistory of DstPrincipal.
///
/// -
/// Forces an audit event and fails the operation if the audit fails.
///
/// -
/// Enters events into the Directory Service Log. Do not confuse this with the Security Audit Log.
///
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsinheritsecurityidentitya NTDSAPI DWORD
// DsInheritSecurityIdentityA( HANDLE hDS, DWORD Flags, LPCSTR SrcPrincipal, LPCSTR DstPrincipal );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "ea467069-f886-4e22-896c-16e6e01f3968")]
public static extern Win32Error DsInheritSecurityIdentity(SafeDsHandle hDS, [Optional] uint Flags, string SrcPrincipal, string DstPrincipal);
///
/// The DsListDomainsInSite function lists all the domains in a site.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the site name. This string is taken from the list of site names returned by
/// the DsListSites function.
/// Pointer to a pointer to a DS_NAME_RESULT structure that receives the list of domains in the site. To free the returned structure,
/// call the DsFreeNameResult function.
///
/// If the function returns a list of domains, the return value is NO_ERROR. If the function fails, the return value can be
/// one of the following error codes.
///
///
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistdomainsinsitea NTDSAPI DWORD DsListDomainsInSiteA(
// HANDLE hDs, LPCSTR site, PDS_NAME_RESULTA *ppDomains );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "3a039c0c-ac5b-4455-960d-b26a207693ed")]
public static extern Win32Error DsListDomainsInSite(SafeDsHandle hDs, string site, out SafeDsNameResult ppDomains);
///
/// The DsListInfoForServer function lists miscellaneous data for a server.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the server name. This name must be the same as one of the strings returned by
/// the DsListServersForDomainInSite or DsListServersInSite function.
///
/// Pointer to a variable that receives a pointer to a DS_NAME_RESULT structure that contains the server data. The returned structure
/// must be deallocated using DsFreeNameResult.
///
///
/// The indexes of the array in the DS_NAME_RESULT structure indicate what data are contained by each array element. The following
/// constants may be used to specify the desired index for a particular piece of data.
///
/// DS_LIST_ACCOUNT_OBJECT_FOR_SERVER
/// Name of the account object for the domain controller (DC).
/// DS_LIST_DNS_HOST_NAME_FOR_SERVER
/// DNS host name of the DC.
/// DS_LIST_DSA_OBJECT_FOR_SERVER
/// GUID of the directory service agent (DSA) for the domain controller (DC).
///
/// If the function returns server data, the return value is NO_ERROR.
/// If the function fails, the return value can be one of the following error codes.
///
///
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistinfoforservera NTDSAPI DWORD DsListInfoForServerA(
// HANDLE hDs, LPCSTR server, PDS_NAME_RESULTA *ppInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "15dcc7ac-4edb-42fa-8466-033794762046")]
public static extern Win32Error DsListInfoForServer(SafeDsHandle hDs, string server, out SafeDsNameResult ppInfo);
///
/// The DsListRoles function lists roles recognized by the server.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
///
/// Pointer to a variable that receives a pointer to a DS_NAME_RESULT structure containing the roles the server recognizes. The
/// returned structure must be deallocated using DsFreeNameResult.
///
///
/// The indexes of the array in the DS_NAME_RESULT structure indicate what data are contained by each array element. The following
/// constants may be used to specify the desired index for a particular piece of data.
///
/// DS_ROLE_DOMAIN_OWNER
/// Server owns the domain.
/// DS_ROLE_INFRASTRUCTURE_OWNER
/// Server owns the infrastructure.
/// DS_ROLE_PDC_OWNER
/// Server owns the PDC.
/// DS_ROLE_RID_OWNER
/// Server owns the RID.
/// DS_ROLE_SCHEMA_OWNER
/// Server owns the schema.
///
/// If the function returns a list of roles, the return value is NO_ERROR.
/// If the function fails, the return value can be one of the following error codes.
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistrolesa NTDSAPI DWORD DsListRolesA( HANDLE hDs,
// PDS_NAME_RESULTA *ppRoles );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "679a2dca-019b-4f6e-acd9-efb30e0d4b44")]
public static extern Win32Error DsListRoles(SafeDsHandle hDs, out SafeDsNameResult ppRoles);
///
/// The DsListServersForDomainInSite function lists all the servers in a domain in a site.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the domain name. This string must be the same as one of the strings returned
/// by DsListDomainsInSite function.
/// Pointer to a null-terminated string that specifies the site name. This string is taken from the list of site names returned by
/// the DsListSites function.
/// Pointer to a pointer to a DS_NAME_RESULT structure that receives the list of servers in the domain. The returned structure must
/// be freed using the DsFreeNameResult function.
///
/// If the function returns a list of servers, the return value is NO_ERROR. If the function fails, the return value can be
/// one of the following error codes.
///
///
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistserversfordomaininsitea NTDSAPI DWORD
// DsListServersForDomainInSiteA( HANDLE hDs, LPCSTR domain, LPCSTR site, PDS_NAME_RESULTA *ppServers );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "1e346532-bbbe-4b3b-a1cb-6a72319cb3e2")]
public static extern Win32Error DsListServersForDomainInSite(SafeDsHandle hDs, string domain, string site, out SafeDsNameResult ppServers);
///
/// The DsListServersInSite function lists all the servers in a site.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the site name. The site name uses a distinguished name format. It is taken
/// from the list of sites returned by the DsListSites function.
/// Pointer to a pointer to a DS_NAME_RESULT structure that receives the list of servers in the site. The returned structure must be
/// freed using the DsFreeNameResult function.
///
/// If the function returns a list of servers, the return value is NO_ERROR. If the function fails, the return value can be
/// one of the following error codes.
///
///
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistserversinsitea NTDSAPI DWORD DsListServersInSiteA(
// HANDLE hDs, LPCSTR site, PDS_NAME_RESULTA *ppServers );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "46773631-d464-4d9e-83e7-aa502599df71")]
public static extern Win32Error DsListServersInSite(SafeDsHandle hDs, string site, out SafeDsNameResult ppServers);
///
/// The DsListSites function lists all the sites in the enterprise forest.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a pointer to a DS_NAME_RESULT structure that receives the list of sites in the enterprise. The site name is returned
/// in the distinguished name (DN) format. The returned structure must be freed using the DsFreeNameResult function.
///
/// If the function returns a list of sites, the return value is NO_ERROR. If the function fails, the return value can be one
/// of the following error codes.
///
///
/// Individual name conversion errors are reported in the returned DS_NAME_RESULT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dslistsitesw NTDSAPI DWORD DsListSitesW( HANDLE hDs,
// PDS_NAME_RESULTW *ppSites );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "d424e750-6700-42b8-9d4f-e430cd0a7e4e")]
public static extern Win32Error DsListSites(SafeDsHandle hDs, out SafeDsNameResult ppSites);
///
/// Constructs a credential handle suitable for use with the DsBindWithCred function.
///
/// A string that contains the user name to use for the credentials.
/// A string that contains the domain that the user is a member of.
/// A string that contains the password to use for the credentials.
/// An RPC_AUTH_IDENTITY_HANDLE value that receives the credential handle. This handle is used in a subsequent call to
/// DsBindWithCred. This handle must be freed with the DsFreePasswordCredentials function when it is no longer required.
/// Returns a Windows error code.
///
/// A null, default credential handle is created if User, Domain and Password are all NULL. Otherwise, User must be present. The
/// Domain parameter may be NULL when User is fully qualified, such as a user in UPN format; for example, "someone@fabrikam.com".
///
/// When the handle returned in pAuthIdentity is passed to DsBindWithCred, DsUnBind must be called before freeing the handle with DsFreePasswordCredentials.
///
///
[DllImport(Lib.NTDSApi, CharSet = CharSet.Auto)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676006")]
public static extern Win32Error DsMakePasswordCredentials(string User, string Domain, string Password, out SafeAuthIdentityHandle pAuthIdentity);
///
/// The DsMapSchemaGuids function converts GUIDs of directory service schema objects to their display names.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Indicates the number of elements in rGuids.
/// Pointer to an array of GUID values for the objects to be mapped.
/// Pointer to a variable that receives a pointer to an array of DS_SCHEMA_GUID_MAP structures that contain the display names of the
/// objects in rGuids. This array must be deallocated using DsFreeSchemaGuidMap.
///
/// Returns a standard error code that includes the following values.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsmapschemaguidsa NTDSAPI DWORD DsMapSchemaGuidsA( HANDLE
// hDs, DWORD cGuids, GUID *rGuids, DS_SCHEMA_GUID_MAPA **ppGuidMap );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "439fff20-51eb-490d-a330-61d07f79c436")]
public static extern Win32Error DsMapSchemaGuids(SafeDsHandle hDs, uint cGuids, [In] Guid[] rGuids, out SafeDsSchemaGuidMap ppGuidMap);
///
/// The DsQuerySitesByCost function gets the communication cost between one site and one or more other sites.
///
/// A directory service handle.
/// Pointer to a null-terminated string that contains the relative distinguished name of the site the costs are measured from.
/// Contains an array of null-terminated string pointers that contain the relative distinguished names of the sites the costs are
/// measured to.
/// Contains the number of elements in the rgwszToSites array.
/// Reserved.
///
/// Pointer to an array of DS_SITE_COST_INFO structures that receives the cost data. Each element in this array contains the cost
/// data between the site identified by the pwszFromSite parameter and the site identified by the corresponding rgwszToSites element.
///
/// The caller must free this memory when it is no longer required by calling DsQuerySitesFree.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error code otherwise. Possible error codes include values listed in
/// the following list.
///
///
/// The cost values obtained by this function are only used to compare and have no meaning by themselves. For example, the cost for
/// site 1 can be compared to the cost for site 2, but the cost for site 1 cannot be compared to a fixed value.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsquerysitesbycosta NTDSAPI_POSTXP DWORD
// DsQuerySitesByCostA( HANDLE hDS, LPSTR pszFromSite, LPSTR *rgszToSites, DWORD cToSites, DWORD dwFlags, PDS_SITE_COST_INFO
// *prgSiteInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "7a4cbd1c-8445-4882-8559-d44b6e5693e7")]
public static extern Win32Error DsQuerySitesByCost(SafeDsHandle hDS, string pszFromSite, [In] string[] rgszToSites,
uint cToSites, [Optional] uint dwFlags, out SafeDsQuerySites prgSiteInfo);
///
/// The DsQuerySitesFree function frees the memory allocated by the DsQuerySitesByCost function.
///
/// Pointer to an array of DS_SITE_COST_INFO structures allocated by a call to DsQuerySitesByCost.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsquerysitesfree void DsQuerySitesFree( PDS_SITE_COST_INFO
// rgSiteInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true)]
[PInvokeData("ntdsapi.h", MSDNShortId = "810caa4f-8275-4ad8-ad3e-72061fc073dd")]
public static extern void DsQuerySitesFree(IntPtr rgSiteInfo);
///
/// The DsRemoveDsDomain function removes all traces of a domain naming context from the global area of the directory service.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the distinguished name of the naming context to remove from the directory service.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error code if unsuccessful. Possible error codes include the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsremovedsdomaina NTDSAPI DWORD DsRemoveDsDomainA( HANDLE
// hDs, LPSTR DomainDN );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "0639cc04-2821-4421-8aa7-363621c1d6b5")]
public static extern Win32Error DsRemoveDsDomain(SafeDsHandle hDs, string DomainDN);
///
/// The DsRemoveDsServer function removes all traces of a directory service agent (DSA) from the global area of the directory service.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the fully qualified distinguished name of the domain controller to remove.
/// Pointer to a null-terminated string that specifies a domain hosted by ServerDN. If this parameter is NULL, no verification
/// is performed to ensure that ServerDN is the last domain controller in DomainDN.
/// Pointer to a Boolean value that receives TRUE if ServerDN is the last DC in DomainDN or FALSE otherwise. This
/// parameter receives FALSE if DomainDN is NULL.
/// Contains a Boolean value that specifies if the domain controller should actually be removed. If this parameter is nonzero,
/// ServerDN is removed. If this parameter is zero, the existence of ServerDN is checked and fLastDcInDomain is written, but the
/// domain controller is not removed.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error code if unsuccessful. Possible error codes include the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsremovedsserverw NTDSAPI DWORD DsRemoveDsServerW( HANDLE
// hDs, LPWSTR ServerDN, LPWSTR DomainDN, BOOL *fLastDcInDomain, BOOL fCommit );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "a79a2b71-10c7-495b-861f-0c7a4d86f720")]
public static extern Win32Error DsRemoveDsServer(SafeDsHandle hDs, string ServerDN, [Optional] string DomainDN, [MarshalAs(UnmanagedType.Bool)] out bool fLastDcInDomain, [MarshalAs(UnmanagedType.Bool)] bool fCommit);
///
/// The DsReplicaAdd function adds a replication source reference to a destination naming context.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// The null-terminated string that specifies the distinguished name (DN) of the destination naming context (NC) for which to add the
/// replica. The destination NC record must exist locally as either an object, instantiated or not, or a reference phantom, for
/// example, a phantom with a GUID.
/// The null-terminated string that specifies the DN of the NTDS-DSA object for the source directory system agent. This
/// parameter is required if Options includes DS_REPADD_ASYNCHRONOUS_REPLICA; otherwise, it is ignored.
/// The null-terminated string that specifies the DN of the interSiteTransport object that represents the transport used for
/// communication with the source server. This parameter is required if Options includes DS_REPADD_INTERSITE_MESSAGING;
/// otherwise, it is ignored.
/// The null-terminated string that specifies the transport-specific address of the source DSA. This source server is identified by a
/// string name, not by its UUID. A string name appropriate for SourceDsaAddress is usually a DNS name based on a GUID, where the
/// GUID part of the name is the GUID of the NTDS-DSA object for the source server.
/// Pointer to a SCHEDULE structure that contains the replication schedule data for the replication source. This parameter is
/// optional and can be NULL if not used.
/// Passes additional data to be used to process the request. This parameter can be a combination of the following values.
/// DS_REPADD_ASYNCHRONOUS_OPERATION
/// Performs this operation asynchronously.
/// DS_REPADD_ASYNCHRONOUS_REPLICA
/// Does not replicate the NC. Instead, save enough state data such that it may be replicated later.
/// DS_REPADD_DISABLE_NOTIFICATION
///
/// Disables notification-based synchronization for the NC from this source. This is expected to be a temporary state. Use
/// DS_REPADD_NEVER_NOTIFY to permanently disable synchronization.
///
/// DS_REPADD_DISABLE_PERIODIC
/// Disables periodic synchronization for the NC from this source.
/// DS_REPADD_INITIAL
/// Synchronizes the NC from this source when the DSA is started.
/// DS_REPADD_INTERSITE_MESSAGING
///
/// Synchronizes from the source DSA using the Intersite Messaging Service (IMS) transport, for example, by SMTP, rather than using
/// the native directory service RPC.
///
/// DS_REPADD_NEVER_NOTIFY
///
/// Disables change notifications from this source. When this flag is set, the source does not notify the destination when changes
/// occur. This is recommended for all intersite replication that may occur over WAN links.
///
/// This is expected to be a permanent state; use DS_REPADD_DISABLE_NOTIFICATION to temporarily disable notifications.
/// DS_REPADD_PERIODIC
/// Synchronizes the NC from this source periodically, as defined in pSchedule.
/// DS_REPADD_USE_COMPRESSION
///
/// Uses compression when replicating. This saves network bandwidth at the expense of CPU overhead at both the source and destination servers.
///
/// DS_REPADD_WRITEABLE
/// Creates a writable replica; otherwise, the replica is read-only.
///
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value can be one of the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicaadda NTDSAPI DWORD DsReplicaAddA( HANDLE hDS,
// LPCSTR NameContext, LPCSTR SourceDsaDn, LPCSTR TransportDn, LPCSTR SourceDsaAddress, const PSCHEDULE pSchedule, DWORD Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "33bd1b61-b9ed-479f-a128-fb7ddbb5e9af")]
public static extern Win32Error DsReplicaAdd(SafeDsHandle hDS, string NameContext, string SourceDsaDn, string TransportDn, string SourceDsaAddress, [Optional] SCHEDULE pSchedule, DsReplicaAddOptions Options);
///
/// The DsReplicaConsistencyCheck function invokes the Knowledge Consistency Checker (KCC) to verify the replication topology.
/// The KCC dynamically adjusts the data replication topology of your network when domain controllers are added to or removed from
/// the network, when a domain controller is unavailable, or when the data replication schedules are changed.
///
/// Contains a directory service handle obtained from either the DSBind, DSBindWithCred, or DsBindWithSpn function.
/// Identifies the task that the KCC should execute. DS_KCC_TASKID_UPDATE_TOPOLOGY is the only currently supported value.
///
/// Contains a set of flags that modify the function behavior. This can be zero or a combination of one or more of the following values.
///
/// DS_KCC_FLAG_ASYNC_OP
/// The task is queued and then the function returns without waiting for the task to complete.
/// DS_KCC_FLAG_DAMPED
/// The task will not be added to the queue if another queued task will run soon.
///
/// If the function performs its operation successfully, the return value is ERROR_SUCCESS. If the function fails, the return
/// value can be one of the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicaconsistencycheck NTDSAPI DWORD
// DsReplicaConsistencyCheck( HANDLE hDS, DS_KCC_TASKID TaskID, DWORD dwFlags );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true)]
[PInvokeData("ntdsapi.h", MSDNShortId = "2a83ffcb-1ebd-4024-a186-9c079896f4e1")]
public static extern Win32Error DsReplicaConsistencyCheck(SafeDsHandle hDS, DS_KCC_TASKID TaskID, DsKCCFlags dwFlags);
///
/// The DsReplicaDel function removes a replication source reference from a destination naming context (NC).
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a constant null-terminated string that specifies the distinguished name (DN) of the destination NC from which to
/// remove the replica. The destination NC record must exist locally as either an object, instantiated or not, or a reference
/// phantom, for example, a phantom with a GUID.
/// Pointer to a constant null-terminated Unicode string that specifies the transport-specific address of the source directory system
/// agent (DSA). This source server is identified by a string name, not by its UUID. A string name appropriate for DsaSrc is
/// usually a DNS name that is based on a GUID, where the GUID part of the name is the GUID of the nTDSDSA
/// object for the source server.
/// Passes additional data used to process the request. This parameter can be a combination of the following values.
/// DS_REPDEL_ASYNCHRONOUS_OPERATION
/// Performs this operation asynchronously.
/// DS_REPDEL_IGNORE_ERRORS
///
/// Ignores any error generated from contacting the source to instruct it to remove this NC from its list of servers to which it replicates.
///
/// DS_REPDEL_INTERSITE_MESSAGING
/// Signifies the replica is mail-based rather than synchronized using native directory service RPC.
/// DS_REPDEL_LOCAL_ONLY
///
/// Does not contact the source to tell it to remove this NC from its list of servers to which it replicates. If this flag is not set
/// and the link is based in RPC, the source is contacted.
///
/// DS_REPDEL_NO_SOURCE
/// Deletes all the objects in the NC. This option is valid only for read-only NCs with no source.
/// DS_REPDEL_REF_OK
/// Allows deletion of a read-only replica even if it sources other read-only replicas.
/// DS_REPDEL_WRITEABLE
/// Signifies that the replica deleted can be written to.
///
/// If the function succeeds, the return value is ERROR_SUCCESS.
///
/// If the function fails, the return value is a standard Win32 API error or ERROR_INVALID_PARAMETER if a parameter is invalid.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicadela NTDSAPI DWORD DsReplicaDelA( HANDLE hDS,
// LPCSTR NameContext, LPCSTR DsaSrc, ULONG Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "68c767c4-bbb6-477b-8ffb-94f3ae235375")]
public static extern Win32Error DsReplicaDel(SafeDsHandle hDS, string NameContext, string DsaSrc, DsReplicaDelOptions Options);
///
/// The DsReplicaFreeInfo function frees the replication state data structure allocated by the DsReplicaGetInfo or
/// DsReplicaGetInfo2 functions.
///
/// Contains one of the DS_REPL_INFO_TYPE values that specifies the type of replication data structure contained in pInfo. This must
/// be the same value passed to the DsReplicaGetInfo or DsReplicaGetInfo2 function when the structure was allocated.
/// Pointer to the replication data structure allocated by the DsReplicaGetInfo or DsReplicaGetInfo2 functions.
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicafreeinfo void DsReplicaFreeInfo(
// DS_REPL_INFO_TYPE InfoType, VOID *pInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true)]
[PInvokeData("ntdsapi.h", MSDNShortId = "32ce378e-a178-4970-b3bd-3887866e97af")]
public static extern void DsReplicaFreeInfo(DS_REPL_INFO_TYPE InfoType, IntPtr pInfo);
///
/// The DsReplicaGetInfo2 function retrieves replication state data from the directory service. This function allows paging of
/// results in cases where there are more than 1000 entries to retrieve.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Contains one of the DS_REPL_INFO_TYPE values that specifies the type of replication data to retrieve. This value also determines
/// which type of structure is returned in ppInfo.
///
/// Pointer to a constant null-terminated Unicode string that identifies the object to retrieve replication data for. The meaning of
/// this parameter depends on the value of the InfoType parameter. The following are possible value codes.
///
/// DS_REPL_INFO_NEIGHBORS
/// pszObject identifies the naming context for which replication neighbors are requested.
/// DS_REPL_INFO_CURSORS_FOR_NC
/// pszObject identifies the naming context for which replication cursors are requested.
/// DS_REPL_INFO_METADATA_FOR_OBJ
/// pszObject identifies the object for which replication metadata is requested.
/// DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_KCC_DSA_LINK_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_PENDING_OPS
/// pszObject must be NULL.
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// pszObject identifies the object for which attribute replication metadata is requested.
/// DS_REPL_INFO_CURSORS_2_FOR_NC
/// DS_REPL_INFO_CURSORS_3_FOR_NC
/// DS_REPL_INFO_METADATA_2_FOR_OBJ
/// pszObject identifies the object for which replication metadata is requested.
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
/// pszObject identifies the object for which attribute replication metadata is requested.
/// Pointer to a GUID value that identifies a specific replication source. If this parameter is not NULL and the
/// InfoType parameter contains DS_REPL_INFO_NEIGHBORS, only neighbor data for the source corresponding to the nTDSDSA object
/// with the given objectGuid in the directory is returned. This parameter is ignored if NULL or if the InfoType
/// parameter is anything other than DS_REPL_INFO_NEIGHBORS.
///
/// Pointer to a null-terminated Unicode string that contains the name of the specific attribute to retrieve replication data for.
///
/// This parameter is only used if the InfoType parameter contains one of the following values.
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
/// Pointer to a null-terminated Unicode string that contains the distinguished name value to match. If the requested attribute is a
/// distinguished name type value, this function return the attributes that contain the specified value.
/// Contains a set of flags that modify the behavior of the function. This parameter can be zero or the following value.
/// DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS
///
/// Causes the attribute metadata to account for metadata on the attribute's linked values. The resulting vector represents changes
/// for all attributes. This modified vector is useful for clients that expect all attributes and metadata to be included in the
/// attribute metadata vector.
///
/// Contains the index of the next entry to retrieve. This parameter must be set to zero the first time this function is called.
/// This parameter is only used if the InfoType parameter contains one of the following values.
/// DS_REPL_INFO_CURSORS_2_FOR_NC
/// DS_REPL_INFO_CURSORS_3_FOR_NC
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
///
/// This function will retrieve a maximum of 1000 entries on each call. If after calling this function, more entries are available,
/// the dwEnumerationContext member of the retrieved structure will contain the index of the next entry to retrieve. The
/// dwEnumerationContext member of the retrieved structure is then used as the dwEnumerationContext parameter in the next call
/// to this function. When all of the entries have been retrieved, the dwEnumerationContext member of the retrieved structure
/// will contain -1. If -1 is passed for this parameter, this function will return ERROR_NO_MORE_ITEMS.
///
///
/// Address of a structure pointer that receives the requested data. The value of the InfoType parameter determines the format of
/// this structure. For more information and a list of possible InfoType values and the corresponding structure types, see DS_REPL_INFO_TYPE.
///
/// The caller must free this memory when it is no longer required by calling DsReplicaFreeInfo.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error otherwise. The following are possible error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicagetinfo2w NTDSAPI DWORD DsReplicaGetInfo2W(
// HANDLE hDS, DS_REPL_INFO_TYPE InfoType, LPCWSTR pszObject, UUID *puuidForSourceDsaObjGuid, LPCWSTR pszAttributeName, LPCWSTR
// pszValue, DWORD dwFlags, DWORD dwEnumerationContext, VOID **ppInfo );
[PInvokeData("ntdsapi.h", MSDNShortId = "5735d91d-1b7d-4dc6-b6c6-61ba38ebe50d")]
public static Win32Error DsReplicaGetInfo2W(SafeDsHandle hDS, DS_REPL_INFO_TYPE InfoType, [Optional] string pszObject, [Optional] Guid? puuidForSourceDsaObjGuid, [Optional] string pszAttributeName,
[Optional] string pszValue, DsReplInfoFlags dwFlags, uint dwEnumerationContext, out SafeDsReplicaInfo ppInfo)
{
unsafe
{
var guid = puuidForSourceDsaObjGuid.GetValueOrDefault();
var ret = DsReplicaGetInfo2W(hDS, InfoType, pszObject, puuidForSourceDsaObjGuid.HasValue ? &guid : null, pszAttributeName, pszValue, dwFlags, dwEnumerationContext, out ppInfo);
ppInfo.Type = InfoType;
return ret;
}
}
///
/// The DsReplicaGetInfo function retrieves replication state data from the directory service.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
///
/// Contains one of the DS_REPL_INFO_TYPE values that specifies the type of replication data to retrieve. This value also determines
/// which type of structure is returned in ppInfo.
///
///
/// Only the following values are supported for this function. If other data types are required, the DsReplicaGetInfo2 function must
/// be used.
///
/// DS_REPL_INFO_NEIGHBORS
/// DS_REPL_INFO_CURSORS_FOR_NC
/// DS_REPL_INFO_METADATA_FOR_OBJ
/// DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES
/// DS_REPL_INFO_KCC_DSA_LINK_FAILURES
/// DS_REPL_INFO_PENDING_OPS
///
/// Pointer to a constant null-terminated Unicode string that identifies the object to retrieve replication data for. The meaning of
/// this parameter depends on the value of the InfoType parameter. The following are possible value codes.
///
/// DS_REPL_INFO_NEIGHBORS
/// pszObject identifies the naming context for which replication neighbors are requested.
/// DS_REPL_INFO_CURSORS_FOR_NC
/// pszObject identifies the naming context for which replication cursors are requested.
/// DS_REPL_INFO_METADATA_FOR_OBJ
/// pszObject identifies the object for which replication metadata is requested.
/// DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_KCC_DSA_LINK_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_PENDING_OPS
/// pszObject must be NULL.
/// Pointer to a GUID value that identifies a specific replication source. If this parameter is not NULL and the
/// InfoType parameter contains DS_REPL_INFO_NEIGHBORS, only neighbor data for the source corresponding to the nTDSDSA object
/// with the given objectGuid in the directory is returned. This parameter is ignored if NULL or if the InfoType
/// parameter is anything other than DS_REPL_INFO_NEIGHBORS.
///
/// Address of a structure pointer that receives the requested data. The value of the InfoType parameter determines the format of
/// this structure. For more information and list of possible InfoType values and the corresponding structure types, see DS_REPL_INFO_TYPE.
///
/// The caller must free this memory when it is no longer required by calling DsReplicaFreeInfo.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error otherwise. The following are possible error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicagetinfow NTDSAPI DWORD DsReplicaGetInfoW( HANDLE
// hDS, DS_REPL_INFO_TYPE InfoType, LPCWSTR pszObject, UUID *puuidForSourceDsaObjGuid, VOID **ppInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("ntdsapi.h", MSDNShortId = "b7ab22fe-ed92-4213-9b66-2dd5526286fa")]
public static extern Win32Error DsReplicaGetInfoW(SafeDsHandle hDS, DS_REPL_INFO_TYPE InfoType, string pszObject, in Guid puuidForSourceDsaObjGuid, out SafeDsReplicaInfo ppInfo);
///
/// The DsReplicaModify function modifies an existing replication source reference for a destination naming context.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a constant null-terminated string that specifies the distinguished name (DN) of the destination naming context (NC).
/// Pointer to the UUID of the source directory system agent (DSA). This parameter may be null if ModifyFields does not include
/// DS_REPMOD_UPDATE_ADDRESS and SourceDsaAddress is not NULL.
/// Reserved for future use. Any value other than NULL results in ERROR_NOT_SUPPORTED being returned.
/// Pointer to a constant null-terminated Unicode string that specifies the transport-specific address of the source DSA. This
/// parameter is ignored if pUuidSourceDsa is not NULL and ModifyFields does not include DS_REPMOD_UPDATE_ADDRESS.
/// Pointer to a SCHEDULE structure that contains the replication schedule data for the replication source. This parameter is
/// optional and can be NULL if not used. This parameter is required if ModifyFields contains the
/// DS_REPMOD_UPDATE_SCHEDULE flag.
/// This parameter is used to control replication behavior and can take the following values.
/// DS_REPL_NBR_SYNC_ON_STARTUP
///
/// Replication of this naming context from this source is attempted when the destination server is booted. This normally only
/// applies to intra-site neighbors.
///
/// DS_REPL_NBR_DO_SCHEDULED_SYNCS
///
/// Perform replication on a schedule. This flag is normally set unless the schedule for this naming context and source is "never",
/// that is, the empty schedule.
///
/// DS_REPL_NBR_TWO_WAY_SYNC
///
/// If set, indicates that when inbound replication is complete, the destination server must tell the source server to synchronize in
/// the reverse direction. This feature is used in dial-up scenarios where only one of the two servers can initiate a dial-up
/// connection. For example, this option would be used in a corporate headquarters and branch office, where the branch office
/// connects to the corporate headquarters over the Internet by means of a dial-up ISP connection.
///
/// DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS
///
/// This neighbor is set to disable notification-based synchronization. Within a site, domain controllers synchronize with each other
/// based on notifications when changes occur. This setting prevents this neighbor from performing a synchronization triggered by a
/// notification. The neighbor will still do synchronization based on its schedule or in response to manually requested synchronization.
///
/// DS_REPL_NBR_DISABLE_SCHEDULED_SYNC
///
/// This neighbor is set to not perform synchronization based on its schedule. The only way this neighbor will perform
/// synchronization is in response to change notifications or to manually requested synchronization.
///
/// DS_REPL_NBR_COMPRESS_CHANGES
///
/// Changes received from this source are to be compressed. This is normally set if, and only if, the source server is in a different site.
///
/// DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS
///
/// No change notifications should be received from this source. This is normally set if, and only if, the source server is in a
/// different site.
///
///
/// Specifies what fields should be modified. At least one field must be specified in ModifyFields. This parameter can be a
/// combination of the following values.
///
/// DS_REPMOD_UPDATE_ADDRESS
/// Updates the address associated with the referenced server.
/// DS_REPMOD_UPDATE_FLAGS
/// Updates the flags associated with the replica.
/// DS_REPMOD_UPDATE_RESULT
/// Not used. Specifying updates of result values is not currently supported. Result values default to 0.
/// DS_REPMOD_UPDATE_SCHEDULE
/// Updates the periodic replication schedule associated with the replica.
/// DS_REPMOD_UPDATE_TRANSPORT
/// Updates the transport associated with the replica.
/// Passes additional data used to process the request. This parameter can be a combination of the following values.
/// DS_REPMOD_ASYNCHRONOUS_OPERATION
/// Performs this operation asynchronously.
/// DS_REPMOD_WRITEABLE
/// Indicates that the replica being modified can be written to.
///
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value can be one of the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicamodifya NTDSAPI DWORD DsReplicaModifyA( HANDLE
// hDS, LPCSTR NameContext, const UUID *pUuidSourceDsa, LPCSTR TransportDn, LPCSTR SourceDsaAddress, const PSCHEDULE pSchedule, DWORD
// ReplicaFlags, DWORD ModifyFields, DWORD Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "aad20527-1211-41bc-b0e9-02e4ab28ae2e")]
public static extern Win32Error DsReplicaModify(SafeDsHandle hDS, string NameContext, in Guid pUuidSourceDsa, [Optional] string TransportDn, [Optional] string SourceDsaAddress,
[Optional] SCHEDULE pSchedule, DsReplNeighborFlags ReplicaFlags, DsReplModFieldFlags ModifyFields, DsReplModOptions Options);
///
/// The DsReplicaModify function modifies an existing replication source reference for a destination naming context.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a constant null-terminated string that specifies the distinguished name (DN) of the destination naming context (NC).
/// Pointer to the UUID of the source directory system agent (DSA). This parameter may be null if ModifyFields does not include
/// DS_REPMOD_UPDATE_ADDRESS and SourceDsaAddress is not NULL.
/// Reserved for future use. Any value other than NULL results in ERROR_NOT_SUPPORTED being returned.
/// Pointer to a constant null-terminated Unicode string that specifies the transport-specific address of the source DSA. This
/// parameter is ignored if pUuidSourceDsa is not NULL and ModifyFields does not include DS_REPMOD_UPDATE_ADDRESS.
/// Pointer to a SCHEDULE structure that contains the replication schedule data for the replication source. This parameter is
/// optional and can be NULL if not used. This parameter is required if ModifyFields contains the
/// DS_REPMOD_UPDATE_SCHEDULE flag.
/// This parameter is used to control replication behavior and can take the following values.
/// DS_REPL_NBR_SYNC_ON_STARTUP
///
/// Replication of this naming context from this source is attempted when the destination server is booted. This normally only
/// applies to intra-site neighbors.
///
/// DS_REPL_NBR_DO_SCHEDULED_SYNCS
///
/// Perform replication on a schedule. This flag is normally set unless the schedule for this naming context and source is "never",
/// that is, the empty schedule.
///
/// DS_REPL_NBR_TWO_WAY_SYNC
///
/// If set, indicates that when inbound replication is complete, the destination server must tell the source server to synchronize in
/// the reverse direction. This feature is used in dial-up scenarios where only one of the two servers can initiate a dial-up
/// connection. For example, this option would be used in a corporate headquarters and branch office, where the branch office
/// connects to the corporate headquarters over the Internet by means of a dial-up ISP connection.
///
/// DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS
///
/// This neighbor is set to disable notification-based synchronization. Within a site, domain controllers synchronize with each other
/// based on notifications when changes occur. This setting prevents this neighbor from performing a synchronization triggered by a
/// notification. The neighbor will still do synchronization based on its schedule or in response to manually requested synchronization.
///
/// DS_REPL_NBR_DISABLE_SCHEDULED_SYNC
///
/// This neighbor is set to not perform synchronization based on its schedule. The only way this neighbor will perform
/// synchronization is in response to change notifications or to manually requested synchronization.
///
/// DS_REPL_NBR_COMPRESS_CHANGES
///
/// Changes received from this source are to be compressed. This is normally set if, and only if, the source server is in a different site.
///
/// DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS
///
/// No change notifications should be received from this source. This is normally set if, and only if, the source server is in a
/// different site.
///
///
/// Specifies what fields should be modified. At least one field must be specified in ModifyFields. This parameter can be a
/// combination of the following values.
///
/// DS_REPMOD_UPDATE_ADDRESS
/// Updates the address associated with the referenced server.
/// DS_REPMOD_UPDATE_FLAGS
/// Updates the flags associated with the replica.
/// DS_REPMOD_UPDATE_RESULT
/// Not used. Specifying updates of result values is not currently supported. Result values default to 0.
/// DS_REPMOD_UPDATE_SCHEDULE
/// Updates the periodic replication schedule associated with the replica.
/// DS_REPMOD_UPDATE_TRANSPORT
/// Updates the transport associated with the replica.
/// Passes additional data used to process the request. This parameter can be a combination of the following values.
/// DS_REPMOD_ASYNCHRONOUS_OPERATION
/// Performs this operation asynchronously.
/// DS_REPMOD_WRITEABLE
/// Indicates that the replica being modified can be written to.
///
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value can be one of the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicamodifya NTDSAPI DWORD DsReplicaModifyA( HANDLE
// hDS, LPCSTR NameContext, const UUID *pUuidSourceDsa, LPCSTR TransportDn, LPCSTR SourceDsaAddress, const PSCHEDULE pSchedule, DWORD
// ReplicaFlags, DWORD ModifyFields, DWORD Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "aad20527-1211-41bc-b0e9-02e4ab28ae2e")]
public static extern Win32Error DsReplicaModify(SafeDsHandle hDS, string NameContext, [Optional] IntPtr pUuidSourceDsa, [Optional] string TransportDn, [Optional] string SourceDsaAddress,
[Optional] SCHEDULE pSchedule, DsReplNeighborFlags ReplicaFlags, DsReplModFieldFlags ModifyFields, DsReplModOptions Options);
///
/// The DsReplicaSync function synchronizes a destination naming context (NC) with one of its sources.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a constant null-terminated string that specifies the distinguished name of the destination NC.
/// Pointer to the UUID of a source that replicates to the destination NC.
/// Passes additional data used to process the request. This parameter can be a combination of the following values.
/// DS_REPSYNC_ADD_REFERENCE
///
/// Causes the source directory system agent (DSA) to verify that the local DSA is present in the source replicates-to list. If not,
/// the local DSA is added. This ensures that the source sends change notifications.
///
/// DS_REPSYNC_ALL_SOURCES
/// This value is not supported.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista and Windows Server 2003: Synchronizes from all sources.
///
/// DS_REPSYNC_ASYNCHRONOUS_OPERATION
/// Performs this operation asynchronously.
///
/// Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista and Windows Server 2003: Required when using DS_REPSYNC_ALL_SOURCES.
///
/// DS_REPSYNC_FORCE
/// Synchronizes even if the link is currently disabled.
/// DS_REPSYNC_FULL
/// Synchronizes starting from the first Update Sequence Number (USN).
/// DS_REPSYNC_INTERSITE_MESSAGING
/// Synchronizes using an ISM.
/// DS_REPSYNC_NO_DISCARD
/// Does not discard this synchronization request, even if a similar synchronization is pending.
/// DS_REPSYNC_PERIODIC
/// Indicates this operation is a periodic synchronization request as scheduled by the administrator.
/// DS_REPSYNC_URGENT
/// Indicates this operation is a notification of an update marked urgent.
/// DS_REPSYNC_WRITEABLE
/// Replica is writable. Otherwise, it is read-only.
///
/// If the function performs its operation successfully, the return value is ERROR_SUCCESS.
/// If the function fails, the return value is one of the standard Win32 API errors.
///
///
///
/// The server that DsReplicaSync executes on is called the destination. The destination naming context is brought up-to-date
/// with respect to a source system, identified by the UUID of the source system NTDS Settings object. The destination system must
/// already be configured so that the source system is one of the systems from which it receives replication data.
///
///
/// Note Forcing manual synchronization can prevent the directory service from properly prioritizing replication operations.
/// For example, synchronizing a new user may preempt an urgent synchronization performed to provide access to a recently locked out
/// user or to add a new trust password. If you call this API often, you can flood the network with requests, which can interfere
/// with other replication operations. For this reason, it is strongly recommended that this function be used only for single-use
/// scenarios rather than incorporating it into an application that would use it on a regular basis.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicasynca NTDSAPI DWORD DsReplicaSyncA( HANDLE hDS,
// LPCSTR NameContext, const UUID *pUuidDsaSrc, ULONG Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "20c7f96d-f298-4321-a6f5-910c25e418db")]
public static extern Win32Error DsReplicaSync(SafeDsHandle hDS, string NameContext, in Guid pUuidDsaSrc, DsReplSyncOptions Options);
///
/// The DsReplicaSyncAll function synchronizes a server with all other servers, using transitive replication, as necessary. By
/// default, DsReplicaSyncAll synchronizes the server with all other servers in its site; however, you can also use it to
/// synchronize across site boundaries.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a null-terminated string that specifies the distinguished name of the naming context to synchronize. The
/// pszNameContext parameter is optional; if its value is NULL, the configuration naming context is replicated.
/// Passes additional data used to process the request. This parameter can be a combination of the following values.
/// DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE
///
/// Generates a fatal error if any server cannot be contacted or if any server is unreachable due to a disconnected or broken topology.
///
/// DS_REPSYNCALL_CROSS_SITE_BOUNDARIES
///
/// Synchronizes across site boundaries. By default, DsReplicaSyncAll attempts to synchronize only with DCs in the same site
/// as the home system. Set this flag to attempt to synchronize with all DCs in the enterprise forest. However, the DCs can be
/// synchronized only if connected by a synchronous (RPC) transport.
///
/// DS_REPSYNCALL_DO_NOT_SYNC
/// Disables all synchronization. The topology is still analyzed, and unavailable or unreachable servers are still identified.
/// DS_REPSYNCALL_ID_SERVERS_BY_DN
/// In the event of a non-fatal error, returns server distinguished names (DN) instead of their GUID DNS names.
/// DS_REPSYNCALL_NO_OPTIONS
/// This option has no effect.
/// DS_REPSYNCALL_PUSH_CHANGES_OUTWARD
///
/// Pushes changes from the home server out to all partners using transitive replication. This reverses the direction of replication,
/// and the order of execution of the replication sets from the usual "pulling" mode of execution.
///
/// DS_REPSYNCALL_SKIP_INITIAL_CHECK
///
/// Assumes that all servers are responding. This speeds operation of the DsReplicaSyncAll function, but if some servers are
/// not responding, some transitive replications may be blocked.
///
/// DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY
/// Disables transitive replication. Synchronization is performed only with adjacent servers.
/// Pointer to an application-defined SyncUpdateProc function called by the DsReplicaSyncAll function when it encounters an
/// error, initiates synchronization of two servers, completes synchronization of two servers, or finishes synchronization of all the
/// servers in the site.
/// Pointer to application-defined data passed as the first argument of the SyncUpdateProc callback function pointed to by the
/// pFnCallBack parameter.
/// A NULL-terminated array of pointers to DS_REPSYNCALL_ERRINFO structures that contain errors that occurred during synchronization.
/// The memory used to hold both the array of pointers and the MsCS\mscs\clusctl_resource_type_get_private_property_fmts.xml data is
/// allocated as a single block of memory and should be freed when no longer required by a single call to LocalFree with the
/// pointer value returned in pErrors used as the argument.
///
/// If the function succeeds, the return value is ERROR_SUCCESS.
/// If the function fails, the return value is as follows.
///
///
///
/// The DsReplicaSyncAll function attempts to bind to all servers before generating a topology to synchronize from. If a
/// server cannot be contacted, the function excludes that server from the topology and attempts to work around it. Setting the
/// DS_REPSYNCALL_SKIP_INITIAL_CHECK flag in ulFlags bypasses the initial binding.
///
///
/// If a server cannot be contacted, the DsReplicaSyncAll function attempts to route around it and replicate from as many
/// servers as possible, unless DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE is set in ulFlags.
///
///
/// The DsReplicaSyncAll function can use the callback function pointed to by pFnCallBack to keep an end user informed about
/// the current status of the replication. Execution of the DsReplicaSyncAll function pauses when it calls the function
/// pointed to by pFnCallBack. If the return value from the callback function is TRUE, replication continues; otherwise, the
/// DsReplicaSyncAll function terminates replication.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicasyncalla NTDSAPI DWORD DsReplicaSyncAllA( HANDLE
// hDS, LPCSTR pszNameContext, ULONG ulFlags, BOOL(* )(LPVOID,PDS_REPSYNCALL_UPDATEA) pFnCallBack, LPVOID pCallbackData,
// PDS_REPSYNCALL_ERRINFOA **pErrors );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "2608adde-4f18-4048-a96f-d736ff09cd4b")]
public static extern Win32Error DsReplicaSyncAll(SafeDsHandle hDS, [Optional] string pszNameContext, DsReplSyncAllFlags ulFlags, SyncUpdateProc pFnCallBack, IntPtr pCallbackData, out SafeDS_REPSYNCALL_ERRINFOArray pErrors);
///
/// The DsReplicaUpdateRefs function adds or removes a replication reference for a destination from a source naming context.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Pointer to a constant null-terminated string that specifies the distinguished name of the source naming context.
/// Pointer to a constant null-terminated string that specifies the transport-specific address of the destination directory system agent.
/// Pointer to a UUID value that contains the destination directory system agent.
///
/// Contains a set of flags that provide additional data used to process the request. This can be zero or a combination of one or
/// more of the following values.
///
/// DS_REPUPD_ADD_REFERENCE
/// A reference to the destination is added to the source server.
/// DS_REPUPD_ASYNCHRONOUS_OPERATION
/// The operation is performed asynchronously.
/// DS_REPUPD_DELETE_REFERENCE
/// A reference to the destination is removed from the source server.
/// DS_REPUPD_WRITEABLE
/// The reference to the replica added or removed is writable. Otherwise, it is read-only.
///
/// If the function succeeds, ERROR_SUCCESS is returned.
/// If the function fails, the return value can be one of the following.
///
///
/// If both DS_REPUPD_ADD_REFERENCE and DS_REPUPD_DELETE_REFERENCE are set in the Options parameter, a reference to the
/// destination is added if one does not already exist on the server. If a reference to the destination already exists, the reference
/// is updated.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicaupdaterefsa NTDSAPI DWORD DsReplicaUpdateRefsA(
// HANDLE hDS, LPCSTR NameContext, LPCSTR DsaDest, const UUID *pUuidDsaDest, ULONG Options );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "158c7e73-0e6c-4b71-a87f-2f60f3db91cb")]
public static extern Win32Error DsReplicaUpdateRefs(SafeDsHandle hDS, string NameContext, string DsaDest, in Guid pUuidDsaDest, DsReplUpdateOptions Options);
///
/// The DsReplicaVerifyObjects function verifies all objects for a naming context with a source.
///
/// Contains a directory service handle obtained from either the DSBind, DSBindWithCred, or DsBindWithSpn function.
/// Pointer to a null-terminated string that contains the distinguished name of the naming context.
/// Pointer to a UUID value that contains the objectGuid of the directory system agent object.
/// Contains a set of flags that modify the behavior of the function. This can be zero or the following value.
/// DS_EXIST_ADVISORY_MODE
/// Do not delete objects in response to this function.
///
/// Returns ERROR_SUCCESS if successful or a Win32 error otherwise. Possible error values include the following.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicaverifyobjectsa NTDSAPI DWORD
// DsReplicaVerifyObjectsA( HANDLE hDS, LPCSTR NameContext, const UUID *pUuidDsaSrc, ULONG ulOptions );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "d0e139dc-6aaf-47e1-a76f-4e84f17aa7c6")]
public static extern Win32Error DsReplicaVerifyObjects(SafeDsHandle hDS, string NameContext, in Guid pUuidDsaSrc, DsReplVerifyOptions ulOptions);
///
///
/// The DsServerRegisterSpn function composes two SPNs for a host-based service. The names are based on the DNS and NetBIOS
/// names of the local computer. The function modifies the servicePrincipalName attribute of either a specified account or of
/// the account associated with the calling thread. The function either registers or unregisters the SPNs.
///
///
/// A host-based service is a service instance that provides services identified with its host computer, as distinguished from a
/// replicable service where clients have no preference which host computer a service instance runs on.
///
///
/// Specifies what operation DsServerRegisterSpn should perform. This parameter can have one of the following values.
/// DS_SPN_ADD_SPN_OP
/// Adds the SPNs to the user or computer account.
/// DS_SPN_DELETE_SPN_OP
/// Deletes the specified SPNs from the account.
/// DS_SPN_REPLACE_SPN_OP
/// Removes all SPNs currently registered on the user or computer account and replaces them with the new SPNs.
/// Pointer to a constant null-terminated string specifying the class of the service. This parameter may be any string unique to that
/// service; either the protocol name (for example, ldap) or the string form of a GUID will work.
/// Pointer to a constant null-terminated string specifying the distinguished name of a user or computer account object to write the
/// SPNs to. If this parameter is NULL, DsServerRegisterSpn writes to the account object of the primary or impersonated
/// user associated with the calling thread. If the thread is running in the security context of the LocalSystem account, the
/// function writes to the account object of the local computer.
///
/// If the function successfully registers one or more SPNs, it returns ERROR_SUCCESS. Modification is performed permissively,
/// so that adding a value that already exists does not return an error.
///
///
/// The two SPNs composed by the DsServerRegisterSpn function have the following format:
///
/// In one SPN, the host computer is the fully qualified DNS name of the local computer. In the other SPN, the host component is the
/// NetBIOS name of the local computer.
///
///
/// In most cases, the DsServerRegisterSpn caller must have domain administrator privileges to successfully modify the
/// servicePrincipalName attribute of an account object. The exception to this rule is if the calling thread is running under
/// the LocalSystem account, DsServerRegisterSpn is allowed if the UserObjectDN parameter is either NULL or specifies
/// the distinguished name of the local computer account.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsserverregisterspna NTDSAPI DWORD DsServerRegisterSpnA(
// DS_SPN_WRITE_OP Operation, LPCSTR ServiceClass, LPCSTR UserObjectDN );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "d95dfa55-f978-4d8d-a63d-cd1339769c79")]
public static extern Win32Error DsServerRegisterSpn(DS_SPN_WRITE_OP Operation, string ServiceClass, [Optional] string UserObjectDN);
///
/// The DsUnBind function finds an RPC session with a domain controller and unbinds a handle to the directory service (DS).
///
/// Pointer to a bind handle to the directory service. This handle is provided by a call to DsBind, DsBindWithCred, or DsBindWithSpn.
/// NO_ERROR
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsunbinda NTDSAPI DWORD DsUnBindA( HANDLE *phDS );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "7106d67f-d421-4a7c-b775-440e5944f25e")]
public static extern Win32Error DsUnBind(ref IntPtr phDS);
///
/// The DsWriteAccountSpn function writes an array of service principal names (SPNs) to the servicePrincipalName
/// attribute of a specified user or computer account object in Active Directory Domain Services. The function can either register or
/// unregister the SPNs.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Contains one of the DS_SPN_WRITE_OP values that specifies the operation that DsWriteAccountSpn will perform.
/// Pointer to a constant null-terminated string that specifies the distinguished name of a user or computer object in Active
/// Directory Domain Services. The caller must have write access to the servicePrincipalName property of this object.
/// Specifies the number of SPNs in rpszSpn. If this value is zero, and Operation contains DS_SPN_REPLACE_SPN_OP, the function
/// removes all values from the servicePrincipalName attribute of the specified account.
/// Pointer to an array of constant null-terminated strings that specify the SPNs to be added to or removed from the account
/// identified by the pszAccount parameter. The DsGetSpn function is used to compose SPNs for a service.
///
/// Returns ERROR_SUCCESS if successful or a Win32, RPC or directory service error if unsuccessful.
///
///
///
/// The DsWriteAccountSpn function registers the SPNs for one or more instances of a service. SPNs are used by clients, in
/// conjunction with a trusted authentication service, to authenticate the service. To protect against security attacks where an
/// application or service fraudulently registers an SPN that identifies some other service, the default DACL on user and computer
/// accounts allows only domain administrators to register SPNs in most cases.
///
///
/// One exception to this rule is that a service running under the LocalSystem account can call DsWriteAccountSpn to register
/// a simple SPN of the form "ServiceClass/Host:Port" if the host specified in the SPN is the DNS or NetBIOS name of the computer on
/// which the service is running.
///
///
/// Another exception is that the default DACL on computer accounts allows callers to register SPNs on themselves, subject to certain
/// constraints. For example, a computer account can have SPNs relative to its computername, of the form "host/<computername>".
/// Because the computername is contained in the SPN, the SPN is allowable.
///
///
/// None of the rules above apply if the DSA is configured to allow any SPN to be written. This reduces security, however, so it is
/// not recommended.
///
///
/// SPNs passed to DsWriteAccountSpn are actually added to the Service-Principal-Name attribute of the computer object
/// in pszAccount. This call is made using RPC to the domain controller where the account object is stored so it can securely enforce
/// policy on what SPNs are allowed on the account. Using LDAP to write directly to the SPN property is not allowed; all writes must
/// come through this RPC call. Reads using LDAP are allowed.
///
/// Permissions required to set SPNs
///
/// To write an arbitrary SPN on an account, the writer requires the "Write ServicePrincipalName" right, which is not granted by
/// default to the person who created the account. That person has the 'Write validated SPN" right(present only on machine accounts).
///
/// Below is a summary of rights per user on machine accounts:
///
///
/// User Type
/// Rights
///
/// -
/// Person creating the Account
/// Write validated SPN
///
/// -
/// Account Operators
/// Write SPN and Write Validated SPN
///
/// -
/// Authenticated Users
/// None
///
/// -
/// (self)
/// Write Validated SPN
///
///
///
/// On user accounts there is no "Validated SPN" property or "Write SPN" right. Rather, the "Write public information" property set
/// grants the ability to create arbitrary SPNs.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dswriteaccountspna NTDSAPI DWORD DsWriteAccountSpnA(
// HANDLE hDS, DS_SPN_WRITE_OP Operation, LPCSTR pszAccount, DWORD cSpn, LPCSTR *rpszSpn );
[DllImport(Lib.NTDSApi, SetLastError = false, CharSet = CharSet.Auto)]
[PInvokeData("ntdsapi.h", MSDNShortId = "2b555f6b-643d-4fa0-9aca-701e6b3313fa")]
public static extern Win32Error DsWriteAccountSpn(SafeDsHandle hDS, DS_SPN_WRITE_OP Operation, string pszAccount, uint cSpn, SpnArrayHandle rpszSpn);
///
/// The DsReplicaGetInfo2 function retrieves replication state data from the directory service. This function allows paging of
/// results in cases where there are more than 1000 entries to retrieve.
///
/// Contains a directory service handle obtained from either the DSBind or DSBindWithCred function.
/// Contains one of the DS_REPL_INFO_TYPE values that specifies the type of replication data to retrieve. This value also determines
/// which type of structure is returned in ppInfo.
///
/// Pointer to a constant null-terminated Unicode string that identifies the object to retrieve replication data for. The meaning of
/// this parameter depends on the value of the InfoType parameter. The following are possible value codes.
///
/// DS_REPL_INFO_NEIGHBORS
/// pszObject identifies the naming context for which replication neighbors are requested.
/// DS_REPL_INFO_CURSORS_FOR_NC
/// pszObject identifies the naming context for which replication cursors are requested.
/// DS_REPL_INFO_METADATA_FOR_OBJ
/// pszObject identifies the object for which replication metadata is requested.
/// DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_KCC_DSA_LINK_FAILURES
/// pszObject must be NULL.
/// DS_REPL_INFO_PENDING_OPS
/// pszObject must be NULL.
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// pszObject identifies the object for which attribute replication metadata is requested.
/// DS_REPL_INFO_CURSORS_2_FOR_NC
/// DS_REPL_INFO_CURSORS_3_FOR_NC
/// DS_REPL_INFO_METADATA_2_FOR_OBJ
/// pszObject identifies the object for which replication metadata is requested.
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
/// pszObject identifies the object for which attribute replication metadata is requested.
/// Pointer to a GUID value that identifies a specific replication source. If this parameter is not NULL and the
/// InfoType parameter contains DS_REPL_INFO_NEIGHBORS, only neighbor data for the source corresponding to the nTDSDSA object
/// with the given objectGuid in the directory is returned. This parameter is ignored if NULL or if the InfoType
/// parameter is anything other than DS_REPL_INFO_NEIGHBORS.
///
/// Pointer to a null-terminated Unicode string that contains the name of the specific attribute to retrieve replication data for.
///
/// This parameter is only used if the InfoType parameter contains one of the following values.
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
/// Pointer to a null-terminated Unicode string that contains the distinguished name value to match. If the requested attribute is a
/// distinguished name type value, this function return the attributes that contain the specified value.
/// Contains a set of flags that modify the behavior of the function. This parameter can be zero or the following value.
/// DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS
///
/// Causes the attribute metadata to account for metadata on the attribute's linked values. The resulting vector represents changes
/// for all attributes. This modified vector is useful for clients that expect all attributes and metadata to be included in the
/// attribute metadata vector.
///
/// Contains the index of the next entry to retrieve. This parameter must be set to zero the first time this function is called.
/// This parameter is only used if the InfoType parameter contains one of the following values.
/// DS_REPL_INFO_CURSORS_2_FOR_NC
/// DS_REPL_INFO_CURSORS_3_FOR_NC
/// DS_REPL_INFO_METADATA_FOR_ATTR_VALUE
/// DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE
///
/// This function will retrieve a maximum of 1000 entries on each call. If after calling this function, more entries are available,
/// the dwEnumerationContext member of the retrieved structure will contain the index of the next entry to retrieve. The
/// dwEnumerationContext member of the retrieved structure is then used as the dwEnumerationContext parameter in the next call
/// to this function. When all of the entries have been retrieved, the dwEnumerationContext member of the retrieved structure
/// will contain -1. If -1 is passed for this parameter, this function will return ERROR_NO_MORE_ITEMS.
///
///
/// Address of a structure pointer that receives the requested data. The value of the InfoType parameter determines the format of
/// this structure. For more information and a list of possible InfoType values and the corresponding structure types, see DS_REPL_INFO_TYPE.
///
/// The caller must free this memory when it is no longer required by calling DsReplicaFreeInfo.
///
/// Returns ERROR_SUCCESS if successful or a Win32 or RPC error otherwise. The following are possible error codes.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/nf-ntdsapi-dsreplicagetinfo2w NTDSAPI DWORD DsReplicaGetInfo2W(
// HANDLE hDS, DS_REPL_INFO_TYPE InfoType, LPCWSTR pszObject, UUID *puuidForSourceDsaObjGuid, LPCWSTR pszAttributeName, LPCWSTR
// pszValue, DWORD dwFlags, DWORD dwEnumerationContext, VOID **ppInfo );
[DllImport(Lib.NTDSApi, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
[PInvokeData("ntdsapi.h", MSDNShortId = "5735d91d-1b7d-4dc6-b6c6-61ba38ebe50d")]
private static unsafe extern Win32Error DsReplicaGetInfo2W(SafeDsHandle hDS, DS_REPL_INFO_TYPE InfoType, [Optional] string pszObject, Guid* puuidForSourceDsaObjGuid, [Optional] string pszAttributeName,
[Optional] string pszValue, DsReplInfoFlags dwFlags, uint dwEnumerationContext, out SafeDsReplicaInfo ppInfo);
/// Provides a handle to a domain controller info structure.
[StructLayout(LayoutKind.Sequential)]
public struct DCInfoHandle : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public DCInfoHandle(IntPtr preexistingHandle) => handle = preexistingHandle;
/// Gets a value indicating whether this instance is a null handle.
public bool IsNull => handle == IntPtr.Zero;
///
public IntPtr DangerousGetHandle() => handle;
/// Gets a list of stored structures from this handle.
/// The type of structure found in the list.
/// The count.
/// The list of structures.
public IEnumerable ToIEnum(uint count) where T : struct => handle.ToIEnum((int)count);
}
/// Indicates that the structure can be passed to DsGetDomainControllerInfo.
public interface IDsGetDCResult { }
///
/// The DS_DOMAIN_CONTROLLER_INFO_1 structure contains data about a domain controller. This structure is returned by the
/// DsGetDomainControllerInfo function.
///
///
///
/// The DsGetDomainControllerInfo function can return different versions of this structure. For more information and a list of the
/// currently supported versions, see the InfoLevel parameter of DsGetDomainControllerInfo.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-ds_domain_controller_info_1a typedef struct
// DS_DOMAIN_CONTROLLER_INFO_1A { #if ... CHAR *NetbiosName; #if ... CHAR *DnsHostName; #if ... CHAR *SiteName; #if ... CHAR
// *ComputerObjectName; #if ... CHAR *ServerObjectName; #else LPSTR NetbiosName; #endif #else LPSTR DnsHostName; #endif #else LPSTR
// SiteName; #endif #else LPSTR ComputerObjectName; #endif #else LPSTR ServerObjectName; #endif BOOL fIsPdc; BOOL fDsEnabled; } *PDS_DOMAIN_CONTROLLER_INFO_1A;
[PInvokeData("ntdsapi.h", MSDNShortId = "6cc829ac-2aa6-49ef-b1ab-9c249249e0d6")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_DOMAIN_CONTROLLER_INFO_1 : IDsGetDCResult
{
///
/// Pointer to a null-terminated string that specifies the NetBIOS name of the domain controller.
///
public StrPtrAuto NetbiosName;
///
/// Pointer to a null-terminated string that specifies the DNS host name of the domain controller.
///
public StrPtrAuto DnsHostName;
///
/// Pointer to a null-terminated string that specifies the site to which the domain controller belongs.
///
public StrPtrAuto SiteName;
///
/// Pointer to a null-terminated string that specifies the name of the computer object on the domain controller.
///
public StrPtrAuto ComputerObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the server object on the domain controller.
///
public StrPtrAuto ServerObjectName;
///
/// A Boolean value that indicates whether or not this domain controller is the primary domain controller. If this value is TRUE,
/// the domain controller is the primary domain controller; otherwise, the domain controller is not the primary domain controller.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsPdc;
///
/// A Boolean value that indicates whether or not the domain controller is enabled. If this value is TRUE, the domain controller
/// is enabled; otherwise, it is not enabled.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fDsEnabled;
}
///
/// The DS_DOMAIN_CONTROLLER_INFO_2 structure contains data about a domain controller. This structure is returned by the
/// DsGetDomainControllerInfo function.
///
///
///
/// The DsGetDomainControllerInfo function can return different versions of this structure. For more information and a list of the
/// currently supported versions, see the InfoLevel parameter of DsGetDomainControllerInfo.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-ds_domain_controller_info_2a typedef struct
// DS_DOMAIN_CONTROLLER_INFO_2A { #if ... CHAR *NetbiosName; #if ... CHAR *DnsHostName; #if ... CHAR *SiteName; #if ... CHAR
// *SiteObjectName; #if ... CHAR *ComputerObjectName; #if ... CHAR *ServerObjectName; #if ... CHAR *NtdsDsaObjectName; #else LPSTR
// NetbiosName; #endif #else LPSTR DnsHostName; #endif #else LPSTR SiteName; #endif #else LPSTR SiteObjectName; #endif #else LPSTR
// ComputerObjectName; #endif #else LPSTR ServerObjectName; #endif #else LPSTR NtdsDsaObjectName; #endif BOOL fIsPdc; BOOL
// fDsEnabled; BOOL fIsGc; GUID SiteObjectGuid; GUID ComputerObjectGuid; GUID ServerObjectGuid; GUID NtdsDsaObjectGuid; } *PDS_DOMAIN_CONTROLLER_INFO_2A;
[PInvokeData("ntdsapi.h", MSDNShortId = "9d45b732-363d-4b20-ae5c-e9e76264bf1f")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_DOMAIN_CONTROLLER_INFO_2 : IDsGetDCResult
{
///
/// Pointer to a null-terminated string that specifies the NetBIOS name of the domain controller.
///
public StrPtrAuto NetbiosName;
///
/// Pointer to a null-terminated string that specifies the DNS host name of the domain controller.
///
public StrPtrAuto DnsHostName;
///
/// Pointer to a null-terminated string that specifies the site to which the domain controller belongs.
///
public StrPtrAuto SiteName;
///
/// Pointer to a null-terminated string that specifies the name of the site object on the domain controller.
///
public StrPtrAuto SiteObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the computer object on the domain controller.
///
public StrPtrAuto ComputerObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the server object on the domain controller.
///
public StrPtrAuto ServerObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the NTDS DSA object on the domain controller.
///
public StrPtrAuto NtdsDsaObjectName;
///
/// A Boolean value that indicates whether or not this domain controller is the primary domain controller. If this value is TRUE,
/// the domain controller is the primary domain controller; otherwise, the domain controller is not the primary domain controller.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsPdc;
///
/// A Boolean value that indicates whether or not the domain controller is enabled. If this value is TRUE, the domain controller
/// is enabled; otherwise, it is not enabled.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fDsEnabled;
///
/// A Boolean value that indicates whether or not the domain controller is global catalog server. If this value is TRUE, the
/// domain controller is a global catalog server; otherwise, it is not a global catalog server.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsGc;
///
/// Contains the GUID for the site object on the domain controller.
///
public Guid SiteObjectGuid;
///
/// Contains the GUID for the computer object on the domain controller.
///
public Guid ComputerObjectGuid;
///
/// Contains the GUID for the server object on the domain controller.
///
public Guid ServerObjectGuid;
///
/// Contains the GUID for the NTDS DSA object on the domain controller.
///
public Guid NtdsDsaObjectGuid;
}
///
/// The DS_DOMAIN_CONTROLLER_INFO_3 structure contains data about a domain controller. This structure is returned by the
/// DsGetDomainControllerInfo function.
///
///
///
/// The DsGetDomainControllerInfo function can return different versions of this structure. For more information and a list of the
/// currently supported versions, see the InfoLevel parameter of DsGetDomainControllerInfo.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-ds_domain_controller_info_3a typedef struct
// DS_DOMAIN_CONTROLLER_INFO_3A { #if ... CHAR *NetbiosName; #if ... CHAR *DnsHostName; #if ... CHAR *SiteName; #if ... CHAR
// *SiteObjectName; #if ... CHAR *ComputerObjectName; #if ... CHAR *ServerObjectName; #if ... CHAR *NtdsDsaObjectName; #else LPSTR
// NetbiosName; #endif #else LPSTR DnsHostName; #endif #else LPSTR SiteName; #endif #else LPSTR SiteObjectName; #endif #else LPSTR
// ComputerObjectName; #endif #else LPSTR ServerObjectName; #endif #else LPSTR NtdsDsaObjectName; #endif BOOL fIsPdc; BOOL
// fDsEnabled; BOOL fIsGc; BOOL fIsRodc; GUID SiteObjectGuid; GUID ComputerObjectGuid; GUID ServerObjectGuid; GUID NtdsDsaObjectGuid;
// } *PDS_DOMAIN_CONTROLLER_INFO_3A;
[PInvokeData("ntdsapi.h", MSDNShortId = "510f458e-4c08-41c7-b290-1372ac9c8beb")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_DOMAIN_CONTROLLER_INFO_3 : IDsGetDCResult
{
///
/// Pointer to a null-terminated string that specifies the NetBIOS name of the domain controller.
///
public StrPtrAuto NetbiosName;
///
/// Pointer to a null-terminated string that specifies the DNS host name of the domain controller.
///
public StrPtrAuto DnsHostName;
///
/// Pointer to a null-terminated string that specifies the site to which the domain controller belongs.
///
public StrPtrAuto SiteName;
///
/// Pointer to a null-terminated string that specifies the name of the site object on the domain controller.
///
public StrPtrAuto SiteObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the computer object on the domain controller.
///
public StrPtrAuto ComputerObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the server object on the domain controller.
///
public StrPtrAuto ServerObjectName;
///
/// Pointer to a null-terminated string that specifies the name of the NTDS DSA object on the domain controller.
///
public StrPtrAuto NtdsDsaObjectName;
///
/// A Boolean value that indicates whether or not this domain controller is the primary domain controller. If this value is TRUE,
/// the domain controller is the primary domain controller; otherwise, the domain controller is not the primary domain controller.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsPdc;
///
/// A Boolean value that indicates whether or not the domain controller is enabled. If this value is TRUE, the domain controller
/// is enabled; otherwise, it is not enabled.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fDsEnabled;
///
/// A Boolean value that indicates whether or not the domain controller is global catalog server. If this value is TRUE, the
/// domain controller is a global catalog server; otherwise, it is not a global catalog server.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsGc;
///
/// A Boolean value that indicates if the domain controller is a read-only domain controller. If this value is TRUE, the domain
/// controller is a read-only domain controller; otherwise, it is not a read-only domain controller.
///
[MarshalAs(UnmanagedType.Bool)]
public bool fIsRodc;
///
/// Contains the GUID for the site object on the domain controller.
///
public Guid SiteObjectGuid;
///
/// Contains the GUID for the computer object on the domain controller.
///
public Guid ComputerObjectGuid;
///
/// Contains the GUID for the server object on the domain controller.
///
public Guid ServerObjectGuid;
///
/// Contains the GUID for the NTDS DSA object on the domain controller.
///
public Guid NtdsDsaObjectGuid;
}
///
/// Used with the DsCrackNames function to contain the names converted by the function.
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676246")]
public struct DS_NAME_RESULT
{
/// Contains the number of elements in the rItems array.
public uint cItems;
///
/// Contains an array of DS_NAME_RESULT_ITEM structure pointers. Each element of this array represents a single converted name.
///
public IntPtr rItems; // PDS_NAME_RESULT_ITEM
///
/// Enumeration of DS_NAME_RESULT_ITEM structures. Each element of this array represents a single converted name.
///
/// The items.
public DS_NAME_RESULT_ITEM[] Items => rItems.ToArray((int)cItems);
}
///
/// Contains a name converted by the DsCrackNames function, along with associated error and domain data.
///
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[PInvokeData("NTDSApi.h", MSDNShortId = "ms676246")]
public struct DS_NAME_RESULT_ITEM
{
///
/// Contains one of the DS_NAME_ERROR values that indicates the status of this name conversion.
///
public DS_NAME_ERROR status;
///
/// A string that specifies the DNS domain in which the object resides. This member will contain valid data if status contains
/// DS_NAME_NO_ERROR or DS_NAME_ERROR_DOMAIN_ONLY.
///
public string pDomain;
/// A string that specifies the newly formatted object name.
public string pName;
///
/// Returns a that represents this instance.
///
/// A that represents this instance.
public override string ToString() => status == DS_NAME_ERROR.DS_NAME_NO_ERROR ? pName : $"{status}";
}
///
/// The DS_REPL_ATTR_META_DATA structure is used with the DsReplicaGetInfo and DsReplicaGetInfo2 functions to contain
/// replication state data for an object attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_meta_data typedef struct
// _DS_REPL_ATTR_META_DATA { LPWSTR pszAttributeName; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; } DS_REPL_ATTR_META_DATA;
[PInvokeData("ntdsapi.h", MSDNShortId = "27ccc1c9-03d7-4d13-b9ec-65d6b8bdfd37")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_META_DATA
{
///
/// Pointer to a null-terminated Unicode string that contains the LDAP display name of the attribute corresponding to this metadata.
///
public string pszAttributeName;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains the time at which the last originating change was made to this attribute. Replication of the change does not affect
/// this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identification of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server (the server from which the DsReplicaGetInfo function retrieved the metadata) at
/// which the last change to this attribute was applied. This value typically is different on all servers.
///
public long usnLocalChange;
}
///
/// The DS_REPL_ATTR_META_DATA_2 structure is used with the DsReplicaGetInfo and DsReplicaGetInfo2 functions to contain
/// replication state data for an object attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_meta_data_2 typedef struct
// _DS_REPL_ATTR_META_DATA_2 { LPWSTR pszAttributeName; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; LPWSTR pszLastOriginatingDsaDN; } DS_REPL_ATTR_META_DATA_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "392457b7-df69-44d0-82b2-8381d5877354")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_META_DATA_2
{
///
/// Pointer to a null-terminated Unicode string that contains the LDAP display name of the attribute that corresponds to this metadata.
///
public string pszAttributeName;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains the time at which the last originating change was made to this attribute. Replication of the change does not affect
/// this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identification of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server (the server from which the DsReplicaGetInfo function retrieved the metadata) at
/// which the last change to this attribute was applied. This value typically is different on all servers.
///
public long usnLocalChange;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the directory system agent server that
/// originated the last replication.
///
public string pszLastOriginatingDsaDN;
}
///
/// The DS_REPL_ATTR_META_DATA_BLOB structure is used to contain replication state data for an object attribute. This
/// structure is similar to the DS_REPL_ATTR_META_DATA_2 structure, but is obtained from the Lightweight Directory Access Protocol
/// API functions when obtaining binary data for the msDS-ReplAttributeMetaData attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_meta_data_blob typedef struct
// _DS_REPL_ATTR_META_DATA_BLOB { DWORD oszAttributeName; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; DWORD oszLastOriginatingDsaDN; } DS_REPL_ATTR_META_DATA_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "eee12de1-287a-4e76-9a9c-37e6b967971f")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_META_DATA_BLOB
{
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the LDAP
/// display name of the attribute corresponding to this metadata. A value of zero indicates an empty or NULL string.
///
public uint oszAttributeName;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains the time at which the last originating change was made to this attribute. Replication of the change does not affect
/// this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identification of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server (the server from which the DsReplicaGetInfo function retrieved the metadata) at
/// which the last change to this attribute was applied. This value typically is different on all servers.
///
public long usnLocalChange;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the directory system agent server that originated the last replication. A value of zero indicates an
/// empty or NULL string.
///
public uint oszLastOriginatingDsaDN;
}
///
/// The DS_REPL_ATTR_VALUE_META_DATA structure is used with the DsReplicaGetInfo2 function to provide metadata for a
/// collection of attribute values.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_value_meta_data typedef struct
// _DS_REPL_ATTR_VALUE_META_DATA { DWORD cNumEntries; DWORD dwEnumerationContext; #if ... DS_REPL_VALUE_META_DATA rgMetaData[]; #else
// DS_REPL_VALUE_META_DATA rgMetaData[1]; #endif } DS_REPL_ATTR_VALUE_META_DATA;
[PInvokeData("ntdsapi.h", MSDNShortId = "b13cdd31-d154-4539-81d6-d7a449e2b3d5")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_VALUE_META_DATA
{
///
/// Contains the number of elements in the rgMetaData array.
///
public uint cNumEntries;
///
/// Contains the zero-based index of the next entry to retrieve if more entries are available. This value is passed for the
/// dwEnumerationContext parameter in the next call to DsReplicaGetInfo2 to retrieve the next block of entries. If no more
/// entries are available, this member contains -1.
///
public uint dwEnumerationContext;
///
/// Contains an array of DS_REPL_VALUE_META_DATA structures that contain the individual attribute replication values. The
/// cNumEntries member contains the number of elements in this array.
///
public IntPtr _rgMetaData;
///
/// Gets an array of DS_REPL_VALUE_META_DATA structures that contain the individual attribute replication values.
///
/// The rg meta data.
public DS_REPL_VALUE_META_DATA[] rgMetaData => _rgMetaData.ToArray((int)cNumEntries);
}
///
/// The DS_REPL_ATTR_VALUE_META_DATA_2 structure is used with the DsReplicaGetInfo2 function to provide metadata for a
/// collection of attribute values.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_value_meta_data_2 typedef struct
// _DS_REPL_ATTR_VALUE_META_DATA_2 { DWORD cNumEntries; DWORD dwEnumerationContext; #if ... DS_REPL_VALUE_META_DATA_2 rgMetaData[];
// #else DS_REPL_VALUE_META_DATA_2 rgMetaData[1]; #endif } DS_REPL_ATTR_VALUE_META_DATA_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "2022362a-e2f7-4cfd-a512-cfe29e5d439d")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_VALUE_META_DATA_2
{
///
/// Contains the number of elements in the rgMetaData array.
///
public uint cNumEntries;
///
/// Contains the zero-based index of the next entry to retrieve if more entries are available. This value is passed for the
/// dwEnumerationContext parameter in the next call to DsReplicaGetInfo2 to retrieve the next block of entries. If no more
/// entries are available, this member contains -1.
///
public uint dwEnumerationContext;
///
/// Contains an array of DS_REPL_VALUE_META_DATA_2 structures that contain the individual attribute replication values. The
/// cNumEntries member contains the number of elements in this array.
///
public IntPtr _rgMetaData;
///
/// Gets an array of DS_REPL_VALUE_META_DATA_2 structures that contain the individual attribute replication values.
///
/// The rg meta data.
public DS_REPL_VALUE_META_DATA_2[] rgMetaData => _rgMetaData.ToArray((int)cNumEntries);
}
///
/// Provides metadata for a collection of attribute replication values.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_attr_value_meta_data_ext typedef struct
// _DS_REPL_ATTR_VALUE_META_DATA_EXT { DWORD cNumEntries; DWORD dwEnumerationContext; #if ... DS_REPL_VALUE_META_DATA_EXT
// rgMetaData[]; #else DS_REPL_VALUE_META_DATA_EXT rgMetaData[1]; #endif } DS_REPL_ATTR_VALUE_META_DATA_EXT;
[PInvokeData("ntdsapi.h", MSDNShortId = "CA41C6BF-A485-4AC7-B761-3A07159C2FF1")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_ATTR_VALUE_META_DATA_EXT
{
/// The number of elements in the rgMetaData array.
public uint cNumEntries;
///
/// The zero-based index of the next entry to retrieve if more entries are available. This value is passed for the
/// dwEnumerationContext parameter in the next call to DsReplicaGetInfo2 to retrieve the next block of entries. If no more
/// entries are available, this member contains -1.
///
public uint dwEnumerationContext;
///
/// Contains an array of DS_REPL_VALUE_META_DATA_EXT structures that contain the individual attribute replication values. The
/// cNumEntries member contains the number of elements in this array.
///
public IntPtr _rgMetaData;
///
/// Gets an array of DS_REPL_VALUE_META_DATA_EXT structures that contain the individual attribute replication values.
///
/// The rg meta data.
public DS_REPL_VALUE_META_DATA_EXT[] rgMetaData => _rgMetaData.ToArray((int)cNumEntries);
}
///
/// The DS_REPL_CURSOR structure contains inbound replication state data with respect to all replicas of a given naming
/// context, as returned by the DsReplicaGetInfo and DsReplicaGetInfo2 functions.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursor typedef struct _DS_REPL_CURSOR { UUID
// uuidSourceDsaInvocationID; USN usnAttributeFilter; } DS_REPL_CURSOR;
[PInvokeData("ntdsapi.h", MSDNShortId = "ab4ee8d8-5ccd-4f3f-a1c0-de78c65a10d3")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSOR
{
///
/// Contains the invocation identifier of the originating server to which the usnAttributeFilter corresponds.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the maximum update sequence number to which the destination server can indicate that it has recorded all changes
/// originated by the given server at update sequence numbers less than, or equal to, this update sequence number. This is used
/// to filter changes at replication source servers that the destination server has already applied.
///
public long usnAttributeFilter;
}
///
/// The DS_REPL_CURSOR_2 structure contains inbound replication state data with respect to all replicas of a given naming
/// context, as returned by the DsReplicaGetInfo2 function. This structure is an enhanced version of the DS_REPL_CURSOR structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursor_2 typedef struct _DS_REPL_CURSOR_2 { UUID
// uuidSourceDsaInvocationID; USN usnAttributeFilter; FILETIME ftimeLastSyncSuccess; } DS_REPL_CURSOR_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "ff839372-41f0-499a-9582-59ace02f1485")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSOR_2
{
///
/// Contains the invocation identifier of the originating server to which the usnAttributeFilter corresponds.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the maximum update sequence number to which the destination server can indicate that it has recorded all changes
/// originated by the given server at update sequence numbers less than, or equal to, this update sequence number. This is used
/// to filter changes at replication source servers that the destination server has already applied.
///
public long usnAttributeFilter;
///
/// Contains a FILETIME structure that contains the date and time of the last successful synchronization operation.
///
public FILETIME ftimeLastSyncSuccess;
}
///
/// The DS_REPL_CURSOR_3 structure contains inbound replication state data with respect to all replicas of a given naming
/// context, as returned by the DsReplicaGetInfo2 function. This structure is an enhanced version of the DS_REPL_CURSOR and
/// DS_REPL_CURSOR_2 structures.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursor_3w typedef struct _DS_REPL_CURSOR_3W {
// UUID uuidSourceDsaInvocationID; USN usnAttributeFilter; FILETIME ftimeLastSyncSuccess; LPWSTR pszSourceDsaDN; } DS_REPL_CURSOR_3W;
[PInvokeData("ntdsapi.h", MSDNShortId = "0361a3e1-814c-4ef2-b574-2870a9289e52")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSOR_3W
{
///
/// Contains the invocation identifier of the originating server to which the usnAttributeFilter corresponds.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the maximum update sequence number to which the destination server can indicate that it has recorded all changes
/// originated by the given server at update sequence numbers less than, or equal to, this update sequence number. This is used
/// to filter changes at replication source servers that the destination server has already applied.
///
public long usnAttributeFilter;
///
/// Contains a FILETIME structure that contains the date and time of the last successful synchronization operation.
///
public FILETIME ftimeLastSyncSuccess;
///
/// Pointer to a null-terminated string that contains the distinguished name of the directory service agent that corresponds to
/// the source server to which this replication state data applies.
///
public string pszSourceDsaDN;
}
///
/// The DS_REPL_CURSOR_BLOB structure contains inbound replication state data with respect to all replicas of a given naming
/// context. This structure is similar to the DS_REPL_CURSOR_3 structure, but is obtained from the Lightweight Directory Access
/// Protocol API functions when obtaining binary data for the msDS-NCReplCursors attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursor_blob typedef struct _DS_REPL_CURSOR_BLOB {
// UUID uuidSourceDsaInvocationID; USN usnAttributeFilter; FILETIME ftimeLastSyncSuccess; DWORD oszSourceDsaDN; } DS_REPL_CURSOR_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "c41e4737-5ef8-40ce-9af1-0afff7e11dc1")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSOR_BLOB
{
///
/// Contains the invocation identifier of the originating server to which the usnAttributeFilter corresponds.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the maximum update sequence number to which the destination server can indicate that it has recorded all changes
/// originated by the given server at update sequence numbers less than, or equal to, this update sequence number. This is used
/// to filter changes at replication source servers that the destination server has already applied.
///
public long usnAttributeFilter;
///
/// Contains a FILETIME structure that contains the date and time of the last successful synchronization operation.
///
public FILETIME ftimeLastSyncSuccess;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the directory service agent that corresponds to the source server to which this replication state data applies.
///
public uint oszSourceDsaDN;
}
///
/// The DS_REPL_CURSORS structure is used with the DsReplicaGetInfo and DsReplicaGetInfo2 function to provide replication
/// state data with respect to all replicas of a given naming context.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursors typedef struct _DS_REPL_CURSORS { DWORD
// cNumCursors; DWORD dwReserved; #if ... DS_REPL_CURSOR rgCursor[]; #else DS_REPL_CURSOR rgCursor[1]; #endif } DS_REPL_CURSORS;
[PInvokeData("ntdsapi.h", MSDNShortId = "0fe5ad72-d3f3-42a8-a36f-ca1fc9c55c50")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSORS
{
/// Contains the number of elements in the rgCursor array.
public uint cNumCursors;
/// Reserved for future use.
public uint dwReserved;
///
/// Contains an array of DS_REPL_CURSOR structures that contain the requested replication data. The cNumCursors member contains
/// the number of elements in this array.
///
public IntPtr _rgCursor;
///
/// Contains an array of DS_REPL_CURSOR structures that contain the requested replication data.
///
/// The rg cursor.
public DS_REPL_CURSOR[] rgCursor => _rgCursor.ToArray((int)cNumCursors);
}
///
/// The DS_REPL_CURSORS_2 structure is used with the DsReplicaGetInfo2 function to provide replication state data with respect
/// to all replicas of a given naming context.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursors_2 typedef struct _DS_REPL_CURSORS_2 {
// DWORD cNumCursors; DWORD dwEnumerationContext; #if ... DS_REPL_CURSOR_2 rgCursor[]; #else DS_REPL_CURSOR_2 rgCursor[1]; #endif } DS_REPL_CURSORS_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "5a1981ac-3b6a-4e48-8430-f8297ddd3283")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSORS_2
{
/// Contains the number of elements in the rgCursor array.
public uint cNumCursors;
///
/// Contains the zero-based index of the next entry to retrieve if more entries are available. This value is passed for the
/// dwEnumerationContext parameter in the next call to DsReplicaGetInfo2 to retrieve the next block of entries. If no more
/// entries are available, this member contains -1.
///
public uint dwEnumerationContext;
///
/// Contains an array of DS_REPL_CURSOR_2 structures that contain the requested replication data. The cNumCursors member contains
/// the number of elements in this array.
///
public IntPtr _rgCursor;
///
/// Contains an array of DS_REPL_CURSOR_2 structures that contain the requested replication data.
///
/// The rg cursor.
public DS_REPL_CURSOR_2[] rgCursor => _rgCursor.ToArray((int)cNumCursors);
}
///
/// The DS_REPL_CURSORS_3 structure is used with the DsReplicaGetInfo2 function to provide replication state data with respect
/// to all replicas of a given naming context.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_cursors_3w typedef struct _DS_REPL_CURSORS_3W {
// DWORD cNumCursors; DWORD dwEnumerationContext; #if ... DS_REPL_CURSOR_3W rgCursor[]; #else DS_REPL_CURSOR_3W rgCursor[1]; #endif } DS_REPL_CURSORS_3W;
[PInvokeData("ntdsapi.h", MSDNShortId = "7b8e0015-dd8f-4cba-8ea2-683cb107f294")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_CURSORS_3W
{
/// Contains the number of elements in the rgCursor array.
public uint cNumCursors;
///
/// Contains the zero-based index of the next entry to retrieve if more entries are available. This value is passed for the
/// dwEnumerationContext parameter in the next call to DsReplicaGetInfo2 to retrieve the next block of entries. If no more
/// entries are available, this member contains -1.
///
public uint dwEnumerationContext;
///
/// Contains an array of DS_REPL_CURSOR_3W structures that contain the requested replication data. The cNumCursors member
/// contains the number of elements in this array.
///
public IntPtr _rgCursor;
///
/// Contains an array of DS_REPL_CURSOR_3W structures that contain the requested replication data.
///
/// The rg cursor.
public DS_REPL_CURSOR_3W[] rgCursor => _rgCursor.ToArray((int)cNumCursors);
}
///
/// The DS_REPL_KCC_DSA_FAILURES structure contains an array of DS_REPL_KCC_DSA_FAILURE structures, which in turn contain
/// replication state data with respect to inbound replication partners, as returned by the DsReplicaGetInfo and DsReplicaGetInfo2 functions.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_kcc_dsa_failuresw typedef struct
// _DS_REPL_KCC_DSA_FAILURESW { DWORD cNumEntries; DWORD dwReserved; #if ... DS_REPL_KCC_DSA_FAILUREW rgDsaFailure[]; #else
// DS_REPL_KCC_DSA_FAILUREW rgDsaFailure[1]; #endif } DS_REPL_KCC_DSA_FAILURESW;
[PInvokeData("ntdsapi.h", MSDNShortId = "bb011502-38ae-43b7-a6ad-de16b499f61b")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_KCC_DSA_FAILURESW
{
///
/// Contains the number of elements in the rgMetaData array.
///
public uint cNumEntries;
/// Reserved for future use.
public uint dwReserved;
///
/// Contains an array of DS_REPL_KCC_DSA_FAILURE structures that contain the requested replication data. The cNumEntries member
/// contains the number of elements in this array.
///
public IntPtr _rgDsaFailure;
///
/// Contains an array of DS_REPL_KCC_DSA_FAILURE structures that contain the requested replication data.
///
/// The rg DSA failure.
public DS_REPL_KCC_DSA_FAILUREW[] rgDsaFailure => _rgDsaFailure.ToArray((int)cNumEntries);
}
///
/// The DS_REPL_KCC_DSA_FAILURE structure contains replication state data about a specific inbound replication partner, as
/// returned by the DsReplicaGetInfo and DsReplicaGetInfo2 function. This state data is compiled and used by the Knowledge
/// Consistency Checker (KCC) to decide when alternate replication routes must be added to account for unreachable servers.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_kcc_dsa_failurew typedef struct
// _DS_REPL_KCC_DSA_FAILUREW { LPWSTR pszDsaDN; UUID uuidDsaObjGuid; FILETIME ftimeFirstFailure; DWORD cNumFailures; DWORD
// dwLastResult; } DS_REPL_KCC_DSA_FAILUREW;
[PInvokeData("ntdsapi.h", MSDNShortId = "7a7131ce-a647-4b3d-a9f3-091b6dcebff7")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_KCC_DSA_FAILUREW
{
///
/// Pointer to a null-terminated string that contains the distinguished name of the directory system agent object in the
/// directory that corresponds to the source server.
///
public string pszDsaDN;
///
/// Contains the objectGuid of the directory system agent object represented by the pszDsaDN member.
///
public Guid uuidDsaObjGuid;
///
///
/// Contains a FILETIME structure which the contents of depends on the value passed for the InfoType parameter when
/// DsReplicaGetInfo or DsReplicaGetInfo2 function was called.
///
/// DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES
/// Contains the date and time that the first failure occurred when replicating from the source server.
/// DS_REPL_INFO_KCC_DSA_LINK_FAILURES
/// Contains the date and time of the last successful replication.
///
public FILETIME ftimeFirstFailure;
///
/// Contains the number of consecutive failures since the last successful replication.
///
public uint cNumFailures;
///
/// Contains the error code associated with the most recent failure, or ERROR_SUCCESS if the specific error is unavailable.
///
public Win32Error dwLastResult;
}
///
/// The DS_REPL_KCC_DSA_FAILUREW_BLOB structure contains replication state data with respect to a specific inbound replication
/// partner. This state data is compiled and used by the Knowledge Consistency Checker (KCC) to decide when alternate replication
/// routes must be added to account for unreachable servers. This structure is similar to the DS_REPL_KCC_DSA_FAILURE structure, but
/// is obtained from the Lightweight Directory Access Protocol API functions when obtaining binary data for the
/// msDS-ReplConnectionFailures or msDS-ReplLinkFailures attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_kcc_dsa_failurew_blob typedef struct
// _DS_REPL_KCC_DSA_FAILUREW_BLOB { DWORD oszDsaDN; UUID uuidDsaObjGuid; FILETIME ftimeFirstFailure; DWORD cNumFailures; DWORD
// dwLastResult; } DS_REPL_KCC_DSA_FAILUREW_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "b0df588a-2ef1-4870-b304-c6f9e07322b0")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_KCC_DSA_FAILUREW_BLOB
{
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated string that contains the distinguished
/// name of the directory system agent object in the directory that corresponds to the source server.
///
public uint oszDsaDN;
///
/// Contains the objectGuid of the directory system agent object represented by the oszDsaDN member.
///
public Guid uuidDsaObjGuid;
///
/// Contains a FILETIME structure which the contents of depends on the requested binary replication data.
/// msDS-ReplConnectionFailures
/// Contains the date and time that the first failure occurred when replicating from the source server.
/// msDS-ReplLinkFailures
/// Contains the date and time of the last successful replication.
///
public FILETIME ftimeFirstFailure;
///
/// Contains the number of consecutive failures since the last successful replication.
///
public uint cNumFailures;
///
/// Contains the error code associated with the most recent failure, or ERROR_SUCCESS if the specific error is unavailable.
///
public Win32Error dwLastResult;
}
///
/// The DS_REPL_NEIGHBOR structure contains inbound replication state data for a particular naming context and source server
/// pair, as returned by the DsReplicaGetInfo and DsReplicaGetInfo2 functions.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_neighborw typedef struct _DS_REPL_NEIGHBORW {
// LPWSTR pszNamingContext; LPWSTR pszSourceDsaDN; LPWSTR pszSourceDsaAddress; LPWSTR pszAsyncIntersiteTransportDN; DWORD
// dwReplicaFlags; DWORD dwReserved; UUID uuidNamingContextObjGuid; UUID uuidSourceDsaObjGuid; UUID uuidSourceDsaInvocationID; UUID
// uuidAsyncIntersiteTransportObjGuid; USN usnLastObjChangeSynced; USN usnAttributeFilter; FILETIME ftimeLastSyncSuccess; FILETIME
// ftimeLastSyncAttempt; DWORD dwLastSyncResult; DWORD cNumConsecutiveSyncFailures; } DS_REPL_NEIGHBORW;
[PInvokeData("ntdsapi.h", MSDNShortId = "acab74f4-5739-4310-895b-081062c0360b")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_NEIGHBOR
{
///
/// Pointer to a null-terminated string that contains the naming context to which this replication state data pertains. Each
/// naming context is replicated independently and has different associated neighbor data, even if the naming contexts are
/// replicated from the same source server.
///
public string pszNamingContext;
///
/// Pointer to a null-terminated string that contains the distinguished name of the directory service agent corresponding to the
/// source server to which this replication state data pertains. Each source server has different associated neighbor data.
///
public string pszSourceDsaDN;
///
/// Pointer to a null-terminated string that contains the transport-specific network address of the source server. That is, a
/// directory name service name for RPC/IP replication, or an SMTP address for an SMTP replication.
///
public string pszSourceDsaAddress;
///
/// Pointer to a null-terminated string that contains the distinguished name of the interSiteTransport object that
/// corresponds to the transport over which replication is performed. This member contains NULL for RPC/IP replication.
///
public string pszAsyncIntersiteTransportDN;
///
///
/// Contains a set of flags that specify attributes and options for the replication data. This can be zero or a combination of
/// one or more of the following flags.
///
/// DS_REPL_NBR_WRITEABLE (16 (0x10))
/// The local copy of the naming context is writable.
/// DS_REPL_NBR_SYNC_ON_STARTUP (32 (0x20))
///
/// Replication of this naming context from this source is attempted when the destination server is booted. This normally only
/// applies to intra-site neighbors.
///
/// DS_REPL_NBR_DO_SCHEDULED_SYNCS (64 (0x40))
///
/// Perform replication on a schedule. This flag is normally set unless the schedule for this naming context/source is "never",
/// that is, the empty schedule.
///
/// DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT (128 (0x80))
///
/// Perform replication indirectly through the Inter-Site Messaging Service. This flag is set only when replicating over SMTP.
/// This flag is not set when replicating over inter-site RPC/IP.
///
/// DS_REPL_NBR_TWO_WAY_SYNC (512 (0x200))
///
/// If set, indicates that when inbound replication is complete, the destination server must tell the source server to
/// synchronize in the reverse direction. This feature is used in dial-up scenarios where only one of the two servers can
/// initiate a dial-up connection. For example, this option would be used in a corporate headquarters and branch office, where
/// the branch office connects to the corporate headquarters over the Internet by means of a dial-up ISP connection.
///
/// DS_REPL_NBR_RETURN_OBJECT_PARENTS (2048 (0x800))
///
/// This neighbor is in a state where it returns parent objects before children objects. It goes into this state after it
/// receives a child object before its parent.
///
/// DS_REPL_NBR_FULL_SYNC_IN_PROGRESS (65536 (0x10000))
///
/// The destination server is performing a full synchronization from the source server. Full synchronizations do not use vectors
/// that create updates (DS_REPL_CURSORS) for filtering updates. Full synchronizations are not used as a part of the normal
/// replication protocol.
///
/// DS_REPL_NBR_FULL_SYNC_NEXT_PACKET (131072 (0x20000))
///
/// The last packet from the source indicated a modification of an object that the destination server has not yet created. The
/// next packet to be requested instructs the source server to put all attributes of the modified object into the packet.
///
/// DS_REPL_NBR_NEVER_SYNCED (2097152 (0x200000))
/// A synchronization has never been successfully completed from this source.
/// DS_REPL_NBR_PREEMPTED (16777216 (0x1000000))
///
/// The replication engine has temporarily stopped processing this neighbor in order to service another higher-priority neighbor,
/// either for this partition or for another partition. The replication engine will resume processing this neighbor after the
/// higher-priority work is completed.
///
/// DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS (67108864 (0x4000000))
///
/// This neighbor is set to disable notification-based synchronizations. Within a site, domain controllers synchronize with each
/// other based on notifications when changes occur. This setting prevents this neighbor from performing syncs that are triggered
/// by notifications. The neighbor will still do synchronizations based on its schedule, or in response to manually requested synchronizations.
///
/// DS_REPL_NBR_DISABLE_SCHEDULED_SYNC (134217728 (0x8000000))
///
/// This neighbor is set to not perform synchronizations based on its schedule. The only way this neighbor will perform
/// synchronizations is in response to change notifications or to manually requested synchronizations.
///
/// DS_REPL_NBR_COMPRESS_CHANGES (268435456 (0x10000000))
///
/// Changes received from this source are to be compressed. This is normally set if, and only if, the source server is in a
/// different site.
///
/// DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS (536870912 (0x20000000))
///
/// No change notifications should be received from this source. Normally set if, and only if, the source server is in a
/// different site.
///
/// DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET (1073741824 (0x40000000))
///
/// This neighbor is in a state where it is rebuilding the contents of this replica because of a change in the partial attribute set.
///
///
public DsReplNeighborFlags dwReplicaFlags;
/// Reserved for future use.
public uint dwReserved;
///
/// Contains the objectGuid of the naming context corresponding to pszNamingContext.
///
public Guid uuidNamingContextObjGuid;
///
/// Contains the objectGuid of the nTDSDSA object corresponding to pszSourceDsaDN.
///
public Guid uuidSourceDsaObjGuid;
///
/// Contains the invocation identifier used by the source server as of the last replication attempt.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the objectGuid of the inter-site transport object corresponding to pszAsyncIntersiteTransportDN.
///
public Guid uuidAsyncIntersiteTransportObjGuid;
///
/// Contains the update sequence number of the last object update received.
///
public long usnLastObjChangeSynced;
///
/// Contains the usnLastObjChangeSynced value at the end of the last complete, successful replication cycle, or 0 if none.
/// Attributes at the source last updated at a update sequence number less than or equal to this value have already been received
/// and applied by the destination.
///
public long usnAttributeFilter;
///
/// Contains a FILETIME structure that contains the date and time the last successful replication cycle was completed from this
/// source. All members of this structure are zero if the replication cycle has never been completed.
///
public FILETIME ftimeLastSyncSuccess;
///
/// Contains a FILETIME structure that contains the date and time of the last replication attempt from this source. All members
/// of this structure are zero if the replication has never been attempted.
///
public FILETIME ftimeLastSyncAttempt;
///
/// Contains an error code associated with the last replication attempt from this source. Contains ERROR_SUCCESS if the
/// last attempt succeeded.
///
public Win32Error dwLastSyncResult;
///
/// Contains the number of failed replication attempts from this source since the last successful replication attempt - or since
/// the source was added as a neighbor, if no previous attempt was successful.
///
public uint cNumConsecutiveSyncFailures;
}
///
/// The DS_REPL_NEIGHBORS structure is used with the DsReplicaGetInfo and DsReplicaGetInfo2 functions to provide inbound
/// replication state data for naming context and source server pairs.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_neighborsw typedef struct _DS_REPL_NEIGHBORSW {
// DWORD cNumNeighbors; DWORD dwReserved; #if ... DS_REPL_NEIGHBORW rgNeighbor[]; #else DS_REPL_NEIGHBORW rgNeighbor[1]; #endif } DS_REPL_NEIGHBORSW;
[PInvokeData("ntdsapi.h", MSDNShortId = "1307399b-de29-43ec-97b4-05cd70c1a92d")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_REPL_NEIGHBORS
{
///
/// Contains the number of elements in the rgNeighbor array.
///
public uint cNumNeighbors;
/// Reserved for future use.
public uint dwReserved;
///
/// Contains an array of DS_REPL_NEIGHBOR structures that contain the requested replication data. The cNumNeighbors member
/// contains the number of elements in this array.
///
public IntPtr _rgNeighbor;
///
/// Contains an array of DS_REPL_NEIGHBOR structures that contain the requested replication data.
///
/// The rg neighbor.
public DS_REPL_NEIGHBOR[] rgNeighbor => _rgNeighbor.ToArray((int)cNumNeighbors);
}
///
/// The DS_REPL_NEIGHBORW_BLOB structure contains inbound replication state data for a particular naming context and source
/// server pair. This structure is similar to the DS_REPL_NEIGHBOR structure, but is obtained from the Lightweight Directory Access
/// Protocol API functions when obtaining binary data for the msDS-NCReplInboundNeighbors attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_neighborw_blob typedef struct
// _DS_REPL_NEIGHBORW_BLOB { DWORD oszNamingContext; DWORD oszSourceDsaDN; DWORD oszSourceDsaAddress; DWORD
// oszAsyncIntersiteTransportDN; DWORD dwReplicaFlags; DWORD dwReserved; UUID uuidNamingContextObjGuid; UUID uuidSourceDsaObjGuid;
// UUID uuidSourceDsaInvocationID; UUID uuidAsyncIntersiteTransportObjGuid; USN usnLastObjChangeSynced; USN usnAttributeFilter;
// FILETIME ftimeLastSyncSuccess; FILETIME ftimeLastSyncAttempt; DWORD dwLastSyncResult; DWORD cNumConsecutiveSyncFailures; } DS_REPL_NEIGHBORW_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "1a56968a-29ed-4c94-80ee-02bdd279f5c2")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_NEIGHBORW_BLOB
{
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// naming context to which this replication state data pertains. Each naming context is replicated independently and has
/// different associated neighbor data, even if the naming contexts are replicated from the same source server.
///
public uint oszNamingContext;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the directory service agent corresponding to the source server to which this replication state data
/// pertains. Each source server has different associated neighbor data.
///
public uint oszSourceDsaDN;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// transport-specific network address of the source server. That is, a directory name service name for RPC/IP replication, or an
/// SMTP address for an SMTP replication.
///
public uint oszSourceDsaAddress;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the interSiteTransport object that corresponds to the transport over which replication is
/// performed. This member contains NULL for RPC/IP replication.
///
public uint oszAsyncIntersiteTransportDN;
///
///
/// Contains a set of flags that specify attributes and options for the replication data. This can be zero or a combination of
/// one or more of the following flags.
///
/// DS_REPL_NBR_WRITEABLE
/// The local copy of the naming context is writable.
/// DS_REPL_NBR_SYNC_ON_STARTUP
///
/// Replication of this naming context from this source is attempted when the destination server is booted. This normally only
/// applies to intra-site neighbors.
///
/// DS_REPL_NBR_DO_SCHEDULED_SYNCS
///
/// Perform replication on a schedule. This flag is normally set unless the schedule for this naming context/source is "never",
/// that is, the empty schedule.
///
/// DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT
///
/// Perform replication indirectly through the Inter-Site Messaging Service. This flag is set only when replicating over SMTP.
/// This flag is not set when replicating over inter-site RPC/IP.
///
/// DS_REPL_NBR_TWO_WAY_SYNC
///
/// If set, indicates that when inbound replication is complete, the destination server must tell the source server to
/// synchronize in the reverse direction. This feature is used in dial-up scenarios where only one of the two servers can
/// initiate a dial-up connection. For example, this option would be used in a corporate headquarters and branch office, where
/// the branch office connects to the corporate headquarters over the Internet by means of a dial-up ISP connection.
///
/// DS_REPL_NBR_FULL_SYNC_IN_PROGRESS
///
/// The destination server is performing a full synchronization from the source server. Full synchronizations do not use vectors
/// that create updates (DS_REPL_CURSORS) for filtering updates. Full synchronizations are not used as a part of the normal
/// replication protocol.
///
/// DS_REPL_NBR_FULL_SYNC_NEXT_PACKET
///
/// The last packet from the source indicated a modification of an object that the destination server has not yet created. The
/// next packet to be requested instructs the source server to put all attributes of the modified object into the packet.
///
/// DS_REPL_NBR_NEVER_SYNCED
/// A synchronization has never been successfully completed from this source.
/// DS_REPL_NBR_COMPRESS_CHANGES
///
/// Changes received from this source are to be compressed. This is normally set if, and only if, the source server is in a
/// different site.
///
/// DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS
///
/// No change notifications should be received from this source. Normally set if, and only if, the source server is in a
/// different site.
///
///
public uint dwReplicaFlags;
/// Reserved for future use.
public uint dwReserved;
///
/// Contains the objectGuid of the naming context that corresponds to pszNamingContext.
///
public Guid uuidNamingContextObjGuid;
///
/// Contains the objectGuid of the nTDSDSA object that corresponds to pszSourceDsaDN.
///
public Guid uuidSourceDsaObjGuid;
///
/// Contains the invocation identifier used by the source server as of the last replication attempt.
///
public Guid uuidSourceDsaInvocationID;
///
/// Contains the objectGuid of the inter-site transport object that corresponds to pszAsyncIntersiteTransportDN.
///
public Guid uuidAsyncIntersiteTransportObjGuid;
///
/// Contains the update sequence number of the last object update received.
///
public long usnLastObjChangeSynced;
///
/// Contains the usnLastObjChangeSynced value at the end of the last complete, successful replication cycle, or 0 if none.
/// Attributes at the source last updated at a update sequence number less than or equal to this value have already been received
/// and applied by the destination.
///
public long usnAttributeFilter;
///
/// Contains a FILETIME structure that contains the date and time the last successful replication cycle was completed from this
/// source. All members of this structure are zero if the replication cycle has never been completed.
///
public FILETIME ftimeLastSyncSuccess;
///
/// Contains a FILETIME structure that contains the date and time of the last replication attempt from this source. All members
/// of this structure are zero if the replication has never been attempted.
///
public FILETIME ftimeLastSyncAttempt;
///
/// Contains a Windows error code associated with the last replication attempt from this source. Contains ERROR_SUCCESS if
/// the last attempt was successful.
///
public uint dwLastSyncResult;
///
/// Contains the number of failed replication attempts that have been made from this source since the last successful replication
/// attempt or since the source was added as a neighbor, if no previous attempt succeeded.
///
public uint cNumConsecutiveSyncFailures;
}
///
/// The DS_REPL_OBJ_META_DATA structure contains an array of DS_REPL_ATTR_META_DATA structures. These structures contain
/// replication state data for past and present attributes for a given object. The replication state data is returned from the
/// DsReplicaGetInfo and DsReplicaGetInfo2 functions. The metadata records data about the last modification of a given object attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_obj_meta_data typedef struct
// _DS_REPL_OBJ_META_DATA { DWORD cNumEntries; DWORD dwReserved; #if ... DS_REPL_ATTR_META_DATA rgMetaData[]; #else
// DS_REPL_ATTR_META_DATA rgMetaData[1]; #endif } DS_REPL_OBJ_META_DATA;
[PInvokeData("ntdsapi.h", MSDNShortId = "7851ffbc-5d05-4ea7-b3b4-1b8b77299be5")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_OBJ_META_DATA
{
///
/// Contains the number of elements in the rgMetaData array.
///
public uint cNumEntries;
/// Not used.
public uint dwReserved;
///
/// Contains an array of DS_REPL_ATTR_META_DATA structures. The cNumEntries member contains the number of elements in this array.
///
public IntPtr _rgMetaData;
///
/// Contains an array of DS_REPL_ATTR_META_DATA structures that contain the requested replication data.
///
/// The rg meta data.
public DS_REPL_ATTR_META_DATA[] rgMetaData => _rgMetaData.ToArray((int)cNumEntries);
}
///
/// The DS_REPL_OBJ_META_DATA_2 structure contains an array of DS_REPL_ATTR_META_DATA_2 structures, which in turn contain
/// replication state data for the attributes (past and present) for a given object, as returned by the DsReplicaGetInfo2 function.
/// This structure is an enhanced version of the DS_REPL_OBJ_META_DATA structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_obj_meta_data_2 typedef struct
// _DS_REPL_OBJ_META_DATA_2 { DWORD cNumEntries; DWORD dwReserved; #if ... DS_REPL_ATTR_META_DATA_2 rgMetaData[]; #else
// DS_REPL_ATTR_META_DATA_2 rgMetaData[1]; #endif } DS_REPL_OBJ_META_DATA_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "2aed753f-432c-4de8-a6be-aa79833f002f")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_REPL_OBJ_META_DATA_2
{
///
/// Contains the number of elements in the rgMetaData array.
///
public uint cNumEntries;
/// Not used.
public uint dwReserved;
///
/// Contains an array of DS_REPL_ATTR_META_DATA_2 structures. The cNumEntries member contains the number of elements in this array.
///
public IntPtr _rgMetaData;
///
/// Contains an array of DS_REPL_ATTR_META_DATA_2 structures that contain the requested replication data.
///
/// The rg meta data.
public DS_REPL_ATTR_META_DATA_2[] rgMetaData => _rgMetaData.ToArray((int)cNumEntries);
}
///
/// The DS_REPL_OP structure describes a replication task currently executing or pending execution, as returned by the
/// DsReplicaGetInfo or DsReplicaGetInfo2 function.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_opw typedef struct _DS_REPL_OPW { FILETIME
// ftimeEnqueued; ULONG ulSerialNumber; ULONG ulPriority; DS_REPL_OP_TYPE OpType; ULONG ulOptions; LPWSTR pszNamingContext; LPWSTR
// pszDsaDN; LPWSTR pszDsaAddress; UUID uuidNamingContextObjGuid; UUID uuidDsaObjGuid; } DS_REPL_OPW;
[PInvokeData("ntdsapi.h", MSDNShortId = "9ea783b3-1529-4424-a582-f46f2a239a60")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_OPW
{
///
/// Contains a FILETIME structure that contains the date and time that this operation was added to the queue.
///
public FILETIME ftimeEnqueued;
///
/// Contains the operation identifier. This value is unique in the startup routine of every computer. When the computer is
/// restarted, the identifiers are no longer unique.
///
public uint ulSerialNumber;
///
/// Contains the priority value of this operation. Tasks with a higher priority value are executed first. The priority is
/// calculated by the server based on the type of operation and its parameters.
///
public uint ulPriority;
///
/// Contains one of the DS_REPL_OP_TYPE values that indicate the type of operation that this structure represents.
///
public DS_REPL_OP_TYPE OpType;
///
///
/// Zero or more bits, the interpretation of which depends on the OpType. For DS_REPL_OP_TYPE_SYNC, the bits should
/// be interpreted as DS_REPSYNC_. ADD, DELETE, MODIFY, and UPDATE_REFS use DS_REPADD_,
/// DS_REPDEL_, DS_REPMOD_, and DS_REPUPD_*. For more information and descriptions of these bits, see
/// DsReplicaSync, DsReplicaAdd, DsReplicaDel, DsReplicaModify, and DsReplicaUpdateRefs.
///
///
/// Contains a set of flags that provides additional data about the operation. The contents of this member is determined by the
/// contents of the OpType member.
///
/// DS_REPL_OP_TYPE_SYNC
///
/// Contains zero or a combination of one or more of the DS_REPSYNC_* values as defined for the Options parameter in DsReplicaSync.
///
/// DS_REPL_OP_TYPE_ADD
///
/// Contains zero or a combination of one or more of the DS_REPADD_* values as defined for the Options parameter in DsReplicaAdd.
///
/// DS_REPL_OP_TYPE_DELETE
///
/// Contains zero or a combination of one or more of the DS_REPDEL_* values as defined for the Options parameter in DsReplicaDel.
///
/// DS_REPL_OP_TYPE_MODIFY
///
/// Contains zero or a combination of one or more of the DS_REPMOD_* values as defined for the Options parameter in DsReplicaModify.
///
/// DS_REPL_OP_TYPE_UPDATE_REFS
///
/// Contains zero or a combination of one or more of the DS_REPSUPD_* values as defined for the Options parameter in DsReplicaUpdateRefs.
///
///
public uint ulOptions;
///
/// Pointer to a null-terminated string that contains the distinguished name of the naming context associated with this
/// operation. For example, the naming context to be synchronized for DS_REPL_OP_TYPE_SYNC.
///
public string pszNamingContext;
///
/// Pointer to a null-terminated string that contains the distinguished name of the directory system agent object associated with
/// the remote server corresponding to this operation. For example, the server from which to request changes for
/// DS_REPL_OP_TYPE_SYNC. This can be NULL.
///
public string pszDsaDN;
///
/// Pointer to a null-terminated string that contains the transport-specific network address of the remote server associated with
/// this operation. For example, the DNS or SMTP address of the server from which to request changes for
/// DS_REPL_OP_TYPE_SYNC. This can be NULL.
///
public string pszDsaAddress;
///
/// Contains the objectGuid of the naming context identified by pszNamingContext.
///
public Guid uuidNamingContextObjGuid;
///
/// Contains the objectGuid of the directory system agent object identified by pszDsaDN.
///
public Guid uuidDsaObjGuid;
}
///
/// The DS_REPL_OPW_BLOB structure describes a replication task currently executing or pending execution. This structure is
/// similar to the DS_REPL_OP structure, but is obtained from the Lightweight Directory Access Protocol API functions when obtaining
/// binary data for the msDS-ReplPendingOps attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_opw_blob typedef struct _DS_REPL_OPW_BLOB {
// FILETIME ftimeEnqueued; ULONG ulSerialNumber; ULONG ulPriority; DS_REPL_OP_TYPE OpType; ULONG ulOptions; DWORD oszNamingContext;
// DWORD oszDsaDN; DWORD oszDsaAddress; UUID uuidNamingContextObjGuid; UUID uuidDsaObjGuid; } DS_REPL_OPW_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "14676159-cc31-4254-b174-dcd84d9ceec1")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_OPW_BLOB
{
///
/// Contains a FILETIME structure that contains the date and time that this operation was added to the queue.
///
public FILETIME ftimeEnqueued;
///
/// Contains the identifier of the operation. This value is unique in the startup routine of every computer. When the computer is
/// restarted, the identifiers are no longer unique.
///
public uint ulSerialNumber;
///
/// Contains the priority value of this operation. Tasks with a higher priority value are executed first. The priority is
/// calculated by the server based on the type of operation and its parameters.
///
public uint ulPriority;
///
/// Contains one of the DS_REPL_OP_TYPE values that indicate the type of operation that this structure represents.
///
public DS_REPL_OP_TYPE OpType;
///
///
/// Zero or more bits, the interpretation of which depends on the OpType. For DS_REPL_OP_TYPE_SYNC, the bits should
/// be interpreted as DS_REPSYNC_. ADD, DELETE, MODIFY, and UPDATE_REFS use DS_REPADD_,
/// DS_REPDEL_, DS_REPMOD_, and DS_REPUPD_*. For more information, and descriptions of these bits, see
/// DsReplicaSync, DsReplicaAdd, DsReplicaDel, DsReplicaModify, and DsReplicaUpdateRefs.
///
///
/// Contains a set of flags that provide additional data about the operation. The contents of this member is determined by the
/// contents of the OpType member.
///
/// This list describes the contents of the ulOptions parameter for each OpType value.
/// DS_REPL_OP_TYPE_SYNC
///
/// Contains zero or a combination of one or more of the DS_REPSYNC_* values as defined for the Options parameter in DsReplicaSync.
///
/// DS_REPL_OP_TYPE_ADD
///
/// Contains zero or a combination of one or more of the DS_REPADD_* values as defined for the Options parameter in DsReplicaAdd.
///
/// DS_REPL_OP_TYPE_DELETE
///
/// Contains zero or a combination of one or more of the DS_REPDEL_* values as defined for the Options parameter in DsReplicaDel.
///
/// DS_REPL_OP_TYPE_MODIFY
///
/// Contains zero or a combination of one or more of the DS_REPMOD_* values as defined for the Options parameter in DsReplicaModify.
///
/// DS_REPL_OP_TYPE_UPDATE_REFS
///
/// Contains zero or a combination of one or more of the DS_REPSUPD_* values as defined for the Options parameter in DsReplicaUpdateRefs.
///
///
public uint ulOptions;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated string that contains the distinguished
/// name of the naming context associated with this operation. For example, the naming context to be synchronized for DS_REPL_OP_TYPE_SYNC.
///
public uint oszNamingContext;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated string that contains the distinguished
/// name of the directory system agent object associated with the remote server corresponding to this operation. For example, the
/// server from which to ask for changes for DS_REPL_OP_TYPE_SYNC. This can be NULL.
///
public uint oszDsaDN;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated string that contains the
/// transport-specific network address of the remote server associated with this operation. For example, the DNS or SMTP address
/// of the server from which to ask for changes for DS_REPL_OP_TYPE_SYNC. This can be NULL.
///
public uint oszDsaAddress;
///
/// Contains the objectGuid of the naming context identified by pszNamingContext.
///
public Guid uuidNamingContextObjGuid;
///
/// Contains the objectGuid of the directory system agent object identified by pszDsaDN.
///
public Guid uuidDsaObjGuid;
}
///
/// The DS_REPL_PENDING_OPS structure contains an array of DS_REPL_OP structures, which in turn describe the replication tasks
/// currently executing and queued to execute, as returned by the DsReplicaGetInfo and DsReplicaGetInfo2 functions. The entries in
/// the queue are processed in priority order, and the first entry is the one currently being executed.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_pending_opsw typedef struct _DS_REPL_PENDING_OPSW
// { FILETIME ftimeCurrentOpStarted; DWORD cNumPendingOps; #if ... DS_REPL_OPW rgPendingOp[]; #else DS_REPL_OPW rgPendingOp[1];
// #endif } DS_REPL_PENDING_OPSW;
[PInvokeData("ntdsapi.h", MSDNShortId = "2e4b96cb-fbd6-496b-aff3-cb7d82f1fa39")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_PENDING_OPSW
{
///
/// Contains a FILETIME structure that contains the date and time at which the first operation in the queue began executing.
///
public FILETIME ftimeCurrentOpStarted;
///
/// Contains the number of elements in the rgPendingOps array.
///
public uint cNumPendingOps;
/// The sequence of replication operations to be performed.
public IntPtr _rgPendingOp;
/// The sequence of replication operations to be performed.
/// The rg pending op.
public DS_REPL_OPW[] rgPendingOp => _rgPendingOp.ToArray((int)cNumPendingOps);
}
///
/// The DS_REPL_QUEUE_STATISTICSW structure is used to contain replication queue statistics.
///
/// Reserved. Obtain this data using the DS_REPL_QUEUE_STATISTICSW_BLOB structure with the Lightweight Directory Access Protocol API
/// functions to obtain binary data for the msDS-ReplQueueStatistics attribute.
///
///
///
/// DS_REPL_QUEUE_STATISTICSW_BLOB is an alias for this structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_queue_statisticsw typedef struct
// _DS_REPL_QUEUE_STATISTICSW { FILETIME ftimeCurrentOpStarted; DWORD cNumPendingOps; FILETIME ftimeOldestSync; FILETIME
// ftimeOldestAdd; FILETIME ftimeOldestMod; FILETIME ftimeOldestDel; FILETIME ftimeOldestUpdRefs; } DS_REPL_QUEUE_STATISTICSW, DS_REPL_QUEUE_STATISTICSW_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "bfddd7ed-0ff4-46ca-84c2-39020acb37d0")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_QUEUE_STATISTICSW
{
///
/// Contains a FILETIME structure that contains the date and time that the currently running operation started.
///
public FILETIME ftimeCurrentOpStarted;
/// Contains the number of currently pending operations.
public uint cNumPendingOps;
///
/// Contains a FILETIME structure that contains the date and time of the oldest synchronization operation.
///
public FILETIME ftimeOldestSync;
///
/// Contains a FILETIME structure that contains the date and time of the oldest add operation.
///
public FILETIME ftimeOldestAdd;
///
/// Contains a FILETIME structure that contains the date and time of the oldest modification operation.
///
public FILETIME ftimeOldestMod;
///
/// Contains a FILETIME structure that contains the date and time of the oldest delete operation.
///
public FILETIME ftimeOldestDel;
///
/// Contains a FILETIME structure that contains the date and time of the oldest reference update operation.
///
public FILETIME ftimeOldestUpdRefs;
}
///
/// The DS_REPL_VALUE_META_DATA structure is used with the DS_REPL_ATTR_VALUE_META_DATA structure to contain attribute value
/// replication metadata.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_value_meta_data typedef struct
// _DS_REPL_VALUE_META_DATA { LPWSTR pszAttributeName; LPWSTR pszObjectDn; DWORD cbData; #if ... BYTE *pbData; #else BYTE *pbData;
// #endif FILETIME ftimeDeleted; FILETIME ftimeCreated; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; } DS_REPL_VALUE_META_DATA;
[PInvokeData("ntdsapi.h", MSDNShortId = "294a466e-8a83-4b33-a8a8-ac7b51d081d4")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_VALUE_META_DATA
{
///
/// Pointer to a null-terminated Unicode string that contains the LDAP display name of the attribute corresponding to this metadata.
///
public string pszAttributeName;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the object that this attribute belongs to.
///
public string pszObjectDn;
/// Contains the number of bytes in the pbData array.
public uint cbData;
///
/// The binary_value portion of the attribute value if the attribute is of syntax Object(DN-Binary), or the string_value portion
/// of the attribute value if the attribute is of syntax Object(DN-String); null otherwise.
///
public IntPtr pbData;
///
/// Contains a FILETIME structure that contains the time this attribute was deleted.
///
public FILETIME ftimeDeleted;
///
/// Contains a FILETIME structure that contains the time this attribute was created.
///
public FILETIME ftimeCreated;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains a FILETIME structure that contains the time at which the last originating change was made to this attribute.
/// Replication of the change does not affect this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identifier of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server, that is the server from which the DsReplicaGetInfo2 function retrieved the
/// metadata, at which the last change to this attribute was applied. This value is typically different on all servers.
///
public long usnLocalChange;
}
///
/// The DS_REPL_VALUE_META_DATA_2 structure is used with the DS_REPL_ATTR_VALUE_META_DATA_2 structure to contain attribute
/// value replication metadata.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_value_meta_data_2 typedef struct
// _DS_REPL_VALUE_META_DATA_2 { LPWSTR pszAttributeName; LPWSTR pszObjectDn; DWORD cbData; #if ... BYTE *pbData; #else BYTE *pbData;
// #endif FILETIME ftimeDeleted; FILETIME ftimeCreated; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; LPWSTR pszLastOriginatingDsaDN; } DS_REPL_VALUE_META_DATA_2;
[PInvokeData("ntdsapi.h", MSDNShortId = "747e32b8-2cc0-4fcd-88dc-027188598361")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_VALUE_META_DATA_2
{
///
/// Pointer to a null-terminated Unicode string that contains the LDAP display name of the attribute that corresponds to this metadata.
///
public string pszAttributeName;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the object that this attribute belongs to.
///
public string pszObjectDn;
/// Contains the number of bytes in the pbData array.
public uint cbData;
///
/// The binary_value portion of the attribute value if the attribute is of syntax Object(DN-Binary), or the string_value portion
/// of the attribute value if the attribute is of syntax Object(DN-String); null otherwise.
///
public IntPtr pbData;
///
/// Contains a FILETIME structure that contains the time this attribute was deleted.
///
public FILETIME ftimeDeleted;
///
/// Contains a FILETIME structure that contains the time this attribute was created.
///
public FILETIME ftimeCreated;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains a FILETIME structure that contains the time at which the last originating change was made to this attribute.
/// Replication of the change does not affect this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identifier of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server, that is, the server from which the DsReplicaGetInfo2 function retrieved the
/// metadata, at which the last change to this attribute was applied. This value is typically different on all servers.
///
public long usnLocalChange;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the directory system agent server that
/// originated the last replication.
///
public string pszLastOriginatingDsaDN;
}
///
/// The DS_REPL_VALUE_META_DATA_BLOB structure is used to contain attribute value replication metadata. This structure is
/// similar to the DS_REPL_VALUE_META_DATA_2 structure, but is obtained from the Lightweight Directory Access Protocol API functions
/// when obtaining binary data for the msDS-ReplValueMetaData attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_value_meta_data_blob typedef struct
// _DS_REPL_VALUE_META_DATA_BLOB { DWORD oszAttributeName; DWORD oszObjectDn; DWORD cbData; DWORD obData; FILETIME ftimeDeleted;
// FILETIME ftimeCreated; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID uuidLastOriginatingDsaInvocationID; USN
// usnOriginatingChange; USN usnLocalChange; DWORD oszLastOriginatingDsaDN; } DS_REPL_VALUE_META_DATA_BLOB;
[PInvokeData("ntdsapi.h", MSDNShortId = "7d8bb666-c5d8-43de-ab72-5b02b6e0593d")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_VALUE_META_DATA_BLOB
{
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the LDAP
/// display name of the attribute corresponding to this metadata. A value of zero indicates an empty or NULL string.
///
public uint oszAttributeName;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the object that this attribute belongs to. A value of zero indicates an empty or NULL string.
///
public uint oszObjectDn;
/// Contains the number of bytes in the pbData array.
public uint cbData;
///
/// Contains a 32-bit offset, in bytes, from the address of this structure to a buffer that contains the attribute replication
/// metadata. The cbData member contains the length, in bytes, of this buffer.
///
public uint obData;
///
/// Contains a FILETIME structure that contains the time that this attribute was deleted.
///
public FILETIME ftimeDeleted;
///
/// Contains a FILETIME structure that contains the time that this attribute was created.
///
public FILETIME ftimeCreated;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains a FILETIME structure that contains the time at which the last originating change was made to this attribute.
/// Replication of the change does not affect this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identifier of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server, that is, the server from which the DsReplicaGetInfo2 function retrieved the
/// metadata, at which the last change to this attribute was applied. This value is typically different on all servers.
///
public long usnLocalChange;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the directory system agent server that originated the last replication. A value of zero indicates an
/// empty or NULL string.
///
public uint oszLastOriginatingDsaDN;
}
///
/// Contains attribute value replication metadata. This structure is similar to the DS_REPL_VALUE_META_DATA_EXT structure, but is
/// obtained from the Lightweight Directory Access Protocol API functions when obtaining binary data for the
/// msDS-ReplValueMetaData attribute.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_value_meta_data_blob_ext typedef struct
// _DS_REPL_VALUE_META_DATA_BLOB_EXT { DWORD oszAttributeName; DWORD oszObjectDn; DWORD cbData; DWORD obData; FILETIME ftimeDeleted;
// FILETIME ftimeCreated; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID uuidLastOriginatingDsaInvocationID; USN
// usnOriginatingChange; USN usnLocalChange; DWORD oszLastOriginatingDsaDN; DWORD dwUserIdentifier; DWORD dwPriorLinkState; DWORD
// dwCurrentLinkState; } DS_REPL_VALUE_META_DATA_BLOB_EXT;
[PInvokeData("ntdsapi.h", MSDNShortId = "095180F4-9E3F-47EE-B39E-107D7D219DCB")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_VALUE_META_DATA_BLOB_EXT
{
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the LDAP
/// display name of the attribute corresponding to this metadata. A value of zero indicates an empty or NULL string.
///
public uint oszAttributeName;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the object that this attribute belongs to. A value of zero indicates an empty or NULL string.
///
public uint oszObjectDn;
/// Contains the number of bytes in the pbData array.
public uint cbData;
///
/// Pointer to a buffer that contains the attribute replication metadata. The cbData member contains the length, in bytes,
/// of this buffer.
///
public uint obData;
///
/// Contains a FILETIME structure that contains the time that this attribute was deleted.
///
public FILETIME ftimeDeleted;
///
/// Contains a FILETIME structure that contains the time that this attribute was created.
///
public FILETIME ftimeCreated;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains a FILETIME structure that contains the time at which the last originating change was made to this attribute.
/// Replication of the change does not affect this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identifier of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server, that is, the server from which the DsReplicaGetInfo2 function retrieved the
/// metadata, at which the last change to this attribute was applied. This value is typically different on all servers.
///
public long usnLocalChange;
///
/// Contains the offset, in bytes, from the address of this structure to a null-terminated Unicode string that contains the
/// distinguished name of the directory system agent server that originated the last replication. A value of zero indicates an
/// empty or NULL string.
///
public uint oszLastOriginatingDsaDN;
/// TBD
public uint dwUserIdentifier;
/// TBD
public uint dwPriorLinkState;
/// TBD
public uint dwCurrentLinkState;
}
///
/// Contains attribute replication meta data for the DS_REPL_ATTR_VALUE_META_DATA_EXT structure.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-_ds_repl_value_meta_data_ext typedef struct
// _DS_REPL_VALUE_META_DATA_EXT { LPWSTR pszAttributeName; LPWSTR pszObjectDn; DWORD cbData; #if ... BYTE *pbData; #else BYTE
// *pbData; #endif FILETIME ftimeDeleted; FILETIME ftimeCreated; DWORD dwVersion; FILETIME ftimeLastOriginatingChange; UUID
// uuidLastOriginatingDsaInvocationID; USN usnOriginatingChange; USN usnLocalChange; LPWSTR pszLastOriginatingDsaDN; DWORD
// dwUserIdentifier; DWORD dwPriorLinkState; DWORD dwCurrentLinkState; } DS_REPL_VALUE_META_DATA_EXT;
[PInvokeData("ntdsapi.h", MSDNShortId = "2BE0F9C4-D688-4DE6-8DB2-15666D8BD070")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DS_REPL_VALUE_META_DATA_EXT
{
///
/// Pointer to a null-terminated Unicode string that contains the LDAP display name of the attribute corresponding to this metadata.
///
public string pszAttributeName;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the object that this attribute belongs to.
///
public string pszObjectDn;
/// Contains the number of bytes in the pbData array.
public uint cbData;
///
/// Pointer to a buffer that contains the attribute replication metadata. The cbData member contains the length, in bytes,
/// of this buffer.
///
public IntPtr pbData;
///
/// Contains a FILETIME structure that contains the time this attribute was deleted.
///
public FILETIME ftimeDeleted;
///
/// Contains a FILETIME structure that contains the time this attribute was created.
///
public FILETIME ftimeCreated;
///
/// Contains the version of this attribute. Each originating modification of the attribute increases this value by one.
/// Replication of a modification does not affect the version.
///
public uint dwVersion;
///
/// Contains a FILETIME structure that contains the time at which the last originating change was made to this attribute.
/// Replication of the change does not affect this value.
///
public FILETIME ftimeLastOriginatingChange;
///
/// Contains the invocation identifier of the server on which the last change was made to this attribute. Replication of the
/// change does not affect this value.
///
public Guid uuidLastOriginatingDsaInvocationID;
///
/// Contains the update sequence number (USN) on the originating server at which the last change to this attribute was made.
/// Replication of the change does not affect this value.
///
public long usnOriginatingChange;
///
/// Contains the USN on the destination server, that is the server from which the DsReplicaGetInfo2 function retrieved the
/// metadata, at which the last change to this attribute was applied. This value is typically different on all servers.
///
public long usnLocalChange;
///
/// Pointer to a null-terminated Unicode string that contains the distinguished name of the directory system agent server that
/// originated the last replication.
///
public string pszLastOriginatingDsaDN;
/// TBD
public uint dwUserIdentifier;
/// TBD
public uint dwPriorLinkState;
/// TBD
public uint dwCurrentLinkState;
}
///
/// The DS_REPSYNCALL_ERRINFO structure is used with the DS_REPSYNCALL_UPDATE structure to contain errors generated by the
/// DsReplicaSyncAll function during replication.
///
// https://webcache.googleusercontent.com/search?q=cache:0plHTsXYeJ0J:https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-ds_repsyncall_errinfoa+&cd=1&hl=en&ct=clnk&gl=us
// typedef struct DS_REPSYNCALL_ERRINFOA { LPSTR pszSvrId; DS_REPSYNCALL_ERROR error; DWORD dwWin32Err; LPSTR pszSrcId; } *PDS_REPSYNCALL_ERRINFOA;
[PInvokeData("ntdsapi.h", MSDNShortId = "70af4e3e-1f0e-49c5-b8c6-5e89114ed4ea")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_REPSYNCALL_ERRINFO
{
///
/// Pointer to a null-terminated string that contains the DNS GUID of the server where the error occurred. Alternatively, this
/// member can contain the distinguished name of the server if DS_REPSYNCALL_ID_SERVERS_BY_DN is specified in the ulFlags
/// parameter of the DsReplicaSyncAll function.
///
public string pszSvrId;
///
/// Contains one of the DS_REPSYNCALL_ERROR values that indicates where in the replication process the error occurred.
///
public DS_REPSYNCALL_ERROR error;
///
/// Indicates the actual Win32 error code generated during replication between the source server referred to by pszSrcId
/// and the destination server referred to by pszSvrId.
///
public Win32Error dwWin32Err;
///
/// Pointer to a null-terminated string that specifies the DNS GUID of the source server. Alternatively, this member can contain
/// the distinguished name of the source server if DS_REPSYNCALL_ID_SERVERS_BY_DN is specified in the ulFlags parameter of
/// the DsReplicaSyncAll function.
///
public string pszSrcId;
}
///
/// The DS_REPSYNCALL_UPDATE structure contains status data about the replication performed by the DsReplicaSyncAll function.
/// The DsReplicaSyncAll function passes this structure to a callback function in its pFnCallBack parameter. For more
/// information about the callback function, see SyncUpdateProc.
///
// https://webcache.googleusercontent.com/search?q=cache:-LzmvZ2eMGsJ:https://docs.microsoft.com/en-us/windows/desktop/api/ntdsapi/ns-ntdsapi-ds_repsyncall_updatea+&cd=1&hl=en&ct=clnk&gl=us
// typedef struct DS_REPSYNCALL_UPDATEA { DS_REPSYNCALL_EVENT event; DS_REPSYNCALL_ERRINFOA *pErrInfo; DS_REPSYNCALL_SYNCA *pSync; } *PDS_REPSYNCALL_UPDATEA;
[PInvokeData("ntdsapi.h", MSDNShortId = "3b0005cb-0fb6-492c-89e5-8a18a88f881b")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_REPSYNCALL_UPDATE
{
///
/// Contains a DS_REPSYNCALL_EVENT value that describes the event which the DS_REPSYNCALL_UPDATE structure represents.
///
public DS_REPSYNCALL_EVENT cEvent;
///
/// Pointer to a DS_REPSYNCALL_ERRINFO structure that contains error data about the replication performed by the DsReplicaSyncAll function.
///
public IntPtr pErrInfo;
///
/// Pointer to a DS_REPSYNCALL_SYNC structure that identifies the source and destination servers that have either initiated or
/// finished synchronization.
///
public IntPtr pSync;
}
///
/// The DS_SCHEMA_GUID_MAP structure contains the results of a call to DsMapSchemaGuids. If DsMapSchemaGuids succeeds in mapping a
/// GUID, DS_SCHEMA_GUID_MAP contains both the GUID and a display name for the object to which the GUID refers.
///
[PInvokeData("ntdsapi.h")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DS_SCHEMA_GUID_MAP
{
/// GUID structure that specifies the object GUID.
public Guid guid;
/// Indicates the type of GUID mapped by DsMapSchemaGuids.
public DsSchemaGuidType guidType;
///
/// Pointer to a null-terminated string value that specifies the display name associated with the GUID. This value may be NULL if
/// DsMapSchemaGuids was unable to map the GUID to a display name.
///
public string pName;
}
///
/// The DS_SITE_COST_INFO structure is used with the DsQuerySitesByCost function to contain communication cost data.
///
// https://msdn.microsoft.com/en-us/windows/ms676286(v=vs.80).aspx
[PInvokeData("ntdsapi.h")]
[StructLayout(LayoutKind.Sequential)]
public struct DS_SITE_COST_INFO
{
///
/// Contains a success or error code that indicates if the cost data for the site could be obtained. This member can contain one
/// of the following values.
///
/// -
/// ERROR_SUCCESS
/// The communication cost of the site was obtained and is contained in the cost member of this structure.
///
/// -
/// ERROR_DS_OBJ_NOT_FOUND
/// The communication cost of the site cannot be obtained. The cost member of this structure should be ignored.
///
///
///
public Win32Error errorCode;
///
/// If the errorCode member contains ERROR_SUCCESS, this member contains the communication cost value of the site.
/// If the errorCode member contains ERROR_DS_OBJ_NOT_FOUND, this contents of this member is undefined.
///
public uint cost;
}
///
/// The SCHEDULE_HEADER structure is used to contain the replication schedule data for a replication source. The SCHEDULE
/// structure contains an array of SCHEDULE_HEADER structures.
///
// https://docs.microsoft.com/en-us/windows/desktop/api/schedule/ns-schedule-_schedule_header typedef struct _SCHEDULE_HEADER { ULONG
// Type; ULONG Offset; } SCHEDULE_HEADER, *PSCHEDULE_HEADER;
[PInvokeData("schedule.h", MSDNShortId = "5453927e-306e-4442-a855-916005dc8e3b")]
[StructLayout(LayoutKind.Sequential)]
public struct SCHEDULE_HEADER
{
///
/// Contains one of the following values that defines the type of schedule data that is contained in this structure.
/// SCHEDULE_INTERVAL
///
/// The schedule contains a set of intervals. The Offset member contains the offset to an array of bytes with
/// SCHEDULE_DATA_ENTRIES elements. Each byte in the array represents an hour of the week. The first hour is 00:00 on
/// Sunday morning GMT.
///
///
/// Each bit of the lower four bits of each byte represents a 15 minute block within the hour that the source is available for
/// replication. The following list lists the binary values and describes each bit of the lower four bits of the hour value.
///
///
///
/// Binary value
/// Description
///
/// -
/// 1000
/// The source is available for replication from 0 to 14 minutes after the hour.
///
/// -
/// 0100
/// The source is available for replication from 15 to 29 minutes after the hour.
///
/// -
/// 0010
/// The source is available for replication from 30 to 44 minutes after the hour.
///
/// -
/// 0001
/// The source is available for replication from 45 to 59 minutes after the hour.
///
///
///
/// These bits can be combined to create multiple 15 minute blocks that the source is available. For example, a binary value of
/// 0111 indicates that the source is available from 0 to 44 minutes after the hour.
///
/// The upper fours bits of each byte are not used.
/// SCHEDULE_BANDWIDTH
/// Not supported.
/// SCHEDULE_PRIORITY
/// Not supported.
///
public ScheduleType Type;
///
/// Contains the offset, in bytes, from the beginning of the SCHEDULE structure to the data for this schedule. The size and form
/// of this data depends on the schedule type defined by the Type member.
///
public uint Offset;
}
/// Provides a handle to an array of one or more service principal names (SPNs).
[StructLayout(LayoutKind.Sequential)]
public struct SpnArrayHandle : IHandle
{
private IntPtr handle;
/// Initializes a new instance of the struct.
/// An object that represents the pre-existing handle to use.
public SpnArrayHandle(IntPtr preexistingHandle) => handle = preexistingHandle;
///
public IntPtr DangerousGetHandle() => handle;
/// Gets the list of service principle names (SPNs) from this handle.
/// The count returned in the pcSpn parameter of .
/// The list of SPNs.
public IEnumerable GetSPNs(uint count) => handle.ToStringEnum((int)count);
}
/// Provides a to an authentication identity that releases its handle at disposal using DsFreePasswordCredentials.
public class SafeAuthIdentityHandle : SafeHANDLE
{
/// Initializes a new instance of the class and assigns an existing handle.
/// An object that represents the pre-existing handle to use.
///
/// to reliably release the handle during the finalization phase; otherwise, (not recommended).
///
public SafeAuthIdentityHandle(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { }
/// Initializes a new instance of the class.
private SafeAuthIdentityHandle() : base() { }
/// Gets a value that marshals as NULL so that the local thread's identity is used.
public static readonly SafeAuthIdentityHandle LocalThreadIdentity = new SafeAuthIdentityHandle();
///
protected override bool InternalReleaseHandle() { DsFreePasswordCredentials(handle); return true; }
}
/// Provides a safe handle to an array of DS_REPSYNCALL_ERRINFO structures returned from .
///
public class SafeDS_REPSYNCALL_ERRINFOArray : GenericSafeHandle, IReadOnlyCollection
{
internal SafeDS_REPSYNCALL_ERRINFOArray() : base(IntPtr.Zero, h => LocalFree(h) == IntPtr.Zero)
{
}
///
public int Count => IsInvalid ? 0 : handle.GetNulledPtrArrayLength();
/// Gets the array of DS_REPSYNCALL_ERRINFO structures.
public DS_REPSYNCALL_ERRINFO[] Items => IsInvalid ? new DS_REPSYNCALL_ERRINFO[0] : handle.ToArray(Count);
///
public IEnumerator GetEnumerator() => Array.AsReadOnly(Items).GetEnumerator();
///
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
[DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr LocalFree(IntPtr hMem);
}
/// A for handles bound to directory services.
///
[SuppressUnmanagedCodeSecurity, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[PInvokeData("NTDSApi.h")]
public class SafeDsHandle : SafeHANDLE
{
/// Initializes a new instance of the class and assigns an existing handle.
/// An object that represents the pre-existing handle to use.
///
/// to reliably release the handle during the finalization phase; otherwise, (not recommended).
///
public SafeDsHandle(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { }
/// Initializes a new instance of the class.
private SafeDsHandle() : base() { }
/// Gets a NULL equivalent for a bound directory services handle.
public static SafeDsHandle Null { get; } = new SafeDsHandle(IntPtr.Zero);
///
protected override bool InternalReleaseHandle() => DsUnBind(ref handle).Succeeded;
}
///
/// A for the results from .
///
///
[PInvokeData("NTDSApi.h")]
public class SafeDsNameResult : GenericSafeHandle, IEnumerable
{
/// Initializes a new instance of the class.
public SafeDsNameResult() : base(h => { DsFreeNameResult(h); return true; }) { }
/// An array of DS_NAME_RESULT_ITEM structures. Each element of this array represents a single converted name.
public DS_NAME_RESULT_ITEM[] Items => IsInvalid ? new DS_NAME_RESULT_ITEM[0] : handle.ToStructure().Items;
///
public IEnumerator GetEnumerator() => ((IEnumerable)Items).GetEnumerator();
///
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
/// A for the results from .
///
[PInvokeData("NTDSApi.h")]
public class SafeDsQuerySites : GenericSafeHandle
{
/// Initializes a new instance of the class.
public SafeDsQuerySites() : base(h => { DsQuerySitesFree(h); return true; }) { }
/// Gets an array of DS_SITE_COST_INFO structures.
///
/// Indicates the number of elements in the array. This value is the same value as that passed into .
///
public DS_SITE_COST_INFO[] GetItems(int cToSites) => IsInvalid ? new DS_SITE_COST_INFO[0] : handle.ToArray(cToSites);
}
/// A for the results from .
[PInvokeData("NTDSApi.h")]
public class SafeDsReplicaInfo : SafeHANDLE
{
internal SafeDsReplicaInfo()
{
}
/// Gets the value.
/// The value.
public object Value
{
get
{
var t = CorrespondingTypeAttribute.GetCorrespondingTypes(Type).FirstOrDefault();
return t == null || IsInvalid ? null : handle.Convert(uint.MaxValue, t);
}
}
internal DS_REPL_INFO_TYPE Type { get; set; }
/// Gets the requested structure.
/// Type of the structure
/// The structure.
public T GetValue() where T : struct
{
if (!CorrespondingTypeAttribute.CanGet(Type, typeof(T))) throw new InvalidCastException();
return handle.ToStructure();
}
///
protected override bool InternalReleaseHandle()
{
DsReplicaFreeInfo(Type, handle);
return true;
}
}
/// A for the results from .
///
[PInvokeData("NTDSApi.h")]
public class SafeDsSchemaGuidMap : GenericSafeHandle
{
/// Initializes a new instance of the class.
public SafeDsSchemaGuidMap() : base(h => { DsFreeSchemaGuidMap(h); return true; }) { }
/// Gets an array of DS_SCHEMA_GUID_MAP structures.
///
/// Indicates the number of elements in the array. This value is the same value as that passed into .
///
public DS_SCHEMA_GUID_MAP[] GetItems(int cGuids) => IsInvalid ? new DS_SCHEMA_GUID_MAP[0] : handle.ToArray(cGuids);
}
///
///
/// The SCHEDULE structure is a variable-length structure used with the DsReplicaAdd and DsReplicaModify functions to contain
/// replication schedule data for a replication source.
///
///
// https://docs.microsoft.com/en-us/windows/desktop/api/schedule/ns-schedule-_schedule typedef struct _SCHEDULE { ULONG Size; ULONG
// Bandwidth; ULONG NumberOfSchedules; SCHEDULE_HEADER Schedules[1]; } SCHEDULE, *PSCHEDULE;
[PInvokeData("schedule.h", MSDNShortId = "d86890db-b34a-415a-820a-6d4790914218")]
[StructLayout(LayoutKind.Sequential)]
public class SCHEDULE : IDisposable
{
private const int intervalByteCount = 24 * 7;
/// Initializes a new instance of the class.
/// The schedule intervals. See for detail about this array.
///
/// scheduleIntervals - Array must have at least 1 schedule and have a second dimension of 24 x 7 bytes.
///
public SCHEDULE(byte[,] scheduleIntervals)
{
if (scheduleIntervals is null || scheduleIntervals.GetLength(0) == 0 || scheduleIntervals.GetLength(1) != intervalByteCount)
throw new ArgumentOutOfRangeException(nameof(scheduleIntervals), "Array must have at least 1 schedule and have a second dimension of 24 x 7 bytes.");
NumberOfSchedules = (uint)scheduleIntervals.GetLength(0);
var hdrSz = NumberOfSchedules * (intervalByteCount + 8);
_Schedules = Marshal.AllocCoTaskMem((int)hdrSz);
var scheds = new SCHEDULE_HEADER[NumberOfSchedules];
Size = (uint)(12 + IntPtr.Size);
var schMemOffset = Size + NumberOfSchedules * Marshal.SizeOf(typeof(SCHEDULE_HEADER));
var offset = 0;
for (var i = 0; i < NumberOfSchedules; i++)
{
scheds[i] = new SCHEDULE_HEADER { Type = ScheduleType.SCHEDULE_INTERVAL, Offset = (uint)(offset + schMemOffset) };
unsafe
{
var schOff = (byte*)_Schedules.Offset(offset).ToPointer();
fixed (byte* retptr = &scheduleIntervals[i, 0])
{
for (var x = 0; x < intervalByteCount; x++)
schOff[x] = retptr[x];
}
}
offset += intervalByteCount;
}
Size += hdrSz;
}
///
///
/// Contains the size, in bytes, of the SCHEDULE structure, including the size of all of the elements and data of the
/// Schedules array.
///
///
public readonly uint Size;
///
/// Not used.
///
public readonly uint Bandwidth;
///
/// Contains the number of elements in the Schedules array.
///
public readonly uint NumberOfSchedules;
///
///
/// Contains an array of SCHEDULE_HEADER structures that contain the replication schedule data for the replication source. The
/// NumberOfSchedules member contains the number of elements in this array. Currently, this array can only contain one element.
///
///
private IntPtr _Schedules;
///
///
/// Contains an array of SCHEDULE_HEADER structures that contain the replication schedule data for the replication source. The
/// NumberOfSchedules member contains the number of elements in this array. Currently, this array can only contain one element.
///
///
public SCHEDULE_HEADER[] Schedules => _Schedules.ToArray((int)NumberOfSchedules);
///
///
/// Gets a two-dimensional array of bytes for each schedule with 7 x 24 elements. Each byte in the array represents an hour of
/// the week. The first hour is 00:00 on Sunday morning GMT.
///
///
/// Each bit of the lower four bits of each byte represents a 15 minute block within the hour that the source is available for
/// replication. The following list lists the binary values and describes each bit of the lower four bits of the hour value.
///
///
///
/// Binary value
/// Description
///
/// -
/// 1000
/// The source is available for replication from 0 to 14 minutes after the hour.
///
/// -
/// 0100
/// The source is available for replication from 15 to 29 minutes after the hour.
///
/// -
/// 0010
/// The source is available for replication from 30 to 44 minutes after the hour.
///
/// -
/// 0001
/// The source is available for replication from 45 to 59 minutes after the hour.
///
///
///
/// These bits can be combined to create multiple 15 minute blocks that the source is available. For example, a binary value of
/// 0111 indicates that the source is available from 0 to 44 minutes after the hour.
///
/// The upper fours bits of each byte are not used.
///
public byte[,] ScheduleIntervals
{
get
{
var s = Schedules;
var ret = new byte[s.Length, intervalByteCount];
for (var i = 0; i < s.Length; i++)
{
if (s[i].Type != ScheduleType.SCHEDULE_INTERVAL) continue;
var offset = (int)s[i].Offset;
unsafe
{
fixed (SCHEDULE_HEADER* sptr = &s[i])
fixed (byte* retptr = &ret[i, 0])
{
var sbptr = (byte*)sptr;
for (var x = 0; x < intervalByteCount; x++)
retptr[x] = sbptr[x + offset];
}
}
}
return ret;
}
}
void IDisposable.Dispose() => Marshal.FreeCoTaskMem(_Schedules);
}
}
}