Exemplo n.º 1
0
        /// <summary>
        /// Gets information about the vertex service
        /// </summary>
        /// <returns></returns>
        VertexStatus IDryadVertexService.CheckStatus()
        {
            DryadLogger.LogMethodEntry();
            VertexStatus status = new VertexStatus();

            status.serviceIsAlive = true;

            //
            // Update information about disk usage
            //
            foreach (string disk in Environment.GetLogicalDrives())
            {
                ulong freeDiskSpaceforUser;
                ulong totalDiskSpace;
                ulong freeDiskSpace;

                if (NativeMethods.GetDiskFreeSpaceEx(disk, out freeDiskSpaceforUser, out totalDiskSpace, out freeDiskSpace))
                {
                    status.freeDiskSpaces.Add(disk, freeDiskSpace);
                }
                else
                {
                    //
                    // Report any errors as warnings, as this is a non-essential call
                    //
                    int       errorCode = Marshal.GetLastWin32Error();
                    Exception lastex    = Marshal.GetExceptionForHR(errorCode);
                    if (lastex != null)
                    {
                        DryadLogger.LogWarning("Unable to get disk space information", "Disk: {0} Error: {1}", disk, lastex.Message);
                    }
                    else
                    {
                        DryadLogger.LogWarning("Unable to get disk space information", "Disk: {0} Error Code: {1}", disk, errorCode);
                    }
                }
            }

            //
            // Update information about memory usage
            //
            NativeMethods.MEMORYSTATUSEX memStatus = new NativeMethods.MEMORYSTATUSEX();
            if (NativeMethods.GlobalMemoryStatusEx(memStatus))
            {
                status.freePhysicalMemory = memStatus.ullAvailPhys;
                status.freeVirtualMemory  = memStatus.ullAvailVirtual;
            }
            else
            {
                //
                // Report any errors as warnings, as this is a non-essential call
                //
                int       errorCode = Marshal.GetLastWin32Error();
                Exception lastex    = Marshal.GetExceptionForHR(errorCode);
                if (lastex != null)
                {
                    DryadLogger.LogWarning("Unable to get memory information", "Error: {0}", lastex.Message);
                }
                else
                {
                    DryadLogger.LogWarning("Unable to get memory information", "Error Code: {0}", errorCode);
                }
            }

            //
            // Get process info for each running vertex process
            //
            status.runningProcessCount = 0;
            lock (vertexProcessTable.SyncRoot)
            {
                foreach (VertexProcess vp in this.vertexProcessTable)
                {
                    VertexProcessInfo vpInfo = new VertexProcessInfo();
                    vpInfo.DryadId     = vp.DryadId;
                    vpInfo.commandLine = vp.commandLine;
                    vpInfo.State       = vp.State;

                    status.vps.Add(vpInfo);

                    if (vp.State == ProcessState.Running)
                    {
                        status.runningProcessCount++;
                    }
                }
            }

            DryadLogger.LogMethodExit(status);
            return(status);
        }
