コード例 #1
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of MethodAccessException.");
     try
     {
         string expectValue = "HELLO";
         ArgumentException notFoundException = new ArgumentException();
         MethodAccessException myException = new MethodAccessException(expectValue, notFoundException);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("001.1", "MethodAccessException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message != expectValue)
         {
             TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue);
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("001.3", "the InnerException should return ArgumentException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #2
0
            public void StreamIdCannotBeEmptyGuid()
            {
                var expectedEx = new ArgumentException(Exceptions.ArgumentEqualToValue.FormatWith(Guid.Empty), "streamId");
                var actualEx = Assert.Throws<ArgumentException>(() => new Snapshot(Guid.Empty, 1, new Object()));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #3
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Using ctor1 to test the message property");

        try
        {
            string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            ArgumentException argumentException = new ArgumentException(randValue);
            if (argumentException.Message != randValue)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                TestLibrary.TestFramework.LogInformation("Expected: " + randValue + "; Actual: " + argumentException.Message);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
コード例 #4
0
 // Returns true if the expected result is right
 // Returns false if the expected result is wrong
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null.");
     try
     {
         string expectValue = null;
         ArgumentException dpoExpection = new ArgumentException();
         MethodAccessException myException = new MethodAccessException(expectValue, dpoExpection);
         if (myException == null)
         {
             TestLibrary.TestFramework.LogError("002.1", "MethodAccessException instance can not create correctly.");
             retVal = false;
         }
         if (myException.Message == expectValue)
         {
             TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value.");
             retVal = false;
         }
         if (!(myException.InnerException is ArgumentException))
         {
             TestLibrary.TestFramework.LogError("002.3", "the InnerException should return MethodAccessException.");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #5
0
            public void HeaderNameCannotBeReservedName(String name)
            {
                var expectedEx = new ArgumentException(Exceptions.ReservedHeaderName.FormatWith(name), nameof(name));
                var actualEx = Assert.Throws<ArgumentException>(() =>new Header(name, "value"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #6
0
            public void TrueThrowsArgumentException()
            {
                var expectedEx = new ArgumentException("Custom Message", "paramName");
                var actualEx = Assert.Throws<ArgumentException>(() => Verify.False(true, "paramName", "Custom Message"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #7
0
            public void BaseTypeNotFoundThrowsArgumentException()
            {
                var expectedEx = new ArgumentException(Exceptions.TypeDoesNotDeriveFromBase.FormatWith(typeof(Exception), typeof(Object)), "paramName");
                var actualEx = Assert.Throws<ArgumentException>(() => Verify.TypeDerivesFrom(typeof(Exception), typeof(Object), "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #8
0
ファイル: SendReceiveTest.cs プロジェクト: ChuangYang/corefx
        public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server)
        {
            using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
            {
                var cts = new CancellationTokenSource(TimeOutMilliseconds);

                string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
                        "net_WebSockets_Argument_InvalidMessageType",
                        "Close",
                        "SendAsync",
                        "Binary",
                        "Text",
                        "CloseOutputAsync");

                var expectedException = new ArgumentException(expectedInnerMessage, "messageType");
                string expectedMessage = expectedException.Message;

                Assert.Throws<ArgumentException>(() =>
                {
                    Task t = cws.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token);
                });

                Assert.Equal(WebSocketState.Open, cws.State);
            }
        }
    public void SetNext() {
        var r = new DiscardRedundantWorkThrottle();
        var ax = new ArgumentException();
        var cx = new OperationCanceledException();

        // results are propagated
        var n = 0;
        r.SetNextToAction(() => n++).AssertRanToCompletion();
        n.AssertEquals(1);
        r.SetNextToFunction(() => 2).AssertRanToCompletion().AssertEquals(2);
        r.SetNextToAsyncFunction(Tasks.RanToCompletion).AssertRanToCompletion();
        r.SetNextToAsyncFunction(() => Task.FromResult(3)).AssertRanToCompletion().AssertEquals(3);

        // faulted tasks are propagated
        r.SetNextToAsyncFunction(() => Tasks.Faulted(ax)).AssertFailed<ArgumentException>();
        r.SetNextToAsyncFunction(() => Tasks.Faulted<int>(ax)).AssertFailed<ArgumentException>();

        // cancelled tasks are propagated
        r.SetNextToAsyncFunction(Tasks.Cancelled).AssertCancelled();
        r.SetNextToAsyncFunction(Tasks.Cancelled<int>).AssertCancelled();

        // thrown cancellation exceptions indicate cancellation
        r.SetNextToAsyncFunction(() => { throw cx; }).AssertCancelled();
        r.SetNextToAsyncFunction<int>(() => { throw cx; }).AssertCancelled();
        r.SetNextToAction(() => { throw cx; }).AssertCancelled();
        r.SetNextToFunction<int>(() => { throw cx; }).AssertCancelled();

        // thrown exceptions are propagated
        r.SetNextToAsyncFunction(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToAsyncFunction<int>(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToAction(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToFunction<int>(() => { throw ax; }).AssertFailed<ArgumentException>();
    }
コード例 #10
0
        public void Constructor_throws_if_invalid_cache_type()
        {
            var exception = new ArgumentException(
                Strings.Generated_View_Type_Super_Class(typeof(object)),
                "cacheType");

            Assert.Equal(exception.Message,
                Assert.Throws<ArgumentException>(() =>
                    new DbMappingViewCacheTypeAttribute(typeof(SampleContext), typeof(object))).Message);
        }
コード例 #11
0
            public void EventTypeMustDeriveFromEvent()
            {
                // ReSharper disable NotResolvedInText
                var mapping = new ObjectEventTypeMapping();
                var expectedEx = new ArgumentException(Exceptions.TypeDoesNotDeriveFromBase.FormatWith(typeof(Event), typeof(Object)), "eventType");
                var ex = Assert.Throws<ArgumentException>(() => mapping.GetMappings(new Mock<IServiceProvider>().Object));

                Assert.Equal(expectedEx.Message, ex.Message);
                // ReSharper restore NotResolvedInText
            }
コード例 #12
0
        public void Ctor()
        {
            DecoderFallbackException ex = new DecoderFallbackException();
            Assert.Null(ex.BytesUnknown);
            Assert.Equal(default(int), ex.Index);
            Assert.Null(ex.StackTrace);
            Assert.Null(ex.InnerException);
            Assert.Equal(0, ex.Data.Count);
            ArgumentException arg = new ArgumentException();

            Assert.Equal(ex.Message, arg.Message);
        }
コード例 #13
0
        public void Cannot_create_mapping_for_non_complex_property()
        {
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var exception = 
                new ArgumentException(
                    Strings.StorageComplexPropertyMapping_OnlyComplexPropertyAllowed, 
                    "property");

            Assert.Equal(
                exception.Message,
                Assert.Throws<ArgumentException>(
                    () => new ComplexPropertyMapping(property)).Message);
        }
コード例 #14
0
	// Test the ArgumentException class.
	public void TestArgumentException()
			{
				ArgumentException e;
				ExceptionTester.CheckMain(typeof(ArgumentException),
										  unchecked((int)0x80070057));
				e = new ArgumentException();
				AssertNull("ArgumentException (1)", e.ParamName);
				e = new ArgumentException("msg");
				AssertNull("ArgumentException (2)", e.ParamName);
				e = new ArgumentException("msg", "p");
				AssertEquals("ArgumentException (3)", "p", e.ParamName);
				e = new ArgumentException("msg", "p", e);
				AssertEquals("ArgumentException (4)", "p", e.ParamName);
			}
コード例 #15
0
        public void CreateODataError_CopiesInnerExceptionInformation()
        {
            Exception innerException = new ArgumentException("innerException");
            Exception exception = new InvalidOperationException("exception", innerException);
            var error = new HttpError(exception, true);

            ODataError oDataError = error.CreateODataError();

            Assert.Equal("An error has occurred.", oDataError.Message);
            Assert.Equal("exception", oDataError.InnerError.Message);
            Assert.Equal("System.InvalidOperationException", oDataError.InnerError.TypeName);
            Assert.Equal("innerException", oDataError.InnerError.InnerError.Message);
            Assert.Equal("System.ArgumentException", oDataError.InnerError.InnerError.TypeName);
        }
コード例 #16
0
 public void CompletedCancelledFaultedTask() {
     Tasks.RanToCompletion().AssertRanToCompletion();
     Tasks.RanToCompletion(1).AssertRanToCompletion().AssertEquals(1);
     
     Tasks.Cancelled().AssertCancelled();
     Tasks.Cancelled<int>().AssertCancelled();
     
     var ex = new ArgumentException();
     
     Tasks.Faulted(ex).AssertFailed<ArgumentException>().AssertEquals(ex);
     Tasks.Faulted<int>(ex).AssertFailed<ArgumentException>().AssertEquals(ex);
     
     Tasks.Faulted(new[] { ex, ex }).AssertFailed<AggregateException>().InnerExceptions.AssertSequenceEquals(new[] { ex, ex });
     Tasks.Faulted<int>(new[] { ex, ex }).AssertFailed<AggregateException>().InnerExceptions.AssertSequenceEquals(new[] { ex, ex });
 }
コード例 #17
0
        public static void Ctor()
        {
            EncoderFallbackException ex = new EncoderFallbackException();
            Assert.Equal(default(char), ex.CharUnknown);
            Assert.Equal(default(char), ex.CharUnknownHigh);
            Assert.Equal(default(char), ex.CharUnknownLow);
            Assert.Equal(default(int), ex.Index);

            Assert.Null(ex.StackTrace);
            Assert.Null(ex.InnerException);
            Assert.Equal(0, ex.Data.Count);

            ArgumentException arg = new ArgumentException();
            Assert.Equal(arg.Message, ex.Message);
        }
コード例 #18
0
        public void Constructors_throw_if_invalid_context_type()
        {
            var cacheTypeName = typeof(SampleMappingViewCache).AssemblyQualifiedName;
            var exception = new ArgumentException(
                Strings.DbMappingViewCacheTypeAttribute_InvalidContextType(typeof(object)),
                "contextType");

            Assert.Equal(exception.Message,
                Assert.Throws<ArgumentException>(() =>
                    new DbMappingViewCacheTypeAttribute(typeof(object), typeof(SampleMappingViewCache))).Message);

            Assert.Equal(exception.Message,
                Assert.Throws<ArgumentException>(() =>
                    new DbMappingViewCacheTypeAttribute(typeof(object), cacheTypeName)).Message);
        }
コード例 #19
0
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Using ctor2 to test the message property");

        try
        {
            string randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            string paramName = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            ArgumentException argumentException = new ArgumentException(randValue, paramName);

            string expectedWindows = randValue + "\r\nParameter name: " + paramName;
            string expectedMac = randValue + "\nParameter name: " + paramName;

            if ((argumentException.Message != randValue))
            {
                if (!Utilities.IsWindows)
                {
                    if (argumentException.Message != expectedMac)
                    {
                        TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
                        TestLibrary.TestFramework.LogInformation("Expected: " + expectedMac + "; Actual: " + argumentException.Message);
                        retVal = false;
                    }
                }
                else if (argumentException.Message != expectedWindows)
                {
                    TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
                    TestLibrary.TestFramework.LogInformation("Expected: " + expectedWindows + "; Actual: " + argumentException.Message);
                    retVal = false;
                }
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
コード例 #20
0
 public bool PosTest1()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize the InvalidCastException instance with message and InnerException 1");
     try
     {
         string message = "HelloWorld";
         ArgumentException innerException = new ArgumentException();
         InvalidCastException myException = new InvalidCastException(message, innerException);
         if (myException == null || myException.Message != message || !myException.InnerException.Equals(innerException))
         {
             TestLibrary.TestFramework.LogError("001", "the InvalidCastException with message and innerException instance creating failed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #21
0
 public bool PosTest2()
 {
     bool retVal = true;
     TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize the InvalidCastException instance with message and InnerException 2");
     try
     {
         string message = null;
         ArgumentException innerException = new ArgumentException();
         InvalidCastException myException = new InvalidCastException(message, innerException);
         if (myException == null || myException.Message == null || !myException.InnerException.Equals(innerException))
         {
             TestLibrary.TestFramework.LogError("003", "Initialize the InvalidCastException instance with null message not succeed");
             retVal = false;
         }
     }
     catch (Exception e)
     {
         TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
         retVal = false;
     }
     return retVal;
 }
コード例 #22
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call ctor to construct a new instance");

        try
        {
            ArgumentException argumentException = new ArgumentException();
            if (argumentException == null)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
コード例 #23
0
    // Returns true if the expected result is right
    // Returns false if the expected result is wrong

    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new ArrayTypeMismatchException instance. ");
        try
        {
            string expectValue = "Hello";
            ArgumentException myAieldExcption = new ArgumentException();
            ArrayTypeMismatchException myException = new ArrayTypeMismatchException(expectValue, myAieldExcption);
            if (myException == null)
            {
                TestLibrary.TestFramework.LogError("001.1", " the constructor should not return  null. ");
                retVal = false;
            }
            else
            {
                if (myException.Message!=expectValue)
                {
                    TestLibrary.TestFramework.LogError("001.2", " the expection message should return " + expectValue);
                    retVal = false;
                }
                if (!(myException.InnerException is ArgumentException))
                {
                    TestLibrary.TestFramework.LogError("001.3", " the inner expection  should return  the specified exception.");
                    retVal = false;
                }
            }
           
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            retVal = false;
        }
       
        return retVal;
    }
コード例 #24
0
        /// <summary>
        /// </summary>
        protected override void BeginProcessing()
        {
            // Validate that WinRM is OK and that the user can query system state
            RemotingCommandUtil.CheckRemotingCmdletPrerequisites();
            PSSessionConfigurationCommandUtilities.ThrowIfNotAdministrator();

            // Get the configuration for the given endpoint
            Collection<PSObject> configurations = null;
            using (PowerShellApi invoker = PowerShellApi.Create(RunspaceMode.CurrentRunspace))
            {
                invoker.AddCommand("Get-PSSessionConfiguration").AddParameter("Name", this.ConfigurationName).AddParameter("ErrorAction", "Stop");

                try
                {
                    // If the session name doesn't exist, this Invoke() throws
                    configurations = invoker.Invoke();
                }
                catch (ActionPreferenceStopException e)
                {
                    ThrowTerminatingError(new ErrorRecord(e.ErrorRecord.Exception, "CouldNotFindSessionConfiguration", ErrorCategory.ObjectNotFound, this.ConfigurationName));
                }
            }

            // The validator that will be applied to the role lookup
            Func<string, bool> validator = (role) => true;

            if (!String.IsNullOrEmpty(this.Username))
            {
                if (this.Username.IndexOf("\\", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    validator = null;

                    // Convert DOMAIN\user to the upn (user@DOMAIN)
                    string[] upnComponents = this.Username.Split(Utils.Separators.Backslash);
                    if (upnComponents.Length == 2)
                    {
                        this.Username = upnComponents[1] + "@" + upnComponents[0];
                    }
                }

                try
                {
                    System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(
                        new System.Security.Principal.WindowsIdentity(this.Username));
                    validator = (role) => windowsPrincipal.IsInRole(role);
                }
                catch (SecurityException e)
                {
                    // Identity could not be mapped
                    string message = StringUtil.Format(RemotingErrorIdStrings.CouldNotResolveUsername, this.Username);
                    ArgumentException ioe = new ArgumentException(message, e);
                    ErrorRecord er = new ErrorRecord(ioe, "CouldNotResolveUsername", ErrorCategory.InvalidArgument, this.Username);
                    ThrowTerminatingError(er);
                    return;
                }
            }

            foreach (PSObject foundConfiguration in configurations)
            {
                string configFilePath = null;
                PSPropertyInfo configFilePathProperty = foundConfiguration.Properties["ConfigFilePath"];
                if (configFilePathProperty != null)
                {
                    configFilePath = configFilePathProperty.Value as string;
                }

                // If we could not get the config file, throw an error that it's not a configuration created with
                // config file-based session configurations.
                if (configFilePath == null)
                {
                    string configurationName = (string)foundConfiguration.Properties["Name"].Value;
                    string message = StringUtil.Format(RemotingErrorIdStrings.SessionConfigurationMustBeFileBased, configurationName);
                    ArgumentException ioe = new ArgumentException(message);
                    ErrorRecord er = new ErrorRecord(ioe, "SessionConfigurationMustBeFileBased", ErrorCategory.InvalidArgument, foundConfiguration);
                    WriteError(er);
                    continue;
                }

                InitialSessionState iss = InitialSessionState.CreateFromSessionConfigurationFile(configFilePath, validator);
                if (this.Full)
                {
                    WriteObject(iss);
                }
                else
                {
                    using (PowerShellApi analyzer = PowerShellApi.Create(iss))
                    {
                        analyzer.AddCommand("Get-Command").AddParameter("CommandType", "All");
                        foreach (PSObject output in analyzer.Invoke())
                        {
                            WriteObject(output);
                        }
                    }
                }
            }
        }
コード例 #25
0
            public void EmptyValueThrowsArgumentException()
            {
                var expectedEx = new ArgumentException(Exceptions.MustContainOneNonWhitespaceCharacter, "paramName");
                var actualEx = Assert.Throws<ArgumentException>(() => Verify.NotNullOrWhiteSpace(String.Empty, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #26
0
        public void LocalCryptographyClientRequiresJsonWebKey()
        {
            ArgumentException ex = Assert.Throws <ArgumentNullException>(() => new LocalCryptographyClient(null));

            Assert.AreEqual("jsonWebKey", ex.ParamName);
        }
コード例 #27
0
ファイル: ExceptionTest.cs プロジェクト: zlxy/Genesis-3D
        [Test]         // .ctor (SerializationInfo, StreamingContext)
        public void Constructor3()
        {
            SerializationInfo si;
            MyException       ex;
            Exception         inner;

            inner = new ArgumentException();
            si    = new SerializationInfo(typeof(Exception),
                                          new FormatterConverter());
            si.AddValue("ClassName", "CLASS");
            si.AddValue("Message", "MSG");
            si.AddValue("InnerException", inner, typeof(Exception));
            si.AddValue("HelpURL", "URL");
            si.AddValue("StackTraceString", null);
            si.AddValue("RemoteStackTraceString", null);
            si.AddValue("RemoteStackIndex", 0);
            si.AddValue("HResult", 10);
            si.AddValue("Source", "SRC");
            si.AddValue("ExceptionMethod", null);
            Hashtable data = new Hashtable();

            data.Add("XX", "ZZ");
            si.AddValue("Data", data, typeof(IDictionary));

            ex = new MyException(si, new StreamingContext());
            Assert.AreEqual("MSG", ex.Message, "#A1");
            Assert.AreSame(inner, ex.InnerException, "#A2");
            Assert.AreEqual("URL", ex.HelpLink, "#A3");
            Assert.AreEqual(10, ex.HResult, "#A4");
            Assert.AreEqual("SRC", ex.Source, "#A5");
#if NET_2_0
            Assert.IsNotNull(ex.Data, "#A6");
            Assert.AreEqual(1, ex.Data.Keys.Count, "#A7");
            Assert.AreEqual("ZZ", ex.Data ["XX"], "#A8");
#endif

            inner = null;
            si    = new SerializationInfo(typeof(Exception),
                                          new FormatterConverter());
            si.AddValue("ClassName", "CLASS");
            si.AddValue("Message", null);
            si.AddValue("InnerException", inner, typeof(Exception));
            si.AddValue("HelpURL", "URL");
            si.AddValue("StackTraceString", null);
            si.AddValue("RemoteStackTraceString", null);
            si.AddValue("RemoteStackIndex", 0);
            si.AddValue("HResult", 10);
            si.AddValue("Source", "SRC");
            si.AddValue("ExceptionMethod", null);

            ex = new MyException(si, new StreamingContext());
            Assert.IsNotNull(ex.Message, "#B1");
            Assert.IsTrue(ex.Message.IndexOf("CLASS") != -1, "#B2");
            Assert.IsNull(ex.InnerException, "#B3");
            Assert.AreEqual("URL", ex.HelpLink, "#B4");
            Assert.AreEqual(10, ex.HResult, "#B5");
            Assert.AreEqual("SRC", ex.Source, "#B6");
#if NET_2_0
            Assert.IsNotNull(ex.Data, "#B7");
            Assert.AreEqual(0, ex.Data.Keys.Count, "#B8");
#endif
        }
コード例 #28
0
        public ParseCommandUndo(string parameters, ParseCommandStacks stacks)
        {
            var badCommandException = new ArgumentException("command is invalid for Undo: " + parameters);

            string[]     parts           = parameters.Split(new char[] { ':' }, 3);
            int          times           = 1;
            bool         isSpecificStack = false;
            CommandTypes stackType       = CommandTypes.Invalid;

            if (parts.Length > 1)
            {
                isSpecificStack = true;

                switch (parts[1])
                {
                case "f":
                    stackType = CommandTypes.Foreground;
                    break;

                case "b":
                    stackType = CommandTypes.Background;
                    break;

                case "g":
                    stackType = CommandTypes.Glyph;
                    break;

                case "e":
                    stackType = CommandTypes.Effect;
                    break;

                case "m":
                    stackType = CommandTypes.Mirror;
                    break;

                case "a":
                    isSpecificStack = false;
                    break;

                default:
                    throw badCommandException;
                }
            }

            if (parts.Length >= 1 && parts[0] != "")
            {
                times = int.Parse(parts[0]);
            }


            for (int i = 0; i < times; i++)
            {
                ParseCommandBase behavior = null;

                if (!isSpecificStack)
                {
                    if (stacks.All.Count != 0)
                    {
                        behavior = stacks.All.Pop();

                        switch (behavior.CommandType)
                        {
                        case CommandTypes.Foreground:
                            stacks.Foreground.Pop();
                            break;

                        case CommandTypes.Background:
                            stacks.Background.Pop();
                            break;

                        case CommandTypes.Glyph:
                            stacks.Glyph.Pop();
                            break;

                        case CommandTypes.Mirror:
                            stacks.Mirror.Pop();
                            break;

                        case CommandTypes.Effect:
                            stacks.Effect.Pop();
                            break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    switch (stackType)
                    {
                    case CommandTypes.Foreground:
                        if (stacks.Foreground.Count != 0)
                        {
                            behavior = stacks.Foreground.Pop();
                        }
                        break;

                    case CommandTypes.Background:
                        if (stacks.Background.Count != 0)
                        {
                            behavior = stacks.Background.Pop();
                        }
                        break;

                    case CommandTypes.Glyph:
                        if (stacks.Glyph.Count != 0)
                        {
                            behavior = stacks.Glyph.Pop();
                        }
                        break;

                    case CommandTypes.Mirror:
                        if (stacks.Mirror.Count != 0)
                        {
                            behavior = stacks.Mirror.Pop();
                        }
                        break;

                    case CommandTypes.Effect:
                        if (stacks.Effect.Count != 0)
                        {
                            behavior = stacks.Effect.Pop();
                        }
                        break;

                    default:
                        break;
                    }

                    if (behavior != null)
                    {
                        List <ParseCommandBase> all = new List <ParseCommandBase>(stacks.All);
                        all.Remove(behavior);
                        stacks.All = new Stack <ParseCommandBase>(all);
                    }
                }
            }

            CommandType = CommandTypes.PureCommand;
        }
コード例 #29
0
        public void FromString(string str)
        {
            Dictionary <string, string> settings = new Dictionary <string, string>();

            string[] components = str.Split(',');
            foreach (string component in components)
            {
                string[] pair = component.Trim().Split('=');
                if (pair == null || pair.Length != 2)
                {
                    var e = new ArgumentException("invalid component to be used as key-value pair:", component);
                    Exceptions.Throw(e, LOGGER);
                }
                settings.Add(pair[0], pair[1]);
            }
            string ipAddress;

            if (!settings.TryGetValue("IP", out ipAddress))
            {
                Exceptions.Throw(new ArgumentException("cannot find IP entry"), LOGGER);
            }
            ipAddress = ipAddress.Split('/').Last();
            string port;

            if (!settings.TryGetValue("Port", out port))
            {
                Exceptions.Throw(new ArgumentException("cannot find Port entry"), LOGGER);
            }
            int portNumber = 0;

            int.TryParse(port, out portNumber);
            string hostName;

            if (!settings.TryGetValue("HostName", out hostName))
            {
                Exceptions.Throw(new ArgumentException("cannot find HostName entry"), LOGGER);
            }
            string memory;

            if (!settings.TryGetValue("Memory", out memory))
            {
                Exceptions.Throw(new ArgumentException("cannot find Memory entry"), LOGGER);
            }
            int memoryInMegaBytes = 0;

            int.TryParse(memory, out memoryInMegaBytes);

            string core;

            if (!settings.TryGetValue("Core", out core))
            {
                Exceptions.Throw(new ArgumentException("cannot find Core entry"), LOGGER);
            }
            int vCore = 0;

            int.TryParse(core, out vCore);

            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), portNumber);

            _nodeDescriptor = new NodeDescriptorImpl();
            _nodeDescriptor.InetSocketAddress = ipEndPoint;
            _nodeDescriptor.HostName          = hostName;
            _type        = EvaluatorType.CLR;
            _megaBytes   = memoryInMegaBytes;
            _virtualCore = vCore;
        }
コード例 #30
0
 public static void ValidateArgumentException(string parameterName, string expectedMessage, ArgumentException exception)
 {
     Assert.Equal(string.Format("{0}{1}Parameter name: {2}", expectedMessage, Environment.NewLine, parameterName), exception.Message);
 }
コード例 #31
0
ファイル: Hooks.cs プロジェクト: chessar/LongPaths
        private static CommonSecurityDescriptor CreateInternalPatched(ResourceType resourceType,
                                                                      bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections,
                                                                      bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
        {
            if (createByName && name is null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            else if (!createByName && handle is null)
            {
                throw new ArgumentNullException(nameof(handle));
            }
            Contract.EndContractBlock();

            try
            {
                object[] parameters = { resourceType, AddLongPathPrefixAndFixSeparators(name), handle, includeSections, null };
                var      error      = (int)win32GetSecurityInfo.Value.Invoke(null, parameters);

                if (error != ERROR_SUCCESS)
                {
                    Exception exception = null;

                    if (exceptionFromErrorCode != null)
                    {
                        exception = exceptionFromErrorCode(error, name, handle, exceptionContext);
                    }

                    if (exception is null)
                    {
                        if (error == ERROR_ACCESS_DENIED)
                        {
                            exception = new UnauthorizedAccessException();
                        }
                        else if (error == ERROR_INVALID_OWNER)
                        {
                            exception = new InvalidOperationException(EnvGetResString1("AccessControl_InvalidOwner"));
                        }
                        else if (error == ERROR_INVALID_PRIMARY_GROUP)
                        {
                            exception = new InvalidOperationException(EnvGetResString1("AccessControl_InvalidGroup"));
                        }
                        else if (error == ERROR_INVALID_PARAMETER)
                        {
                            exception = new InvalidOperationException(EnvGetResString2("AccessControl_UnexpectedError", error));
                        }
                        else if (error == ERROR_INVALID_NAME)
                        {
                            exception = new ArgumentException(EnvGetResString2("Argument_InvalidName"), nameof(name));
                        }
                        else if (error == ERROR_FILE_NOT_FOUND)
                        {
                            exception = (name is null ? new FileNotFoundException() : new FileNotFoundException(name));
                        }
                        else if (error == ERROR_NO_SECURITY_ON_OBJECT)
                        {
                            exception = new NotSupportedException(EnvGetResString1("AccessControl_NoAssociatedSecurity"));
                        }
                        else
                        {
                            Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error));
                            exception = new InvalidOperationException(EnvGetResString2("AccessControl_UnexpectedError", error));
                        }
                    }

                    throw exception;
                }

                var rawSD = (RawSecurityDescriptor)parameters[parameters.Length - 1];
                return((CommonSecurityDescriptor)csdCtor.Value
                       .Invoke(new object[] { isContainer, false, rawSD, true }));
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException != null)
                {
                    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                }
                throw;
            }
            catch (NullReferenceException nre)
            {
                if (win32GetSecurityInfo.Value is null)
                {
                    throw new MissingMethodException("Method 'System.Security.AccessControl.Win32.GetSecurityInfo' not found.", nre.InnerException ?? nre);
                }
                else if (csdCtor.Value is null)
                {
                    throw new MissingMethodException("Constructor 'CommonSecurityDescriptor' with 4 args not found.", nre.InnerException ?? nre);
                }
                throw;
            }
        }
コード例 #32
0
        public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server)
        {
            string closeDescription = new string('C', CloseDescriptionMaxLength + 1);

            using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
            {
                var cts = new CancellationTokenSource(TimeOutMilliseconds);

                string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
                    "net_WebSockets_InvalidCloseStatusDescription",
                    closeDescription,
                    CloseDescriptionMaxLength);
                    
                var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription");
                string expectedMessage = expectedException.Message;

                Assert.Throws<ArgumentException>(() =>
                    { Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); });

                Assert.Equal(WebSocketState.Open, cws.State);
            }
        }
コード例 #33
0
ファイル: TaskAwaiterTests.cs プロジェクト: ESgarbi/corefx
        public static void GetResult_FaultedTask_MultipleExceptions_ThrowsFirstException()
        {
            var exception = new ArgumentException("uh oh");
            var tcs = new TaskCompletionSource<string>();
            tcs.SetException(new Exception[] { exception, new InvalidOperationException("uh oh") });
            Task<string> task = tcs.Task;

            // Task.GetAwaiter and Task<T>.GetAwaiter
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.GetAwaiter().GetResult()));

            // w/ ConfigureAwait false and true
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(true).GetAwaiter().GetResult()));
        }
コード例 #34
0
        public static Exception ToIotHubClientContract(Error error)
        {
            Exception retException;

            if (error == null)
            {
                retException = new IotHubException("Unknown error.");
                return(retException);
            }

            string message = error.Description;

            string trackingId = null;

            if (error.Info != null && error.Info.TryGetValue(AmqpIoTConstants.TrackingId, out trackingId))
            {
                message = "{0}{1}{2}".FormatInvariant(message, Environment.NewLine, "Tracking Id:" + trackingId);
            }

            if (error.Condition.Equals(TimeoutError))
            {
                retException = new TimeoutException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotFound))
            {
                retException = new DeviceNotFoundException(message, (Exception)null);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotImplemented))
            {
                retException = new NotSupportedException(message);
            }
            else if (error.Condition.Equals(MessageLockLostError))
            {
                retException = new DeviceMessageLockLostException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.NotAllowed))
            {
                retException = new InvalidOperationException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.UnauthorizedAccess))
            {
                retException = new UnauthorizedException(message);
            }
            else if (error.Condition.Equals(ArgumentError))
            {
                retException = new ArgumentException(message);
            }
            else if (error.Condition.Equals(ArgumentOutOfRangeError))
            {
                retException = new ArgumentOutOfRangeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.MessageSizeExceeded))
            {
                retException = new MessageTooLargeException(message);
            }
            else if (error.Condition.Equals(AmqpErrorCode.ResourceLimitExceeded))
            {
                retException = new DeviceMaximumQueueDepthExceededException(message);
            }
            else if (error.Condition.Equals(DeviceContainerThrottled))
            {
                retException = new IotHubThrottledException(message, null);
            }
            else if (error.Condition.Equals(IotHubSuspended))
            {
                retException = new IotHubSuspendedException(message);
            }
            else
            {
                retException = new IotHubException(message);
            }

            if (trackingId != null && retException is IotHubException)
            {
                IotHubException iotHubException = (IotHubException)retException;
                iotHubException.TrackingId = trackingId;
            }
            return(retException);
        }
コード例 #35
0
        /// <summary>
        /// Remove a job from the store
        /// </summary>
        /// <param name="job">job object to remove</param>
        public override void RemoveJob(Job2 job)
        {
            if (job == null)
            {
                throw new ArgumentNullException("job");
            }
            _structuredTracer.RemoveJobStarted(job.InstanceId);

            var jobInMemory = _jobRepository.GetItem(job.InstanceId);

            if (jobInMemory == null)
            {
                // the specified job is not available in memory
                // load the job repository
                PopulateJobRepositoryIfRequired();
            }

            if (!(job is ContainerParentJob))
            {
                throw new InvalidOperationException(Resources.CannotRemoveWorkflowJobDirectly);
            }

            _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "WorkflowJobSourceAdapter: Removing Workflow job with instance id: {0}", job.InstanceId));

            Exception innerException = null;

            foreach (Job childJob in job.ChildJobs)
            {
                PSWorkflowJob workflowChildJob = childJob as PSWorkflowJob;

                if (workflowChildJob == null)
                {
                    continue;
                }

                try
                {
                    GetJobManager().RemoveJob(workflowChildJob.InstanceId);
                    _structuredTracer.JobRemoved(job.InstanceId,
                                                 childJob.InstanceId, workflowChildJob.WorkflowGuid);
                }
                catch (ArgumentException exception)
                {
                    //ignoring the error message and just logging them into ETW
                    _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                       "WorkflowJobSourceAdapter: Ignoring the exception. Exception details: {0}",
                                                       exception));
                    innerException = exception;
                    _structuredTracer.JobRemoveError(job.InstanceId,
                                                     childJob.InstanceId, workflowChildJob.WorkflowGuid,
                                                     exception.Message);
                }
            }

            // remove the container parent job from repository
            try
            {
                _jobRepository.Remove((ContainerParentJob)job);
            }
            catch (ArgumentException exception)
            {
                //ignoring the error message and just logging them into ETW
                _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture,
                                                   "WorkflowJobSourceAdapter: Ignoring the exception. Exception details: {0}",
                                                   exception));
                innerException = exception;
            }
            job.Dispose();

            // Failed to remove the job?
            if (innerException != null)
            {
                ArgumentException exc = new ArgumentException(Resources.WorkflowChildCouldNotBeRemoved, "job", innerException);
                throw exc;
            }
        }
コード例 #36
0
ファイル: CacheFetcher.cs プロジェクト: BenButzer/iFactr-Data
        /// <summary>
        /// Performs an asynchronous fetch from the cache index.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="timeoutMilliseconds">The timeout milliseconds.</param>
        public void FetchAsynch(Object parameters, int timeoutMilliseconds)
        {
            var fetchParameters = (FetchParameters)parameters;

            var request = (HttpWebRequest)WebRequest.Create(fetchParameters.CacheIndex.GetAbsouteUri(fetchParameters.CacheIndexItem));

            request.Method = "GET";
            //request.Proxy = null;

            request.AutomaticDecompression = DecompressionMethods.GZip;

            if (fetchParameters.Headers != null && fetchParameters.Headers.Any())
            {
                foreach (string key in fetchParameters.Headers.Keys)
                {
                    if (key.ToLower() == "accept")
                    {
                        request.Accept = fetchParameters.Headers[key];
                    }
                    else if (key.ToLower() == "content-type")
                    {
                        request.ContentType = fetchParameters.Headers[key];
                    }
                    else if (key.ToLower() == "host")
                    {
                        //TODO: add the URL explaining PCL incompatibility
                        Exception ex = new ArgumentException("Host header value cannot be set in PCL libraries.");
                        Device.Log.Error(ex);
                        throw ex;
                    }
                    else
                    {
                        request.Headers[key] = fetchParameters.Headers[key];
                    }
                }
            }

            RequestState state = new RequestState()
            {
                Request        = request,
                CacheFileName  = fetchParameters.CacheIndex.GetCachePath(fetchParameters.CacheIndexItem),
                CacheIndex     = fetchParameters.CacheIndex,
                CacheIndexItem = fetchParameters.CacheIndexItem,
                RelativeUri    = fetchParameters.CacheIndexItem.RelativeUri,
                BaseUri        = fetchParameters.CacheIndex.BaseUri,
                Expiration     = DateTime.UtcNow.Add(fetchParameters.DefaultExpiration),
            };

            try
            {
                // Start the asynchronous request.
                IAsyncResult result = request.BeginGetResponse(ResponseCallback, state);
                if (!_allDone.WaitOne(timeoutMilliseconds))
                {
                    try { request.Abort(); } catch (Exception) { } // .Abort() always throws exception
                    return;
                }
            }
            catch (Exception exc)
            {
                Device.Log.Error("CacheFetcher.FetchAsynch encountered exception", exc);
                _autoEvent.Set();
            }
        }
コード例 #37
0
        /// <summary>
        /// This is task which validates data
        /// Documentation: https://github.com/CommunityHiQ/Frends.Community.SecurityThreatDiagnostics
        /// Throws application exception if diagnostics find vulnerability from the payload challenge.
        /// </summary>
        /// <param name="validation">Runtime element to be diagnosted.</param>
        /// <param name="options">Options for the runtime validation.</param>
        /// <param name="cancellationToken"></param>
        /// <returns>{bool challenges for validation} </returns>
        public static SecurityThreatDiagnosticsResult ChallengeAgainstSecurityThreats(
            [PropertyTab] Validation validation,
            [PropertyTab] Options options,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            Dictionary <string, string> dictionary   = new Dictionary <string, string>();
            StringBuilder validationChallengeMessage = new StringBuilder();

            validationChallengeMessage
            .Append("Payload challenged for input validation [")
            .Append(validation.Payload)
            .Append("] \n\n");

            StringBuilder innerExceptionMessage = new StringBuilder();

            innerExceptionMessage
            .Append("Payload challenged for input validation [")
            .Append(validation.Payload)
            .Append("] \n\n");

            ConcurrentDictionary <string, SecurityRuleFilter> ruleDictionary = SecurityFilterReader.Instance;

            foreach (var entry in ruleDictionary)
            {
                ChallengeCharacterSetEncoding(validation.Payload, options);
                string base64DecodedPayload = DecodeBase64Encoding(validation.Payload);

                if (entry.Value.Rule.IsMatch(validation.Payload) ||
                    entry.Value.Rule.IsMatch(base64DecodedPayload) &&
                    options.Base64Decode)
                {
                    validationChallengeMessage
                    .Append("id [")
                    .Append(entry.Key)
                    .Append("]")
                    .Append(" contains vulnerability [")
                    .Append(entry.Value.Description)
                    .Append("], ")
                    .Append("encoded value [")
                    .Append(base64DecodedPayload)
                    .Append("]");
                    dictionary.Add(entry.Key, validationChallengeMessage.ToString());
                    innerExceptionMessage
                    .Append("id [")
                    .Append(entry.Key)
                    .Append("] ")
                    .Append("Validation pattern [")
                    .Append(entry.Value.Rule.ToString())
                    .Append("], ")
                    .Append("encoded value [")
                    .Append(base64DecodedPayload)
                    .Append("]");
                }
            }

            if (dictionary.Count > 0)
            {
                ArgumentException    argumentException    = new ArgumentException("Invalid argument information " + innerExceptionMessage.ToString());
                ApplicationException applicationException = new ApplicationException(validationChallengeMessage.ToString(), argumentException);
                throw applicationException;
            }

            SecurityThreatDiagnosticsResult securityThreatDiagnosticsResult = new SecurityThreatDiagnosticsResult();

            securityThreatDiagnosticsResult.IsValid = true;

            return(securityThreatDiagnosticsResult);
        }
コード例 #38
0
ファイル: CngProvider.cs プロジェクト: z77ma/runtime
 public CngProvider(string provider)
 {
     ArgumentException.ThrowIfNullOrEmpty(provider);
     _provider = provider;
 }
コード例 #39
0
        }//End BeginProcessing()

        #region private


        private void QuickConfigRemoting(bool serviceonly)
        {
            IWSManSession m_SessionObj = null;

            try
            {
                string   transport;
                IWSManEx wsmanObject = (IWSManEx) new WSManClass();
                m_SessionObj = (IWSManSession)wsmanObject.CreateSession(null, 0, null);
                string xpathEnabled     = string.Empty;
                string xpathText        = string.Empty;
                string xpathUpdate      = string.Empty;
                string analysisInputXml = string.Empty;
                string action           = string.Empty;
                string xpathStatus      = string.Empty;
                string xpathResult      = string.Empty;


                if (!usessl)
                {
                    transport = "http";
                }
                else
                {
                    transport = "https";
                }

                if (serviceonly)
                {
                    analysisInputXml = @"<AnalyzeService_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""></AnalyzeService_INPUT>";
                    action           = "AnalyzeService";
                }
                else
                {
                    string openAllProfiles = skipNetworkProfileCheck ? "<Force/>" : String.Empty;
                    analysisInputXml = @"<Analyze_INPUT xmlns=""http://schemas.microsoft.com/wbem/wsman/1/config/service""><Transport>" + transport + "</Transport>" + openAllProfiles + "</Analyze_INPUT>";
                    action           = "Analyze";
                }


                string      analysisOutputXml = m_SessionObj.Invoke(action, "winrm/config/service", analysisInputXml, 0);
                XmlDocument resultopxml       = new XmlDocument();
                resultopxml.LoadXml(analysisOutputXml);

                if (serviceonly)
                {
                    xpathEnabled = "/cfg:AnalyzeService_OUTPUT/cfg:RemotingEnabled";
                    xpathText    = "/cfg:AnalyzeService_OUTPUT/cfg:Results";
                    xpathUpdate  = "/cfg:AnalyzeService_OUTPUT/cfg:EnableService_INPUT";
                }
                else
                {
                    xpathEnabled = "/cfg:Analyze_OUTPUT/cfg:RemotingEnabled";
                    xpathText    = "/cfg:Analyze_OUTPUT/cfg:Results";
                    xpathUpdate  = "/cfg:Analyze_OUTPUT/cfg:EnableRemoting_INPUT";
                }



                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", "http://schemas.microsoft.com/wbem/wsman/1/config/service");
                string  enabled         = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText;
                XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source");
                string  source          = null;
                if (sourceAttribute != null)
                {
                    source = sourceAttribute.Value;
                }
                string rxml = "";
                if (enabled.Equals("true"))
                {
                    string Err_Msg = "";
                    if (serviceonly)
                    {
                        Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoServiceChangesNeeded_Message");
                    }
                    else
                    {
                        Err_Msg = WSManResourceLoader.GetResourceString("L_QuickConfigNoChangesNeeded_Message");
                    }
                    //  ArgumentException e = new ArgumentException(Err_Msg);
                    // ErrorRecord er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    //  WriteError(er);
                    WriteObject(Err_Msg);
                    return;
                }
                if (!enabled.Equals("false"))
                {
                    ArgumentException e  = new ArgumentException(WSManResourceLoader.GetResourceString("L_QuickConfig_InvalidBool_0_ErrorMessage"));
                    ErrorRecord       er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText;
                if (source != null && source.Equals("GPO"))
                {
                    String Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage");
                    Info_Msg += " " + resultAction;
                    ArgumentException e = new ArgumentException(Info_Msg);
                    WriteError(new ErrorRecord(e, "NotSpecified", ErrorCategory.NotSpecified, null));
                    return;
                }

                string inputXml = resultopxml.SelectSingleNode(xpathUpdate, nsmgr).OuterXml;
                if (resultAction.Equals("") || inputXml.Equals(""))
                {
                    ArgumentException e  = new ArgumentException(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfig_MissingUpdateXml_0_ErrorMessage"));
                    ErrorRecord       er = new ErrorRecord(e, "InvalidOperation", ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                if (serviceonly)
                {
                    action = "EnableService";
                }
                else
                {
                    action = "EnableRemoting";
                }
                rxml = m_SessionObj.Invoke(action, "winrm/config/service", inputXml, 0);
                XmlDocument finalxml = new XmlDocument();
                finalxml.LoadXml(rxml);

                if (serviceonly)
                {
                    xpathStatus = "/cfg:EnableService_OUTPUT/cfg:Status";
                    xpathResult = "/cfg:EnableService_OUTPUT/cfg:Results";
                }
                else
                {
                    xpathStatus = "/cfg:EnableRemoting_OUTPUT/cfg:Status";
                    xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results";
                }
                if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded"))
                {
                    if (serviceonly)
                    {
                        WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdatedService_Message"));
                    }
                    else
                    {
                        WriteObject(WSManResourceLoader.GetResourceString("L_QuickConfigUpdated_Message"));
                    }
                    WriteObject(finalxml.SelectSingleNode(xpathResult, nsmgr).InnerText);
                }
                else
                {
                    helper.AssertError(WSManResourceLoader.GetResourceString("L_ERR_Message") + WSManResourceLoader.GetResourceString("L_QuickConfigUpdateFailed_ErrorMessage"), false, null);
                }
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }
                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
コード例 #40
0
        private static Expression InvalidType(Type type, string message)
        {
            var ex = new ArgumentException(message, "type");

            return(Block(Throw(Constant(ex)), Constant(null, type)));
        }
コード例 #41
0
        public async override Tasks.Task RunCommand(object sender)
        {
            var engine           = (IAutomationEngineInstance)sender;
            var exceptionMessage = (string)await v_ExceptionMessage.EvaluateCode(engine);

            Exception ex;

            switch (v_ExceptionType)
            {
            case "AccessViolationException":
                ex = new AccessViolationException(exceptionMessage);
                break;

            case "ArgumentException":
                ex = new ArgumentException(exceptionMessage);
                break;

            case "ArgumentNullException":
                ex = new ArgumentNullException(exceptionMessage);
                break;

            case "ArgumentOutOfRangeException":
                ex = new ArgumentOutOfRangeException(exceptionMessage);
                break;

            case "DivideByZeroException":
                ex = new DivideByZeroException(exceptionMessage);
                break;

            case "Exception":
                ex = new Exception(exceptionMessage);
                break;

            case "FileNotFoundException":
                ex = new FileNotFoundException(exceptionMessage);
                break;

            case "FormatException":
                ex = new FormatException(exceptionMessage);
                break;

            case "IndexOutOfRangeException":
                ex = new IndexOutOfRangeException(exceptionMessage);
                break;

            case "InvalidDataException":
                ex = new InvalidDataException(exceptionMessage);
                break;

            case "InvalidOperationException":
                ex = new InvalidOperationException(exceptionMessage);
                break;

            case "KeyNotFoundException":
                ex = new KeyNotFoundException(exceptionMessage);
                break;

            case "NotSupportedException":
                ex = new NotSupportedException(exceptionMessage);
                break;

            case "NullReferenceException":
                ex = new NullReferenceException(exceptionMessage);
                break;

            case "OverflowException":
                ex = new OverflowException(exceptionMessage);
                break;

            case "TimeoutException":
                ex = new TimeoutException(exceptionMessage);
                break;

            default:
                throw new NotImplementedException("Selected exception type " + v_ExceptionType + " is not implemented.");
            }
            throw ex;
        }
コード例 #42
0
        public static void ThrowsArgumentOutOfRangeException(string paramName, Action action)
        {
            ArgumentException exception = Throws <ArgumentOutOfRangeException>(action);

            Assert.AreEqual(paramName, exception.ParamName);
        }
コード例 #43
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Reports a load exception in the scrDataSource.
 /// </summary>
 /// <param name="e">The exception.</param>
 /// ------------------------------------------------------------------------------------
 void scrDataSource_LoadException(ArgumentException e)
 {
     ErrorReporter.ReportException(e, m_app.SettingsKey, m_app.SupportEmailAddress,
                                   ParentForm, false);
 }
コード例 #44
0
        public void Throw_GiveArgumentException_ThrowsArgumentException()
        {
            var argumentException = new ArgumentException();

            ExceptionManager.Throw(argumentException);
        }
コード例 #45
0
 public ValidationError(ArgumentException e) : base(e.Message)
 {
 }
コード例 #46
0
        /// <summary>
        /// Starts the transcription.
        /// </summary>
        protected override void BeginProcessing()
        {
            // If they haven't specified a path, figure out the correct output path.
            if (!_isFilenameSet)
            {
                // read the filename from $TRANSCRIPT
                object value = this.GetVariableValue("global:TRANSCRIPT", null);

                // $TRANSCRIPT is not set, so create a file name (the default: $HOME/My Documents/PowerShell_transcript.YYYYMMDDmmss.txt)
                if (value == null)
                {
                    // If they've specified an output directory, use it. Otherwise, use "My Documents"
                    if (OutputDirectory != null)
                    {
                        _outFilename   = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false);
                        _isLiteralPath = true;
                    }
                    else
                    {
                        _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath();
                    }
                }
                else
                {
                    _outFilename = (string)value;
                }
            }

            // Normalize outFilename here in case it is a relative path
            try
            {
                string effectiveFilePath = ResolveFilePath(Path, _isLiteralPath);

                if (!ShouldProcess(effectiveFilePath))
                {
                    return;
                }

                if (System.IO.File.Exists(effectiveFilePath))
                {
                    if (NoClobber && !Append)
                    {
                        string message = StringUtil.Format(TranscriptStrings.TranscriptFileExistsNoClobber,
                                                           effectiveFilePath,
                                                           "NoClobber"); // prevents localization
                        Exception   uae         = new UnauthorizedAccessException(message);
                        ErrorRecord errorRecord = new ErrorRecord(
                            uae, "NoClobber", ErrorCategory.ResourceExists, effectiveFilePath);

                        // NOTE: this call will throw
                        ThrowTerminatingError(errorRecord);
                    }

                    System.IO.FileInfo fInfo = new System.IO.FileInfo(effectiveFilePath);
                    if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                    {
                        // Save some disk write time by checking whether file is readonly..
                        if (Force)
                        {
                            // Make sure the file is not read only
                            // Note that we will not clear the ReadOnly flag later
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                        else
                        {
                            string errorMessage = string.Format(
                                System.Globalization.CultureInfo.CurrentCulture,
                                TranscriptStrings.TranscriptFileReadOnly,
                                effectiveFilePath);
                            Exception innerException = new ArgumentException(errorMessage);
                            ThrowTerminatingError(new ErrorRecord(innerException, "FileReadOnly", ErrorCategory.InvalidArgument, effectiveFilePath));
                        }
                    }

                    // If they didn't specify -Append, empty the file
                    if (!_shouldAppend)
                    {
                        System.IO.File.WriteAllText(effectiveFilePath, string.Empty);
                    }
                }

                System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                    this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
                Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), UseMinimalHeader.IsPresent);

                // ch.StartTranscribing(effectiveFilePath, Append);

                // NTRAID#Windows Out Of Band Releases-931008-2006/03/21
                // Previous behavior was to write this even if ShouldProcess
                // returned false.  Why would we want that?
                PSObject outputObject = new PSObject(
                    StringUtil.Format(TranscriptStrings.TranscriptionStarted, Path));
                outputObject.Properties.Add(new PSNoteProperty("Path", Path));
                WriteObject(outputObject);
            }
            catch (Exception e)
            {
                try
                {
                    Host.UI.StopTranscribing();
                }
                catch
                {
                }

                string errorMessage = string.Format(
                    System.Globalization.CultureInfo.CurrentCulture,
                    TranscriptStrings.CannotStartTranscription,
                    e.Message);
                ErrorRecord er = new ErrorRecord(
                    PSTraceSource.NewInvalidOperationException(e, errorMessage),
                    "CannotStartTranscription", ErrorCategory.InvalidOperation, null);
                ThrowTerminatingError(er);
            }
        }
コード例 #47
0
ファイル: ExceptionTest.cs プロジェクト: zlxy/Genesis-3D
        public void GetObjectData()
        {
            string            msg   = "MESSAGE";
            Exception         inner = new ArgumentException("whatever");
            SerializationInfo si;
            Exception         se;

            se = new Exception(msg, inner);
            si = new SerializationInfo(typeof(Exception),
                                       new FormatterConverter());
            se.GetObjectData(si, new StreamingContext());
#if NET_2_0
            Assert.AreEqual(11, si.MemberCount, "#A1");
#else
            Assert.AreEqual(10, si.MemberCount, "#A1");
#endif
            Assert.AreEqual(typeof(Exception).FullName, si.GetString("ClassName"), "#A2");
#if NET_2_0
            Assert.IsNull(si.GetValue("Data", typeof(IDictionary)), "#A3");
#endif
            Assert.AreSame(msg, si.GetString("Message"), "#A4");
            Assert.AreSame(inner, si.GetValue("InnerException", typeof(Exception)), "#A5");
            Assert.AreSame(se.HelpLink, si.GetString("HelpURL"), "#A6");
            Assert.IsNull(si.GetString("StackTraceString"), "#A7");
            Assert.IsNull(si.GetString("RemoteStackTraceString"), "#A8");
            Assert.AreEqual(0, si.GetInt32("RemoteStackIndex"), "#A9");
            Assert.AreEqual(-2146233088, si.GetInt32("HResult"), "#A10");
            Assert.IsNull(si.GetString("Source"), "#A11");
            Assert.IsNull(si.GetString("ExceptionMethod"), "#A12");

            // attempt initialization of lazy init members
#if NET_2_0
            Assert.IsNotNull(se.Data);
#endif
            Assert.IsNull(se.Source);
            Assert.IsNull(se.StackTrace);

            si = new SerializationInfo(typeof(Exception),
                                       new FormatterConverter());
            se.GetObjectData(si, new StreamingContext());
#if NET_2_0
            Assert.AreEqual(11, si.MemberCount, "#B1");
#else
            Assert.AreEqual(10, si.MemberCount, "#B1");
#endif
            Assert.AreEqual(typeof(Exception).FullName, si.GetString("ClassName"), "#B2");
#if NET_2_0
            Assert.AreSame(se.Data, si.GetValue("Data", typeof(IDictionary)), "#B3");
#endif
            Assert.AreSame(msg, si.GetString("Message"), "#B4");
            Assert.AreSame(inner, si.GetValue("InnerException", typeof(Exception)), "#B5");
            Assert.AreSame(se.HelpLink, si.GetString("HelpURL"), "#B6");
            Assert.IsNull(si.GetString("StackTraceString"), "#B7");
            Assert.IsNull(si.GetString("RemoteStackTraceString"), "#B8");
            Assert.AreEqual(0, si.GetInt32("RemoteStackIndex"), "#B9");
            Assert.AreEqual(-2146233088, si.GetInt32("HResult"), "#B10");
            Assert.IsNull(si.GetString("Source"), "#B11");
            Assert.IsNull(si.GetString("ExceptionMethod"), "#B12");

            try {
                throw new Exception(msg, inner);
            } catch (Exception ex) {
                si = new SerializationInfo(typeof(Exception),
                                           new FormatterConverter());
                ex.GetObjectData(si, new StreamingContext());
#if NET_2_0
                Assert.AreEqual(11, si.MemberCount, "#C1");
#else
                Assert.AreEqual(10, si.MemberCount, "#C1");
#endif
                Assert.AreEqual(typeof(Exception).FullName, si.GetString("ClassName"), "#C2");
#if NET_2_0
                Assert.IsNull(si.GetValue("Data", typeof(IDictionary)), "#C3");
#endif
                Assert.AreSame(msg, si.GetString("Message"), "#C4");
                Assert.AreSame(inner, si.GetValue("InnerException", typeof(Exception)), "#C5");
                Assert.AreSame(se.HelpLink, si.GetString("HelpURL"), "#C6");
                Assert.IsNotNull(si.GetString("StackTraceString"), "#C7");
                Assert.IsNull(si.GetString("RemoteStackTraceString"), "#C8");
                Assert.AreEqual(0, si.GetInt32("RemoteStackIndex"), "#C9");
                Assert.AreEqual(-2146233088, si.GetInt32("HResult"), "#C10");
                Assert.IsNotNull(si.GetString("Source"), "#C11");
                //Assert.IsNotNull (si.GetString ("ExceptionMethod"), "#C12");
            }

            try {
                throw new Exception(msg, inner);
            } catch (Exception ex) {
                // force initialization of lazy init members
#if NET_2_0
                Assert.IsNotNull(ex.Data);
#endif
                Assert.IsNotNull(ex.StackTrace);

                si = new SerializationInfo(typeof(Exception),
                                           new FormatterConverter());
                ex.GetObjectData(si, new StreamingContext());
#if NET_2_0
                Assert.AreEqual(11, si.MemberCount, "#D1");
#else
                Assert.AreEqual(10, si.MemberCount, "#D1");
#endif
                Assert.AreEqual(typeof(Exception).FullName, si.GetString("ClassName"), "#D2");
#if NET_2_0
                Assert.AreSame(ex.Data, si.GetValue("Data", typeof(IDictionary)), "#D3");
#endif
                Assert.AreSame(msg, si.GetString("Message"), "#D4");
                Assert.AreSame(inner, si.GetValue("InnerException", typeof(Exception)), "#D5");
                Assert.AreSame(ex.HelpLink, si.GetString("HelpURL"), "#D6");
                Assert.IsNotNull(si.GetString("StackTraceString"), "#D7");
                Assert.IsNull(si.GetString("RemoteStackTraceString"), "#D8");
                Assert.AreEqual(0, si.GetInt32("RemoteStackIndex"), "#D9");
                Assert.AreEqual(-2146233088, si.GetInt32("HResult"), "#D10");
                Assert.AreEqual(typeof(ExceptionTest).Assembly.GetName().Name, si.GetString("Source"), "#D11");
                //Assert.IsNotNull (si.GetString ("ExceptionMethod"), "#D12");
            }
        }
コード例 #48
0
ファイル: PathBase.cs プロジェクト: sahilmgandhi/BuildXL
 protected static bool IsIllegalCharactersInPathError(ArgumentException e)
 {
     return(e.Message.Contains(IllegalCharactersInPathErrorMessage));
 }
コード例 #49
0
 /// <summary>
 /// Errors the message argument exception
 /// </summary>
 /// <param name="functionName">Name of the function.</param>
 /// <param name="e">The e.</param>
 /// <returns>System.String.</returns>
 private static string ErrorMessage(string functionName, ArgumentException e) => $"{ClassLocation}.{functionName} - {e.Message}";
コード例 #50
0
        Prompt(string caption, string message, Collection <FieldDescription> descriptions)
        {
            // Need to implement EchoOnPrompt
            HandleThrowOnReadAndPrompt();

            if (descriptions == null)
            {
                throw PSTraceSource.NewArgumentNullException("descriptions");
            }

            if (descriptions.Count < 1)
            {
                throw PSTraceSource.NewArgumentException("descriptions",
                                                         ConsoleHostUserInterfaceStrings.PromptEmptyDescriptionsErrorTemplate, "descriptions");
            }

            // we lock here so that multiple threads won't interleave the various reads and writes here.

            lock (_instanceLock)
            {
                Dictionary <string, PSObject> results = new Dictionary <string, PSObject>();

                bool cancelInput = false;

                if (!string.IsNullOrEmpty(caption))
                {
                    // Should be a skin lookup

                    WriteLineToConsole();
                    WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption));
                }

                if (!string.IsNullOrEmpty(message))
                {
                    WriteLineToConsole(WrapToCurrentWindowWidth(message));
                }

                if (AtLeastOneHelpMessageIsPresent(descriptions))
                {
                    WriteLineToConsole(WrapToCurrentWindowWidth(ConsoleHostUserInterfaceStrings.PromptHelp));
                }

                int descIndex = -1;

                foreach (FieldDescription desc in descriptions)
                {
                    descIndex++;
                    if (desc == null)
                    {
                        throw PSTraceSource.NewArgumentException("descriptions",
                                                                 ConsoleHostUserInterfaceStrings.NullErrorTemplate,
                                                                 string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex));
                    }

                    PSObject inputPSObject = null;
                    string   fieldPrompt   = null;
                    fieldPrompt = desc.Name;

                    bool fieldEchoOnPrompt = true;

                    // FieldDescription.ParameterAssemblyFullName never returns null. But this is
                    // defense in depth.
                    if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName))
                    {
                        string paramName =
                            string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex);
                        throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName);
                    }

                    Type fieldType = InternalHostUserInterface.GetFieldType(desc);
                    if (fieldType == null)
                    {
                        if (InternalHostUserInterface.IsSecuritySensitiveType(desc.ParameterTypeName))
                        {
                            string errMsg =
                                StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptTypeLoadErrorTemplate,
                                                  desc.Name, desc.ParameterTypeFullName);
                            PromptingException e = new PromptingException(errMsg,
                                                                          null, "BadTypeName", ErrorCategory.InvalidType);
                            throw e;
                        }

                        fieldType = typeof(string);
                    }

                    if (fieldType.GetInterface(typeof(IList).FullName) != null)
                    {
                        // field is a type implementing IList
                        ArrayList inputList = new ArrayList(); // stores all converted user input before
                        // assigned to an array

                        // if the field is an array, the element type can be found; else, use Object
                        Type elementType = typeof(Object);
                        if (fieldType.IsArray)
                        {
                            elementType = fieldType.GetElementType();
                            int rank = fieldType.GetArrayRank();
                            // This check may be redundant because it doesn't seem possible to create
                            // an array of zero dimension.
                            if (rank <= 0)
                            {
                                string            msg            = StringUtil.Format(ConsoleHostUserInterfaceStrings.RankZeroArrayErrorTemplate, desc.Name);
                                ArgumentException innerException = PSTraceSource.NewArgumentException(
                                    string.Format(CultureInfo.InvariantCulture,
                                                  "descriptions[{0}].AssemblyFullName", descIndex));
                                PromptingException e = new PromptingException(msg, innerException, "ZeroRankArray", ErrorCategory.InvalidOperation);
                                throw e;
                            }
                        }

                        StringBuilder fieldPromptList = new StringBuilder(fieldPrompt);
                        // fieldPromptList = fieldPrompt + "[i] :"
                        fieldPromptList.Append("[");

                        while (true)
                        {
                            fieldPromptList.Append(
                                string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count));
                            bool   inputListEnd = false;
                            object convertedObj = null;
                            string inputString  = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message,
                                                                      desc, fieldEchoOnPrompt, true, out inputListEnd, out cancelInput, out convertedObj);

                            if (cancelInput || inputListEnd)
                            {
                                break;
                            }
                            else if (!cancelInput)
                            {
                                inputList.Add(convertedObj);
                                // Remove the indices from the prompt
                                fieldPromptList.Length = fieldPrompt.Length + 1;
                            }
                        }
                        // if cancelInput, should throw OperationCancelException?
                        if (!cancelInput)
                        {
                            object tryConvertResult = null;
                            if (LanguagePrimitives.TryConvertTo(inputList, fieldType, out tryConvertResult))
                            {
                                inputPSObject = PSObject.AsPSObject(tryConvertResult);
                            }
                            else
                            {
                                inputPSObject = PSObject.AsPSObject(inputList);
                            }
                        }
                    }
                    else
                    {
                        string printFieldPrompt = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptFieldPromptInputSeparatorTemplate,
                                                                    fieldPrompt);
                        // field is not a list
                        object convertedObj = null;
                        bool   dummy        = false;

                        PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc,
                                            fieldEchoOnPrompt, false, out dummy, out cancelInput, out convertedObj);
                        if (!cancelInput)
                        {
                            inputPSObject = PSObject.AsPSObject(convertedObj);
                        }
                    }

                    if (cancelInput)
                    {
                        s_tracer.WriteLine("Prompt canceled");
                        WriteLineToConsole();
                        results.Clear();
                        break;
                    }

                    results.Add(desc.Name, PSObject.AsPSObject(inputPSObject));
                }

                return(results);
            }
        }
