コード例 #1
0
ファイル: TagHandler.cs プロジェクト: karkn/MochaRefs
        public async Task <TagUse> RenameTagUseAsync(RenameTagUseRequest request)
        {
            SystemContract.RequireNotNullOrWhiteSpace(request.NewName, "request.NewName");
            SystemContract.RequireNotNullOrWhiteSpace(request.OldName, "request.OldName");

            /// NewNameの使用確認
            var newNameTagUseQuery = _refsContext.TagUses.Include("Owner").AsNoTracking().
                                     Where(u => u.OwnerId == request.OwnerId && u.Name == request.NewName);
            /// collationをcase insensitiveにしているので大文字小文字が異なるTagUseも取得される
            var newNameTagUses = await newNameTagUseQuery.ToArrayAsync();

            var isNewNameTagUseExists = newNameTagUses.Any(u => u.Name == request.NewName);

            BusinessContract.Require(!isNewNameTagUseExists, Errors.TagUseNameAlreadyExists, request.NewName);

            var oldNameTagUseQuery = _refsContext.TagUses.Include("Owner").
                                     Where(t => t.OwnerId == request.OwnerId && t.Name == request.OldName);
            /// collationをcase insensitiveにしているので大文字小文字が異なるTagUseも取得される
            var storedTagUses = await oldNameTagUseQuery.ToArrayAsync();

            var storedTagUse = storedTagUses.Single(u => u.Name == request.OldName);

            BusinessContract.ValidateWritePermission(request.OwnerId);
            BusinessContract.ValidateRowVersion(request.TagUseIdentity.RowVersion, storedTagUse.RowVersion);

            var tag = await EnsureTagAsync(request.NewName);

            storedTagUse.TagId = tag.Id;
            storedTagUse.Name  = request.NewName;

            _refsContext.MarkAsModified(storedTagUse);
            await _refsContext.SaveChangesAsync();

            return(storedTagUse);
        }
コード例 #2
0
        public async Task <EntityIdentity> MoveRefAsync(EntityIdentity identity, int oldIndex, int newIndex)
        {
            if (newIndex == oldIndex)
            {
                return(identity);
            }

            var query =
                from l in _refsContext.RefLists.Include("Refs")
                where l.Id == identity.Id
                select l;

            var storedRefList = await query.SingleOrDefaultAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRefList.RowVersion, identity.RowVersion);

            var refs   = storedRefList.Refs.OrderBy(r => r.DisplayOrder).ToList();
            var moving = refs[oldIndex];

            refs.RemoveAt(oldIndex);
            refs.Insert(newIndex, moving);
            for (int i = 0; i < refs.Count; ++i)
            {
                refs[i].DisplayOrder = i;
            }

            _refsContext.MarkAsModified(storedRefList);
            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(identity.Id);

            identity.RowVersion = storedRefList.RowVersion;
            return(identity);
        }
コード例 #3
0
        public async Task <ActionResult> AddByBookmarklet(string url)
        {
            /// bindするとvalidateで「<」とか「>」とかがだめになる
            var title = Request.Unvalidated.QueryString["title"];

            SystemContract.RequireNotNullOrWhiteSpace(url, "url");
            BusinessContract.Require(url.Length <= WebConsts.MaxRefLinkUrlLength, Errors.UrlTooLong);

            if (!string.IsNullOrWhiteSpace(title) && title.Length > WebConsts.MaxRefLinkTitleLength)
            {
                title = title.Substring(0, WebConsts.MaxRefLinkTitleLength);
            }

            var model = new AddByBookmarkletPageViewModel()
            {
                Uri   = url,
                Title = title,
            };

            var user = GetUser();
            var req  = new GetRefListsRequest(
                user.Id, null, null, null, "", null, PublishingStatusConditionKind.All, 0, 500, RefListSortKind.UpdatedDateDescending
                );
            var resp = await _refListHandler.GetRefListsAsync(req);

            model.RefLists = Mapper.Map <ICollection <RefListViewModel> >(resp.RefLists);

            return(View(model));
        }
