コード例 #1
0
        public async void Delete_WhenNotValid()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var vehicleServiceMoq = new Mock <IVehicleService>();

            vehicleServiceMoq.Setup(x => x.Delete(It.IsAny <Guid>()))
            .ReturnsAsync(() => ResultCode.BadRequest);

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new VehiclesController(vehicleServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Delete(TestVehicle().Id);

            var badRequestResult = result as BadRequestResult;

            // assert
            Assert.NotNull(badRequestResult);
        }
コード例 #2
0
        public async void Put_WhenValid()
        {
            // arrange
            var testVehicle        = TestVehicleModel();
            var errorCodeConverter = new ErrorCodeConverter();

            var vehicleServiceMoq = new Mock <IVehicleService>();

            vehicleServiceMoq.Setup(x => x.Update(It.IsAny <Vehicle>()))
            .ReturnsAsync(() => new Result <Guid>(ResultCode.Success, testVehicle.Id));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new VehiclesController(vehicleServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Put(testVehicle.Id, testVehicle);

            var okResult = result as OkObjectResult;

            // assert
            Assert.NotNull(okResult);
        }
コード例 #3
0
        public async Task <IActionResult> DeleteAsync()
        {
            RUserProfileServiceResponse result = null;

            using (IDisposable blocker = _sessionManager.BlockSessionsCreationForUser(User.Identity, true)) {
                var  username = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
                var  domain   = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);
                uint error    = NativeMethods.CredUIParseUserName(User.Identity.Name, username, username.Capacity, domain, domain.Capacity);
                if (error != 0)
                {
                    return(new ApiErrorResult(BrokerApiError.Win32Error, ErrorCodeConverter.MessageFromErrorCode((int)error)));
                }

#if DEBUG
                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMinutes(10));
#else
                CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
#endif

                string sid = ((WindowsIdentity)User.Identity).User.Value;
                result = await _userProfileManager.DeleteProfileAsync(new RUserProfileServiceRequest(username.ToString(), domain.ToString(), sid), cts.Token);
            }

            if (result.Error == 0)
            {
                return(Ok());
            }

            return(new ApiErrorResult(BrokerApiError.Win32Error, ErrorCodeConverter.MessageFromErrorCode((int)result.Error)));
        }
コード例 #4
0
        public async void GetAll_WhenFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var vehicleServiceMoq = new Mock <IVehicleService>();

            vehicleServiceMoq.Setup(x => x.GetAll())
            .ReturnsAsync(() => new Result <IEnumerable <Vehicle> >(ResultCode.Success, TestVehicles()));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            dataStructureConverterMoq.Setup(x => x.Convert(It.IsAny <string>(), It.IsAny <object>()))
            .Returns(new Dictionary <string, object>
            {
                { "vehicles", TestVehicles() }
            });

            var sut = new VehiclesController(vehicleServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();

            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary <string, object>;

            // assert
            Assert.Equal(200, okResult.StatusCode);
        }
        public async void Put_WhenNotValid()
        {
            // arrange
            var testLocation       = TestLocationModel();
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Update(It.IsAny <Location>()))
            .ReturnsAsync(() => new Result <Guid>(ResultCode.BadRequest, TestLocation().Id));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Put(testLocation.Id, testLocation);

            var badRequestResult = result as BadRequestResult;

            // assert
            Assert.NotNull(badRequestResult);
        }
        public async void Delete_WhenNotFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Delete(It.IsAny <Guid>()))
            .ReturnsAsync(() => ResultCode.NotFound);

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Delete(TestLocation().Id);

            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.NotNull(notFoundResult);
        }
        public async void Get_WhenNotFound()
        {
            // arrange
            var targetId           = Guid.NewGuid();
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Get(It.IsAny <Guid>()))
            .ReturnsAsync(() => new Result <Location>(ResultCode.NotFound));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Get(targetId);

            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.Equal(404, notFoundResult.StatusCode);
        }
        private async void GetAllVehicles_ReturnsData()
        {
            // arrange
            var locationId         = IdentifierHelper.LocationId;
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny <Guid>()))
            .ReturnsAsync(() => new Result <IEnumerable <Vehicle> >(ResultCode.Success, TestVehicles()));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            dataStructureConverterMoq.Setup(x => x.ConvertAndMap <IEnumerable <VehicleModel>, IEnumerable <Vehicle> >(It.IsAny <string>(), It.IsAny <IEnumerable <Vehicle> >()))
            .Returns(new Dictionary <string, object>
            {
                { "vehicles", VehicleModelHelper.GetMany() }
            });

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAllVehicles(locationId);

            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary <string, object>;

            // assert
            Assert.NotNull(response.Values);
        }
        public async void Post_WhenConflict()
        {
            // arrange
            var testLocation       = TestLocationModel();
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Insert(It.IsAny <Location>()))
            .ReturnsAsync(() => new Result <Guid>(ResultCode.Conflict, TestLocation().Id));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Post(testLocation);

            var conflictResult = result as StatusCodeResult;

            // assert
            Assert.Equal(409, conflictResult.StatusCode);
        }