コード例 #51
0
            public void EqualThrowsArgumentException()
            {
                var expectedEx = new ArgumentException(Exceptions.ArgumentEqualToValue.FormatWith(Guid.Empty), "paramName");
                var actualEx = Assert.Throws<ArgumentException>(() => Verify.NotEqual(Guid.Empty, Guid.Empty, "paramName"));

                Assert.Equal(expectedEx.Message, actualEx.Message);
            }
コード例 #52
0
        public void DuplicateEntriesThrowArgumentException()
        {
            var context = Create(
                "Target",
                "Target/runtime",
                true,
                null,
                runtimeLibraries: new[]
            {
                new RuntimeLibrary(
                    "package",
                    "DuplicatePackageName",
                    "1.2.3",
                    "HASH",
                    new [] {
                    new RuntimeAssetGroup(string.Empty, "Banana.dll"),
                    new RuntimeAssetGroup("win7-x64", "Banana.Win7-x64.dll")
                },
                    new [] {
                    new RuntimeAssetGroup(string.Empty, "runtimes\\linux\\native\\native.so"),
                    new RuntimeAssetGroup("win7-x64", "native\\Banana.Win7-x64.so")
                },
                    new [] { new ResourceAssembly("en-US\\Banana.Resource.dll", "en-US") },
                    new [] {
                    new Dependency("Fruits.Abstract.dll", "2.0.0")
                },
                    true,
                    "PackagePath",
                    "PackageHashPath",
                    "placeHolderManifest.xml"
                    ),

                new RuntimeLibrary(
                    "package",
                    "DuplicatePackageName",
                    "1.2.3",
                    "HASH",
                    new [] {
                    new RuntimeAssetGroup(string.Empty, "Banana.dll"),
                    new RuntimeAssetGroup("win7-x64", "Banana.Win7-x64.dll")
                },
                    new [] {
                    new RuntimeAssetGroup(string.Empty, "runtimes\\linux\\native\\native.so"),
                    new RuntimeAssetGroup("win7-x64", "native\\Banana.Win7-x64.so")
                },
                    new [] { new ResourceAssembly("en-US\\Banana.Resource.dll", "en-US") },
                    new [] {
                    new Dependency("Fruits.Abstract.dll", "2.0.0")
                },
                    true,
                    "PackagePath",
                    "PackageHashPath",
                    "placeHolderManifest.xml"
                    ),
            },
                runtimeGraph: new[]
            {
                new RuntimeFallbacks("win7-x64", new [] { "win6", "win5" }),
                new RuntimeFallbacks("win8-x64", new [] { "win7-x64" }),
            });

            ArgumentException ex = Assert.Throws <ArgumentException>(() => Save(context));

            Assert.Contains("DuplicatePackageName", ex.Message);
        }