コード例 #4
0
        /// <summary>
        /// refListIdのRefListにrefeを追加します。
        /// bookmarkletから呼ばれ、呼出し後はリダイレクトされるのでRowVersionのことは考えなくてよい。
        /// </summary>
        public async Task AddRefWithoutRowVersionAsync(long refListId, Ref refe)
        {
            var query =
                from l in _refsContext.RefLists.Include("Refs")
                where l.Id == refListId
                select l;

            var storedRefList = await query.SingleAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);

            refe.DisplayOrder = storedRefList.Refs.Count;
            refe.RefListId    = 0;
            refe.RefList      = null;
            storedRefList.Refs.Add(refe);

            /// update statistics
            if (refe.Kind == RefKind.Link)
            {
                var statisticsQuery  = _refsContext.RefListStatistics.Where(s => s.RefListId == refListId);
                var storedStatistics = await statisticsQuery.SingleAsync();

                storedStatistics.LinkCount = storedRefList.Refs.Count(r => r.Kind == RefKind.Link);
            }

            _refsContext.MarkAsModified(storedRefList);
            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(refListId);
        }
コード例 #5
0
 protected BusinessTransaction Map(IUserSettings userSettings, IProduct product, ApiTransactionSet transaction, ApiPerformance performance)
 {
     var businessTransaction = new BusinessTransaction()
     {
         Hash            = transaction.Hash,
         ContractAddress = product.Token.Address,
         BlockNumber     = transaction.BlockNumber,
         Confirmations   = transaction.Confirmations,
         ConfirmedAt     = transaction.ConfirmedAt,
         Success         = transaction.Success,
         Eth             = transaction.Eth,
         Gas             = transaction.Gas,
         GasLimit        = transaction.GasLimit,
         GasUsed         = transaction.GasUsed,
         Sender          = transaction.Sender,
         Recipient       = transaction.Recipient,
         Price           = performance != null
             ? new BusinessPrice()
         {
             MarketValuePerToken   = performance.MarketValuePerToken,
             NetAssetValuePerToken = performance.NetAssetValuePerToken
         }
             : null,
         Operations = transaction.Operations
                      .Select(operation => new BusinessOperation()
         {
             IsEth         = operation.IsEth,
             Sender        = operation.Sender,
             Address       = operation.Address,
             PricePerToken =
                 performance != null &&
                 operation.PricePerToken == default &&
                 operation.Contract.Symbol.Equals(product.Token.Symbol.ToString(), StringComparison.OrdinalIgnoreCase)
                         ? performance.MarketValuePerToken ?? performance.NetAssetValuePerToken
                         : operation.PricePerToken,
             Priority       = operation.Priority,
             Quantity       = operation.Quantity,
             Type           = operation.Type,
             Value          = operation.Value,
             Recipient      = operation.Recipient,
             TransferAction = GetOperationTransferAction(operation),
             Contract       = new BusinessContract()
             {
                 Symbol     = operation.Contract.Symbol,
                 Address    = operation.Contract.Address,
                 Decimals   = operation.Contract.Decimals,
                 Holders    = operation.Contract.Holders,
                 Issuances  = operation.Contract.Issuances,
                 Name       = operation.Contract.Name,
                 Link       = operation.Contract.Links.Link,
                 ImageLink  = operation.Contract.Links.ImageLink,
                 MarketLink = operation.Contract.Links.MarketLink
             }
         })
コード例 #6
0
        public async Task <AddRefResponse> AddRefAsync(EntityIdentity refListIdentity, int refIndex, Ref refe)
        {
            var query =
                from l in _refsContext.RefLists.Include("Refs")
                where l.Id == refListIdentity.Id
                select l;

            var storedRefList = await query.SingleAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRefList.RowVersion, refListIdentity.RowVersion);

            refe.RefListId = 0;
            refe.RefList   = null;

            var refs = storedRefList.Refs.OrderBy(r => r.DisplayOrder).ToList();

            refs.Insert(refIndex, refe);
            for (int i = 0; i < refs.Count; ++i)
            {
                refs[i].DisplayOrder = i;
            }

            storedRefList.Refs.Add(refe);

            /// update statistics
            if (refe.Kind == RefKind.Link)
            {
                var statisticsQuery  = _refsContext.RefListStatistics.Where(s => s.RefListId == refListIdentity.Id);
                var storedStatistics = await statisticsQuery.SingleAsync();

                storedStatistics.LinkCount = storedRefList.Refs.Count(r => r.Kind == RefKind.Link);
            }

            _refsContext.MarkAsModified(storedRefList);
            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(refListIdentity.Id);

            var ret = new AddRefResponse()
            {
                RefListIdentity = new EntityIdentity(storedRefList.Id, storedRefList.RowVersion),
                RefId           = refe.Id,
            };

            return(ret);
        }
コード例 #7
0
ファイル: TagHandler.cs プロジェクト: karkn/MochaRefs
        public async Task RemoveTagUsesAsync(EntityIdentity identity)
        {
            SystemContract.RequireEntityIdentity(identity);

            var query = _refsContext.TagUses.Include("RefLists").
                        Where(t => t.Id == identity.Id);

            var storedTagUse = await query.SingleAsync();

            BusinessContract.ValidateRowVersion(storedTagUse.RowVersion, identity.RowVersion);
            BusinessContract.ValidateWritePermission(storedTagUse.OwnerId);

            storedTagUse.RefLists.Clear();
            _refsContext.TagUses.Remove(storedTagUse);

            await _refsContext.SaveChangesAsync();
        }
コード例 #8
0
        public async Task <EntityIdentity> UpdateRefAsync(EntityIdentity identity, Ref updatedRef)
        {
            var query =
                from r in _refsContext.Refs.Include("RefList")
                where r.Id == updatedRef.Id
                select r;

            var storedRef = await query.SingleAsync();

            if (storedRef.RefListId != identity.Id)
            {
                throw new ArgumentException("リストのIdが正しくありません");
            }
            BusinessContract.ValidateWritePermission(storedRef.RefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRef.RefList.RowVersion, identity.RowVersion);

            switch (updatedRef.Kind)
            {
            case RefKind.Link:
                storedRef.Uri     = updatedRef.Uri;
                storedRef.Title   = updatedRef.Title;
                storedRef.Comment = updatedRef.Comment;
                break;

            case RefKind.Heading:
                storedRef.Title = updatedRef.Title;
                break;

            case RefKind.Text:
                storedRef.Comment = updatedRef.Comment;
                break;
            }

            if (_refsContext.IsModified(storedRef))
            {
                _refsContext.MarkAsModified(storedRef.RefList);
            }
            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(identity.Id);

            identity.RowVersion = storedRef.RefList.RowVersion;
            return(identity);
        }
コード例 #9
0
        public async Task <ActionResult> Detail(string userName, string titleSearch = "", string tag = null)
        {
            if (string.IsNullOrWhiteSpace(userName))
            {
                return(RedirectToAction("Index", "User"));
            }

            var author = await _UserHandler.GetUserByUserNameAsync(userName);

            BusinessContract.Require(author != null, Errors.UserNotFound, userName);

            /// 非公開設定の確認のため本人でもPublishしか見れないようにする。
            var req = new GetRefListsRequest(
                author.Id, null, null, tag, titleSearch, null, PublishingStatusConditionKind.PublishOnly, 0, WebConsts.RefListsPageSize,
                RefListSortKind.PublishedDateDescending
                );
            var result = await _refListHandler.GetRefListsAsync(req);

            var tagUses = await _tagHandler.GetAllTagUsesAsync(author.Id);

            var vm = new DetailPageViewModel()
            {
                Author       = Mapper.Map <UserViewModel>(author),
                OwnedTagUses = Mapper.Map <ICollection <TagUseViewModel> >(tagUses),
                TitleSearch  = titleSearch,
                TagUse       = tag,
                PageIndex    = result.PageIndex + 1,
                PageCount    = result.PageCount,
                RefLists     = Mapper.Map <ICollection <RefListViewModel> >(result.RefLists),
            };

            var isFavored = false;

            if (IsAuthenticated())
            {
                var user = GetUser();
                isFavored = await _favoriteHandler.ExistsFavoriteUserAsync(user.Id, author.Id);
            }
            vm.IsFavored = isFavored;

            return(View(vm));
        }
コード例 #10
0
        //public async Task<RefList> CreateUnfiledRefListAsync(long userId)
        //{
        //    var user = await _userHandler.GetUserAsync(userId);
        //    _refsContext.Users.Attach(user);

        //    var refList = new RefList()
        //    {
        //        Kind = RefListKind.Unfiled,
        //        Author = user,
        //        Title = "unfiled",
        //        Comment = "",
        //        PublishingStatus = PublishingStatusKind.Private,
        //        Refs = new Ref[0],
        //        Statistics = null,
        //    };
        //    _refsContext.RefLists.Add(refList);
        //    await _refsContext.SaveChangesAsync();

        //    return refList;
        //}

        public async Task RemoveRefListAsync(EntityIdentity refListIdentity)
        {
            var query         = _refsContext.RefLists.Include("TagUses").Where(l => l.Id == refListIdentity.Id);
            var storedRefList = await query.SingleAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRefList.RowVersion, refListIdentity.RowVersion);

            storedRefList.TagUses.Clear();
            foreach (var fav in storedRefList.FavoringFavorites.ToArray())
            {
                _refsContext.Favorites.Remove(fav);
            }
            _refsContext.RefListStatistics.Remove(storedRefList.Statistics);
            _refsContext.RefLists.Remove(storedRefList);

            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(refListIdentity.Id);
        }
