Example #1
0
        //[ChunkedEncodingFilter(typeof(AssetProductivityTargets), "assetProductivitySettings")]
        public async Task <ActionResult <EditProductivityTargetsResponse> > Put(AssetProductivityTargets assetProductivityParameter)
        {
            assetProductivityParameter = await base.ReadRequestContentAsync(assetProductivityParameter);

            assetProductivityParameter.UserUID     = base.GetUserContext(Request);
            assetProductivityParameter.CustomerUID = base.GetCustomerContext(Request);
            _loggingService.Debug(string.Format("UserUID : {0}, CustomerUID : {1}", assetProductivityParameter.UserUID, assetProductivityParameter.CustomerUID), "AssetSettingsPublisher.publishAssetWeeklySettings");
            _loggingService.Debug(string.Format("Given Request : {0}", JsonConvert.SerializeObject(assetProductivityParameter)), "AssetSettingsPublisher.publishAssetWeeklySettings");

            var editResponse = await _productivityTargetsService.EditAssetSettings(assetProductivityParameter.assetProductivitySettings.ToArray());

            var userAssetWeeklySettings = new List <AssetSettingsGetDBResponse>();

            assetProductivityParameter.assetProductivitySettings.ForEach(target => userAssetWeeklySettings.AddRange(_converter.GetCommonResponseFromProductivityTargetsAndAssetTargets(target)));
            _publisher.PublishUserWeeklyAssetSettings(userAssetWeeklySettings, assetProductivityParameter.UserUID.Value, assetProductivityParameter.CustomerUID.Value);

            if (editResponse != null && editResponse.Errors != null && editResponse.Errors.Any())
            {
                return(base.SendResponse(HttpStatusCode.BadRequest, editResponse));
            }

            if (editResponse == null)
            {
                return(base.SendResponse <EditProductivityTargetsResponse>(HttpStatusCode.NoContent, null));
            }
            return(base.SendResponse(HttpStatusCode.OK, editResponse));
        }
        public void Sign(string path, bool strongName = false)
        {
            /*  try
             * {
             *
             *
             *    try
             *    {
             *        _loggingService.Debug("LoggingInAuthenticodeSign");
             *        //LogManager.GetLogger(GetType()).DebugFormat("path is {0}", path);
             *        var certRef = new CertificateReference(Certificate);
             *        _loggingService.Debug("Going to load binary at {0}".format(path));
             *        /*
             *        if (new FileInfo(path).Length < 4)
             *        {
             *            throw new InvalidFileToSignException();
             *        }*/
            if (strongName)
            {
                using (var wrap = new StrongNameCertificateWrapper(Certificate))
                {
                    wrap.Sign(path);
                }
            }

            _loggingService.Debug("Signing {0} with {1}".format(path, Certificate.SerialNumber));
            AuthenticodeCertificateWrapper.SignUsingDefaultTimeStampUrls(path, Certificate, _loggingService);
            _loggingService.Debug("Finished signing {0} with {1}".format(path, Certificate.SerialNumber));

/*
 *                  r = BinaryLoad(path);
 *                  _loggingService.Debug("Binary at {0} loaded".format(path));
 *                  //LogManager.GetLogger(GetType()).DebugFormat("filename of Binary is {0}", r.Filename);
 *                  r.SigningCertificate = certRef;
 *                  if (strongName)
 *                      r.StrongNameKeyCertificate = certRef;
 *
 *                  _loggingService.Debug("Going to do the signing");
 *
 *                  _loggingService.Debug("signgin finished successfully");
 *              }
 *
 *              catch (AggregateException ae)
 *              {
 *                  _loggingService.Debug("Something is wrong!");
 *                  foreach (var i in ae.Flatten().InnerExceptions)
 *                  {
 *                      _loggingService.Error("Bad", i);
 *                  }
 *
 *                  if (ae.Flatten()
 *                        .InnerExceptions.OfType<DigitalSignFailure>()
 *                        .Any(dsf => dsf.Win32Code == 2148204547))
 *                  {
 *                      throw new InvalidFileToSignException();
 *                  }
 *                  throw;
 *              }
 *          }*/
        }
Example #3
0
        public bool SaveItem(ITreeNodeContent node, ItemChanges changes)
        {
            if (!changes.HasFieldsChanged)
            {
                return(false);
            }

            var category = Category.Get(int.Parse(node.ItemId));

            if (category == null)
            {
                string message = string.Format("Category with id: {0} not found for ITreeNodeContent.", node.ItemId);
                _loggingService.Debug <ProductCatalogGroupTemplateBuilder>(message);
                throw new InvalidDataException(message);
            }

            foreach (FieldChange fieldChange in changes.FieldChanges)
            {
                UpdateStoreValueFor(fieldChange, category, changes.Item);
            }

            ObjectFactory.Instance.Resolve <IPipeline <Category> >("SaveCategory").Execute(category);

            return(true);
        }
