public async Task WhenResponseContainsAbortAndAbortMessage_ThenThrow()
        {
            // Arrange
            var provider       = _mockProvider;
            var uri            = new Uri("http://host/");
            var proxy          = null as IWebProxy;
            var type           = CredentialRequestType.Unauthorized;
            var message        = null as string;
            var isRetry        = true;
            var nonInteractive = true;

            _mockProvider.Setup(x => x.Execute(It.IsAny <PluginCredentialRequest>(), It.IsAny <CancellationToken>()))
            .Throws(PluginException.CreateAbortMessage(@"c:\path\plugin.exe", "Extra message."));

            // Act & Assert
            var exception = await Record.ExceptionAsync(async() => await provider.Object.GetAsync(
                                                            uri,
                                                            proxy,
                                                            type,
                                                            message,
                                                            isRetry,
                                                            nonInteractive,
                                                            CancellationToken.None));

            Assert.IsAssignableFrom <PluginException>(exception);
            Assert.Contains(
                @"Credential plugin c:\path\plugin.exe handles this request, but is unable to provide credentials. Extra message.",
                exception.Message);
        }
        public void ConstructionWithMessage()
        {
            var             message = "message";
            PluginException ex      = new PluginException(message);

            Assert.AreEqual(message, ex.Message);
        }
 public void ConstructingWithMessageAndInnerException()
 {
     Exception inner = new NotImplementedException();
       string message = "message";
       PluginException ex = new PluginException(message, inner);
       Assert.AreEqual(message, ex.Message);
       Assert.AreSame(inner, ex.InnerException);
 }
 public void ConstructingWithFormattedMessage()
 {
     var message = "message {0} {1}";
       var arg1 = 55;
       var arg2 = "arg2";
       var formatted = string.Format(message, arg1, arg2);
       PluginException ex = new PluginException(message, arg1, arg2);
       Assert.AreEqual(formatted, ex.Message);
 }
        public void ConstructingWithMessageAndInnerException()
        {
            Exception       inner   = new NotImplementedException();
            string          message = "message";
            PluginException ex      = new PluginException(message, inner);

            Assert.AreEqual(message, ex.Message);
            Assert.AreSame(inner, ex.InnerException);
        }
        public void ConstructingWithFormattedMessage()
        {
            var             message   = "message {0} {1}";
            var             arg1      = 55;
            var             arg2      = "arg2";
            var             formatted = string.Format(message, arg1, arg2);
            PluginException ex        = new PluginException(message, arg1, arg2);

            Assert.AreEqual(formatted, ex.Message);
        }
        public void CreateShouldThrowOnUnresolvedAssembly()
        {
            using (MockDomain domain = new MockDomain())
            {
                MockAssemblyRepository repository = new MockAssemblyRepository();
                IPluginCreator         tested     = PluginCreator.GetCreator(domain);
                QualifiedName          fakeName   = new QualifiedName(
                    typeof(string).FullName.Replace("mscorlib", "NonExistingAssemblyName"),
                    typeof(string).Assembly.FullName.Replace("mscorlib", "NonExistingAssemblyName"));

                PluginDescriptor descriptor = MockPluginDescriptor.For(fakeName);

                PluginException ex = DoAssert.Throws <PluginException>(() => tested.Create(descriptor, repository, null));
                Assert.IsNotNull(ex.InnerException);
                Assert.IsInstanceOfType(ex.InnerException, typeof(FileNotFoundException));
            }
        }
        public void ShouldSerializeAndDeserialize()
        {
            Exception inner = new NotImplementedException();
              string message = "message";
              PluginException toSerialize = new PluginException(message, inner);
              var knownTypes = new Type[] { typeof(NotImplementedException) };
              PluginException deserialized;

              using (var memstream = new MemoryStream())
              {
            XmlTextWriter writer = new XmlTextWriter(memstream, Encoding.UTF8);
            var serializer = new DataContractSerializer(toSerialize.GetType(), knownTypes);
            serializer.WriteObject(writer, toSerialize);
            writer.Flush();

            memstream.Seek(0, SeekOrigin.Begin);
            XmlTextReader reader = new XmlTextReader(memstream);
            deserialized = serializer.ReadObject(reader) as PluginException;
              }

              Assert.AreEqual(toSerialize.Message, deserialized.Message);
              Assert.IsNotNull(deserialized.InnerException);
              Assert.AreEqual(toSerialize.InnerException.Message, deserialized.InnerException.Message);
        }
        public void ShouldSerializeAndDeserialize()
        {
            Exception       inner       = new NotImplementedException();
            string          message     = "message";
            PluginException toSerialize = new PluginException(message, inner);
            var             knownTypes  = new Type[] { typeof(NotImplementedException) };
            PluginException deserialized;

            using (var memstream = new MemoryStream())
            {
                XmlTextWriter writer     = new XmlTextWriter(memstream, Encoding.UTF8);
                var           serializer = new DataContractSerializer(toSerialize.GetType(), knownTypes);
                serializer.WriteObject(writer, toSerialize);
                writer.Flush();

                memstream.Seek(0, SeekOrigin.Begin);
                XmlTextReader reader = new XmlTextReader(memstream);
                deserialized = serializer.ReadObject(reader) as PluginException;
            }

            Assert.AreEqual(toSerialize.Message, deserialized.Message);
            Assert.IsNotNull(deserialized.InnerException);
            Assert.AreEqual(toSerialize.InnerException.Message, deserialized.InnerException.Message);
        }
Exemple #10
0
 /// <summary>
 ///     Sends an Error Event through the PluginSystem OnError Handler
 /// </summary>
 /// <param name="eventArgs">The Error</param>
 public static void SendError(PluginException eventArgs)
 {
     OnError?.Invoke(eventArgs);
 }
 public void ConstructionWithMessage()
 {
     var message = "message";
       PluginException ex = new PluginException(message);
       Assert.AreEqual(message, ex.Message);
 }
 public void ConstructingDefault()
 {
     PluginException ex = new PluginException();
       Assert.IsNotNull(ex);
 }
        private void ProcessFixtureDelete(Fixture fixtureDelta)
        {
            _logger.Info(
                $"{_resource} has been deleted from the GTP Fixture Factory. Suspending all markets and stopping the stream.");

            Fixture fixtureDeleted = new Fixture
            {
                Id          = _fixtureId,
                FixtureName = fixtureDelta.FixtureName,
                MatchStatus = ((int)MatchStatus.Deleted).ToString()
            };

            if (_marketsRuleManager.CurrentState != null)
            {
                fixtureDeleted.Sequence = _marketsRuleManager.CurrentState.FixtureSequence;
            }

            try
            {
                SuspendFixture(SuspensionReason.FIXTURE_DELETED);
                try
                {
                    _streamStatsActor.Tell(new UpdatePluginStatsStartMsg()
                    {
                        Fixture          = fixtureDelta,
                        Sequence         = fixtureDelta.Sequence,
                        IsSnapshot       = false,
                        UpdateReceivedAt = DateTime.UtcNow,
                        PluginMethod     = "ProcessFixtureDeletion"
                    });

                    _platformConnector.ProcessFixtureDeletion(fixtureDeleted);
                    _streamStatsActor.Tell(new UpdatePluginStatsFinishMsg
                    {
                        CompletedAt = DateTime.UtcNow
                    });
                }
                catch (Exception ex)
                {
                    var pluginError = new PluginException($"Plugin ProcessFixtureDeletion {fixtureDeleted} error occured", ex);
                    UpdateStatsError(pluginError);
                    throw pluginError;
                }
            }
            catch (Exception e)
            {
                _logger.Error($"An exception occured while trying to process fixture deletion for {_resource}", e);
                throw;
            }

            //reset fixture state
            _marketsRuleManager.OnFixtureUnPublished();
            var fixtureStateActor     = Context.System.ActorSelection(FixtureStateActor.Path);
            var updateFixtureStateMsg = new UpdateFixtureStateMsg
            {
                FixtureId = _fixtureId,
                Sport     = _resource.Sport,
                Status    = MatchStatus.Deleted,
                Sequence  = -1,
                Epoch     = _currentEpoch
            };

            fixtureStateActor.Tell(updateFixtureStateMsg);
        }
        private void ProcessInvalidEpoch(Fixture fixtureDelta, bool hasEpochChanged)
        {
            _fixtureStartTime = fixtureDelta.StartTime ?? _fixtureStartTime;

            if (fixtureDelta.IsDeleted)
            {
                ProcessFixtureDelete(fixtureDelta);
                UpdateSupervisorState(fixtureDelta, false);
                StopStreaming();
                return;
            }

            if (fixtureDelta.IsMatchStatusChanged)
            {
                if (!string.IsNullOrEmpty(fixtureDelta.MatchStatus))
                {
                    _logger.Debug(
                        $"{_resource} has changed matchStatus={Enum.Parse(typeof(MatchStatus), fixtureDelta.MatchStatus)}");

                    try
                    {
                        _streamStatsActor.Tell(new UpdatePluginStatsStartMsg()
                        {
                            Fixture          = fixtureDelta,
                            Sequence         = fixtureDelta.Sequence,
                            IsSnapshot       = false,
                            UpdateReceivedAt = DateTime.UtcNow,
                            PluginMethod     = "ProcessMatchStatus"
                        });
                        _platformConnector.ProcessMatchStatus(fixtureDelta);
                        _streamStatsActor.Tell(new UpdatePluginStatsFinishMsg
                        {
                            CompletedAt = DateTime.UtcNow
                        });
                    }
                    catch (Exception ex)
                    {
                        var pluginError = new PluginException($"Plugin ProcessMatchStatus {fixtureDelta} error occured", ex);
                        UpdateStatsError(pluginError);
                        throw pluginError;
                    }
                }

                if (fixtureDelta.IsMatchOver)
                {
                    ProcessMatchOver();
                    StopStreaming();
                    return;
                }
            }

            //epoch change reason - aggregates LastEpochChange reasons into string like "BaseVariables,Starttime"
            var reason =
                fixtureDelta.LastEpochChangeReason != null && fixtureDelta.LastEpochChangeReason.Length > 0
                    ? fixtureDelta.LastEpochChangeReason.Select(x => ((EpochChangeReason)x).ToString())
                .Aggregate((first, second) => $"{first}, {second}")
                    : "Unknown";

            _logger.Info(
                $"Stream update {fixtureDelta} has epoch change with reason {reason}, the snapshot will be processed instead.");

            SuspendAndReprocessSnapshot(hasEpochChanged);
        }
        private void ProcessSnapshot(Fixture snapshot, bool isFullSnapshot, bool hasEpochChanged, bool skipMarketRules = false)
        {
            var logString = isFullSnapshot ? "snapshot" : "stream update";

            if (snapshot == null || (snapshot != null && string.IsNullOrWhiteSpace(snapshot.Id)))
            {
                throw new ArgumentException($"Received empty {logString} for {_resource}");
            }

            _logger.Info($"Processing {logString} for {snapshot}");

            try
            {
                if (isFullSnapshot && !VerifySequenceOnSnapshot(snapshot))
                {
                    return;
                }

                _streamStatsActor.Tell(new UpdateStatsStartMsg
                {
                    Fixture          = snapshot,
                    Sequence         = snapshot.Sequence,
                    IsSnapshot       = isFullSnapshot,
                    UpdateReceivedAt = DateTime.UtcNow
                });

                _logger.Info($"BeforeMarketRules MarketsCount={snapshot.Markets.Count} ActiveMarketsCount={snapshot.Markets.Count(_ => _.IsActive)} SelectionsCount={snapshot.Markets.SelectMany(_ => _.Selections).Count()}  {snapshot}");
                if (!skipMarketRules)
                {
                    _marketsRuleManager.ApplyRules(snapshot);
                    snapshot.IsModified = true;
                }
                else
                {
                    _marketsRuleManager.ApplyRules(snapshot, true);
                }
                _logger.Info($"AfterMarketRules MarketsCount={snapshot.Markets.Count} ActiveMarketsCount={snapshot.Markets.Count(_ => _.IsActive)} SelectionsCount={snapshot.Markets.SelectMany(_ => _.Selections).Count()}  {snapshot}");

                if (isFullSnapshot)
                {
                    try
                    {
                        _streamStatsActor.Tell(new UpdatePluginStatsStartMsg()
                        {
                            Fixture          = snapshot,
                            Sequence         = snapshot.Sequence,
                            IsSnapshot       = true,
                            UpdateReceivedAt = DateTime.UtcNow,
                            PluginMethod     = "ProcessSnapshot"
                        });
                        _platformConnector.ProcessSnapshot(snapshot, hasEpochChanged);
                        _streamStatsActor.Tell(new UpdatePluginStatsFinishMsg
                        {
                            CompletedAt = DateTime.UtcNow
                        });
                    }
                    catch (Exception ex)
                    {
                        var pluginError = new PluginException($"Plugin ProcessSnapshot {snapshot} error occured", ex);
                        UpdateStatsError(pluginError);
                        throw pluginError;
                    }
                }
                else
                {
                    try
                    {
                        _streamStatsActor.Tell(new UpdatePluginStatsStartMsg()
                        {
                            Fixture          = snapshot,
                            Sequence         = snapshot.Sequence,
                            IsSnapshot       = false,
                            UpdateReceivedAt = DateTime.UtcNow,
                            PluginMethod     = "ProcessStreamUpdate"
                        });
                        _platformConnector.ProcessStreamUpdate(snapshot, hasEpochChanged);
                        _streamStatsActor.Tell(new UpdatePluginStatsFinishMsg
                        {
                            CompletedAt = DateTime.UtcNow
                        });
                    }
                    catch (Exception ex)
                    {
                        var pluginError = new PluginException($"Plugin ProcessStreamUpdate {snapshot} error occured", ex);
                        UpdateStatsError(pluginError);
                        throw pluginError;
                    }
                }


                UpdateFixtureState(snapshot, isFullSnapshot);
                UpdateSupervisorState(snapshot, isFullSnapshot);

                _streamStatsActor.Tell(new UpdateStatsFinishMsg
                {
                    CompletedAt = DateTime.UtcNow
                });
            }
            catch (FixtureIgnoredException)
            {
                _logger.Warn($"{_resource} received a FixtureIgnoredException");
            }
            catch (AggregateException ex)
            {
                _marketsRuleManager.RollbackChanges();

                int total = ex.InnerExceptions.Count;
                int count = 0;
                foreach (var e in ex.InnerExceptions)
                {
                    _logger.Error($"Error processing {logString} for {snapshot} ({++count}/{total})", e);
                }
                throw;
            }
            catch (Exception ex)
            {
                _marketsRuleManager.RollbackChanges();

                _logger.Error($"Error processing {logString} {snapshot}", ex);
                throw;
            }

            _logger.Info($"Finished processing {logString} for {snapshot}");
        }
        public void ConstructingDefault()
        {
            PluginException ex = new PluginException();

            Assert.IsNotNull(ex);
        }