コード例 #11
0
        public async Task <EntityIdentity> RemoveRefAsync(EntityIdentity refListIdentity, int refIndex)
        {
            var query =
                from l in _refsContext.RefLists.Include("Refs")
                where l.Id == refListIdentity.Id
                select l;

            var storedRefList = await query.SingleOrDefaultAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRefList.RowVersion, refListIdentity.RowVersion);

            var refs     = storedRefList.Refs.OrderBy(r => r.DisplayOrder).ToList();
            var removing = refs[refIndex];

            refs.RemoveAt(refIndex);

            for (int i = 0; i < refs.Count; ++i)
            {
                refs[i].DisplayOrder = i;
            }

            _refsContext.Refs.Remove(removing);

            /// update statistics
            if (removing.Kind == RefKind.Link)
            {
                var statisticsQuery  = _refsContext.RefListStatistics.Where(s => s.RefListId == refListIdentity.Id);
                var storedStatistics = await statisticsQuery.SingleAsync();

                storedStatistics.LinkCount = storedRefList.Refs.Count(r => r.Kind == RefKind.Link);
            }

            _refsContext.MarkAsModified(storedRefList);
            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(refListIdentity.Id);

            refListIdentity.RowVersion = storedRefList.RowVersion;
            return(refListIdentity);
        }
