当前位置: 首页>>代码示例>>C#>>正文


C# System.ArgumentException类代码示例

本文整理汇总了C#中System.ArgumentException的典型用法代码示例。如果您正苦于以下问题:C# ArgumentException类的具体用法?C# ArgumentException怎么用?C# ArgumentException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ArgumentException类属于System命名空间,在下文中一共展示了ArgumentException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UnzipDatabase

 public string UnzipDatabase(string zipFilePath, string sharedFolderPath)
 {
     var tmpDir = PathUtils.PrepareDirectory(sharedFolderPath, PathUtils.GetFileName(Path.GetRandomFileName()));
     _log.InfoFormat("Unzip DB to {0}", tmpDir);
     using (var zipFile = new ZipFile(zipFilePath)) {
         var db = zipFile.SelectEntries("name = *.bak", "db").FirstOrDefault();
         if (db == null) {
             var ex = new ArgumentException("zipFilePath");
             _log.ErrorFormat("Can't find database backup in zip file: {0}", zipFilePath);
             _log.Error(ex);
             throw ex;
         }
         _log.InfoFormat("Extracting database to {0}", tmpDir);
         try {
             db.Extract(tmpDir, ExtractExistingFileAction.OverwriteSilently);
         }
         catch (Exception ex) {
             _log.Error(ex);
             throw;
         }
         var extractedFile = Directory.EnumerateFiles(tmpDir, "*.bak", SearchOption.AllDirectories).FirstOrDefault();
         if (extractedFile == null) {
             var ex = new Exception("zipFilePath");
             _log.ErrorFormat("Can't find extracted database backup in : {0}", tmpDir);
             _log.Error(ex);
             throw ex;
         }
         _log.DebugFormat("Backup found: {0}", extractedFile);
         return extractedFile;
     }
 }
开发者ID:vadimart92,项目名称:TeamCityTools,代码行数:31,代码来源:ZipUtils.cs

示例2: DoProcessing

        protected override void DoProcessing()
        {
            using (ServerManager serverManager = new ServerManager())
            {
                ServerManagerWrapper serverManagerWrapper = new ServerManagerWrapper(serverManager, this.SiteName, this.VirtualPath);
                PHPConfigHelper configHelper = new PHPConfigHelper(serverManagerWrapper);
                PHPIniFile phpIniFile = configHelper.GetPHPIniFile();

                PHPIniSetting setting = Helper.FindSetting(phpIniFile.Settings, Name);
                if (setting == null)
                {
                    if (ShouldProcess(Name))
                    {
                        RemoteObjectCollection<PHPIniSetting> settings = new RemoteObjectCollection<PHPIniSetting>();
                        settings.Add(new PHPIniSetting(Name, Value, Section));
                        configHelper.AddOrUpdatePHPIniSettings(settings);
                    }
                }
                else
                {
                    ArgumentException ex = new ArgumentException(String.Format(Resources.SettingAlreadyExistsError, Name));
                    ReportNonTerminatingError(ex, "InvalidArgument", ErrorCategory.InvalidArgument);
                }
            }
        }
开发者ID:modulexcite,项目名称:PHPManager,代码行数:25,代码来源:NewPHPSettingCmdlet.cs

示例3: ClearHistoryByCmdLine

 private void ClearHistoryByCmdLine()
 {
     if (this._countParamterSpecified && (this.Count < 0))
     {
         Exception exception = new ArgumentException(StringUtil.Format(HistoryStrings.InvalidCountValue, new object[0]));
         base.ThrowTerminatingError(new ErrorRecord(exception, "ClearHistoryInvalidCountValue", ErrorCategory.InvalidArgument, this._count));
     }
     if (this._commandline != null)
     {
         if (!this._countParamterSpecified)
         {
             foreach (string str in this._commandline)
             {
                 this.ClearHistoryEntries(0L, 1, str, this._newest);
             }
         }
         else if (this._commandline.Length > 1)
         {
             Exception exception2 = new ArgumentException(StringUtil.Format(HistoryStrings.NoCountWithMultipleCmdLine, new object[0]));
             base.ThrowTerminatingError(new ErrorRecord(exception2, "NoCountWithMultipleCmdLine ", ErrorCategory.InvalidArgument, this._commandline));
         }
         else
         {
             this.ClearHistoryEntries(0L, this._count, this._commandline[0], this._newest);
         }
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:27,代码来源:ClearHistoryCommand.cs

示例4: ProcessRecord

        protected override void ProcessRecord()
        {
            if (!this.CheckFileExists(this.Filename))
            {
                return;
            }

            this.WriteVerbose("Loading {0} as xml", this.Filename);
            var xmldoc = SXL.XDocument.Load(this.Filename);

            var root = xmldoc.Root;
            this.WriteVerbose("Root element name ={0}", root.Name);
            if (root.Name == "directedgraph")
            {
                this.WriteVerbose("Loading as a Directed Graph");
                var dg_model = VAS.DirectedGraph.DirectedGraphBuilder.LoadFromXML(
                    this.client,
                    xmldoc);
                this.WriteObject(dg_model);               
            }
            else if (root.Name == "orgchart")
            {
                this.WriteVerbose("Loading as an Org Chart");
                var oc = VAS.OrgChart.OrgChartBuilder.LoadFromXML(this.client, xmldoc);
                this.WriteObject(oc);
            }
            else
            {
                var exc = new ArgumentException("Unknown root element for XML");
                throw exc;
            }
        }
开发者ID:shekharssorot2002,项目名称:VisioAutomation2.0,代码行数:32,代码来源:Import_VisioModel.cs

示例5: MergeIn

 public void MergeIn(ParameterParser p)
 {
     foreach (string s in p.parsers.Keys)
     {
         if (!parsers.ContainsKey(s))
         {
             ConstructorInfo ci;
             p.parsers.TryGetValue(s, out ci);
             parsers.Add(s, ci);
         }
         else
         {
             ConstructorInfo oldC;
             ConstructorInfo newC;
             parsers.TryGetValue(s, out oldC);
             p.parsers.TryGetValue(s, out newC);
             if (!oldC.Equals(newC))
             {
                 var e = new ArgumentException(
                 "Conflict detected when merging parameter parsers! To parse " + s
                 + " I have a: " + ReflectionUtilities.GetAssemblyQualifiedName(oldC.DeclaringType)
                 + " the other instance has a: " + ReflectionUtilities.GetAssemblyQualifiedName(newC.DeclaringType));
                 Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
             }
         }
     }
 }
开发者ID:NurimOnsemiro,项目名称:reef,代码行数:27,代码来源:ParameterParser.cs

示例6: SeqDateNode

        public SeqDateNode(DateTime startDate_, DateTime endDate_, string strgIncrementType)
        {
            //ガード
            if (startDate_ > endDate_)
            {
                ArgumentException aexcep = new ArgumentException("startDateがendDateより大きな数です。");
                throw aexcep;
            }

            this.startDate = startDate_;
            this.endDate = endDate_;

            this.IncrementType = strgIncrementType;

            this.currentDate = this.startDate;

            switch (this.IncrementType)
            {
                case "日":
                    this.currentDate = this.currentDate.AddDays(-1);
                    break;
                case "月":
                    this.currentDate = this.currentDate.AddMonths(-1);
                    break;
                case "年":
                    this.currentDate = this.currentDate.AddYears(-1);
                    break;
                default:
                    break;
            }
        }
开发者ID:kabahandle,项目名称:MyDummySQLPro,代码行数:31,代码来源:SeqDateNode.cs

示例7: Should_not_accept_negatives_numbers

        public void Should_not_accept_negatives_numbers()
        {
            var argumentException = new ArgumentException();

            _argumentValidator.Expect(validator => validator.FirstNumberIsValid(Arg<long>.Is.Anything)).Throw(argumentException);
            _fibonacciGenerator.Generate(-1, 1);
        }
开发者ID:gigapr,项目名称:Kata,代码行数:7,代码来源:SequenceGeneratorTests.cs

示例8: Main

        static void Main()
        {
            try
            {
                Thread.CurrentThread.Name = "ConsoleClientThread";

                try
                {
                    var ex = new ArgumentException("Ex", new Exception("Inner"));
                    ex.Data.Add("Key3", "Value3");

                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Key1", "Value1");
                    ex.Data.Add("Key2", "Value2");
                    new Logger().Log(MethodBase.GetCurrentMethod(), LogLevel.Error, "Error", ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Message sent");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
开发者ID:mrvshah,项目名称:Logging,代码行数:29,代码来源:Program.cs

示例9: ProcessRecord

        protected override void ProcessRecord()
        {
            const string particular = @"Software\ParticularSoftware";

            ProviderInfo provider;
            PSDriveInfo drive;
            var psPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LicenseFile, out provider, out drive);
            

            if (provider.ImplementingType != typeof(FileSystemProvider))
            {
                var ex = new ArgumentException(string.Format("{0} does not resolve to a path on the FileSystem provider.", psPath));
                var error = new ErrorRecord(ex, "InvalidProvider", ErrorCategory.InvalidArgument, psPath);
                WriteError(error);
                return;
            }

            var content = File.ReadAllText(psPath);
            if (!CheckFileContentIsALicenseFile(content))
            {
                var ex = new InvalidDataException(string.Format("{0} is not not a valid license file", psPath));
                var error = new ErrorRecord(ex, "InvalidLicense", ErrorCategory.InvalidData, psPath);
                WriteError(error);
                return;
            }

            if (EnvironmentHelper.Is64BitOperatingSystem)
            {
                RegistryHelper.LocalMachine(RegistryView.Registry64).WriteValue(particular, "License", content, RegistryValueKind.String);    
            }
            RegistryHelper.LocalMachine(RegistryView.Registry32).WriteValue(particular, "License", content, RegistryValueKind.String);
        }
开发者ID:james-wu,项目名称:NServiceBus.PowerShell,代码行数:32,代码来源:InstallPlatformLicense.cs

示例10: Create

        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="statement"></param>
        /// <returns></returns>
        public static AVM1.AbstractAction Create(string actionName, string statement)
        {
            AbstractAction product = null;

            if ((null == actionName) || (null == statement))
            {
                ArgumentException e = new ArgumentException("actionName or statement is null");
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            product = (AbstractAction)MethodBase.GetCurrentMethod().DeclaringType.Assembly.CreateInstance("Recurity.Swf.AVM1." + actionName);

            if (null == product)
            {
                AVM1ExceptionSourceFormat e = new AVM1ExceptionSourceFormat(actionName + " is not a valid AVM1 action");
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            if (!product.ParseFrom(statement))
            {
                AVM1ExceptionSourceFormat e = new AVM1ExceptionSourceFormat("Illegal statement: " + statement);
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            return product;
        }
开发者ID:rtezli,项目名称:Blitzableiter,代码行数:35,代码来源:AVM1Factory.cs

示例11: VerifyNotNullOrEmpty

 private static void VerifyNotNullOrEmpty(ArgumentException argumentException, string paramName)
 {
     Assert.Equal(
         ToFullArgExMessage(String.Format(CommonResources.Argument_NotNullOrEmpty, paramName), paramName),
         argumentException.Message);
     VerifyArgEx(argumentException, paramName);
 }
开发者ID:davidfowl,项目名称:ReviewR,代码行数:7,代码来源:ContractAssert.cs

示例12: GetDocumentNoParse

 private static DiscoveryDocument GetDocumentNoParse(ref string url, DiscoveryClientProtocol client)
 {
     DiscoveryDocument document2;
     DiscoveryDocument document = (DiscoveryDocument) client.Documents[url];
     if (document != null)
     {
         return document;
     }
     string contentType = null;
     Stream stream = client.Download(ref url, ref contentType);
     try
     {
         XmlTextReader xmlReader = new XmlTextReader(new StreamReader(stream, RequestResponseUtils.GetEncoding(contentType))) {
             WhitespaceHandling = WhitespaceHandling.Significant,
             XmlResolver = null,
             DtdProcessing = DtdProcessing.Prohibit
         };
         if (!DiscoveryDocument.CanRead(xmlReader))
         {
             ArgumentException innerException = new ArgumentException(System.Web.Services.Res.GetString("WebInvalidFormat"));
             throw new InvalidOperationException(System.Web.Services.Res.GetString("WebMissingDocument", new object[] { url }), innerException);
         }
         document2 = DiscoveryDocument.Read(xmlReader);
     }
     finally
     {
         stream.Close();
     }
     return document2;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:30,代码来源:DiscoveryDocumentReference.cs

示例13: CreateFromResponseAuthenticateHeader

        /// <summary>
        /// Creates authentication parameters from the WWW-Authenticate header in response received from resource. This method expects the header to contain authentication parameters.
        /// </summary>
        /// <param name="authenticateHeader">Content of header WWW-Authenticate header</param>
        /// <returns>AuthenticationParameters object containing authentication parameters</returns>
        public static AuthenticationParameters CreateFromResponseAuthenticateHeader(string authenticateHeader)
        {
            if (string.IsNullOrWhiteSpace(authenticateHeader))
            {
                throw new ArgumentNullException("authenticateHeader");
            }

            authenticateHeader = authenticateHeader.Trim();

            // This also checks for cases like "BearerXXXX authorization_uri=...." and "Bearer" and "Bearer "
            if (!authenticateHeader.StartsWith(Bearer, StringComparison.OrdinalIgnoreCase) 
                || authenticateHeader.Length < Bearer.Length + 2
                || !char.IsWhiteSpace(authenticateHeader[Bearer.Length]))
            {
                var ex = new ArgumentException(AdalErrorMessage.InvalidAuthenticateHeaderFormat, "authenticateHeader");
                Logger.Error(null, ex);
                throw ex;
            }

            authenticateHeader = authenticateHeader.Substring(Bearer.Length).Trim();

            Dictionary<string, string> authenticateHeaderItems = EncodingHelper.ParseKeyValueList(authenticateHeader, ',', false, null);

            var authParams = new AuthenticationParameters();
            string param;
            authenticateHeaderItems.TryGetValue(AuthorityKey, out param);
            authParams.Authority = param;
            authenticateHeaderItems.TryGetValue(ResourceKey, out param);
            authParams.Resource = param;

            return authParams;
        }
开发者ID:ankurchoubeymsft,项目名称:azure-activedirectory-library-for-dotnet,代码行数:37,代码来源:AuthenticationParameters.cs

示例14: ParseCommandGradient

        public ParseCommandGradient(string parameters)
        {
            var badCommandException = new ArgumentException("command is invalid for Recolor: " + parameters);

            string[] parametersArray = parameters.Split(':');

            if (parametersArray.Length > 3)
            {
                CommandType = parametersArray[0] == "b" ? CommandTypes.Background : CommandTypes.Foreground;
                Counter = Length = int.Parse(parametersArray[parametersArray.Length - 1]);

                bool keep;
                bool useDefault;

                List<Color> steps = new List<Color>();

                for (int i = 1; i < parametersArray.Length - 1; i++)
                {
                    steps.Add(Color.White.FromParser(parametersArray[i], out keep, out keep, out keep, out keep, out useDefault));
                }

                GradientString = new ColorGradient(steps.ToArray()).ToColoredString(new string(' ', Length));
            }

            else
                throw badCommandException;
        }
开发者ID:Thraka,项目名称:SadConsole,代码行数:27,代码来源:ParseCommandGradient.cs

示例15: GetProcessingStrategy

        public IGameObjectProcessingStrategy GetProcessingStrategy(ObjectType queryResponseType)
        {
            try
            {
                IGameObjectProcessingStrategy currentStrategy;

                switch (queryResponseType)
                {
                    case ObjectType.Champion:
                        currentStrategy = this.GetChampionStrategy();
                        break;
                    case ObjectType.Item:
                        currentStrategy = this.GetItemStrategy();
                        break;
                    case ObjectType.Rune:
                        currentStrategy = this.GetRuneStrategy();
                        break;
                    case ObjectType.Mastery:
                        currentStrategy = this.GetMasteryStrategy();
                        break;
                    default:
                        var exception = new ArgumentException("Invalid argument supplied for query object type.");
                        this.logger.Fatal("Cannot get strategy for query object type: {0}", exception);
                        throw exception;
                }

                return currentStrategy;
            }
            catch (Exception ex)
            {
                this.logger.FatalFormat("Exception raised while getting processing strategy for {0}: {1}", queryResponseType.ToString(), ex);
                throw ex;
            }
        }
开发者ID:NasC0,项目名称:LeagueComparer,代码行数:34,代码来源:ProcessingStrategyFactory.cs


注:本文中的System.ArgumentException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。