Example #4
0
        /// <summary>
        /// Sends the request to the specified end point.
        /// </summary>
        /// <typeparam name="T">The type of data to be received back.</typeparam>
        /// <param name="webMethod">The web method to call.</param>
        /// <param name="endPointTemplate">The template string for the end point.</param>
        /// <param name="args">The args to be substituted into the end point template.</param>
        /// <returns>The result of the request.</returns>
        private async Task <T> SendRequest <T>(Func <Uri, Task <HttpResponseMessage> > webMethod, string endPointTemplate, params string[] args)
        {
            var uri      = FormatUri(endPointTemplate, args);
            var endPoint = uri.AbsoluteUri;

            LoggingService.Debug($"{nameof(SendRequest)}<{typeof(T)}>({endPoint})");

            T   result;
            var stopwatch = Stopwatch.StartNew();

            try
            {
                var response = await webMethod(uri).Caf();

                stopwatch.Stop();
                LoggingService.Debug($"{endPoint} completed successfully in {stopwatch.ElapsedMilliseconds}ms");
                result = await ReadResult <T>(response).Caf();
            }
            catch (Exception ex)
            {
                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }
                LoggingService.Error($"{endPoint} completed with errors in {stopwatch.ElapsedMilliseconds}ms");
                LoggingService.Error($"{ex.Message}\n{ex.StackTrace}");
                throw;
            }

            return(result);
        }
Example #5
0
        private void StoreObjectIntoCache(object cacheObject, string cacheKey, System.Web.HttpContext context, int MinutesToLive, CacheModes cacheMode, System.Web.Caching.CacheItemPriority priority)
        {
            // Only add to the cache when the object is not null
            if (cacheObject != null)
            {
                loggingService.Debug("Storing {0} object {1} into cache", cacheMode.ToString(), cacheKey);

                // Different insert for different cache mode
                switch (cacheMode)
                {
                case CacheModes.Absolute:
                    context.Cache.Insert(cacheKey,
                                         cacheObject,
                                         null,
                                         DateTime.Now.AddMinutes(MinutesToLive),
                                         System.Web.Caching.Cache.NoSlidingExpiration,
                                         priority,
                                         null);
                    break;

                case CacheModes.Sliding:
                    context.Cache.Insert(cacheKey,
                                         cacheObject,
                                         null,
                                         System.Web.Caching.Cache.NoAbsoluteExpiration,
                                         new TimeSpan(0, MinutesToLive, 0),
                                         priority,
                                         null);
                    break;
                }
            }
        }
Example #6
0
        public static async Task <T[]> GetSetAsync <T>(this IDatabase cache,
                                                       ILoggingService loggingService,
                                                       LoggingOptions loggingOptions,
                                                       ISerializer serializer,
                                                       string key)
        {
            var members = await cache.SetMembersAsync(key).ConfigureAwait(false);

            if (members == null &&
                loggingOptions.LogCacheMisses)
            {
                loggingService.Debug($"Cache Miss. Key: {key}");
            }
            else if (members != null &&
                     loggingOptions.LogCacheHits)
            {
                loggingService.Debug($"Cache Hit. Key: {key}");
            }

            var items = new List <T>();

            if (members != null)
            {
                items.AddRange(members.Select(member => serializer.Deserialize <T>(member)));
            }

            return(items.ToArray());
        }