Exemplo n.º 2
0
        public void WriteEvent(EventPayload payload)
        {
            try
            {
                System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();

                if (((string)Helpers.IsNull(payload.CustomText, string.Empty)) != string.Empty)
                {
                    errorMessage.AppendFormat("{0}\r\n", payload.CustomText);
                }

                if (payload.Exception != null)
                {
                    string exceptionMessage = Exceptions.GetExceptionText(payload.Exception);

                    //If we do not have a message, then we have to find something to report on.
                    if (exceptionMessage == null || exceptionMessage == string.Empty)
                    {
                        if (payload.Exception.HResult != 0)
                        {
                            Exception hresultEx = null;

                            try
                            {
                                hresultEx = Marshal.GetExceptionForHR(payload.Exception.HResult);
                            }
                            catch
                            {
                                //throw away...
                            }

                            if (hresultEx != null)
                            {
                                exceptionMessage = string.Format("{0}\r\n", Exceptions.GetExceptionText(hresultEx));
                            }
                            else
                            {
                                exceptionMessage = string.Format("HResult: {0}\r\n", payload.Exception.HResult.ToString());
                            }
                        }
                    }

                    if (exceptionMessage != null && exceptionMessage != string.Empty)
                    {
                        errorMessage.AppendFormat("Exception: {0}\r\n", exceptionMessage);
                    }
                }

                if (payload.Exception != null && payload.Severity == Severity.Error)
                {
                    StackTrace stackTrace = new StackTrace();
                    MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
                    errorMessage.AppendFormat("Calling Method: {0}\r\n", methodBase.Name);

                    if (payload.Exception != null && payload.Exception.StackTrace != null)
                    {
                        errorMessage.AppendFormat("Stack: {0}\r\n", payload.Exception.StackTrace);
                    }
                }

                this.WriteEvent(payload.Severity, errorMessage.ToString());
            }
            catch
            {
                //Discard error - we don't want a failure to log a verbose event to cause service failure.
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Start Chrome headless with the debugger set to the given port
        /// </summary>
        /// <remarks>
        ///     If Chrome is already running then this step is skipped
        /// </remarks>
        /// <exception cref="ChromeException"></exception>
        private void StartChromeHeadless()
        {
            if (IsChromeRunning())
            {
                return;
            }

            WriteToLog($"Starting Chrome from location {_chromeExeFileName}");

            _chromeProcess = new Process();
            var processStartInfo = new ProcessStartInfo
            {
                FileName               = _chromeExeFileName,
                Arguments              = string.Join(" ", _defaultArguments),
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
            };

            if (!string.IsNullOrWhiteSpace(_userName))
            {
                var userName = string.Empty;

                if (_userName.Contains("\\"))
                {
                    userName = _userName.Split('\\')[1];
                }

                var domain = _userName.Split('\\')[0];

                WriteToLog($"Starting Chrome with user '{userName}' on domain '{domain}'");

                processStartInfo.Domain   = domain;
                processStartInfo.UserName = userName;

                var secureString = new SecureString();
                foreach (var t in _password)
                {
                    secureString.AppendChar(t);
                }

                processStartInfo.Password = secureString;
            }

            _chromeProcess.StartInfo = processStartInfo;

            var waitEvent = new ManualResetEvent(false);

            _chromeProcess.ErrorDataReceived += (sender, args) =>
            {
                if (args.Data == null)
                {
                    return;
                }

                if (args.Data.StartsWith("DevTools listening on"))
                {
                    // DevTools listening on ws://127.0.0.1:50160/devtools/browser/53add595-f351-4622-ab0a-5a4a100b3eae
                    _communicator = new Browser(new Uri(args.Data.Replace("DevTools listening on ", string.Empty)));
                    WriteToLog("Connected to dev protocol");
                    waitEvent.Set();
                }
                else if (!string.IsNullOrWhiteSpace(args.Data))
                {
                    WriteToLog($"Error: {args.Data}");
                }
            };

            _chromeProcess.Exited += (sender, args) =>
            {
                WriteToLog("Chrome process: " + _chromeExeFileName);
                WriteToLog("Arguments used: " + string.Join(" ", _defaultArguments));
                var exception = ExceptionHelpers.GetInnerException(Marshal.GetExceptionForHR(_chromeProcess.ExitCode));
                WriteToLog("Exception: " + exception);
                throw new ChromeException("Could not start Chrome, " + exception);
            };

            _chromeProcess.Start();
            _chromeProcess.BeginErrorReadLine();
            waitEvent.WaitOne();

            WriteToLog("Chrome started");
        }
Exemplo n.º 4
0
        public bool Install(string path, out string errorMessage)
        {
            var manager = NativeMethods.OpenSCManager(null, null,
                                                      ServiceControlManagerAccessRights.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                errorMessage = "OpenSCManager returned zero.";
                return(false);
            }

            var service = NativeMethods.CreateService(manager, id, id,
                                                      ServiceAccessRights.SERVICE_ALL_ACCESS,
                                                      ServiceType.SERVICE_KERNEL_DRIVER, StartType.SERVICE_DEMAND_START,
                                                      ErrorControl.SERVICE_ERROR_NORMAL, path, null, null, null, null,
                                                      null);

            if (service == IntPtr.Zero)
            {
                if (Marshal.GetHRForLastWin32Error() == ERROR_SERVICE_EXISTS)
                {
                    errorMessage = "Service already exists";
                    return(false);
                }
                errorMessage = "CreateService returned the error: " +
                               Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                NativeMethods.CloseServiceHandle(manager);
                return(false);
            }

            if (!NativeMethods.StartService(service, 0, null))
            {
                if (Marshal.GetHRForLastWin32Error() != ERROR_SERVICE_ALREADY_RUNNING)
                {
                    errorMessage = "StartService returned the error: " +
                                   Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                    NativeMethods.CloseServiceHandle(service);
                    NativeMethods.CloseServiceHandle(manager);
                    return(false);
                }
            }

            NativeMethods.CloseServiceHandle(service);
            NativeMethods.CloseServiceHandle(manager);

            try
            {
                // restrict the driver access to system (SY) and builtin admins (BA)
                // TODO: replace with a call to IoCreateDeviceSecure in the driver
                var fileSecurity = File.GetAccessControl(@"\\.\" + id);
                fileSecurity.SetSecurityDescriptorSddlForm(
                    "O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)");
                File.SetAccessControl(@"\\.\" + id, fileSecurity);
            }
            catch
            {
            }

            errorMessage = null;
            return(true);
        }
Exemplo n.º 5
0
        private static void CheckTransaction()
        {
            uint error = (uint)Marshal.GetLastWin32Error();
            int  hr    = Marshal.GetHRForLastWin32Error();

            switch (error)
            {
            case Win32Errors.ERROR_TRANSACTION_ALREADY_ABORTED:
                throw new TransactionAlreadyAbortedException("Transaction was already aborted", Marshal.GetExceptionForHR(hr));

            case Win32Errors.ERROR_TRANSACTION_ALREADY_COMMITTED:
                throw new TransactionAlreadyAbortedException("Transaction was already committed", Marshal.GetExceptionForHR(hr));

            default:
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                break;
            }
        }
Exemplo n.º 6
0
        public static void ThrowException(uint errorCode, string readPath, string writePath)
        {
            string errorMessage = string.Format(CultureInfo.CurrentCulture, "({0}) {1}.", errorCode, new Win32Exception((int)errorCode).Message);

            if (!Utils.IsNullOrWhiteSpace(readPath))
            {
                errorMessage = string.Format(CultureInfo.CurrentCulture, "{0}: [{1}]", errorMessage.TrimEnd('.'), readPath);
            }

            if (!Utils.IsNullOrWhiteSpace(writePath))
            {
                errorMessage = string.Format(CultureInfo.CurrentCulture, "{0}: [{1}]", errorMessage.TrimEnd('.'), writePath);
            }

            switch (errorCode)
            {
            case Win32Errors.ERROR_INVALID_DRIVE:
                throw new DriveNotFoundException(errorMessage);

            case Win32Errors.ERROR_OPERATION_ABORTED:
                throw new OperationCanceledException(errorMessage);

            case Win32Errors.ERROR_FILE_NOT_FOUND:
                throw new FileNotFoundException(errorMessage);

            case Win32Errors.ERROR_PATH_NOT_FOUND:
                throw new DirectoryNotFoundException(errorMessage);

            case Win32Errors.ERROR_BAD_RECOVERY_POLICY:
                throw new PolicyException(errorMessage);

            case Win32Errors.ERROR_FILE_READ_ONLY:
            case Win32Errors.ERROR_ACCESS_DENIED:
            case Win32Errors.ERROR_NETWORK_ACCESS_DENIED:
                throw new UnauthorizedAccessException(errorMessage);

            case Win32Errors.ERROR_ALREADY_EXISTS:
            case Win32Errors.ERROR_FILE_EXISTS:
                throw new AlreadyExistsException(errorMessage);

            case Win32Errors.ERROR_DIR_NOT_EMPTY:
                throw new DirectoryNotEmptyException(errorMessage);

            case Win32Errors.ERROR_NOT_READY:
                throw new DeviceNotReadyException(errorMessage);


                #region Transactional

            case Win32Errors.ERROR_INVALID_TRANSACTION:
                throw new InvalidTransactionException(Resources.Transaction_Invalid, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_ALREADY_COMMITTED:
                throw new TransactionAlreadyCommittedException(Resources.Transaction_Already_Committed, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_ALREADY_ABORTED:
                throw new TransactionAlreadyAbortedException(Resources.Transaction_Already_Aborted, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTIONAL_CONFLICT:
                throw new TransactionalConflictException(Resources.Transactional_Conflict, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_NOT_ACTIVE:
                throw new TransactionException(Resources.Transaction_Not_Active, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_NOT_REQUESTED:
                throw new TransactionException(Resources.Transaction_Not_Requested, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTION_REQUEST_NOT_VALID:
                throw new TransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE:
                throw new UnsupportedRemoteTransactionException(Resources.Invalid_Transaction_Request, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

            case Win32Errors.ERROR_NOT_A_REPARSE_POINT:
                throw new NotAReparsePointException(Resources.Not_A_Reparse_Point, Marshal.GetExceptionForHR(Win32Errors.GetHrFromWin32Error(errorCode)));

                #endregion // Transacted

            case Win32Errors.ERROR_SUCCESS:
            case Win32Errors.ERROR_SUCCESS_REBOOT_INITIATED:
            case Win32Errors.ERROR_SUCCESS_REBOOT_REQUIRED:
            case Win32Errors.ERROR_SUCCESS_RESTART_REQUIRED:
                // We should really never get here, throwing an exception for a successful operation.
                throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, "{0} {1}", Resources.Exception_From_Successful_Operation, errorMessage));

            default:
                // We don't have a specific exception to generate for this error.
                throw new IOException(errorMessage, (int)errorCode);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a list of stack keys, as specified. If this method is not called,
        /// by default the folder will not be stacked.
        /// </summary>
        /// <param name="canonicalNames">Array of canonical names for properties on which the folder is stacked.</param>
        /// <exception cref="System.ArgumentException">If one of the given canonical names is invalid.</exception>
        public void SetStacks(params string[] canonicalNames)
        {
            if (canonicalNames == null)
            {
                throw new ArgumentNullException("canonicalNames");
            }
            List <PropertyKey> propertyKeyList = new List <PropertyKey>();

            foreach (string prop in canonicalNames)
            {
                // Get the PropertyKey using the canonicalName passed in
                PropertyKey propKey;
                int         result = PropertySystemNativeMethods.PSGetPropertyKeyFromName(prop, out propKey);

                if (!CoreErrorHelper.Succeeded(result))
                {
                    throw new ArgumentException(LocalizedMessages.ShellInvalidCanonicalName, "canonicalNames", Marshal.GetExceptionForHR(result));
                }

                propertyKeyList.Add(propKey);
            }

            if (propertyKeyList.Count > 0)
            {
                SetStacks(propertyKeyList.ToArray());
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Returns true if ReSharper is installed, enabled, and not suspended.
        /// </summary>
        private async ValueTask <ReSharperStatus> IsReSharperRunningAsync(ReSharperStatus lastStatus, CancellationToken cancellationToken)
        {
            // Quick exit if resharper is either uninstalled or not enabled
            if (!_resharperExtensionInstalledAndEnabled)
            {
                return(ReSharperStatus.NotInstalledOrDisabled);
            }

            await EnsureOleCommandTargetAsync().ConfigureAwait(false);

            // poll until either suspend or resume botton is available, or until operation is canceled
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var suspendFlag = await QueryStatusAsync(SuspendId).ConfigureAwait(false);

                // In the case of an error when attempting to get the status, pretend that ReSharper isn't enabled. We also
                // shut down monitoring so we don't keep hitting this.
                if (suspendFlag == 0)
                {
                    return(ReSharperStatus.NotInstalledOrDisabled);
                }

                var resumeFlag = await QueryStatusAsync(ResumeId).ConfigureAwait(false);

                if (resumeFlag == 0)
                {
                    return(ReSharperStatus.NotInstalledOrDisabled);
                }

                // When ReSharper is running, the ReSharper_Suspend command is Enabled and not Invisible
                if (suspendFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !suspendFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE))
                {
                    return(ReSharperStatus.Enabled);
                }

                // When ReSharper is suspended, the ReSharper_Resume command is Enabled and not Invisible
                if (resumeFlag.HasFlag(OLECMDF.OLECMDF_ENABLED) && !resumeFlag.HasFlag(OLECMDF.OLECMDF_INVISIBLE))
                {
                    return(ReSharperStatus.Suspended);
                }

                // ReSharper has not finished initializing, so try again later
                await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken).ConfigureAwait(false);
            }

            async Task <OLECMDF> QueryStatusAsync(uint cmdId)
            {
                var cmds = new OLECMD[1];

                cmds[0].cmdID = cmdId;
                cmds[0].cmdf  = 0;

                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();

                var hr = _oleCommandTarget.QueryStatus(ReSharperCommandGroup, (uint)cmds.Length, cmds, IntPtr.Zero);

                if (ErrorHandler.Failed(hr))
                {
                    FatalError.ReportWithoutCrash(Marshal.GetExceptionForHR(hr));
                    await ShutdownAsync().ConfigureAwait(false);

                    return(0);
                }

                return((OLECMDF)cmds[0].cmdf);
            }

            async Task EnsureOleCommandTargetAsync()
            {
                if (_oleCommandTarget != null)
                {
                    return;
                }

                await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();

                _oleCommandTarget = _serviceProvider.GetService <IOleCommandTarget, SUIHostCommandDispatcher>();
            }
        }
Exemplo n.º 9
0
            //------------------------------------------------------------------------------
            // DefineSequencePoints() wrapper
            //------------------------------------------------------------------------------
            void ISymbolWriter.DefineSequencePoints(
                ISymbolDocumentWriter document,
                int[] offsets,
                int[] lines,
                int[] columns,
                int[] endLines,
                int[] endColumns
                )
            {
                int spCount = 0;

                if (offsets != null)
                {
                    spCount = offsets.Length;
                }
                else if (lines != null)
                {
                    spCount = lines.Length;
                }
                else if (columns != null)
                {
                    spCount = columns.Length;
                }
                else if (endLines != null)
                {
                    spCount = endLines.Length;
                }
                else if (endColumns != null)
                {
                    spCount = endColumns.Length;
                }
                if (spCount == 0)
                {
                    return;
                }
                if (
                    (offsets != null && offsets.Length != spCount) ||
                    (lines != null && lines.Length != spCount) ||
                    (columns != null && columns.Length != spCount) ||
                    (endLines != null && endLines.Length != spCount) ||
                    (endColumns != null && endColumns.Length != spCount)
                    )
                {
                    throw new ArgumentException();
                }

                // Sure, claim to accept any type that implements ISymbolDocumentWriter but the only one that actually
                // works is the one returned by DefineDocument. The .NET Framework ISymWrapper commits the same signature fraud.
                // Ideally we'd just return a sealed opaque cookie type, which had an internal accessor to
                // get the writer out.
                // Regardless, this cast is important for security - we cannot allow our caller to provide
                // arbitrary instances of this interface.
                SymDocumentWriter docwriter = (SymDocumentWriter)document;
                int hr = m_vtable.DefineSequencePoints(
                    m_pWriter,
                    docwriter.GetUnmanaged(),
                    spCount !,
                    offsets !,
                    lines !,
                    columns !,
                    endLines !,
                    endColumns !
                    );

                if (hr < 0)
                {
                    throw Marshal.GetExceptionForHR(hr) !;
                }
            }
        public static void From_HR(int hr)
        {
            FileNotFoundException exception = Assert.IsAssignableFrom <FileNotFoundException>(Marshal.GetExceptionForHR(hr));

            // Don't validate the message.  Currently .NET Native does not produce HR-specific messages
            ExceptionUtility.ValidateExceptionProperties(exception, hResult: hr, validateMessage: false);
        }
Exemplo n.º 11
0
        private void StorePropVariantValue(PropVariant propVar)
        {
            Guid           guid = new Guid(ShellIIDGuid.IPropertyStore);
            IPropertyStore writablePropStore = null;

            try
            {
                int hr = ParentShellObject.NativeShellItem2.GetPropertyStore(
                    ShellNativeMethods.GetPropertyStoreOptions.ReadWrite,
                    ref guid,
                    out writablePropStore);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty,
                                                      Marshal.GetExceptionForHR(hr));
                }

                HResult result = writablePropStore.SetValue(ref propertyKey, propVar);

                if (!AllowSetTruncatedValue && (int)result == ShellNativeMethods.InPlaceStringTruncated)
                {
                    throw new ArgumentOutOfRangeException("propVar", LocalizedMessages.ShellPropertyValueTruncated);
                }

                if (!CoreErrorHelper.Succeeded(result))
                {
                    throw new PropertySystemException(LocalizedMessages.ShellPropertySetValue, Marshal.GetExceptionForHR((int)result));
                }

                writablePropStore.Commit();
            }
            catch (InvalidComObjectException e)
            {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty, e);
            }
            catch (InvalidCastException)
            {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty);
            }
            finally
            {
                if (writablePropStore != null)
                {
                    Marshal.ReleaseComObject(writablePropStore);
                    writablePropStore = null;
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Test if windows user account belongs to the Administrators group on this machine.
        /// Warning: This will fail if you are validating a domain user account while you
        ///          are logged in a local machine or alternate domain user account.
        ///          Use ValidateAdminCredentials() instead.
        /// </summary>
        /// <param name="username">Username may be in either UPN or SAM formats. If NULL, assumes current logged in self.</param>
        /// <returns></returns>
        private static bool IsAdministrator(string username = null)
        {
            bool isAdmin = false;

            if (username.IsNullOrEmpty())
            {
                #region Test Current User
                //http://www.davidmoore.info/blog/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/
                var identity = WindowsIdentity.GetCurrent();
                if (identity == null)
                {
                    throw new InvalidOperationException("Couldn't get the current user identity");
                }
                var principal = new WindowsPrincipal(identity);

                // Check if this user has the Administrator role. If they do, return immediately.
                // If UAC is on, and the process is not elevated, then this will actually return false.
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    return(true);
                }

                // If we're not running in Vista onwards, we don't have to worry about checking for UAC.
                if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6)
                {
                    // Operating system does not support UAC; skipping elevation check.
                    return(false);
                }

                int    tokenInfLength   = Marshal.SizeOf(typeof(int));
                IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength);

                try
                {
                    var token  = identity.Token;
                    var result = GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

                    if (!result)
                    {
                        var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                        throw new InvalidOperationException("Couldn't get token information", exception);
                    }

                    var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);

                    switch (elevationType)
                    {
                    case TokenElevationType.TokenElevationTypeDefault:
                        // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
                        return(false);

                    case TokenElevationType.TokenElevationTypeFull:
                        // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
                        return(true);

                    case TokenElevationType.TokenElevationTypeLimited:
                        // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator.
                        return(true);

                    default:
                        // Unknown token elevation type.
                        return(false);
                    }
                }
                finally
                {
                    if (tokenInformation != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(tokenInformation);
                    }
                }
                #endregion
            }

            if (username.IsNullOrEmpty())
            {
                username = WindowsIdentity.GetCurrent().Name;
            }
            else
            {
                username = FixSamAccountName(username);
            }
            try
            {
                if (username.Contains('\\'))
                {
                    PrincipalContext ctx = null;
                    UserPrincipal    up  = null;
                    var items            = username.Split('\\');
                    if (items[0].EqualsI(Dns.GetHostName()))
                    {
                        ctx     = new PrincipalContext(ContextType.Machine);
                        up      = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
                        isAdmin = up.IsMemberOf(ctx, IdentityType.Name, "Administrators");
                        return(isAdmin);
                    }
                    ctx     = new PrincipalContext(ContextType.Domain, items[0], null, ContextOptions.Negotiate, null, null);
                    up      = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
                    isAdmin = (up != null && up.IsMemberOf(new PrincipalContext(ContextType.Machine), IdentityType.Name, "Administrators"));
                    return(isAdmin);
                }

                WindowsIdentity ident = new WindowsIdentity(username);
                isAdmin = new WindowsPrincipal(ident).IsInRole(WindowsBuiltInRole.Administrator);
                return(isAdmin);
            }
            catch              //(Exception ex)
            {
                return(false); //If we get this far, then IsMemberOf() or IsInRole() failed because both require administrative privileges to execute!
                //throw ex.PrefixMessage(string.Format("IsUserAdmin(\"{0}\")", username));
            }
        }
Exemplo n.º 13
0
        int IProjectSourceNode.ExcludeFromProject()
        {
            WixProjectNode projectNode = this.ProjectMgr as WixProjectNode;

            if (projectNode == null || projectNode.IsClosed)
            {
                return((int)OleConstants.OLECMDERR_E_NOTSUPPORTED);
            }
            else if (this.IsNonMemberItem)
            {
                return(VSConstants.S_OK); // do nothing, just ignore it.
            }

            using (WixHelperMethods.NewWaitCursor())
            {
                // Check out the project file.
                if (!projectNode.QueryEditProjectFile(false))
                {
                    throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                }

                // remove children, if any, before removing from the hierarchy
                for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling)
                {
                    IProjectSourceNode node = child as IProjectSourceNode;
                    if (node != null)
                    {
                        int result = node.ExcludeFromProject();
                        if (result != VSConstants.S_OK)
                        {
                            return(result);
                        }
                    }
                }

                if (projectNode != null && projectNode.ShowAllFilesEnabled && Directory.Exists(this.Url))
                {
                    string url = this.Url;
                    this.SetProperty((int)__VSHPROPID.VSHPROPID_IsNonMemberItem, true);
                    this.ItemNode.RemoveFromProjectFile();
                    this.ItemNode = new ProjectElement(this.ProjectMgr, null, true);  // now we have to create a new ItemNode to indicate that this is virtual node.
                    this.ItemNode.Rename(url);
                    this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.Url);
                    this.ReDraw(UIHierarchyElement.Icon); // we have to redraw the icon of the node as it is now not a member of the project and shoul be drawn using a different icon.
                }
                else if (this.Parent != null)             // the project node has no parentNode
                {
                    // this is important to make it non member item. otherwise, the multi-selection scenario would
                    // not work if it has any parent child relation.
                    this.SetProperty((int)__VSHPROPID.VSHPROPID_IsNonMemberItem, true);

                    // remove from the hierarchy
                    this.OnItemDeleted();
                    this.Parent.RemoveChild(this);
                    this.ItemNode.RemoveFromProjectFile();
                }

                // refresh property browser...
                WixHelperMethods.RefreshPropertyBrowser();
            }

            return(VSConstants.S_OK);
        }
Exemplo n.º 14
0
        private static IntPtr CreateSpecialFolderPidl(Environment.SpecialFolder folder)
        {
            Native.CSIDL csidl;
            switch (folder)
            {
            case Environment.SpecialFolder.MyComputer:
                csidl = Native.CSIDL.CSIDL_DRIVES;
                break;

            case Environment.SpecialFolder.MyDocuments:
                csidl = Native.CSIDL.CSIDL_PERSONAL;
                break;

            case Environment.SpecialFolder.MyMusic:
                csidl = Native.CSIDL.CSIDL_MYMUSIC;
                break;

            case Environment.SpecialFolder.MyPictures:
                csidl = Native.CSIDL.CSIDL_MYPICTURES;
                break;

            case Environment.SpecialFolder.Desktop:
                csidl = Native.CSIDL.CSIDL_DESKTOP;
                break;

            default:
                throw new NotSupportedException(string.Format("The specified SpecialFolder '{0}' is not supported.", folder));
            }

            IntPtr pidl;
            int    hResult = Native.Shell32.SHGetFolderLocation(IntPtr.Zero, csidl, IntPtr.Zero, 0, out pidl);

            if (hResult != 0)
            {
                throw new Exception(string.Format("SHGetFolderLocation failed to return the PIDL of the specified SpecialFolder '{0}'.", folder), Marshal.GetExceptionForHR(hResult));
            }
            return(pidl);
        }
Exemplo n.º 15
0
        public void HookEatTableOfModule(TDelegate newFunc)
        {
            var moduleBase = NativeApi.LoadLibrary(_moduleName);

            if (moduleBase == IntPtr.Zero)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            var imageExportDirectoryPtr = NativeApi.ImageDirectoryEntryToDataEx(
                moduleBase,
                true,
                NativeConstants.IMAGE_DIRECTORY_ENTRY_EXPORT,
                out _,
                out _);

            if (imageExportDirectoryPtr == IntPtr.Zero)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            var imageExportDirectory = Marshal.PtrToStructure <
                NativeStructs.IMAGE_EXPORT_DIRECTORY>(imageExportDirectoryPtr);

            var moduleBaseAddress = moduleBase.ToInt64();

            if (!TryFindExportNameOrdinal(imageExportDirectory, moduleBaseAddress, out var nameOrdinal, out var originalFuncRva))
            {
                throw new EntryPointNotFoundException($"Export name {_exportName} could not be found in module {_moduleName}.");
            }

            var newFuncPointer = Marshal.GetFunctionPointerForDelegate(newFunc);

            int newFuncRva = IntPtr.Size == Marshal.SizeOf <int>()
                ? newFuncPointer.ToInt32() - moduleBase.ToInt32()
                : CreateX64Trampoline(moduleBaseAddress, newFuncPointer);

            var eatFuncEntrySize = new IntPtr(Marshal.SizeOf <int>());

            var addrOfFuncAddress = new IntPtr(
                moduleBaseAddress + imageExportDirectory.AddressOfFunctions + nameOrdinal * Marshal.SizeOf <int>());

            var protectResult = NativeApi.VirtualProtect(
                addrOfFuncAddress,
                eatFuncEntrySize,
                NativeConstants.PAGE_WRITECOPY,
                out var oldProtect);

            if (!protectResult)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            Marshal.WriteInt32(addrOfFuncAddress, newFuncRva);
            GCHandle.Alloc(newFunc);

            protectResult = NativeApi.VirtualProtect(
                addrOfFuncAddress,
                eatFuncEntrySize,
                oldProtect,
                out _);

            if (!protectResult)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            OriginalFunction = Marshal.GetDelegateForFunctionPointer <TDelegate>(
                new IntPtr(moduleBaseAddress + originalFuncRva));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Copies an existing configuration name or creates a new one.
        /// </summary>
        /// <param name="name">The name of the new configuration.</param>
        /// <param name="cloneName">the name of the configuration to copy, or a null reference, indicating that AddCfgsOfCfgName should create a new configuration.</param>
        /// <param name="fPrivate">Flag indicating whether or not the new configuration is private. If fPrivate is set to true, the configuration is private. If set to false, the configuration is public. This flag can be ignored.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
        public virtual int AddCfgsOfCfgName(string name, string cloneName, int fPrivate)
        {
            // We need to QE/QS the project file
            if (!this.ProjectMgr.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // First create the condition that represent the configuration we want to clone
            string condition = (cloneName == null ? String.Empty : String.Format(CultureInfo.InvariantCulture, configString, cloneName).Trim());

            // Get all configs
            List <ProjectPropertyGroupElement> configGroup   = new List <ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
            ProjectPropertyGroupElement        configToClone = null;

            if (cloneName != null)
            {
                // Find the configuration to clone
                foreach (ProjectPropertyGroupElement currentConfig in configGroup)
                {
                    // Only care about conditional property groups
                    if (currentConfig.Condition == null || currentConfig.Condition.Length == 0)
                    {
                        continue;
                    }

                    // Skip if it isn't the group we want
                    if (String.Compare(currentConfig.Condition.Trim(), condition, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        continue;
                    }

                    configToClone = currentConfig;
                }
            }

            ProjectPropertyGroupElement newConfig = null;

            if (configToClone != null)
            {
                // Clone the configuration settings
                newConfig = this.project.ClonePropertyGroup(configToClone);
                //Will be added later with the new values to the path

                foreach (ProjectPropertyElement property in newConfig.Properties)
                {
                    if (property.Name.Equals("OutputPath", StringComparison.OrdinalIgnoreCase))
                    {
                        property.Parent.RemoveChild(property);
                    }
                }
            }
            else
            {
                // no source to clone from, lets just create a new empty config
                newConfig = this.project.BuildProject.Xml.AddPropertyGroup();
                // Get the list of property name, condition value from the config provider
                IList <KeyValuePair <KeyValuePair <string, string>, string> > propVals = this.NewConfigProperties;
                foreach (KeyValuePair <KeyValuePair <string, string>, string> data in propVals)
                {
                    KeyValuePair <string, string> propData = data.Key;
                    string value = data.Value;
                    ProjectPropertyElement newProperty = newConfig.AddProperty(propData.Key, value);
                    if (!String.IsNullOrEmpty(propData.Value))
                    {
                        newProperty.Condition = propData.Value;
                    }
                }
            }


            //add the output path
            string outputBasePath = this.ProjectMgr.OutputBaseRelativePath;

            if (outputBasePath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                outputBasePath = Path.GetDirectoryName(outputBasePath);
            }
            newConfig.AddProperty("OutputPath", Path.Combine(outputBasePath, name) + Path.DirectorySeparatorChar.ToString());

            // Set the condition that will define the new configuration
            string newCondition = String.Format(CultureInfo.InvariantCulture, configString, name);

            newConfig.Condition = newCondition;

            NotifyOnCfgNameAdded(name);
            return(VSConstants.S_OK);
        }
Exemplo n.º 17
0
        public bool Install(string path, out string errorMessage)
        {
            IntPtr manager = AdvApi32.OpenSCManager(null, null, AdvApi32.SC_MANAGER_ACCESS_MASK.SC_MANAGER_ALL_ACCESS);

            if (manager == IntPtr.Zero)
            {
                errorMessage = "OpenSCManager returned zero.";
                return(false);
            }

            IntPtr service = AdvApi32.CreateService(manager,
                                                    _id,
                                                    _id,
                                                    AdvApi32.SERVICE_ACCESS_MASK.SERVICE_ALL_ACCESS,
                                                    AdvApi32.SERVICE_TYPE.SERVICE_KERNEL_DRIVER,
                                                    AdvApi32.SERVICE_START.SERVICE_DEMAND_START,
                                                    AdvApi32.SERVICE_ERROR.SERVICE_ERROR_NORMAL,
                                                    path,
                                                    null,
                                                    null,
                                                    null,
                                                    null,
                                                    null);

            if (service == IntPtr.Zero)
            {
                if (Marshal.GetHRForLastWin32Error() == Kernel32.ERROR_SERVICE_EXISTS)
                {
                    errorMessage = "Service already exists";
                    return(false);
                }

                errorMessage = "CreateService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                AdvApi32.CloseServiceHandle(manager);
                return(false);
            }

            if (!AdvApi32.StartService(service, 0, null))
            {
                if (Marshal.GetHRForLastWin32Error() != Kernel32.ERROR_SERVICE_ALREADY_RUNNING)
                {
                    errorMessage = "StartService returned the error: " + Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()).Message;
                    AdvApi32.CloseServiceHandle(service);
                    AdvApi32.CloseServiceHandle(manager);
                    return(false);
                }
            }

            AdvApi32.CloseServiceHandle(service);
            AdvApi32.CloseServiceHandle(manager);

#if NETFRAMEWORK
            try
            {
                // restrict the driver access to system (SY) and builtin admins (BA)
                // TODO: replace with a call to IoCreateDeviceSecure in the driver
                FileSecurity fileSecurity = File.GetAccessControl(@"\\.\" + _id);
                fileSecurity.SetSecurityDescriptorSddlForm("O:BAG:SYD:(A;;FA;;;SY)(A;;FA;;;BA)");
                File.SetAccessControl(@"\\.\" + _id, fileSecurity);
            }
            catch
            { }
#endif
            errorMessage = null;
            return(true);
        }
Exemplo n.º 18
0
 public HcsException(int resultCode, string result) : base("HCS function call returned error.", Marshal.GetExceptionForHR(resultCode))
 {
     HResult      = resultCode;
     ExtendedInfo = result;
 }
Exemplo n.º 19
0
        internal string ResourceFromPri(string packageFullName, string resourceReference)
        {
            const string prefix = "ms-resource:";

            // Using OrdinalIgnoreCase since this is used internally
            if (!string.IsNullOrWhiteSpace(resourceReference) && resourceReference.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
            {
                // magic comes from @talynone
                // https://github.com/talynone/Wox.Plugin.WindowsUniversalAppLauncher/blob/master/StoreAppLauncher/Helpers/NativeApiHelper.cs#L139-L153
                string key = resourceReference.Substring(prefix.Length);
                string parsed;

                // Using Ordinal/OrdinalIgnoreCase since these are used internally
                if (key.StartsWith("//", StringComparison.Ordinal))
                {
                    parsed = prefix + key;
                }
                else if (key.StartsWith("/", StringComparison.Ordinal))
                {
                    parsed = prefix + "//" + key;
                }
                else if (key.Contains("resources", StringComparison.OrdinalIgnoreCase))
                {
                    parsed = prefix + key;
                }
                else
                {
                    parsed = prefix + "///resources/" + key;
                }

                var    outBuffer = new StringBuilder(128);
                string source    = $"@{{{packageFullName}? {parsed}}}";
                var    capacity  = (uint)outBuffer.Capacity;
                var    hResult   = NativeMethods.SHLoadIndirectString(source, outBuffer, capacity, IntPtr.Zero);
                if (hResult == Hresult.Ok)
                {
                    var loaded = outBuffer.ToString();
                    if (!string.IsNullOrEmpty(loaded))
                    {
                        return(loaded);
                    }
                    else
                    {
                        ProgramLogger.Exception($"Can't load null or empty result pri {source} in uwp location {Package.Location}", new NullReferenceException(), GetType(), Package.Location);

                        return(string.Empty);
                    }
                }
                else
                {
                    // https://github.com/Wox-launcher/Wox/issues/964
                    // known hresult 2147942522:
                    // 'Microsoft Corporation' violates pattern constraint of '\bms-resource:.{1,256}'.
                    // for
                    // Microsoft.MicrosoftOfficeHub_17.7608.23501.0_x64__8wekyb3d8bbwe: ms-resource://Microsoft.MicrosoftOfficeHub/officehubintl/AppManifest_GetOffice_Description
                    // Microsoft.BingFoodAndDrink_3.0.4.336_x64__8wekyb3d8bbwe: ms-resource:AppDescription
                    var e = Marshal.GetExceptionForHR((int)hResult);
                    ProgramLogger.Exception($"Load pri failed {source} with HResult {hResult} and location {Package.Location}", e, GetType(), Package.Location);

                    return(string.Empty);
                }
            }
            else
            {
                return(resourceReference);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Requests a synchronous data update from the sensor. The method throws an exception if the request fails.
        /// </summary>
        public void UpdateData( )
        {
            HRESULT hr = InternalUpdateData( );

            if (hr != HRESULT.S_OK)
            {
                throw new SensorPlatformException("Unable to get report from sensor", Marshal.GetExceptionForHR((int)hr));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates a list of sort column directions, as specified.
        /// </summary>
        /// <remarks>This property may not work correctly with the ExplorerBrowser control.</remarks>
        public void SortColumns(SortColumn[] value)
        {
            HResult hr = NativeSearchFolderItemFactory.SetSortColumns(value == null ? 0 : (uint)value.Length, value);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                throw new ShellException(LocalizedMessages.ShellSearchFolderUnableToSetSortColumns, Marshal.GetExceptionForHR((int)hr));
            }
        }
Exemplo n.º 22
0
        // Internal for testing.
        internal static IEnumerable <FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects(
            FusionAssemblyIdentity.IAssemblyName partialNameFilter,
            ImmutableArray <ProcessorArchitecture> architectureFilter)
        {
            IAssemblyEnum enumerator;

            FusionAssemblyIdentity.IApplicationContext applicationContext = null;

            int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero);

            if (hr == S_FALSE)
            {
                // no assembly found
                yield break;
            }
            else if (hr != S_OK)
            {
                Exception e = Marshal.GetExceptionForHR(hr);
                if (e is FileNotFoundException)
                {
                    // invalid assembly name:
                    yield break;
                }
                else if (e != null)
                {
                    throw e;
                }
                else
                {
                    // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception:
#if SCRIPTING
                    throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName);
#else
                    throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.InvalidAssemblyName);
#endif
                }
            }

            while (true)
            {
                FusionAssemblyIdentity.IAssemblyName nameObject;

                hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0);
                if (hr != 0)
                {
                    if (hr < 0)
                    {
                        Marshal.ThrowExceptionForHR(hr);
                    }

                    break;
                }

                if (!architectureFilter.IsDefault)
                {
                    var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject);
                    if (!architectureFilter.Contains(assemblyArchitecture))
                    {
                        continue;
                    }
                }

                yield return(nameObject);
            }
        }
        public IntPtr GetImageHandle(double width, double height)
        {
            var    size  = new SIZE(width, height);
            var    flags = GetFlags();
            IntPtr result;
            var    hr = this.shllItemImageFactoryInterface.GetImage(size, flags, out result);

            if (HRESULT.Failed(hr))
            {
                if (hr == 0x8004B200 && this.FormatOption == ShellItemImageFormatOptions.ThumbnailOnly)
                {
                    throw new InvalidOperationException(
                              ErrorMessages.ShellThumbnailDoesNotHaveThumbnail, Marshal.GetExceptionForHR(hr));
                }
                if (hr == 0x80040154)
                {
                    throw new NotSupportedException(ErrorMessages.ShellThumbnailNoHandler, Marshal.GetExceptionForHR(hr));
                }
                throw ShellException.FromHRESULT(hr);
            }

            return(result);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Utility function to ease the pain of calling Marshal.GetExceptionForHR(HRESULT_FROM_WIN32((ulong)GetLastError()))...
 /// </summary>
 /// <returns></returns>
 public static Exception GetExceptionForLastError()
 => Marshal.GetExceptionForHR(HRESULT_FROM_WIN32((ulong)GetLastError()));
Exemplo n.º 25
0
        int IProjectSourceNode.ExcludeFromProject()
        {
            if (ProjectMgr == null || ProjectMgr.IsClosed)
            {
                return((int)OleConstants.OLECMDERR_E_NOTSUPPORTED);
            }

            if (IsNonMemberItem)
            {
                return(VSConstants.S_OK);                // do nothing, just ignore it.
            }
            ((NemerlePackage)ProjectMgr.Package).SetWaitCursor();
            // Ask Document tracker listeners if we can remove the item.
            {             // just to limit the scope.
                string   documentToRemove = GetMkDocument();
                string[] filesToBeDeleted = new[] { documentToRemove };
                VSQUERYREMOVEFILEFLAGS[] queryRemoveFlags = GetQueryRemoveFileFlags(filesToBeDeleted);
                if (!ProjectMgr.Tracker.CanRemoveItems(filesToBeDeleted, queryRemoveFlags))
                {
                    return((int)OleConstants.OLECMDERR_E_CANCELED);
                }

                // Close the document if it has a manager.
                DocumentManager manager = GetDocumentManager();
                if (manager != null)
                {
                    if (manager.Close(__FRAMECLOSE.FRAMECLOSE_PromptSave) == VSConstants.E_ABORT)
                    {
                        return(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                    }
                }

                if (!ProjectMgr.QueryEditProjectFile(false))
                {
                    throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                }
            }

            // close the document window if open.
            CloseDocumentWindow(this);

            NemerleProjectNode projectNode = ProjectMgr as NemerleProjectNode;

            if (projectNode != null && projectNode.ShowAllFilesEnabled && File.Exists(Url))
            {
                string url = Url;                 // need to store before removing the node.
                ItemNode.RemoveFromProjectFile();
                ProjectMgr.Tracker.OnItemRemoved(url, VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags);
                SetProperty((int)__VSHPROPID.VSHPROPID_IsNonMemberItem, true);         // Set it as non member item
                ItemNode = new ProjectElement(ProjectMgr, null, true);                 // now we have to set a new ItemNode to indicate that this is virtual node.
                ItemNode.Rename(url);
                ItemNode.SetMetadata(ProjectFileConstants.Name, url);

                //ProjectMgr.OnItemDeleted();
                var proj = ProjectInfo.FindProject(ProjectMgr);
                if (proj != null)
                {
                    proj.RemoveSource(this.Url);
                }

                ReDraw(UIHierarchyElement.Icon);     // We have to redraw the icon of the node as it is now not a member of the project and should be drawn using a different icon.
                ReDraw(UIHierarchyElement.SccState); // update the SCC state icon.
            }
            else if (Parent != null)                 // the project node has no parentNode
            {
                // Remove from the Hierarchy
                OnItemDeleted();
                Parent.RemoveChild(this);
                ItemNode.RemoveFromProjectFile();
            }

            ResetProperties();

            HierarchyHelpers.RefreshPropertyBrowser(this);

            return(VSConstants.S_OK);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Gets called to rename the eventually running document this hierarchyitem points to
        /// </summary>
        /// returns FALSE if the doc can not be renamed
        internal bool RenameDocument(string oldName, string newName)
        {
            IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (pRDT == null)
            {
                return(false);
            }
            IntPtr       docData = IntPtr.Zero;
            IVsHierarchy pIVsHierarchy;
            uint         itemId;
            uint         uiVsDocCookie;

            SuspendFileChanges sfc = null;

            if (File.Exists(oldName))
            {
                sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
                sfc.Suspend();
            }

            try
            {
                // Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished.
                // Scenario that could fail if we do not suspend.
                // We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.)
                // 1. User renames a file in  the above project sytem relying on MPF
                // 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file.
                // 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded.
                //    The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process.
                //    The result is that the project re-evaluates itself wrongly.
                VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
                ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));

                if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr))
                {
                    // Don't rename it if it wasn't opened by us.
                    return(false);
                }

                // ask other potentially running packages
                if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
                {
                    return(false);
                }

                if (IsFileOnDisk(oldName))
                {
                    RenameInStorage(oldName, newName);
                }

                if (!CommonUtils.IsSamePath(oldName, newName))
                {
                    // Check out the project file if necessary.
                    if (!this.ProjectMgr.QueryEditProjectFile(false))
                    {
                        throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                    }

                    this.RenameFileNode(oldName, newName);
                }
                else
                {
                    this.RenameCaseOnlyChange(oldName, newName);
                }

                DocumentManager.UpdateCaption(this.ProjectMgr.Site, Caption, docData);

                // changed from MPFProj:
                // http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=8231
                this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
            }
            finally
            {
                if (sfc != null)
                {
                    sfc.Resume();
                }
                if (docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                }
            }

            return(true);
        }
Exemplo n.º 27
0
 private static void ThrowLastWin32Error(string message)
 {
     throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
 }
Exemplo n.º 28
0
        private static int CreateX64Trampoline(long moduleBaseAddress, IntPtr newFuncPointer)
        {
            var memoryInfoStructSize = Marshal.SizeOf <NativeStructs.MEMORY_BASIC_INFORMATION64>();
            var memoryInfoStructPtr  = Marshal.AllocHGlobal(memoryInfoStructSize);

            var trampolineAddress = IntPtr.Zero;
            var trampoline        = GetTrampolineInstructions(newFuncPointer);

            var memoryRegionSize = new IntPtr(TrampolineMemoryRegionSize);

            var tryMemoryBlock = moduleBaseAddress;
            var tryMemoryBound = moduleBaseAddress + uint.MaxValue;

            do
            {
                tryMemoryBlock += TrampolineMemoryRegionSize;

                var memoryBlockPtr = new IntPtr(tryMemoryBlock);

                var structSize = NativeApi.VirtualQuery(
                    memoryBlockPtr,
                    memoryInfoStructPtr,
                    new IntPtr(memoryInfoStructSize));

                if (structSize == IntPtr.Zero)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                var memoryInfo = Marshal.PtrToStructure <
                    NativeStructs.MEMORY_BASIC_INFORMATION64>(memoryInfoStructPtr);

                if (memoryInfo.State == NativeConstants.MEM_FREE &&
                    memoryInfo.RegionSize >= TrampolineMemoryRegionSize)
                {
                    trampolineAddress = NativeApi.VirtualAlloc(
                        memoryBlockPtr,
                        memoryRegionSize,
                        NativeConstants.MEM_COMMIT | NativeConstants.MEM_RESERVE,
                        NativeConstants.PAGE_EXECUTE_READWRITE);
                }
            }while (trampolineAddress == IntPtr.Zero && tryMemoryBlock <= tryMemoryBound);

            Marshal.FreeHGlobal(memoryInfoStructPtr);

            if (trampolineAddress == IntPtr.Zero)
            {
                throw new InvalidOperationException("Failed to allocate space for trampoline.");
            }

            Marshal.Copy(trampoline, 0, trampolineAddress, trampoline.Length);
            int newFuncRva = unchecked ((int)(trampolineAddress.ToInt64() - moduleBaseAddress));

            var protectResult = NativeApi.VirtualProtect(
                trampolineAddress,
                memoryRegionSize,
                NativeConstants.PAGE_EXECUTE_READ,
                out _);

            if (!protectResult)
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            var processHandle = Process.GetCurrentProcess().Handle;

            NativeApi.FlushInstructionCache(processHandle, trampolineAddress, memoryRegionSize);

            return(newFuncRva);
        }
Exemplo n.º 29
0
        int NativeInterfaces.IFileDialogEvents.OnFileOk(NativeInterfaces.IFileDialog pfd)
        {
            int hr = NativeConstants.S_OK;

            NativeInterfaces.IShellItem shellItem = null;

            if (NativeMethods.SUCCEEDED(hr))
            {
                hr = FileSaveDialog.GetResult(out shellItem);
            }

            if (!NativeMethods.SUCCEEDED(hr))
            {
                throw Marshal.GetExceptionForHR(hr);
            }

            string pathName = null;

            try
            {
                shellItem.GetDisplayName(NativeConstants.SIGDN.SIGDN_FILESYSPATH, out pathName);
            }

            finally
            {
                if (shellItem != null)
                {
                    try
                    {
                        Marshal.ReleaseComObject(shellItem);
                    }

                    catch (Exception)
                    {
                    }

                    shellItem = null;
                }
            }

            string pathNameResolved = ResolveName(pathName);

            NativeInterfaces.IOleWindow oleWindow = (NativeInterfaces.IOleWindow)pfd;

            try
            {
                IntPtr hWnd = IntPtr.Zero;
                oleWindow.GetWindow(out hWnd);
                Win32Window win32Window = new Win32Window(hWnd, oleWindow);

                // File name/path validation
                if (hr >= 0)
                {
                    try
                    {
                        // Verify that these can be parsed correctly
                        string fileName = Path.GetFileName(pathNameResolved);
                        string dirName  = Path.GetDirectoryName(pathNameResolved);
                    }

                    catch (Exception ex)
                    {
                        if (!FileDialogUICallbacks.ShowError(win32Window, pathNameResolved, ex))
                        {
                            throw;
                        }

                        hr = NativeConstants.S_FALSE;
                    }
                }

                if (hr >= 0)
                {
                    // Overwrite existing file
                    if (!OverwritePrompt)
                    {
                        hr = NativeConstants.S_OK;
                    }
                    else if (File.Exists(pathNameResolved))
                    {
                        FileOverwriteAction action = FileDialogUICallbacks.ShowOverwritePrompt(win32Window, pathNameResolved);

                        switch (action)
                        {
                        case FileOverwriteAction.Cancel:
                            hr = NativeConstants.S_FALSE;
                            break;

                        case FileOverwriteAction.Overwrite:
                            hr = NativeConstants.S_OK;
                            break;

                        default:
                            throw new InvalidEnumArgumentException();
                        }
                    }
                }
            }

            catch (Exception)
            {
            }

            finally
            {
                try
                {
                    Marshal.ReleaseComObject(oleWindow);
                }

                catch (Exception)
                {
                }

                oleWindow = null;
            }

            return(hr);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Copies an existing platform name or creates a new one.
        /// </summary>
        /// <param name="platformName">The name of the new platform.</param>
        /// <param name="clonePlatformName">The name of the platform to copy, or a null reference, indicating that AddCfgsOfPlatformName should create a new platform.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public virtual int AddCfgsOfPlatformName(string platformName, string clonePlatformName)
        {
            // We need to QE/QS the project file
            if (!this.ProjectMgr.QueryEditProjectFile(false))
            {
                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
            }

            // Get all configs
            List <ProjectPropertyGroupElement> configGroup = new List <ProjectPropertyGroupElement>(this.project.BuildProject.Xml.PropertyGroups);
            // configName -> property group
            var configToClone = new Dictionary <string, ProjectPropertyGroupElement>(StringComparer.Ordinal);


            if (clonePlatformName != null)
            {
                // Find the configuration to clone
                foreach (var currentConfig in configGroup)
                {
                    // Only care about conditional property groups
                    if (currentConfig.Condition == null || currentConfig.Condition.Length == 0)
                    {
                        continue;
                    }
                    var configCanonicalName = ConfigCanonicalName.OfCondition(currentConfig.Condition);

                    // Skip if it isn't the group we want
                    if (!configCanonicalName.MatchesPlatform(clonePlatformName))
                    {
                        continue;
                    }

                    if (!configToClone.ContainsKey(configCanonicalName.ConfigName))
                    {
                        configToClone.Add(configCanonicalName.ConfigName, currentConfig);
                    }
                }
            }


            var configNames = GetPropertiesConditionedOn(ProjectFileConstants.Configuration);

            if (configNames.Length == 0)
            {
                return(VSConstants.E_FAIL);
            }

            foreach (var configName in configNames)
            {
                // If we have any property groups to clone, and we do not have sourec for this config, skip
                if (configToClone.Count > 0 && !configToClone.ContainsKey(configName))
                {
                    continue;
                }
                var newCanonicalName = new ConfigCanonicalName(configName, platformName);

                ProjectPropertyGroupElement newConfig = null;
                if (configToClone.ContainsKey(configName))
                {
                    // Clone the configuration settings
                    newConfig = this.project.ClonePropertyGroup(configToClone[configName]);
                    foreach (ProjectPropertyElement property in newConfig.Properties)
                    {
                        if (property.Name.Equals(ProjectFileConstants.PlatformTarget, StringComparison.OrdinalIgnoreCase))
                        {
                            property.Parent.RemoveChild(property);
                        }
                    }
                }
                else
                {
                    // no source to clone from, lets just create a new empty config
                    PopulateEmptyConfig(ref newConfig);
                    this.AddOutputPath(newConfig, configName);
                }

                newConfig.AddProperty(ProjectFileConstants.PlatformTarget, newCanonicalName.PlatformTarget);

                // Set the condition that will define the new configuration
                string newCondition = newCanonicalName.ToMSBuildCondition();
                newConfig.Condition = newCondition;
            }
            NotifyOnPlatformNameAdded(platformName);
            return(VSConstants.S_OK);
        }