Inheritance: SystemException, ISerializable
Example #1
0
 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;
     }
 }
        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);
                }
            }
        }
Example #3
0
 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);
         }
     }
 }
        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;
            }
        }
Example #5
0
 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);
             }
         }
     }
 }
Example #6
0
        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;
            }
        }
Example #7
0
        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);
        }
Example #8
0
        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();
        }
        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);
        }
Example #10
0
        /// <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;
        }
Example #11
0
 private static void VerifyNotNullOrEmpty(ArgumentException argumentException, string paramName)
 {
     Assert.Equal(
         ToFullArgExMessage(String.Format(CommonResources.Argument_NotNullOrEmpty, paramName), paramName),
         argumentException.Message);
     VerifyArgEx(argumentException, paramName);
 }
 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;
 }
        /// <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;
        }
Example #14
0
        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;
        }
        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;
            }
        }
Example #16
0
        internal static string GetTokenFromResponseUri(Uri uri)
        {
            var badSessionInfoException = new ArgumentException("The session response (" + uri.AbsoluteUri + ") does not contain connection information.", "uri");

            string query = uri.Query;

            if (!query.Contains("code="))
                throw badSessionInfoException;

            string[] splittedQuery = query.Split('=');
            if (!splittedQuery[0].Contains("code"))
                throw badSessionInfoException;

            var code = splittedQuery[1];

            string accessTokenUrl = String.Format(ACCESS_TOKEN_URL, appId, SUCCESS_URL, apiSecret, code);
            var token = Post(accessTokenUrl);

            if (!token.Contains("access_token="))
                throw badSessionInfoException;

            var accessToken = token.Split('=')[1];

            return accessToken;
        }
        private static void WarnAboutUnsupportedActionPreferences(
            Cmdlet cmdlet,
            ActionPreference effectiveActionPreference,
            string nameOfCommandLineParameter,
            Func<string> inquireMessageGetter,
            Func<string> stopMessageGetter)
        {
            string message;
            switch (effectiveActionPreference)
            {
                case ActionPreference.Stop:
                    message = stopMessageGetter();
                    break;

                case ActionPreference.Inquire:
                    message = inquireMessageGetter();
                    break;

                default:
                    return; // we can handle everything that is not Stop or Inquire
            }

            bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);
            if (actionPreferenceComesFromCommandLineParameter)
            {
                Exception exception = new ArgumentException(message);
                ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
		public void DefaultConstructorWorks() {
			var ex = new ArgumentException();
			Assert.IsTrue((object)ex is ArgumentException, "is ArgumentException");
			Assert.IsTrue(ex.ParamName == null, "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.AreEqual(ex.Message, DefaultMessage);
		}
 public override void InsertInfo()
 {
     for (int i = 0; i < container.Length; i++)
     {
         int x;
         int y;
         int z;
         string name;
         Console.WriteLine("Enter Point {0} info:", i + 1);
         Console.Write("Enter X: ");
         x = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Y: ");
         y = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Z: ");
         z = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter name: ");
         name = Console.ReadLine();
         Point pnt = new Point(x, y, z, name);
         try
         {
             container[i] = pnt;
         }
         catch (System.IndexOutOfRangeException ex)
         {
             System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "", ex);
             throw argEx;
         }
     } 
 }
		public void ConstructorWithMessageAndParamNameWorks() {
			var ex = new ArgumentException("The message", "someParam");
			Assert.IsTrue((object)ex is ArgumentException, "is ArgumentException");
			Assert.AreEqual(ex.ParamName, "someParam", "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.AreEqual(ex.Message, "The message");
		}
Example #21
0
        /// <summary>
        /// Create a new ContextRuntime.
        /// </summary>
        /// <param name="serviceInjector"></param>
        /// <param name="contextConfiguration">the Configuration for this context.</param>
        /// <param name="parentContext"></param>
        public ContextRuntime(
                IInjector serviceInjector,
                IConfiguration contextConfiguration,
                Optional<ContextRuntime> parentContext)
        {
            ContextConfiguration config = contextConfiguration as ContextConfiguration;
            if (config == null)
            {
                var e = new ArgumentException("contextConfiguration is not of type ContextConfiguration");
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
            }
            _contextLifeCycle = new ContextLifeCycle(config.Id);
            _serviceInjector = serviceInjector;
            _parentContext = parentContext;
            try
            {
                _contextInjector = serviceInjector.ForkInjector();
            }
            catch (Exception e)
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);

                Optional<string> parentId = ParentContext.IsPresent() ?
                    Optional<string>.Of(ParentContext.Value.Id) :
                    Optional<string>.Empty();
                ContextClientCodeException ex = new ContextClientCodeException(ContextClientCodeException.GetId(contextConfiguration), parentId, "Unable to spawn context", e);
                
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
            }
            // Trigger the context start events on contextInjector.
            _contextLifeCycle.Start();
        }
    /// <summary>
    /// Invokes the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="getNext">The get next.</param>
    /// <returns>The method return result.</returns>
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
      foreach (var argument in input.Arguments)
      {
        string target = argument as string;

        if (string.IsNullOrEmpty(target))
        {
          continue;
        }

        if (Regex.Match(target, @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").Success)
        {
          continue;
        }

        ArgumentException argumentException = new ArgumentException("Invalid e-mail format", input.MethodBase.Name);

        Log.Error("Argument exception", argumentException, this);

        return input.CreateExceptionMethodReturn(argumentException);
      }

      return getNext()(input, getNext);
    }
        public static List<BindingMap> GetMaps(string paths)
        {
            var scan = new StringScan(paths);

            var ex = new ArgumentException("Invalid path");

            var maps = new List<BindingMap>();
            var state = ParseState.Begin;
            var current = StringScan.EOF;

            //Parsing State Machine
            switch (state)
            {
                case ParseState.Begin:
                case ParseState.BeginMap:
                    var map = ParseMap(scan);
                    if (!maps.Contains(map))
                        maps.Add(map);
                    goto case ParseState.EndMap;
                case ParseState.EndMap:
                    current = scan.Current();
                    if (current == ',')
                    {
                        scan.MoveNext();
                        goto case ParseState.BeginMap;
                    }
                    if (current == StringScan.EOF)
                        goto case ParseState.End;
                    throw scan.CreateException();
                case ParseState.End:
                    break;
            }

            return maps;
        }
Example #24
0
        public void WhenAnEventIsWrittenToTheSinkItIsRetrievableFromTheDocumentStore()
        {
            using (var documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize())
            {
                var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
                var exception = new ArgumentException("Mládek");
                const LogEventLevel level = LogEventLevel.Information;
                const string messageTemplate = "{Song}++";
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };

                using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null))
                {
                    var template = new MessageTemplateParser().Parse(messageTemplate);
                    var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);
                    ravenSink.Emit(logEvent);
                }

                using (var session = documentStore.OpenSession())
                {
                    var events = session.Query<LogEvent>().Customize(x => x.WaitForNonStaleResults()).ToList();
                    Assert.AreEqual(1, events.Count);
                    var single = events.Single();
                    Assert.AreEqual(messageTemplate, single.MessageTemplate);
                    Assert.AreEqual("\"New Macabre\"++", single.RenderedMessage);
                    Assert.AreEqual(timestamp, single.Timestamp);
                    Assert.AreEqual(level, single.Level);
                    Assert.AreEqual(1, single.Properties.Count);
                    Assert.AreEqual("New Macabre", single.Properties["Song"]);
                    Assert.AreEqual(exception.Message, single.Exception.Message);
                }
            }
        }
        public ParseExecuteElements(XmlElementType elementType)
        {
            if (elementType != XmlElementType.ExecuteCommand)
            {
                var ex = new ArgumentException("Invalid XmlElement Type For this Xml Parser!");

                var err = new FileOpsErrorMessageDto
                {
                    DirectoryPath = string.Empty,
                    ErrId = 1,
                    ErrorMessage = ex.Message,
                    ErrSourceMethod = "Constructor()",
                    ErrException = ex,
                    FileName = string.Empty,
                    LoggerLevel = LogLevel.FATAL
                };

                ErrorMgr.LoggingStatus = ErrorLoggingStatus.On;
                ErrorMgr.WriteErrorMsg(err);

                throw ex;
            }

            ElementType = elementType;
        }
		public void CreateEntityWithPropertiesShouldGenerateValidRowKey()
		{
			var timestamp = new DateTimeOffset(2014, 12, 01, 18, 42, 20, 666, TimeSpan.FromHours(2));
			var exception = new ArgumentException("Some exceptional exception happened");
			var level = LogEventLevel.Information;
			var additionalRowKeyPostfix = "POSTFIX";

			var postLength = additionalRowKeyPostfix.Length + 1 + Guid.NewGuid().ToString().Length;
			var messageSpace = 1024 - (level.ToString().Length + 1) - (1 + postLength);

			// Message up to available space, plus some characters (Z) that will be removed
			var messageTemplate = new string('x', messageSpace-4) + "ABCD" + new string('Z', 20);

			var template = new MessageTemplateParser().Parse(messageTemplate);
			var properties = new List<LogEventProperty>();

			var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);

			var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, additionalRowKeyPostfix);

			// Row Key
			var expectedRowKeyWithoutGuid = "Information|" + new string('x', messageSpace-4) + "ABCD|POSTFIX|";
			var rowKeyWithoutGuid = entity.RowKey.Substring(0, expectedRowKeyWithoutGuid.Length);
			var rowKeyGuid = entity.RowKey.Substring(expectedRowKeyWithoutGuid.Length);

			Assert.AreEqual(1024, entity.RowKey.Length);
			Assert.AreEqual(expectedRowKeyWithoutGuid, rowKeyWithoutGuid);
			Assert.DoesNotThrow(() => Guid.Parse(rowKeyGuid));
			Assert.AreEqual(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid);
			Assert.False(entity.RowKey.Contains('Z'));
		}
        protected override void ProcessRecord()
        {
            if (!File.Exists(this.Filename))
            {
                this.WriteVerbose("File already exists");
                if (this.Overwrite)
                {
                    File.Delete(this.Filename);
                }
                else
                {
                    string msg = $"File \"{this.Filename}\" already exists";
                    var exc = new ArgumentException(msg);
                    throw exc;
                }
            }

            string ext = Path.GetExtension(this.Filename).ToLowerInvariant();

            if (ext == ".html" || ext == ".xhtml" || ext == ".htm")
            {
                this.client.Export.SelectionToSVGXHTML(this.Filename);                
            }
            else
            {
                this.client.Export.SelectionToFile(this.Filename);
            }
        }
 public void TestDisposeExceptions()
 {
     var d1 = Substitute.For<IDisposable>();
     var e1 = new ArgumentException();
     d1.When(d=>d.Dispose()).Do(d => { throw e1; });
     var d2 = Substitute.For<IDisposable>();
     var e2 = new InvalidOperationException();
     d2.When(d => d.Dispose()).Do(d => { throw e2; });
     var d3 = Substitute.For<IDisposable>();
     var exceptionThrown = false;
     try
     {
         using (var c = new CompositeDisposable())
         {
             c.Add(d1);
             c.Add(d2);
             c.Add(d3);
         }
     }
     catch (AggregateException e)
     {
         exceptionThrown = true;
         Assert.IsTrue(e.InnerExceptions.Contains(e1));
         Assert.IsTrue(e.InnerExceptions.Contains(e2));
     }
     Assert.IsTrue(exceptionThrown);
     d1.Received(1).Dispose();
     d2.Received(1).Dispose();
     d3.Received(1).Dispose();
 }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
        public X509Certificate2KeyEncryptionKey(X509Certificate2 x509Certificate2) : base(x509Certificate2)
        {
            // base handles lots of the validation
            if (!x509Certificate2.HasPrivateKey)
            {
                throw new ArgumentException(string.Format("x509Certificate2 with thumbprint '{0}' does not have a private key.", x509Certificate2.Thumbprint));
            }

            var badPrivateKeyEx = new ArgumentException(string.Format("x509Certificate2 with thumbprint '{0}' does not have a private key.", x509Certificate2.Thumbprint));

            try
            {
                if (x509Certificate2.PrivateKey == null)
                {
                    throw badPrivateKeyEx;
                }
            }
            catch (Exception ex)
            {
                if (ex == badPrivateKeyEx)
                {
                    throw;
                }
                throw new ArgumentException(badPrivateKeyEx.Message, ex);
            }
            _x5092 = x509Certificate2;
        }