コード例 #10
0
        public async void GetAll_WhenNotFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.GetAll())
            .ReturnsAsync(() => new Result <IEnumerable <Location> >(ResultCode.NotFound));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();

            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.NotNull(notFoundResult);
        }
コード例 #11
0
        public async void GetAll_ReturnsData()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var skuServiceMoq = new Mock<ISkuService>();
            skuServiceMoq.Setup(x => x.GetAll())
                .ReturnsAsync(() => new Result<IEnumerable<Sku>>(ResultCode.Success, TestSkus()));

            var dataStructureConverterMoq = new Mock<IDataStructureConverter>();
            dataStructureConverterMoq.Setup(x => x.ConvertAndMap<IEnumerable<SkuModel>, IEnumerable<Sku>>(It.IsAny<string>(), It.IsAny<IEnumerable<Sku>>()))
                .Returns(new Dictionary<string, object>
                        {
                            { "skus", SkuModelHelper.GetMany() }
                        });

            var sut = new SkusController(skuServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();
            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary<string, object>;

            // assert
            Assert.NotNull(response.Values);
        }
コード例 #12
0
        public async void Post_WhenValid()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Insert(It.IsAny <Location>()))
            .ReturnsAsync(() => new Result <Guid>(ResultCode.Success, TestLocation().Id));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Post(TestLocationModel());

            var createdAtRouteResult = result as CreatedAtRouteResult;

            // assert
            Assert.NotNull(createdAtRouteResult);
        }
コード例 #13
0
        public async void Get_ReturnsData()
        {
            // arrange
            var targetId           = IdentifierHelper.LocationId;
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.Get(It.IsAny <Guid>()))
            .ReturnsAsync(() => new Result <Location>(ResultCode.Success, TestLocation()));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            dataStructureConverterMoq.Setup(x => x.ConvertAndMap <LocationModel, Location>(It.IsAny <string>(), It.IsAny <Location>()))
            .Returns(new Dictionary <string, object>
            {
                { "location", TestLocation() }
            });

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.Get(targetId);

            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary <string, object>;

            // assert
            Assert.NotNull(response.Values);
        }
コード例 #14
0
        public async void GetAll_WhenFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.GetAll())
            .ReturnsAsync(() => new Result <IEnumerable <Location> >(ResultCode.Success, TestLocations()));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();

            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary <string, object>;

            // assert
            Assert.Equal(200, okResult.StatusCode);
        }
コード例 #15
0
        public async void GetAll_WhenNotFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var skuServiceMoq = new Mock<ISkuService>();
            skuServiceMoq.Setup(x => x.GetAll())
                .ReturnsAsync(() => new Result<IEnumerable<Sku>>(ResultCode.NotFound));

            var dataStructureConverterMoq = new Mock<IDataStructureConverter>();
            dataStructureConverterMoq.Setup(x => x.Convert(It.IsAny<string>(), It.IsAny<object>()))
                .Returns(new Dictionary<string, object>
                        {
                            { "skus", SkuHelper.GetMany() }
                        });

            var sut = new SkusController(skuServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();
            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.NotNull(notFoundResult);
        }
コード例 #16
0
        public async void GetAllVehicles_WithBadId()
        {
            // arrange
            var targetId           = Guid.Empty;
            var errorCodeConverter = new ErrorCodeConverter();

            var locationServiceMoq = new Mock <ILocationService>();

            locationServiceMoq.Setup(x => x.GetVehicles(It.IsAny <Guid>()))
            .ReturnsAsync(() => new Result <IEnumerable <Vehicle> >(ResultCode.Success, TestVehicles()));

            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            var sut = new LocationsController(locationServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAllVehicles(targetId);

            var badRequestResult = result as BadRequestObjectResult;

            // assert
            Assert.NotNull(badRequestResult);
        }
コード例 #17
0
        public void InternalServerError(ResultCode value)
        {
            // arrange
            var expected = StatusCodes.Status500InternalServerError;
            var sut      = new ErrorCodeConverter();

            // act
            var result      = sut.Convert(value);
            var codedResult = result as StatusCodeResult;

            // assert
            Assert.Equal(expected, codedResult.StatusCode);
        }
コード例 #18
0
        public void NotFound()
        {
            // arrange
            var payload = ResultCode.NotFound;
            var sut     = new ErrorCodeConverter();

            // act
            var result         = sut.Convert(payload);
            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.NotNull(notFoundResult);
        }
コード例 #19
0
        public void BadRequest()
        {
            // arrange
            var payload  = ResultCode.BadRequest;
            var expected = StatusCodes.Status400BadRequest;
            var sut      = new ErrorCodeConverter();

            // act
            var result         = sut.Convert(payload);
            var conflictResult = result as StatusCodeResult;

            // assert
            Assert.Equal(expected, conflictResult.StatusCode);
        }
コード例 #20
0
ファイル: Session.cs プロジェクト: jflam/RTVS
 private void StartSession()
 {
     _process.Start();
     _process.WaitForExit(250);
     if (_process.HasExited && _process.ExitCode < 0)
     {
         var message = ErrorCodeConverter.MessageFromErrorCode(_process.ExitCode);
         if (!string.IsNullOrEmpty(message))
         {
             throw new Win32Exception(message);
         }
         throw new Win32Exception(_process.ExitCode);
     }
 }
コード例 #21
0
        public void Unauthorized()
        {
            // arrange
            var payload  = ResultCode.Unauthorized;
            var expected = StatusCodes.Status401Unauthorized;
            var sut      = new ErrorCodeConverter();

            // act
            var result         = sut.Convert(payload);
            var conflictResult = result as StatusCodeResult;

            // assert
            Assert.Equal(expected, conflictResult.StatusCode);
        }
コード例 #22
0
        private Process StartBroker(ProcessStartInfo psi)
        {
            var process = _services.ProcessServices.Start(psi);

            process.WaitForExit(250);
            if (process.HasExited && process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new RHostDisconnectedException(Resources.Error_UnableToStartBrokerException.FormatInvariant(message), new Win32Exception(message));
                }
                throw new RHostDisconnectedException(Resources.Error_UnableToStartBrokerException.FormatInvariant(process.ExitCode.ToString()), new Win32Exception(process.ExitCode));
            }
            return(process);
        }
コード例 #23
0
        public async void Post_WhenNotValid()
        {
            // arrange
            var logService = new Mock <ILogService>();

            logService.Setup(x => x.Log(It.IsAny <LogEntry>()))
            .ReturnsAsync(new Result <object>(ResultCode.BadRequest));

            IErrorCodeConverter processor = new ErrorCodeConverter();

            var level   = "warning";
            var message = "test message";
            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            dataStructureConverterMoq.Setup(x => x.Map <LogEntry, LogEntryModel>(It.IsAny <LogEntryModel>()))
            .Returns(new LogEntry()
            {
                Level   = level,
                Message = message
            });

            var sut = new LogController(logService.Object, processor, dataStructureConverterMoq.Object);

            var logEntryModel = new LogEntryModel()
            {
                Level   = level,
                Message = message
            };

            // act
            var result = await sut.Post(logEntryModel);

            var badRequestResult = result as BadRequestResult;

            // assert
            Assert.NotNull(badRequestResult);
        }
コード例 #24
0
        public async void Post_PassesMessageToService()
        {
            // arrange
            var logService = new Mock <ILogService>();

            logService.Setup(x => x.Log(It.IsAny <LogEntry>()))
            .ReturnsAsync(new Result <object>(ResultCode.Success));

            IErrorCodeConverter processor = new ErrorCodeConverter();

            var level   = "warning";
            var message = "test message";
            var dataStructureConverterMoq = new Mock <IDataStructureConverter>();

            dataStructureConverterMoq.Setup(x => x.Map <LogEntry, LogEntryModel>(It.IsAny <LogEntryModel>()))
            .Returns(new LogEntry()
            {
                Level   = level,
                Message = message
            });

            var sut = new LogController(logService.Object, processor, dataStructureConverterMoq.Object);

            var logEntryModel = new LogEntryModel()
            {
                Level   = level,
                Message = message
            };

            // act
            var result = await sut.Post(logEntryModel);

            var createdResult = result as CreatedResult;

            // assert
            logService.Verify(x => x.Log(It.Is <LogEntry>(entry => entry.Message == message)));
        }
コード例 #25
0
        public void StartHost(string profilePath, string logFolder, ILogger outputLogger, LogVerbosity verbosity)
        {
            if (_hostEnd != null)
            {
                throw new InvalidOperationException("Host process is already running");
            }

            var useridentity = User as WindowsIdentity;
            // In remote broker User Identity type is always WindowsIdentity
            string suppressUI     = (useridentity == null) ? string.Empty : "--rhost-suppress-ui ";
            string isRepl         = _isInteractive ? "--rhost-interactive " : string.Empty;
            string brokerPath     = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath   = Path.Combine(brokerPath, RHostExe);
            string logFolderParam = string.IsNullOrEmpty(logFolder) ? string.Empty : Invariant($"--rhost-log-dir \"{logFolder}\"");
            string commandLine    = Invariant($"\"{rhostExePath}\" {suppressUI}{isRepl}--rhost-name \"{Id}\" {logFolderParam} --rhost-log-verbosity {(int)verbosity} {CommandLineArguments}");
            var    usernameBldr   = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
            var    domainBldr     = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);

            // Get R_HOME value
            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(Interpreter.Info.Path, shortHome, shortHome.Capacity);

            Stream stdout, stdin, stderror;
            bool   loggedOnUser = useridentity != null && WindowsIdentity.GetCurrent().User != useridentity.User;

            // build user environment block
            Win32EnvironmentBlock eb;

            if (loggedOnUser)
            {
                uint error = NativeMethods.CredUIParseUserName(User.Name, usernameBldr, usernameBldr.Capacity, domainBldr, domainBldr.Capacity);
                if (error != 0)
                {
                    _sessionLogger.LogError(Resources.Error_UserNameParse, User.Name, error);
                    throw new ArgumentException(Resources.Error_UserNameParse.FormatInvariant(User.Name, error));
                }

                string username = usernameBldr.ToString();
                string domain   = domainBldr.ToString();

                eb = CreateEnvironmentBlockForUser(useridentity, username, profilePath);
            }
            else
            {
                eb = Win32EnvironmentBlock.Create((useridentity ?? WindowsIdentity.GetCurrent()).Token);
            }

            // add additional variables to the environment block
            eb["R_HOME"] = shortHome.ToString();
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "R_HOME", eb["R_HOME"]);
            eb["PATH"] = Invariant($"{Interpreter.Info.BinPath};{Environment.GetEnvironmentVariable("PATH")}");
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "PATH", eb["PATH"]);


            _sessionLogger.LogInformation(Resources.Info_StartingRHost, Id, User.Name, commandLine);
            using (Win32NativeEnvironmentBlock nativeEnv = eb.GetNativeEnvironmentBlock()) {
                if (loggedOnUser)
                {
                    _process = Win32Process.StartProcessAsUser(useridentity, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
                else
                {
                    _process = Win32Process.StartProcessAsUser(null, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv, out stdin, out stdout, out stderror);
                }
            }

            _process.Exited += delegate(object o, Win32ProcessExitEventArgs exitState){
                _hostEnd?.Dispose();
                _hostEnd = null;
                State    = SessionState.Terminated;
                if (exitState.HasError())
                {
                    _sessionLogger.LogInformation(Resources.Error_ExitRHost, exitState.ExitCode);
                }
            };

            _process.WaitForExit(250);
            if (_process.HasExited && _process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(_process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new Win32Exception(message);
                }
                throw new Win32Exception(_process.ExitCode);
            }

            _sessionLogger.LogInformation(Resources.Info_StartedRHost, Id, User.Name);

            var hostEnd = _pipe.ConnectHost(_process.ProcessId);

            _hostEnd = hostEnd;

            ClientToHostWorker(stdin, hostEnd).DoNotWait();
            HostToClientWorker(stdout, hostEnd).DoNotWait();

            HostToClientErrorWorker(stderror, _process.ProcessId, (int processid, string errdata) => {
                outputLogger?.LogTrace(Resources.Trace_ErrorDataReceived, processid, errdata);
            }).DoNotWait();
        }
コード例 #26
0
        public IProcess StartHost(Interpreter interpreter, string profilePath, string userName, WindowsIdentity useridentity, string commandLine)
        {
            string brokerPath   = Path.GetDirectoryName(typeof(Program).Assembly.GetAssemblyPath());
            string rhostExePath = Path.Combine(brokerPath, RHostExe);

            commandLine = FormattableString.Invariant($"\"{rhostExePath}\" {commandLine}");
            var usernameBldr = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1);
            var domainBldr   = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1);

            // Get R_HOME value
            var shortHome = new StringBuilder(NativeMethods.MAX_PATH);

            NativeMethods.GetShortPathName(interpreter.Info.Path, shortHome, shortHome.Capacity);

            var loggedOnUser = useridentity != null && WindowsIdentity.GetCurrent().User != useridentity.User;

            // build user environment block
            Win32EnvironmentBlock eb;

            if (loggedOnUser)
            {
                uint error = NativeMethods.CredUIParseUserName(userName, usernameBldr, usernameBldr.Capacity, domainBldr, domainBldr.Capacity);
                if (error != 0)
                {
                    _sessionLogger.LogError(Resources.Error_UserNameParse, userName, error);
                    throw new ArgumentException(Resources.Error_UserNameParse.FormatInvariant(userName, error));
                }

                string username = usernameBldr.ToString();
                string domain   = domainBldr.ToString();

                eb = CreateEnvironmentBlockForUser(useridentity, username, profilePath);
            }
            else
            {
                eb = Win32EnvironmentBlock.Create((useridentity ?? WindowsIdentity.GetCurrent()).Token);
            }

            // add additional variables to the environment block
            eb["R_HOME"] = shortHome.ToString();
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "R_HOME", eb["R_HOME"]);
            eb["PATH"] = FormattableString.Invariant($"{interpreter.Info.BinPath};{Environment.GetEnvironmentVariable("PATH")}");
            _sessionLogger.LogTrace(Resources.Trace_EnvironmentVariable, "PATH", eb["PATH"]);

            Win32Process win32Process;

            using (Win32NativeEnvironmentBlock nativeEnv = eb.GetNativeEnvironmentBlock()) {
                if (loggedOnUser)
                {
                    win32Process = Win32Process.StartProcessAsUser(useridentity, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv);
                }
                else
                {
                    win32Process = Win32Process.StartProcessAsUser(null, rhostExePath, commandLine, Path.GetDirectoryName(rhostExePath), nativeEnv);
                }
            }

            win32Process.WaitForExit(250);
            if (win32Process.HasExited && win32Process.ExitCode < 0)
            {
                var message = ErrorCodeConverter.MessageFromErrorCode(win32Process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new Win32Exception(message);
                }
                throw new Win32Exception(win32Process.ExitCode);
            }

            return(win32Process);
        }
コード例 #27
0
        internal static CredentialHandle ReadFromCredentialManager(string authority)
        {
            if (NativeMethods.CredRead(authority, NativeMethods.CRED_TYPE.GENERIC, 0, out IntPtr creds))
            {
                return(new CredentialHandle(creds));
            }
            var error = Marshal.GetLastWin32Error();

            // if credentials were not found then continue to prompt user for credentials.
            // otherwise there was an error while reading credentials.
            if (error != NativeMethods.ERROR_NOT_FOUND)
            {
                Win32MessageBox.Show(IntPtr.Zero, Invariant($"{Resources.Error_CredReadFailed} {ErrorCodeConverter.MessageFromErrorCode(error)}"),
                                     Win32MessageBox.Flags.OkOnly | Win32MessageBox.Flags.Topmost | Win32MessageBox.Flags.TaskModal);
            }
            return(null);
        }