コード例 #12
0
        public async Task <EntityIdentity> UpdateRefListAsync(UpdateRefListRequest request)
        {
            var query =
                from l in _refsContext.RefLists.Include("TagUses.Tag").Include("TagUses.Statistics")
                where l.Id == request.Id
                select l;

            var storedRefList = await query.SingleOrDefaultAsync();

            BusinessContract.ValidateWritePermission(storedRefList.AuthorId);
            BusinessContract.ValidateRowVersion(storedRefList.RowVersion, request.RowVersion);

            var isPublishingStatusChanged = storedRefList.PublishingStatus != request.PublishingStatus;
            var isPublishedInThisTime     =
                storedRefList.PublishingStatus != PublishingStatusKind.Publish &&
                request.PublishingStatus == PublishingStatusKind.Publish;

            storedRefList.Title            = request.Title;
            storedRefList.Comment          = request.Comment;
            storedRefList.PublishingStatus = request.PublishingStatus;
            if (isPublishedInThisTime)
            {
                storedRefList.PublishedDate = DateTime.Now;
            }
            await SetTagUsesAsync(storedRefList, request.TagUses, isPublishingStatusChanged);

            await _refsContext.SaveChangesAsync();

            SendRefListUpdated(request.Id);

            return(new EntityIdentity()
            {
                Id = request.Id,
                RowVersion = storedRefList.RowVersion,
            });
        }