Example #7
0
        public List <AssetSettingsGetDBResponse> GetAssetUtilizationTargetRunTimeByStartDateAndAssetUID(string AssetUIDs, DateTime startDate, DateTime endDate)
        {
            try
            {
                var sql = string.Format(@"Select * From (Select HEX(AWC.fk_AssetUID) As AssetID, HEX(AWC.AssetWeeklyConfigUID) As AssetWeeklyConfigUID, AWC.SundayConfigValue As Sunday, AWC.MondayConfigValue As Monday, AWC.TuesdayConfigValue As Tuesday, 
                                                AWC.WednesdayConfigValue AS Wednesday, AWC.ThursdayConfigValue AS Thursday, AWC.FridayConfigValue As Friday, 
                                                AWC.SaturdayConfigValue AS Saturday, AWC.StartDate as StartDate, AWC.EndDate as EndDate, ACT.ConfigTypeName AS 'ConfigType' FRom md_asset_AssetWeeklyConfig AWC 
                                                Inner Join md_asset_AssetConfigType ACT On ACT.AssetConfigTypeID = AWC.fk_AssetConfigTypeID And ACT.ConfigTypeName IN ('" +
                                        AssetTargetType.RuntimeHours.ToString() + "', '" + AssetTargetType.IdletimeHours.ToString() + @"')
                                                Where AWC.fk_AssetUID In ({0}) AND ('{1}' Between StartDate And EndDate OR '{2}' Between StartDate And EndDate) Order By AWC.StartDate)A 
                                                UNION
                                                Select * From (Select HEX(AWC.fk_AssetUID) As AssetID, HEX(AWC.AssetWeeklyConfigUID) As AssetWeeklyConfigUID, AWC.SundayConfigValue As Sunday, AWC.MondayConfigValue As Monday, AWC.TuesdayConfigValue As Tuesday, 
                                                AWC.WednesdayConfigValue AS Wednesday, AWC.ThursdayConfigValue AS Thursday, AWC.FridayConfigValue As Friday, 
                                                AWC.SaturdayConfigValue AS Saturday, AWC.StartDate as StartDate, AWC.EndDate as EndDate, ACT.ConfigTypeName AS 'ConfigType' FRom md_asset_AssetWeeklyConfig AWC 
                                                Inner Join md_asset_AssetConfigType ACT On ACT.AssetConfigTypeID = AWC.fk_AssetConfigTypeID And ACT.ConfigTypeName IN ('" +
                                        AssetTargetType.RuntimeHours.ToString() + "', '" + AssetTargetType.IdletimeHours.ToString() + @"')
                                                Where AWC.fk_AssetUID In ({0}) AND (StartDate Between '{1}' AND '{2}' OR EndDate Between '{1}' AND '{2}') Order By AWC.StartDate ASC) B",
                                        AssetUIDs, startDate.ToDateTimeStringWithYearMonthDayFormat(), endDate.ToDateTimeStringWithYearMonthDayFormat());

                _loggingService.Debug(string.Format("Data Access requested for the query {0}", sql), "WeeklyAssetSettingsRepository.GetAssetUtilizationTargetRunTimeByStartDateAndAssetUID");

                return(_transaction.Get <AssetSettingsGetDBResponse>(sql).ToList());
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public bool SaveItem(ITreeNodeContent node, ItemChanges changes)
        {
            if (!changes.HasFieldsChanged)
            {
                return(false);
            }

            var productVariant = Product.Get(Convert.ToInt32(node.ItemId));

            if (productVariant == null)
            {
                var message = string.Format("Product with id: {0} not found for ITreeNodeContent. ", node.ItemId);
                _loggingService.Debug <ProductCatalogTemplateBuilder>(message);
                throw new InvalidDataException(message);
            }

            foreach (FieldChange fieldChange in changes.FieldChanges)
            {
                UpdateVariantValue(fieldChange, productVariant, changes.Item);
            }

            ObjectFactory.Instance.Resolve <IPipeline <Product> >("SaveProduct").Execute(productVariant.ParentProduct);

            return(true);
        }
Example #9
0
        /// <summary>
        /// Instructs the eventstore <seealso cref="IEventStore"/> to load all events,
        /// processes them and publish them on the eventbus <seealso cref="IEventBus"/>
        /// </summary>
        public void Replay()
        {
            if (_isInitialized)
            {
                throw new EventStoreInitializeException(
                          "The eventstore is already initialized. This can only be done once at startup");
            }

            _loggingService.Debug("Start replay");

            var  count = 0;
            long msec  = 0;

            using (new TimeMeasure(t => msec = t))
            {
                foreach (var @event in _eventStore.GetEvents())
                {
                    count++;
                    _eventBus.Publish(@event);
                }
            }

            //Logging performance
            _loggingService.Debug($"Replayed {count} events in {msec / 1000} seconds");

            foreach (var result in _performanceMeasurementService.GetResults())
            {
                _loggingService.Info(result.Display);
            }

            //Inform all process handlers that initialization is finished
            _eventBus.Publish(new ReplayFinishedEvent());

            _isInitialized = true;
        }
Example #10
0
        public void Buy(BuyOptions options)
        {
            lock (SyncRoot)
            {
                IRule rule = signalsService.Rules.Entries.FirstOrDefault(r => r.Name == options.Metadata.SignalRule);

                ITradingPair swappedPair = Account.GetTradingPairs().OrderBy(p => p.CurrentMargin).FirstOrDefault(tradingPair =>
                {
                    IPairConfig pairConfig = GetPairConfig(tradingPair.Pair);
                    return(pairConfig.SellEnabled && pairConfig.SwapEnabled && pairConfig.SwapSignalRules != null && pairConfig.SwapSignalRules.Contains(options.Metadata.SignalRule) &&
                           pairConfig.SwapTimeout < (DateTimeOffset.Now - tradingPair.OrderDates.Max()).TotalSeconds);
                });

                if (swappedPair != null)
                {
                    Swap(new SwapOptions(swappedPair.Pair, options.Pair, options.Metadata));
                }
                else if (rule?.Action != Constants.SignalRuleActions.Swap)
                {
                    if (CanBuy(options, out string message))
                    {
                        tradingTimedTask.InitiateBuy(options);
                    }
                    else
                    {
                        loggingService.Debug(message);
                    }
                }
            }
        }
Example #11
0
 public T Get <T>(string key)
 {
     if (TryGet(key, out object data))
     {
         return((T)data);
     }
     else
     {
         logService.Debug($"No key {key} value found in current session");
         return(default(T));
     }
 }
Example #12
0
        public void Buy(BuyOptions options)
        {
            lock (syncRoot)
            {
                PauseTasks();
                try
                {
                    IRule       rule       = signalsService.Rules.Entries.FirstOrDefault(r => r.Name == options.Metadata.SignalRule);
                    RuleAction  ruleAction = rule?.Action ?? RuleAction.Default;
                    IPairConfig pairConfig = GetPairConfig(options.Pair);

                    bool arbitragePair = pairConfig.ArbitrageEnabled && pairConfig.ArbitrageSignalRules.Contains(options.Metadata.SignalRule);
                    if (arbitragePair)
                    {
                        Arbitrage arbitrage = Exchange.GetArbitrage(options.Pair, Config.Market, pairConfig.ArbitrageMarkets, pairConfig.ArbitrageType);
                        if (arbitrage.IsAssigned)
                        {
                            Arbitrage(new ArbitrageOptions(options.Pair, arbitrage, options.Metadata));
                        }
                    }
                    else
                    {
                        ITradingPair swappedPair = Account.GetTradingPairs().OrderBy(p => p.CurrentMargin).FirstOrDefault(tradingPair =>
                        {
                            IPairConfig tradingPairConfig = GetPairConfig(tradingPair.Pair);
                            return(tradingPairConfig.SellEnabled && tradingPairConfig.SwapEnabled && tradingPairConfig.SwapSignalRules != null &&
                                   tradingPairConfig.SwapSignalRules.Contains(options.Metadata.SignalRule) &&
                                   tradingPairConfig.SwapTimeout < (DateTimeOffset.Now - tradingPair.OrderDates.DefaultIfEmpty().Max()).TotalSeconds);
                        });

                        if (swappedPair != null)
                        {
                            Swap(new SwapOptions(swappedPair.Pair, options.Pair, options.Metadata));
                        }
                        else if (ruleAction == RuleAction.Default)
                        {
                            if (CanBuy(options, out string message))
                            {
                                tradingTimedTask.InitiateBuy(options);
                            }
                            else
                            {
                                loggingService.Debug(message);
                            }
                        }
                    }
                }
                finally
                {
                    ContinueTasks();
                }
            }
        }
Example #13
0
        public static void Debug <T>(this ILoggingService logging, IEnumerable <T> set)
        {
            if (set == null)
            {
                logging.Debug($"Mobile::Infrastructure::LoggingExtensions::Debug() - enumerable set in null");
                return;
            }

            foreach (var item in set)
            {
                logging.Debug(item);
            }
        }
Example #14
0
        private void StoreObjectIntoCache(object cacheObject, string cacheKey, System.Web.HttpContext context)
        {
            if (cacheObject != null)
            {
                loggingService.Debug("Storing object {0} into context cache", cacheKey);
            }

            // Only add to the cache when the object is not null
            if (cacheObject != null)
            {
                context.Items.Add(cacheKey, cacheObject);
            }
        }
        protected async Task <T> FindItemInCacheOrDataStoreAsync <T>(
            CacheIdentity cacheIdentity,
            Func <Task <T> > dataStoreQuery) where T : class
        {
            var cacheProviderMisses = new HashSet <int>();
            T   result = null;

            for (var i = 0; i <= _cacheProviders.Length - 1; i++)
            {
                var cacheProvider = _cacheProviders[i];

                _loggingService.Debug("Checking L{0} cache...", i + 1);

                var cached = await cacheProvider.GetAsync <T>(cacheIdentity.CacheKey);

                if (cached == null)
                {
                    _loggingService.Debug("L{0} - MISS", i + 1);
                    cacheProviderMisses.Add(i);
                }
                else
                {
                    _loggingService.Debug("L{0} - HIT", i + 1);
                    result = cached;
                    break;
                }
            }

            if (result == null)
            {
                _loggingService.Debug("Fetching data from data store...");
                result = await dataStoreQuery();

                if (result == null)
                {
                    _loggingService.Info("Couldn't find data in data store. Not adding to any caches.");
                    return(null);
                }
            }

            foreach (var cacheProviderMiss in cacheProviderMisses)
            {
                var cacheProvider = _cacheProviders[cacheProviderMiss];

                var expiryOnThisLevel = new TimeSpan(cacheIdentity.Expiry.Ticks / ((_cacheProviders.Length + 1) - (cacheProviderMiss + 1)));
                _loggingService.Debug("Adding to L{0} cache with an expiry of {1} minutes...", cacheProviderMiss + 1, expiryOnThisLevel.TotalMinutes);
                await cacheProvider.AddAsync(cacheIdentity.CacheKey, result, expiryOnThisLevel);
            }

            return(result);
        }
Example #16
0
        public void CreateDebugLog_GetDebugLogs_ReturnsDebugLogs()
        {
            //arrange

            logService.Debug("debug message");

            //act

            var logList = logService.GetLogs(LogType.Debug);

            //assert

            Assert.That(logList.ToArray().Count(), Is.EqualTo(1));
        }
Example #17
0
        public override async Task Update()
        {
            IsNoteFocused  = true;
            IsLoadingDecks = true;
            Note           = _repository.GetGameNote()?.ToString();

            Deck deck;

            if (EndGame.Settings.Get(Strings.DeveloperMode).Bool)
            {
                deck = _repository.GetOpponentDeckLive();
            }
            else
            {
                deck = _repository.GetOpponentDeck();
            }

            Cards.Clear();
            deck.Cards.ForEach(c => Cards.Add(c));
            PlayerClass = deck.Class.ToString();

            Decks.Clear();
            if (Cards.Count <= 0)
            {
                EndGame.Logger.Debug("NoteVM: Opponent deck is empty, skipping");
                IsLoadingDecks = false;
                return;
            }
            await Task.Run(() =>
            {
                var alldecks = _repository
                               .GetAllDecksWithTag(Strings.ArchetypeTag)
                               .Select(d => new ArchetypeDeck(d))
                               .ToList();
                var format  = EndGame.Data.GetGameFormat();
                var results = ViewModelHelper.MatchArchetypes(format, deck, alldecks);
                results.ForEach(r => Decks.Add(r));
                results.ForEach(r => _log.Debug($"Archetype: ({r.Similarity}, {r.Containment}) " +
                                                $"{r.Deck.DisplayName} ({r.Deck.Class})"));

                var firstDeck = Decks.FirstOrDefault();
                if (firstDeck != null && firstDeck.Similarity > MatchResult.THRESHOLD)
                {
                    DeckSelected(firstDeck);
                }

                IsLoadingDecks = false;
            });
        }
Example #18
0
        private static void ImportFile(string file)
        {
            if (!mFileSystem.File.Exists(file))
            {
                throw new FileNotFoundException(file);
            }

            mDataReader.FileName = file;

            mLoggingService.Debug("Reading set from '{0}'...", file);
            var setData = mFileSystem.File.ReadAllText(file);

            var set = mDataReader.ReadSet(setData);

            if (set == null)
            {
                throw new Exception("Set not found! Aborting.");
            }

            if (set.Type.ToLower() == "promo" && mSkipPromos)
            {
                mLoggingService.Info("Set '{0}' is a promp; skipping...", set.Name);

                return;
            }

            mLoggingService.Debug("Inserting set '{0}' [{1}]...",
                                  set.Name,
                                  set.Code);

            var cards = mDataReader.ReadCards(setData);

            var status = mImporter.Import(set, cards).Result;

            if (status != null)
            {
                mLoggingService.Info("Import Successful. Set={0}; CardsImported={1}; CardsFailed={2}",
                                     status.ImportedSet.Name,
                                     status.ImportedCards.Count,
                                     status.FailedCards.Count);
            }
            else
            {
                mLoggingService.Error("Import failed");
            }

            mLoggingService.Debug("Done reading cards from set '{0}'!", file);
        }
Example #19
0
        public async Task <GetAssetWeeklyTargetsResponse> GetAssetSettings(string[] assetUIDs, DateTime?startDate, DateTime?endDate)
        {
            GetAssetWeeklyTargetsResponse response = null;

            try
            {
                var isValidRequest = DoValidation(assetUIDs, startDate, endDate);

                if (assetUIDs.All(assetUID => isValidRequest.Select(request => request.AssetUID).Contains(assetUID)))
                {
                    //Condition Where All the Asset Has Error, Throw Domain Exception Then
                    throw new DomainException
                          {
                              Errors = isValidRequest
                          };
                }

                if (isDatePresent(startDate, endDate))
                {
                    _loggingService.Debug(string.Format("DatePresent - Call To DB For Extracting AssetWeeklySettingsBased on StartDate : {0} And EndDate : {1}", startDate.Value, endDate.Value), "AssetWeeklySettingsService.GetAssetSettings");
                    var assetSettings = GetAssetSettingsForTargetTypeWithAssetUIDStartDateAndEndDate(string.Join(",", assetUIDs.Where(assetUID => !isValidRequest.Select(request => request.AssetUID).Contains(assetUID))).WrapCommaSeperatedStringsWithUnhex(), startDate.Value, endDate.Value);
                    response = new GetAssetWeeklyTargetsResponse(_Converter.ExtractToAssetUtilizationTargets(assetSettings, _groupType).ToList());
                }
                else
                {
                    _loggingService.Debug(string.Format("DatePresent - Call To DB For Extracting AssetWeeklySettings Based on AssertUID {0}", string.Join(",", assetUIDs.Where(assetUID => !isValidRequest.Select(request => request.AssetUID).Contains(assetUID)))), "AssetWeeklySettingsService.GetAssetSettings");
                    var assetSettingsByAssetUID = GetAssetSettingsForTargetTypeWithAssetUID(string.Join(",", assetUIDs.Where(assetUID => !isValidRequest.Select(request => request.AssetUID).Contains(assetUID))).WrapCommaSeperatedStringsWithUnhex());
                    response = new GetAssetWeeklyTargetsResponse(_Converter.ExtractToAssetUtilizationTargets(assetSettingsByAssetUID, _groupType).ToList());
                }
                if (isValidRequest.Count > 0)
                {
                    response.Errors = isValidRequest;
                }
            }
            catch (DomainException ex)
            {
                _loggingService.Error(ex.Message, "AssetWeeklySettingsService.GetAssetSettings", ex);
                return(new GetAssetWeeklyTargetsResponse(new List <AssetErrorInfo>(ex.Errors.OfType <AssetErrorInfo>().ToList())));
            }
            catch (ArgumentException ex)
            {
                _loggingService.Error(ex.Message, "AssetWeeklySettingsService.GetAssetSettings", ex);
                return(new GetAssetWeeklyTargetsResponse(new AssetErrorInfo {
                    Message = "Arguments Are Wrong", ErrorCode = 400102
                }));
            }
            return(response);
        }
        /// <summary>
        /// Gets the quotes for the specified WKN.
        /// </summary>
        /// <param name="wkn">The WKN.</param>
        /// <param name="since">The minimum date for getting quotes (including).</param>
        /// <returns></returns>
        public IEnumerable <IQuotation> Get(string wkn, DateTime since)
        {
            var result = Enumerable.Empty <IQuotation>();

            try
            {
                long msec = 0;
                using (new TimeMeasure(t => msec = t))
                {
                    var provider = new QuotationDownloadBoerseDuesseldorf();

                    result = provider
                             .Initialize(wkn, $"http://www.boerse-duesseldorf.de/aktien/wkn/{wkn}/historische_kurse")
                             .Download()
                             .ExtractInformation(since);
                }

                _loggingService.Debug($"Downloaded quotes for {wkn} in {msec / 1000} seconds");
            }
            catch (Exception ex)
            {
                _loggingService.Error($"Download of quotes for {wkn} failed with message '{ex.Message}'");
            }

            return(result);
        }
Example #21
0
        /// <summary>
        /// Processes the given event <paramref name="eventData"/>
        /// </summary>
        /// <param name="eventData">Event data</param>
        public void Handle(StaticsticsBasicDataChangedEvent eventData)
        {
            var slices = _timeSliceCreationService.CreateTimeSlices(eventData.Date);

            //Re-calculate the statistics for all slices in parallel, because they to not overlap. The items in the repository
            //are therefore accessed in a non-blocking way.
            Parallel.ForEach(slices.GetAllSlices(),
                             slice =>
            {
                using (new TimeMeasure(ms => _loggingService.Debug($"Re-Calculate statistics for time range: {slice} in {ms} msec")))
                {
                    var calculationResult = _statisticService.Calculate(slice);

                    if (calculationResult == null)
                    {
                        return;
                    }

                    var item = _modelRepository.GetById(calculationResult);

                    if (item != null)
                    {
                        _modelRepository.Update(calculationResult);
                    }
                    else
                    {
                        _modelRepository.Add(calculationResult);
                    }
                }
            });
        }
    public async Task <Location> GetLastKnownLocationAsync()
    {
        Location location = null;

        try
        {
            location = await Geolocation.GetLastKnownLocationAsync();

            loggingService.Debug($"{nameof(GeolocationService)} : Location is successful");
        }
        catch (FeatureNotSupportedException fnsEx)
        {
            loggingService.Error(fnsEx);
        }
        catch (PermissionException pEx)
        {
            loggingService.Error(pEx);
        }
        catch (Exception ex)
        {
            loggingService.Error(ex);
        }

        return(location);
    }
Example #23
0
        public async Task <WrapResult <T> > TryWithErrorHandlingAsync <T>(
            Func <Task <T> > task,
            Func <Exception, Task <bool> > customErrorHandler = null)
        {
            var  result = WrapResult <T> .Failed;
            bool keepTrying;

            whenStarting?.Invoke();

            if (!connectivityService.IsThereInternet)
            {
                loggingService?.Warning("There's no Internet access");
                return(result);
            }

            do
            {
                keepTrying = false;

                try
                {
                    T actualResult = await task();

                    result = new WrapResult <T>(actualResult, true);
                }
                catch (HttpRequestException exception)
                {
                    loggingService?.Warning($"{exception}");

                    if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception))
                    {
                        await Application.Current.MainPage.DisplayAlert(
                            Resources.Alert_Title_UnexpectedError,
                            Resources.Alert_Message_InternetError,
                            Resources.Alert_OK_OKEllipsis);
                    }
                }
                catch (TaskCanceledException exception)
                {
                    loggingService?.Debug($"{exception}");
                }
                catch (Exception exception)
                {
                    loggingService?.Error(exception);

                    if (customErrorHandler == null || !await customErrorHandler?.Invoke(exception))
                    {
                        await Application.Current.MainPage.DisplayAlert(
                            Resources.Alert_Title_UnexpectedError,
                            Resources.Alert_Message_InternetError,
                            Resources.Alert_OK_OKEllipsis);
                    }
                }
            }while (keepTrying);

            whenFinished?.Invoke();

            return(result);
        }
Example #24
0
        private Dictionary <long, EITManager> _eitManagers = new Dictionary <long, EITManager>();  // frequency -> EITManager

        public DVBTDriverManager(ILoggingService loggingService, DVBTTelevizorConfiguration config)
        {
            _log = loggingService;

            _log.Debug($"Initializing DVBT driver manager");

            _config = config;
        }
        public VersionUriList GetItemVersions()
        {
            MakeSureWeAreReady();
            if (_versions == null)
            {
                var languages = LanguageManager.GetLanguages(Factory.GetDatabase(SitecoreConstants.SitecoreMasterDatabaseName)).Distinct();
                var versions  = new VersionUriList();
                foreach (var language in languages)
                {
                    _log.Debug <TemplateDataProvider>("Adding language to list of versions: " + language.CultureInfo.Name);
                    versions.Add(language, Version.First);
                }

                _versions = versions;
            }

            return(_versions);
        }
Example #26
0
 public virtual void LogDebug(string message, int logMessageType   = UNKNOWNLOGMESSAGETYPE,
                              [CallerMemberName] string methodName = "",
                              [CallerFilePath] string sourceFile   = "",
                              [CallerLineNumber] int lineNumber    = 0)
 {
     _log.Debug(message: message, logMessageType: logMessageType,
                methodName: methodName,
                sourceFile: sourceFile,
                lineNumber: lineNumber);
 }
        private async Task <DbConnection> OpenConnection(ConnectionName name, ApplicationIntent applicationIntent)
        {
            _loggingService.Debug($"Getting connection {name}:{applicationIntent}");
            var connStr = await ResolveConnString(name.ToString(), applicationIntent).Caf();

            var cnn = new SqlConnection(connStr);

            cnn.Open();
            return(cnn);
        }
Example #28
0
        public int Initialize(bool isSubProcess, params string[] args)
        {
            var path    = AppDomain.CurrentDomain.BaseDirectory;
            var binPath = isSubProcess ? path : Path.Combine(path, "bin");

            loggingService.Debug("[Initialize] cefPath: {0}", binPath);

            CefRuntime.Load(binPath);

            loggingService.Debug("[Initialize] Cef binaries found");

            var mainArgs = new CefMainArgs(args);

            var exitCode = CefRuntime.ExecuteProcess(mainArgs, this, IntPtr.Zero);

            loggingService.Debug("[Initialize] exitCode: " + exitCode);

            if (exitCode != -1 || isSubProcess)
            {
                // Sub-process will return here
                return(exitCode);
            }

            var settings = new CefSettings
            {
                SingleProcess            = false,
                MultiThreadedMessageLoop = true,
                LogSeverity = CefLogSeverity.Verbose,
                WindowlessRenderingEnabled = true,
                IgnoreCertificateErrors    = true,
                PersistSessionCookies      = false,
                BrowserSubprocessPath      = Path.Combine(binPath, "Axh.PageTracker.SubProcess.exe"),
                LocalesDirPath             = Path.Combine(binPath, "locales"),
                Locale  = "en-GB",
                LogFile = "C:\\Temp\\Cef.log"
            };

            CefRuntime.Initialize(mainArgs, settings, this, IntPtr.Zero);
            this.isInitialized = true;

            loggingService.Debug("[Initialize] Success");
            return(0);
        }
Example #29
0
        public Tuple <bool, List <DeviceConfigMsg> > ProcessMessage(DeviceConfigRequestBase requestBase, CommonModels.DeviceConfigMessage configMessage)
        {
            var failedAssets = String.Empty;

            try
            {
                _loggingService.Debug("Device Request Message : " + JsonConvert.SerializeObject(requestBase), "MessageConstructor.ProcessMessage");
                _loggingService.Debug("Device Config Message : " + JsonConvert.SerializeObject(configMessage), "MessageConstructor.ProcessMessage");
                if (requestBase == null || configMessage == null || !_groupContainer.ContainsKey(configMessage.Group.GroupName) || !_deviceTypeFamilyContainer.ContainsKey(requestBase.DeviceType))
                {
                    _loggingService.Info("Device Message Group Name / Device Type is invalid !!", "MessageConstructor.ProcessMessage");
                    return(Tuple.Create <bool, List <DeviceConfigMsg> >(false, null));
                }
                var deviceDetails     = new List <DeviceDetails>();
                var kafkaObjects      = new List <object>();
                var groupBuilder      = _groupContainer[configMessage.Group.GroupName];
                var deviceTypeFamily  = _deviceTypeFamilyContainer[requestBase.DeviceType];
                var failedAssetsList  = new List <string>();
                var deviceDataDetails = this.GetDeviceData(requestBase.AssetUIDs, requestBase, configMessage);
                switch (deviceTypeFamily.FamilyName)
                {
                case "DataOut":
                    failedAssetsList.AddRange(this.ProcessDataOutMessage(groupBuilder, requestBase, deviceDetails, kafkaObjects, configMessage, deviceDataDetails));
                    break;

                case "MTS":
                    failedAssetsList.AddRange(this.ProcessMtsOutMessage(groupBuilder, requestBase, deviceDetails, kafkaObjects, configMessage, deviceDataDetails));
                    break;

                case "PL":
                    failedAssetsList.AddRange(this.ProcessPLOutMessage(groupBuilder, requestBase, deviceDetails, kafkaObjects, configMessage, deviceDataDetails));
                    break;
                }
                var deviceConfigMsgs = GetDeviceConfigMsg(deviceDetails).ToList();
                if (!(failedAssets.Any() || !PersistPublish(deviceConfigMsgs, kafkaObjects)))
                {
                    return(Tuple.Create(true, deviceConfigMsgs));
                }
                else
                {
                    Exception ex = new MessageConstructorException("Unable to Complete Device Configuration for assetuid " + failedAssets);
                    _loggingService.Error("Unable to Complete Device Configuration for assetuid " + failedAssets, "MessageConstructor.ProcessMessage", ex);
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                _loggingService.Error("Unable to Complete Device Configuration for assetuid " + failedAssets, "MessageConstructor.ProcessMessage", ex);
                throw new MessageConstructorException("Unable to Complete Device Configuration for assetuid " + failedAssets);
            }
        }
        private void Closing()
        {
            var screenshot = Screenshots?.FirstOrDefault(s => s.IsSelected);

            if (screenshot != null)
            {
                _log.Debug($"Attempting to save screenshot #{screenshot.Index}");
                try
                {
                    _cap.SaveImage(screenshot);
                }
                catch (Exception e)
                {
                    _log.Error(e.Message);
                }
            }
            else
            {
                _log.Debug($"No screenshot selected (len={Screenshots?.Count})");
            }
        }