コード例 #53
0
        /// <summary>
        /// Stop copy operation by CloudBlob object
        /// </summary>
        /// <param name="blob">CloudBlob object</param>
        /// <param name="copyId">Copy id</param>
        private async Task StopCopyBlob(long taskId, IStorageBlobManagement localChannel, CloudBlob blob, string copyId, bool fetchCopyIdFromBlob = false)
        {
            ValidateBlobType(blob);

            AccessCondition    accessCondition    = null;
            BlobRequestOptions abortRequestOption = RequestOptions ?? new BlobRequestOptions();

            //Set no retry to resolve the 409 conflict exception
            abortRequestOption.RetryPolicy = new NoRetry();

            if (null == blob)
            {
                throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlob).Name));
            }

            string specifiedCopyId = copyId;

            if (string.IsNullOrEmpty(specifiedCopyId) && fetchCopyIdFromBlob)
            {
                if (blob.CopyState != null)
                {
                    specifiedCopyId = blob.CopyState.CopyId;
                }
            }

            string abortCopyId = string.Empty;

            if (string.IsNullOrEmpty(specifiedCopyId) || Force)
            {
                //Make sure we use the correct copy id to abort
                //Use default retry policy for FetchBlobAttributes
                BlobRequestOptions options = RequestOptions;
                await localChannel.FetchBlobAttributesAsync(blob, accessCondition, options, OperationContext, CmdletCancellationToken);

                if (blob.CopyState == null || String.IsNullOrEmpty(blob.CopyState.CopyId))
                {
                    ArgumentException e = new ArgumentException(String.Format(Resources.CopyTaskNotFound, blob.Name, blob.Container.Name));
                    OutputStream.WriteError(taskId, e);
                }
                else
                {
                    abortCopyId = blob.CopyState.CopyId;
                }

                if (!Force)
                {
                    string confirmation = String.Format(Resources.ConfirmAbortCopyOperation, blob.Name, blob.Container.Name, abortCopyId);
                    if (!await OutputStream.ConfirmAsync(confirmation))
                    {
                        string cancelMessage = String.Format(Resources.StopCopyOperationCancelled, blob.Name, blob.Container.Name);
                        OutputStream.WriteVerbose(taskId, cancelMessage);
                    }
                }
            }
            else
            {
                abortCopyId = specifiedCopyId;
            }

            await localChannel.AbortCopyAsync(blob, abortCopyId, accessCondition, abortRequestOption, OperationContext, CmdletCancellationToken);

            string message = String.Format(Resources.StopCopyBlobSuccessfully, blob.Name, blob.Container.Name);

            OutputStream.WriteObject(taskId, message);
        }