コード例 #13
0
        public async Task <EntityIdentity> MoveRefToAsync(
            EntityIdentity fromListIdentity, EntityIdentity toListIdentity, int fromRefIndex, int toRefIndex = -1
            )
        {
            using (var tran = _refsContext.BeginTransaction())
            {
                try
                {
                    SystemContract.Require(
                        fromRefIndex > -1,
                        () => new ArgumentOutOfRangeException("fromRefIndex: " + fromRefIndex)
                        );

                    var fromQuery = _refsContext.RefLists.Include("Refs").
                                    Where(l => l.Id == fromListIdentity.Id);
                    var fromStoredRefList = await fromQuery.SingleAsync();

                    SystemContract.Require(
                        fromRefIndex < fromStoredRefList.Refs.Count,
                        () => new ArgumentOutOfRangeException("fromRefIndex: " + fromRefIndex)
                        );
                    BusinessContract.ValidateWritePermission(fromStoredRefList.AuthorId);
                    BusinessContract.ValidateRowVersion(fromStoredRefList.RowVersion, fromListIdentity.RowVersion);

                    var toQuery = _refsContext.RefLists.Include("Refs").
                                  Where(l => l.Id == toListIdentity.Id);
                    var toStoredRefList = await toQuery.SingleAsync();

                    BusinessContract.ValidateWritePermission(toStoredRefList.AuthorId);
                    BusinessContract.ValidateRowVersion(toStoredRefList.RowVersion, toListIdentity.RowVersion);

                    /// fromから削除
                    var fromRefs = fromStoredRefList.Refs.OrderBy(r => r.DisplayOrder).ToList();
                    var moving   = fromRefs[fromRefIndex];
                    fromRefs.RemoveAt(fromRefIndex);
                    for (int i = 0; i < fromRefs.Count; ++i)
                    {
                        fromRefs[i].DisplayOrder = i;
                    }
                    fromStoredRefList.Refs.Remove(moving);

                    /// toに追加
                    var toRefs = toStoredRefList.Refs.OrderBy(r => r.DisplayOrder).ToList();
                    if (toRefIndex < 0)
                    {
                        toRefs.Add(moving);
                    }
                    else
                    {
                        toRefs.Insert(toRefIndex, moving);
                    }
                    for (int i = 0; i < toRefs.Count; ++i)
                    {
                        toRefs[i].DisplayOrder = i;
                    }
                    toStoredRefList.Refs.Add(moving);

                    _refsContext.MarkAsModified(fromStoredRefList);
                    await _refsContext.SaveChangesAsync(); // toのUpdatedDateをfromより後にするため早めに書き込む

                    /// update statistics
                    if (moving.Kind == RefKind.Link)
                    {
                        var fromStatQuery  = _refsContext.RefListStatistics.Where(s => s.RefListId == fromListIdentity.Id);
                        var storedFromStat = await fromStatQuery.SingleAsync();

                        storedFromStat.LinkCount = fromStoredRefList.Refs.Count(r => r.Kind == RefKind.Link);

                        var toStatQuery  = _refsContext.RefListStatistics.Where(s => s.RefListId == toListIdentity.Id);
                        var storedToStat = await toStatQuery.SingleAsync();

                        storedToStat.LinkCount = toStoredRefList.Refs.Count(r => r.Kind == RefKind.Link);
                    }

                    _refsContext.MarkAsModified(toStoredRefList);
                    await _refsContext.SaveChangesAsync(); // toのUpdatedDateをfromより後にするため遅めに書き込む

                    SendRefListUpdated(fromListIdentity.Id);
                    SendRefListUpdated(toListIdentity.Id);

                    fromListIdentity.RowVersion = fromStoredRefList.RowVersion;

                    tran.Commit();
                    return(fromListIdentity);
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }