當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。