コード例 #54
0
        public void KeyVaultKeyIdentifierNullThrows()
        {
            ArgumentException ex = Assert.Throws <ArgumentNullException>(() => new KeyVaultKeyIdentifier(null));

            Assert.AreEqual("id", ex.ParamName);
        }
コード例 #55
0
ファイル: convert-HTML.cs プロジェクト: kmahesh123/kmahesh
        /// <summary>
        ///
        /// </summary>
        protected override void BeginProcessing()
        {
            //ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here
            if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim())))
            {
                ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri"));
                ErrorRecord       er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri");
                ThrowTerminatingError(er);
            }

            _propertyMshParameterList = ProcessParameter(_property);

            if (!String.IsNullOrEmpty(_title))
            {
                WebUtility.HtmlEncode(_title);
            }

            // This first line ensures w3c validation will succeed. However we are not specifying
            // an encoding in the HTML because we don't know where the text will be written and
            // if a particular encoding will be used.

            if (!_fragment)
            {
                if (!_transitional)
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
                }
                else
                {
                    WriteObject("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
                }
                WriteObject("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
                WriteObject("<head>");
                if (_charsetSpecified)
                {
                    WriteObject("<meta charset=\"" + _charset + "\">");
                }
                if (_metaSpecified)
                {
                    List <string> useditems = new List <string>();
                    foreach (string s in _meta.Keys)
                    {
                        if (!useditems.Contains(s))
                        {
                            switch (s.ToLower())
                            {
                            case "content-type":
                            case "default-style":
                            case "x-ua-compatible":
                                WriteObject("<meta http-equiv=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            case "application-name":
                            case "author":
                            case "description":
                            case "generator":
                            case "keywords":
                            case "viewport":
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;

                            default:
                                MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
                                string            Message           = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]);
                                WarningRecord     record            = new WarningRecord(Message);
                                InvocationInfo    invocationInfo    = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo;

                                if (invocationInfo != null)
                                {
                                    record.SetInvocationInfo(invocationInfo);
                                }
                                mshCommandRuntime.WriteWarning(record);
                                WriteObject("<meta name=\"" + s + "\" content=\"" + _meta[s] + "\">");
                                break;
                            }
                            useditems.Add(s);
                        }
                    }
                }
                WriteObject(_head ?? new string[] { "<title>" + _title + "</title>" }, true);
                if (_cssuriSpecified)
                {
                    WriteObject("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _cssuri + "\" />");
                }
                WriteObject("</head><body>");
                if (_body != null)
                {
                    WriteObject(_body, true);
                }
            }
            if (_preContent != null)
            {
                WriteObject(_preContent, true);
            }
            WriteObject("<table>");
            _isTHWritten       = false;
            _propertyCollector = new StringCollection();
        }
コード例 #56
0
        public void CreateFileAndForgetEventName_WhenMemberNameIsNullOrEmpty_Throws(string memberName)
        {
            ArgumentException exception = Assert.Throws <ArgumentException>(() => TelemetryUtility.CreateFileAndForgetEventName("typeName", memberName));

            Assert.Equal("memberName", exception.ParamName);
        }
コード例 #57
0
ファイル: TaskAwaiterTests.cs プロジェクト: ESgarbi/corefx
        public static void GetResult_FaultedTask_OneException_ThrowsOriginalException()
        {
            var exception = new ArgumentException("uh oh");
            Task<string> task = Task.FromException<string>(exception);

            // Task.GetAwaiter and Task<T>.GetAwaiter
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.GetAwaiter().GetResult()));

            // w/ ConfigureAwait false and true
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult()));
            Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(true).GetAwaiter().GetResult()));
        }
コード例 #58
0
        private void ProcessExpandParameter(PSObject inputObject, List <PSNoteProperty> matchedProperties)
        {
            // expand parameter is used
            // expand the property value from the inputobject
            object propValue = null;

            try
            {
                propValue = GetPropValue(inputObject, expand);
            }
            catch (Exception e)
            {
                WriteNonTerminatingError(expand, "PropertyAccessException",
                                         e, ErrorCategory.InvalidData);

                return;
            }

            if (null == propValue)
            {
                string message = string.Format(CultureInfo.CurrentCulture, GetErrorMessage(PROPERTYNOTFOUND),
                                               expand);

                Exception e = new ArgumentException(message);
                WriteNonTerminatingError(expand, "PropertyNotFound",
                                         e, ErrorCategory.InvalidData);

                return;
            }

            // Expand prop value using a Enumerator
            System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(propValue);
            if (results == null)
            {
                string message = string.Format(CultureInfo.CurrentCulture, GetErrorMessage(NOTHINGTOEXPAND),
                                               expand);

                Exception e = new ArgumentException(message);
                WriteNonTerminatingError(expand, "NothingToExpand",
                                         e, ErrorCategory.InvalidArgument);

                return;
            }

            foreach (object expandedValue in results)
            {
                if (expandedValue == null)
                {
                    WriteVerbose("One of the expanded values is null");
                    continue;
                }

                PSObject expandedObject = PSObject.AsPSObject(expandedValue);
                foreach (PSNoteProperty noteProperty in matchedProperties)
                {
                    try
                    {
                        if (expandedObject.Properties[noteProperty.Name] != null)
                        {
                            WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject);
                        }
                        else
                        {
                            expandedObject.Properties.Add(noteProperty);
                        }
                    }
                    catch (ExtendedTypeSystemException)
                    {
                        WriteAlreadyExistingPropertyError(noteProperty.Name, inputObject);
                    }
                }

                SendToOutputPipe(expandedObject, matchedProperties);
            }
        }
コード例 #59
0
        /// <summary>
        /// Computes and returns the supported command type given a stipulated command type and command object.
        /// </summary>
        /// <remarks>
        /// If the returned type does not match the stipulated type,
        /// a warning event is raised on the given command object. 
        /// </remarks>
        /// <param name="commandType">Type of the command.</param>
        /// <param name="command">The command.</param>
        /// <returns>the supported command type</returns>
        private static CommandType ToSupportedCommandType(CommandType commandType, HsqlCommand command)
        {
            switch (commandType)
            {
                case CommandType.StoredProcedure:
                case CommandType.TableDirect:
                case CommandType.Text:
                    {
                        return commandType;
                    }
                default:
                    {
                        ArgumentException ex = new ArgumentException(
                            "commandType", string.Format(
                            "[{0}] is not a valid command type", commandType));
                        HsqlDataSourceException hex = new HsqlDataSourceException("Warning.", ex);

                        command.OnWarning(new HsqlWarningEventArgs(hex));

                        return CommandType.Text;
                    }
            }
        }
コード例 #60
0
        internal static Exception MakeException(SpotCamReturnCode returnCode, bool treatWarningAsError = false)
        {
            if (SpotCamReturnCode.Success == returnCode || (!treatWarningAsError && returnCode < 0))
            {
                return(null);
            }
            Exception exception = null;

            switch (returnCode)
            {
            case SpotCamReturnCode.WarnServiceConfigurationUnknown:
                break;

            case SpotCamReturnCode.WarnColorLibNotLoaded:
                break;

            case SpotCamReturnCode.WarnInvalidOutputIcc:
                break;

            case SpotCamReturnCode.WarnInvalidInputIcc:
                break;

            case SpotCamReturnCode.WarnUnsupportedCameraFeatures:
                break;

            case SpotCamReturnCode.Abort:
                exception = new OperationCanceledException();
                break;

            case SpotCamReturnCode.ErrorOutOfMemory:
                exception = new OutOfMemoryException();
                break;

            case SpotCamReturnCode.ErrorExposureTooShort:
                break;

            case SpotCamReturnCode.ErrorExposureTooLong:
                break;

            case SpotCamReturnCode.ErrorNoCameraResponse:
                break;

            case SpotCamReturnCode.ErrorValueOutOfRange:
                break;

            case SpotCamReturnCode.ErrorInvalidParam:
                exception = new ArgumentException("The SpotCam parameter is not valid");
                break;

            case SpotCamReturnCode.ErrorDriverNotInitialized:
                break;

            case SpotCamReturnCode.ErrorRegistryQuery:
                break;

            case SpotCamReturnCode.ErrorRegistrySet:
                break;

            case SpotCamReturnCode.ErrorDeviveDriverLoad:
                break;

            case SpotCamReturnCode.ErrorCameraError:
                break;

            case SpotCamReturnCode.ErrorDriverAlreadyInit:
                break;

            case SpotCamReturnCode.ErrorDmaSetup:
                break;

            case SpotCamReturnCode.ErrorReadingCameraInfo:
                break;

            case SpotCamReturnCode.ErrorNotCapable:
                break;

            case SpotCamReturnCode.ErrorColorFilterNotIn:
                break;

            case SpotCamReturnCode.ErrorColorFilterNotOut:
                break;

            case SpotCamReturnCode.ErrorCameraBusy:
                break;

            case SpotCamReturnCode.ErrorCameraNotSupported:
                break;

            case SpotCamReturnCode.ErrorNoImageAvailable:
                break;

            case SpotCamReturnCode.ErrorFileOpen:
                break;

            case SpotCamReturnCode.ErrorFlatfieldIncompatible:
                break;

            case SpotCamReturnCode.ErrorNoDevicesFound:
                break;

            case SpotCamReturnCode.ErrorBrightnessChanged:
                break;

            case SpotCamReturnCode.ErrorCameraAndCardIncompatible:
                break;

            case SpotCamReturnCode.ErrorBiasFrameIncompatible:
                break;

            case SpotCamReturnCode.ErrorBackgroundImageIncompatible:
                break;

            case SpotCamReturnCode.ErrorBackgroundTooBright:
                break;

            case SpotCamReturnCode.ErrorInvalidFile:
                break;

            case SpotCamReturnCode.ErrorMisc:
                break;

            case SpotCamReturnCode.ErrorImageTooBright:
                break;

            case SpotCamReturnCode.ErrorNothingToDo:
                break;

            case SpotCamReturnCode.ErrorNoCameraPower:
                break;

            case SpotCamReturnCode.ErrorInsuf1394IsocBandwidth:
                break;

            case SpotCamReturnCode.ErrorInsuf1394IsocResources:
                break;

            case SpotCamReturnCode.ErrorNo1394IsocChannel:
                break;

            case SpotCamReturnCode.ErrorUsbVersionLowerThan2:
                break;

            case SpotCamReturnCode.ErrorStartupAlreadyDone:
                break;

            case SpotCamReturnCode.ErrorStartupNotDone:
                break;

            case SpotCamReturnCode.ErrorSpotcamServiceNotFound:
                break;

            case SpotCamReturnCode.ErrorWrongSpotcamServiceVersion:
                break;

            case SpotCamReturnCode.ErrorOperationNotSupported:
                break;

            case SpotCamReturnCode.ErrorServiceConfigurationFileError:
                break;

            case SpotCamReturnCode.ErrorServiceConfigurationSyntaxError:
                break;

            case SpotCamReturnCode.ErrorServiceConfigurationInvalid:
                break;

            default:
                break;
            }
            if (null == exception)
            {
                exception = new Exception(String.Format("SpotCam error {0}", returnCode));
            }
            return(exception);
        }