public IList <ForeignExchangeRateModel> ToForeignExchangeRateModels(ForeignExchangeRateDto foreignExchangeRateDto, string date)
        {
            if (foreignExchangeRateDto == null || ListExtensions.IsNullOrEmpty(foreignExchangeRateDto.TargetCurrencies))
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var dateAsInt = GetDateAsInt(foreignExchangeRateDto.PublicationDate);

            if (dateAsInt.ToString() != date)
            {
                return(new List <ForeignExchangeRateModel>());
            }

            var rates = new List <ForeignExchangeRateDto> {
                foreignExchangeRateDto
            };

            return(rates.SelectMany(rate => rate.TargetCurrencies, (r, c) => new ForeignExchangeRateModel {
                Id = Guid.NewGuid(),
                Date = dateAsInt,
                BaseCurrency = TextExtensions.ToEnglishUpper(r.BaseCurrency),
                TargetCurrency = TextExtensions.ToEnglishUpper(c.TargetCurrency),
                InverseRate = ConvertExtensions.ToDecimal(c.InverseRate),
                PublicationDate = r.PublicationDate
            }).ToList());
        }
Ejemplo n.º 2
0
 public void IsNullOrEmptyTest()
 {
     Assert.IsTrue(ListExtensions.IsNullOrEmpty(null));
     Assert.IsTrue(ListExtensions.IsNullOrEmpty(new List <string>()));
     Assert.IsTrue(ListExtensions.IsNullOrEmpty(new List <string>()
     {
         string.Empty
     }));
     Assert.IsTrue(ListExtensions.IsNullOrEmpty(new List <string>()
     {
         ""
     }));
     Assert.IsTrue(ListExtensions.IsNullOrEmpty(new List <string>()
     {
         "", ""
     }));
     Assert.IsFalse(ListExtensions.IsNullOrEmpty(new List <string>()
     {
         "test"
     }));
     Assert.IsFalse(ListExtensions.IsNullOrEmpty(new List <string>()
     {
         "", "test"
     }));
 }
        public async Task BulkSaveAsync(IList <ForeignExchangeRateModel> foreignExchangeRates, IList <ForeignExchangeRateModel> foreignExchangeRatesToDelete)
        {
            if (!ListExtensions.IsNullOrEmpty(foreignExchangeRatesToDelete))
            {
                await _context.BulkDeleteAsync(foreignExchangeRatesToDelete);
            }

            if (!ListExtensions.IsNullOrEmpty(foreignExchangeRates))
            {
                await _context.AddRangeAsync(foreignExchangeRates);
            }
        }
        public InverseRatesDto ToInverseRatesDto(string @base, IList <ForeignExchangeRateModel> foreignExchangeRates)
        {
            if (ListExtensions.IsNullOrEmpty(foreignExchangeRates))
            {
                return(new InverseRatesDto {
                    Base = @base
                });
            }

            return(new InverseRatesDto
            {
                Base = foreignExchangeRates.FirstOrDefault()?.BaseCurrency ?? @base,
                Rates = foreignExchangeRates.ToDictionary(x => x.TargetCurrency, x => x.InverseRate.ToDecimalString(_cultureInfo))
            });
        }
        public async Task <GetForeignExchangeRateResponse> Handle(GetForeignExchangeRateRequest request, CancellationToken cancellationToken)
        {
            var response = new GetForeignExchangeRateResponse();

            var publicationDate = _publicationDateService.GetPublicationDate(request.Date);

            string cacheKey = _foreignExchangeRatesService.GetCacheKey(request.Base, request.Date, publicationDate);

            var dateAsInt = Convert.ToInt32(request.Date);

            var foreignExchangeRates = await _cachingService.GetOrCreateAsync
                                       (
                cacheKey,
                () => {
                return(_unitOfWork.ForeignExchangeRate
                       .GetWhereAsync(x => x.BaseCurrency == request.Base && x.Date == dateAsInt && x.PublicationDate == publicationDate));
            },
                AppConstants.CacheDurationInHourForeignExchangeRatesOfCurrency
                                       );

            if (ListExtensions.IsNullOrEmpty(foreignExchangeRates))
            {
                foreignExchangeRates = await _foreignExchangeRatesService.GetForeignExchangeRateModels(request.Base, request.Date);

                var foreignExchangeRatesToDelete = await _unitOfWork.ForeignExchangeRate.GetWhereAsync(x => x.BaseCurrency == request.Base && x.Date == dateAsInt && x.PublicationDate == publicationDate);

                await _unitOfWork.ForeignExchangeRate.BulkSaveAsync(foreignExchangeRates, foreignExchangeRatesToDelete);

                if (!ListExtensions.IsNullOrEmpty(foreignExchangeRates) || !ListExtensions.IsNullOrEmpty(foreignExchangeRatesToDelete))
                {
                    await _unitOfWork.CompleteAsync();
                }

                await _cachingService.SetAsync(cacheKey, foreignExchangeRates);
            }

            if (ListExtensions.IsNullOrEmpty(foreignExchangeRates))
            {
                foreignExchangeRates = new List <ForeignExchangeRateModel>();
            }

            response.Data = _foreignExchangeRatesService.ToInverseRatesDto(request.Base, foreignExchangeRates);

            return(response);
        }
 private void RespondToSelection(List <User> users, List <FriendsList> lists)
 {
     if (ListExtensions.IsNullOrEmpty((IList)users) && ListExtensions.IsNullOrEmpty((IList)lists))
     {
         return;
     }
     if (this._goBackOnResult)
     {
         ParametersRepository.SetParameterForId("SelectedUsers", users);
         if (ListExtensions.NotNullAndHasAtLeastOneNonNullElement((IList)lists))
         {
             ParametersRepository.SetParameterForId("SelectedLists", lists);
         }
         ((Page)this).NavigationService.GoBackSafe();
     }
     else if (this._createChat || users.Count > 1)
     {
         this.CreateChatAndProceed((List <long>)Enumerable.ToList <long>(Enumerable.Select <User, long>(users, (Func <User, long>)(u => u.uid))));
     }
     else
     {
         Navigator.Current.NavigateToConversation(((User)Enumerable.First <User>(users)).uid, false, true, "", 0, false);
     }
 }
Ejemplo n.º 7
0
        private List <IVirtualizable> GenereateVirtualizableItemsToAdd()
        {
            List <IVirtualizable> virtualizableList = new List <IVirtualizable>();

            if (!this._commentsAreLoaded)
            {
                LikesInfo likesInfo1 = new LikesInfo();
                likesInfo1.count        = this.VM.LikesCount;
                likesInfo1.repostsCount = this.VM.RepostsCount;
                List <long>     likesAllIds = this.VM.LikesAllIds;
                List <UserLike> m0List      = (likesAllIds != null ? Enumerable.ToList <UserLike>(Enumerable.Select <long, UserLike>(likesAllIds, (Func <long, UserLike>)(uid => new UserLike()
                {
                    uid = uid
                }))) :  null) ?? new List <UserLike>();
                likesInfo1.users = ((List <UserLike>)m0List);
                LikesInfo       likesInfo2 = likesInfo1;
                double          width1     = 480.0;
                Thickness       margin1    = new Thickness();
                LikedObjectData objectData = new LikedObjectData();
                objectData.OwnerId = this.VM.OwnerId;
                objectData.ItemId  = this.VM.ItemId;
                objectData.Type    = (int)this.VM.LikeObjectType;
                LikesInfo   likesInfo3   = likesInfo2;
                int         num1         = this.VM.CanRepost ? 1 : 0;
                int         num2         = this.VM.UserLiked ? 1 : 0;
                User        loggedInUser = AppGlobalStateManager.Current.GlobalState.LoggedInUser;
                List <User> users        = this.VM.Users;
                this._likesItem = new LikesItem(width1, margin1, objectData, likesInfo3, num1 != 0, num2 != 0, loggedInUser, users);
                virtualizableList.Add((IVirtualizable)this._likesItem);
                ISupportOtherVideos otherVideosVm = this.OtherVideosVM;
                List <VKClient.Common.Backend.DataObjects.Video> videoList;
                if (otherVideosVm == null)
                {
                    videoList = null;
                }
                else
                {
                    VKList <VKClient.Common.Backend.DataObjects.Video> otherVideos = otherVideosVm.OtherVideos;
                    videoList = otherVideos != null ? otherVideos.items :  null;
                }
                if (videoList != null && otherVideosVm.OtherVideos.items.Count > 0)
                {
                    VKList <VKClient.Common.Backend.DataObjects.Video> otherVideos = otherVideosVm.OtherVideos;
                    List <Group> groupList = new List <Group>();
                    List <User>  userList  = new List <User>();
                    if (otherVideos.profiles != null)
                    {
                        userList.AddRange((IEnumerable <User>)Enumerable.Select <User, User>(otherVideos.profiles, (Func <User, User>)(profile => new User()
                        {
                            id         = profile.id,
                            first_name = profile.first_name,
                            last_name  = profile.last_name
                        })));
                    }
                    if (otherVideos.groups != null)
                    {
                        groupList.AddRange((IEnumerable <Group>)Enumerable.Select <Group, Group>(otherVideos.groups, (Func <Group, Group>)(profile => new Group()
                        {
                            id   = profile.id,
                            name = profile.name
                        })));
                    }
                    double    width2  = 480.0;
                    Thickness margin2 = new Thickness(0.0, 0.0, 0.0, 8.0);
                    Func <UserControlVirtualizable> func1 = (Func <UserControlVirtualizable>)(() => (UserControlVirtualizable) new TextSeparatorUC()
                    {
                        Text = CommonResources.OtherVideos
                    });
                    // ISSUE: variable of the null type
                    double landscapeWidth1 = 0.0;
                    int    num3            = 0;
                    //Func<UserControlVirtualizable> getUserControlFunc1;
                    UCItem ucItem1 = new UCItem(width2, margin2, func1, (Func <double>)(() => 56.0), null, landscapeWidth1, num3 != 0);
                    virtualizableList.Add((IVirtualizable)ucItem1);
                    IVideoCatalogItemUCFactory catalogItemFactory = ServiceLocator.Resolve <IVideoCatalogItemUCFactory>();
                    IEnumerator <VKClient.Common.Backend.DataObjects.Video> enumerator = ((IEnumerable <VKClient.Common.Backend.DataObjects.Video>)Enumerable.Take <VKClient.Common.Backend.DataObjects.Video>(otherVideos.items, 3)).GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            VKClient.Common.Backend.DataObjects.Video video = enumerator.Current;
                            List <User>  knownUsers  = userList;
                            List <Group> knownGroups = groupList;
                            UCItem       ucItem2     = new UCItem(480.0, new Thickness(), (Func <UserControlVirtualizable>)(() =>
                            {
                                UserControlVirtualizable controlVirtualizable = catalogItemFactory.Create(video, knownUsers, knownGroups, StatisticsActionSource.video_recommend, this.CreateVideoContext(otherVideos.context));
                                ((System.Windows.Controls.Panel)(controlVirtualizable as CatalogItemUC).GridLayoutRoot).Background = ((Brush)(Application.Current.Resources["PhoneNewsBackgroundBrush"] as SolidColorBrush));
                                return(controlVirtualizable);
                            }), new Func <double> (() => catalogItemFactory.Height), null, 0.0, false);
                            virtualizableList.Add((IVirtualizable)ucItem2);
                        }
                    }
                    finally
                    {
                        if (enumerator != null)
                        {
                            enumerator.Dispose();
                        }
                    }
                    double    width3  = 480.0;
                    Thickness margin3 = new Thickness();
                    Func <UserControlVirtualizable> func2 = (Func <UserControlVirtualizable>)(() => new UserControlVirtualizable());
                    // ISSUE: variable of the null type
                    double landscapeWidth2 = 0.0;
                    int    num4            = 0;
                    //Func<UserControlVirtualizable> getUserControlFunc2;
                    UCItem ucItem3 = new UCItem(width3, margin3, func2, (Func <double>)(() => 8.0), null, landscapeWidth2, num4 != 0);
                    virtualizableList.Add((IVirtualizable)ucItem3);
                    if (otherVideos.items.Count > 3)
                    {
                        this._moreVideosUCItem = new UCItem(480.0, new Thickness(), (Func <UserControlVirtualizable>)(() => (UserControlVirtualizable) new CategoryFooterShortUC()
                        {
                            TapAction = new Action(this.MoreVideos_OnTap)
                        }), (Func <double>)(() => 64.0), null, 0.0, false);
                        virtualizableList.Add((IVirtualizable)this._moreVideosUCItem);
                    }
                }
                int totalCommentsCount = this.VM.TotalCommentsCount;
                this._commentsCountSeparatorUC = new TextSeparatorUC()
                {
                    Text = CommentsItemsGeneratorHelper.GetTextForCommentsCount(totalCommentsCount)
                };
                this._commentsCountItem = new UCItem(480.0, new Thickness(), (Func <UserControlVirtualizable>)(() => (UserControlVirtualizable)this._commentsCountSeparatorUC), (Func <double>)(() => 56.0), null, 0.0, false);
                virtualizableList.Add((IVirtualizable)this._commentsCountItem);
            }
            if (this.CommentsCountForReload > 0 && !ListExtensions.IsNullOrEmpty((IList)this.VM.Comments))
            {
                ShowMoreCommentsUC showMoreCommentsUc = new ShowMoreCommentsUC();
                double             num = 54.0;
                ((FrameworkElement)showMoreCommentsUc).Height = num;
                Action action = (Action)(() => this._loadMoreCommentsItem_Tap(null, null));
                showMoreCommentsUc.OnClickAction = action;
                string textFor = CommentsItemsGeneratorHelper.GetTextFor(this.CommentsCountForReload);
                showMoreCommentsUc.Text = textFor;
                ShowMoreCommentsUC showMoreCommentsUC = showMoreCommentsUc;
                this._loadMoreCommentsItem = new UCItem(480.0, new Thickness(), (Func <UserControlVirtualizable>)(() => (UserControlVirtualizable)showMoreCommentsUC), (Func <double>)(() => 54.0), null, 0.0, false);
                virtualizableList.Add((IVirtualizable)this._loadMoreCommentsItem);
            }
            long        num5         = -1;
            CommentItem commentItem1 = Enumerable.FirstOrDefault <IVirtualizable>(this.virtPanel.VirtualizableItems, (Func <IVirtualizable, bool>)(i => i is CommentItem)) as CommentItem;

            if (commentItem1 != null)
            {
                num5 = commentItem1.Comment.cid;
            }
            List <Comment> .Enumerator enumerator1 = this.VM.Comments.GetEnumerator();
            try
            {
                while (enumerator1.MoveNext())
                {
                    Comment current = enumerator1.Current;
                    if (current.cid != num5)
                    {
                        CommentItem commentItem2 = this.CreateCommentItem(current);
                        virtualizableList.Add((IVirtualizable)commentItem2);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            finally
            {
                enumerator1.Dispose();
            }
            ((UIElement)this.ucNewComment).Opacity          = (this.VM.CanComment ? 1.0 : 0.6);
            ((UIElement)this.ucNewComment).IsHitTestVisible = this.VM.CanComment;
            return(virtualizableList);
        }
Ejemplo n.º 8
0
        public async Task DownloadMetadataAsync(
            List <Game> games,
            GameDatabase database,
            MetadataDownloaderSettings settings,
            Action <Game, int, int> processCallback,
            CancellationTokenSource cancelToken)
        {
            await Task.Run(() =>
            {
                if (games == null || games.Count == 0)
                {
                    return;
                }

                for (int i = 0; i < games.Count; i++)
                {
                    if (cancelToken?.IsCancellationRequested == true)
                    {
                        return;
                    }

                    GameMetadata storeData = null;
                    GameMetadata igdbData  = null;
                    GameMetadata gameData  = null;

                    // We need to get new instance from DB in case game got edited or deleted.
                    // We don't want to block game editing while metadata is downloading for other games.
                    // TODO: Use Id instead of GameId once we replace LiteDB and have proper autoincrement Id
                    var game = database.GamesCollection.FindOne(a => a.PluginId == games[i].PluginId && a.GameId == games[i].GameId);
                    if (game == null)
                    {
                        logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata download.");
                        processCallback?.Invoke(null, i, games.Count);
                        continue;
                    }

                    try
                    {
                        logger.Debug($"Downloading metadata for {game.PluginId} game {game.Name}, {game.GameId}");

                        // Name
                        if (!game.IsCustomGame && settings.Name.Import)
                        {
                            gameData = ProcessField(game, settings.Name, ref storeData, ref igdbData, (a) => a.GameData?.Name);
                            if (!string.IsNullOrEmpty(gameData?.GameData?.Name))
                            {
                                game.Name       = StringExtensions.RemoveTrademarks(gameData.GameData.Name);
                                var sortingName = StringExtensions.ConvertToSortableName(game.Name);
                                if (sortingName != game.Name)
                                {
                                    game.SortingName = sortingName;
                                }
                            }
                        }

                        // Genre
                        if (settings.Genre.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Genres)))
                            {
                                gameData    = ProcessField(game, settings.Genre, ref storeData, ref igdbData, (a) => a.GameData?.Genres);
                                game.Genres = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Genres) ? game.Genres : gameData.GameData.Genres;
                            }
                        }

                        // Release Date
                        if (settings.ReleaseDate.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.ReleaseDate == null))
                            {
                                gameData         = ProcessField(game, settings.ReleaseDate, ref storeData, ref igdbData, (a) => a.GameData?.ReleaseDate);
                                game.ReleaseDate = gameData?.GameData?.ReleaseDate ?? game.ReleaseDate;
                            }
                        }

                        // Developer
                        if (settings.Developer.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Developers)))
                            {
                                gameData        = ProcessField(game, settings.Developer, ref storeData, ref igdbData, (a) => a.GameData?.Developers);
                                game.Developers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Developers) ? game.Developers : gameData.GameData.Developers;
                            }
                        }

                        // Publisher
                        if (settings.Publisher.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Publishers)))
                            {
                                gameData        = ProcessField(game, settings.Publisher, ref storeData, ref igdbData, (a) => a.GameData?.Publishers);
                                game.Publishers = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Publishers) ? game.Publishers : gameData.GameData.Publishers;
                            }
                        }

                        // Tags / Features
                        if (settings.Tag.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && ListExtensions.IsNullOrEmpty(game.Tags)))
                            {
                                gameData  = ProcessField(game, settings.Tag, ref storeData, ref igdbData, (a) => a.GameData?.Tags);
                                game.Tags = ListExtensions.IsNullOrEmpty(gameData?.GameData?.Tags) ? game.Tags : gameData.GameData.Tags;
                            }
                        }

                        // Description
                        if (settings.Description.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Description)))
                            {
                                gameData         = ProcessField(game, settings.Description, ref storeData, ref igdbData, (a) => a.GameData?.Description);
                                game.Description = string.IsNullOrEmpty(gameData?.GameData?.Description) == true ? game.Description : gameData.GameData.Description;
                            }
                        }

                        // Links
                        if (settings.Links.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.Links == null))
                            {
                                gameData   = ProcessField(game, settings.Links, ref storeData, ref igdbData, (a) => a.GameData?.Links);
                                game.Links = gameData?.GameData?.Links ?? game.Links;
                            }
                        }

                        // Critic Score
                        if (settings.CriticScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CriticScore == null))
                            {
                                gameData         = ProcessField(game, settings.CriticScore, ref storeData, ref igdbData, (a) => a.GameData?.CriticScore);
                                game.CriticScore = gameData?.GameData?.CriticScore == null ? game.CriticScore : gameData.GameData.CriticScore;
                            }
                        }

                        // Community Score
                        if (settings.CommunityScore.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && game.CommunityScore == null))
                            {
                                gameData            = ProcessField(game, settings.CommunityScore, ref storeData, ref igdbData, (a) => a.GameData?.CommunityScore);
                                game.CommunityScore = gameData?.GameData?.CommunityScore == null ? game.CommunityScore : gameData.GameData.CommunityScore;
                            }
                        }

                        // BackgroundImage
                        if (settings.BackgroundImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.BackgroundImage)))
                            {
                                gameData             = ProcessField(game, settings.BackgroundImage, ref storeData, ref igdbData, (a) => a.BackgroundImage);
                                game.BackgroundImage = string.IsNullOrEmpty(gameData?.BackgroundImage) ? game.BackgroundImage : gameData.BackgroundImage;
                            }
                        }

                        // Cover
                        if (settings.CoverImage.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.CoverImage)))
                            {
                                gameData = ProcessField(game, settings.CoverImage, ref storeData, ref igdbData, (a) => a.Image);
                                if (gameData?.Image != null)
                                {
                                    if (!string.IsNullOrEmpty(game.CoverImage))
                                    {
                                        database.DeleteImageSafe(game.CoverImage, game);
                                    }

                                    var imageId     = database.AddFileNoDuplicate(gameData.Image);
                                    game.CoverImage = imageId;
                                }
                            }
                        }

                        // Icon
                        if (settings.Icon.Import)
                        {
                            if (!settings.SkipExistingValues || (settings.SkipExistingValues && string.IsNullOrEmpty(game.Icon)))
                            {
                                gameData = ProcessField(game, settings.Icon, ref storeData, ref igdbData, (a) => a.Icon);
                                if (gameData?.Icon != null)
                                {
                                    if (!string.IsNullOrEmpty(game.Icon))
                                    {
                                        database.DeleteImageSafe(game.Icon, game);
                                    }

                                    var iconId = database.AddFileNoDuplicate(gameData.Icon);
                                    game.Icon  = iconId;
                                }
                            }
                        }

                        // TODO make this configurable and re-downalodable manually
                        // Only update them if they don't exist yet
                        if (game.OtherActions?.Any() != true && storeData != null)
                        {
                            if (storeData?.GameData?.OtherActions?.Any() == true)
                            {
                                game.OtherActions = new System.Collections.ObjectModel.ObservableCollection <GameAction>();
                                foreach (var task in storeData.GameData.OtherActions)
                                {
                                    game.OtherActions.Add(task);
                                }
                            }
                        }

                        // Just to be sure check if somebody didn't remove game while downloading data
                        if (database.GamesCollection.FindOne(a => a.GameId == games[i].GameId) != null)
                        {
                            database.UpdateGameInDatabase(game);
                        }
                        else
                        {
                            logger.Warn($"Game {game.GameId} no longer in DB, skipping metadata update in DB.");
                        }
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, $"Failed to download metadata for game {game.Name}, {game.GameId}");
                    }
                    finally
                    {
                        processCallback?.Invoke(game, i, games.Count);
                    }
                }
            });
        }