コード例 #1
0
 public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
 {
     return(AsyncInfo.Run(c => loadContentAsync()));
 }
コード例 #2
0
 /// <summary>
 /// Retrieve the account details for a subaccount. Makes a GET request to an Account Instance resource.
 /// </summary>
 /// <param name="accountSid">The Sid of the subaccount to retrieve</param>
 public IAsyncOperation <Account> GetAccountAsync(string accountSid)
 {
     return((IAsyncOperation <Account>)AsyncInfo.Run((System.Threading.CancellationToken ct) => GetAccountAsyncInternal(accountSid)));
 }
コード例 #3
0
 /// <summary>
 /// Creates a new subaccount under the authenticated account. Makes a POST request to the Account List resource.
 /// </summary>
 /// <param name="friendlyName">Name associated with this account for your own reference (can be empty string)</param>
 public IAsyncOperation <Account> CreateSubAccountAsync(string friendlyName)
 {
     return((IAsyncOperation <Account>)AsyncInfo.Run((System.Threading.CancellationToken ct) => CreateSubAccountAsyncInternal(friendlyName)));
 }
コード例 #4
0
        }  // ReadAsync_MemoryStream

        internal static IAsyncOperationWithProgress <IBuffer, uint> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count,
                                                                                             InputStreamOptions options)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanRead);
            Debug.Assert(buffer != null);
            Debug.Assert(buffer is IBufferByteAccess);
            Debug.Assert(0 <= count);
            Debug.Assert(count <= int.MaxValue);
            Debug.Assert(count <= buffer.Capacity);
            Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);

            int bytesRequested = (int)count;

            // Check if the buffer is our implementation.
            // IF YES: In that case, we can read directly into its data array.
            // IF NO:  The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only
            //         read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read.
            //         The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own
            //         buffer instance, read data *directly* into the array backing it and then return it to the user.
            //         Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
            //         an array to read into either way.

            IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;

            if (dataBuffer == null)
            {
                dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
            }

            // This operation delegate will we run inside of the returned IAsyncOperationWithProgress:
            Func <CancellationToken, IProgress <uint>, Task <IBuffer> > readOperation = async(cancelToken, progressListener) =>
            {
                // No bytes read yet:
                dataBuffer.Length = 0;

                // Get the buffer backing array:
                byte[] data;
                int    offset;
                bool   managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
                Debug.Assert(managedBufferAssert);

                // Init tracking values:
                bool done           = cancelToken.IsCancellationRequested;
                int  bytesCompleted = 0;

                // Loop until EOS, cancelled or read enough data according to options:
                while (!done)
                {
                    int bytesRead = 0;

                    try
                    {
                        // Read asynchronously:
                        bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken)
                                    .ConfigureAwait(continueOnCapturedContext: false);

                        // We will continue here on a different thread when read async completed:
                        bytesCompleted += bytesRead;
                        // We will handle a cancelation exception and re-throw all others:
                    }
                    catch (OperationCanceledException)
                    {
                        // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed.
                        // (we check cancelToken.IsCancellationRequested later)
                        Debug.Assert(cancelToken.IsCancellationRequested);

                        // This is because if the cancellation came after we read some bytes we want to return the results we got instead
                        // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation:
                        if (bytesCompleted == 0 && bytesRead == 0)
                        {
                            throw;
                        }
                    }

                    // Update target buffer:
                    dataBuffer.Length = (uint)bytesCompleted;

                    Debug.Assert(bytesCompleted <= bytesRequested);

                    // Check if we are done:
                    done = options == InputStreamOptions.Partial || // If no complete read was requested, any amount of data is OK
                           bytesRead == 0 ||                          // this implies EndOfStream
                           bytesCompleted == bytesRequested ||        // read all requested bytes
                           cancelToken.IsCancellationRequested;       // operation was cancelled

                    // Call user Progress handler:
                    if (progressListener != null)
                    {
                        progressListener.Report(dataBuffer.Length);
                    }
                }  // while (!done)

                // If we got here, then no error was detected. Return the results buffer:
                return(dataBuffer);
            };  // readOperation

            return(AsyncInfo.Run <IBuffer, uint>(readOperation));
        }  // ReadAsync_AbstractStream
コード例 #5
0
        internal IAsyncOperation <TableResult> ExecuteAsync(CloudTableClient client, string tableName, TableRequestOptions requestOptions, OperationContext operationContext)
#endif
        {
            TableRequestOptions modifiedOptions = TableRequestOptions.ApplyDefaults(requestOptions, client);

            operationContext = operationContext ?? new OperationContext();

            CommonUtility.AssertNotNullOrEmpty("tableName", tableName);
            RESTCommand <TableResult> cmdToExecute = null;

            if (this.OperationType == TableOperationType.Insert ||
                this.OperationType == TableOperationType.InsertOrMerge ||
                this.OperationType == TableOperationType.InsertOrReplace)
            {
                if (!this.isTableEntity && this.OperationType != TableOperationType.Insert)
                {
                    CommonUtility.AssertNotNull("Upserts require a valid PartitionKey", this.Entity.PartitionKey);
                    CommonUtility.AssertNotNull("Upserts require a valid RowKey", this.Entity.RowKey);
                }

                cmdToExecute = InsertImpl(this, client, tableName, modifiedOptions);
            }
            else if (this.OperationType == TableOperationType.Delete)
            {
                if (!this.isTableEntity)
                {
                    CommonUtility.AssertNotNullOrEmpty("Delete requires a valid ETag", this.Entity.ETag);
                    CommonUtility.AssertNotNull("Delete requires a valid PartitionKey", this.Entity.PartitionKey);
                    CommonUtility.AssertNotNull("Delete requires a valid RowKey", this.Entity.RowKey);
                }

                cmdToExecute = DeleteImpl(this, client, tableName, modifiedOptions);
            }
            else if (this.OperationType == TableOperationType.Merge)
            {
                CommonUtility.AssertNotNullOrEmpty("Merge requires a valid ETag", this.Entity.ETag);
                CommonUtility.AssertNotNull("Merge requires a valid PartitionKey", this.Entity.PartitionKey);
                CommonUtility.AssertNotNull("Merge requires a valid RowKey", this.Entity.RowKey);

                cmdToExecute = MergeImpl(this, client, tableName, modifiedOptions);
            }
            else if (this.OperationType == TableOperationType.Replace)
            {
                CommonUtility.AssertNotNullOrEmpty("Replace requires a valid ETag", this.Entity.ETag);
                CommonUtility.AssertNotNull("Replace requires a valid PartitionKey", this.Entity.PartitionKey);
                CommonUtility.AssertNotNull("Replace requires a valid RowKey", this.Entity.RowKey);

                cmdToExecute = ReplaceImpl(this, client, tableName, modifiedOptions);
            }
            else if (this.OperationType == TableOperationType.Retrieve)
            {
                cmdToExecute = RetrieveImpl(this, client, tableName, modifiedOptions);
            }
            else
            {
                throw new NotSupportedException();
            }

#if ASPNET_K || PORTABLE
            return(Task.Run(() => Executor.ExecuteAsync(
                                cmdToExecute,
                                modifiedOptions.RetryPolicy,
                                operationContext,
                                cancellationToken), cancellationToken));
#else
            return(AsyncInfo.Run((cancellationToken) => Executor.ExecuteAsync(
                                     cmdToExecute,
                                     modifiedOptions.RetryPolicy,
                                     operationContext,
                                     cancellationToken)));
#endif
        }
コード例 #6
0
 /// <summary>
 /// List AuthorizedConnectApps on current account
 /// </summary>
 public IAsyncOperation <AuthorizedConnectAppResult> ListAuthorizedConnectAppsAsync()
 {
     return((IAsyncOperation <AuthorizedConnectAppResult>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ListAuthorizedConnectAppsAsyncInternal(null, null)));
 }
コード例 #7
0
ファイル: RestRequest.cs プロジェクト: fifa0329/RestRT
 /// <summary>
 /// Adds a file to the Files collection to be included with a POST or PUT request
 /// (other methods do not support file uploads).
 /// </summary>
 /// <param name="name">The parameter name to use in the request</param>
 /// <param name="path">Full path to file to upload</param>
 /// <returns>This request</returns>
 public IAsyncOperation <IRestRequest> AddFileAsync(string name, string path)
 {
     return((IAsyncOperation <IRestRequest>)AsyncInfo.Run((System.Threading.CancellationToken ct) => AddFileAsyncInternal(name, path)));
 }
コード例 #8
0
 /// <summary>
 /// Retrieves information about current state of the channel. This method is thread-safe.
 /// </summary>
 /// <returns>
 /// ChannelStateOperationResult with OperationStatus.Completed, OperationStatus.Cancelled or OperationStatus.Timeout as well as ChannelState indicating current number of active messages in the queue
 /// </returns>
 public IAsyncOperation <ChannelStateOperationResult> GetChannelStateAsync(TimeSpan timeout)
 {
     return(AsyncInfo.Run(async cancellationToken => new ChannelStateOperationResult(await _internal.GetChannelStateAsync(cancellationToken, timeout))));
 }
コード例 #9
0
 /// <summary>
 /// Asynchronously waits until writer will add new messafe to the queue. This method is thread-safe.
 /// </summary>
 /// <param name="timeout">Operation timeout.</param>
 /// <returns>
 /// OperationStatus.Completed, OperationStatus.Cancelled or OperationStatus.Timeout.
 /// </returns>
 public IAsyncOperation <OperationStatus> WhenQueueHasMessagesAsync(TimeSpan timeout)
 {
     return(AsyncInfo.Run(async cancellationToken => (OperationStatus)(await _internal.WhenQueueHasMessagesAsync(cancellationToken, timeout))));
 }
コード例 #10
0
        public override IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode)
        {
            return(AsyncInfo.Run <IRandomAccessStream>(async(cancellationToken) =>
            {
                bool rw = accessMode == FileAccessMode.ReadWrite;
                if (Path == ContainerPath)
                {
                    if (BackingFile != null)
                    {
                        return await BackingFile.OpenAsync(accessMode);
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, rw);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        return new FileStream(hFile, rw ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream();
                    }
                }

                if (!rw)
                {
                    ZipFile zipFile = await OpenZipFileAsync(accessMode);
                    if (zipFile == null)
                    {
                        return null;
                    }
                    zipFile.IsStreamOwner = true;
                    var znt = new ZipNameTransform(ContainerPath);
                    var entry = zipFile.GetEntry(znt.TransformFile(Path));
                    if (entry != null)
                    {
                        return new NonSeekableRandomAccessStreamForRead(zipFile.GetInputStream(entry), (ulong)entry.Size)
                        {
                            DisposeCallback = () => zipFile.Close()
                        };
                    }
                }
                else
                {
                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformFile(Path);

                    using (ZipFile zipFile = await OpenZipFileAsync(accessMode))
                    {
                        var entry = zipFile.GetEntry(zipDesiredName);
                        if (entry != null)
                        {
                            zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                            zipFile.Delete(entry);
                            zipFile.CommitUpdate();
                        }
                    }

                    if (BackingFile != null)
                    {
                        var zos = new ZipOutputStream((await BackingFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream(), true);
                        await zos.PutNextEntryAsync(new ZipEntry(zipDesiredName));
                        return new NonSeekableRandomAccessStreamForWrite(zos);
                    }
                    else
                    {
                        var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                        if (hFile.IsInvalid)
                        {
                            return null;
                        }
                        var zos = new ZipOutputStream(new FileStream(hFile, FileAccess.ReadWrite), true);
                        await zos.PutNextEntryAsync(new ZipEntry(zipDesiredName));
                        return new NonSeekableRandomAccessStreamForWrite(zos);
                    }
                }
                return null;
            }));
        }
コード例 #11
0
 public IAsyncAction BackgroundUpdate(CoreDispatcher uiDispatcher)
 {
     return(AsyncInfo.Run(SyncAll));
 }
コード例 #12
0
 public IAsyncOperation <bool> FlushAsync()
 {
     return(AsyncInfo.Run <bool>(_ => Task.Run(() => true)));
 }
コード例 #13
0
 public IAsyncOperation <Object> WriteScoreAsync(string name, string level, string score, MedalType medal)
 {
     return((IAsyncOperation <Object>)AsyncInfo.Run((CancellationToken token) => WriteTopScore(name, level, score, medal)));
 }
コード例 #14
0
 /// <summary>
 /// Deserializes Xml into an AnalyticsConfig object.
 /// </summary>
 /// <param name="source">The source URI of the config file.</param>
 /// <returns>An awaitable result.</returns>
 public static IAsyncOperation <AnalyticsConfig> Load(Uri source)
 {
     return(AsyncInfo.Run(c => InternalLoad(source)));
 }
コード例 #15
0
 /// <summary>
 /// Retrieve the details of a single transcription.
 /// Makes a GET request to a Transcription Instance resource.
 /// </summary>
 /// <param name="transcriptionSid">The Sid of the transcription to retrieve</param>
 public IAsyncOperation <Transcription> GetTranscriptionAsync(string transcriptionSid)
 {
     return((IAsyncOperation <Transcription>)AsyncInfo.Run((System.Threading.CancellationToken ct) => GetTranscriptionAsyncInternal(transcriptionSid)));
 }
コード例 #16
0
 /// <summary>
 /// Asynchronously waits when client will open this channel. This method is thread-safe.
 /// </summary>
 /// <returns>
 /// OpertionStatus.Completed or OperationStatus.Cancelled.
 /// </returns>
 public IAsyncOperation <OperationStatus> WhenClientConnectedAsync()
 {
     return(AsyncInfo.Run(async cancellationToken => (OperationStatus)await _internal.WhenClientConnectedAsync(cancellationToken, Timeout.InfiniteTimeSpan)));
 }
コード例 #17
0
 /// <summary>
 /// Retrieve the details for an AuthorizedConnectApp instance. Makes a GET request to an AuthorizedConnectApp Instance resource.
 /// </summary>
 /// <param name="authorizedConnectAppSid">The Sid of the AuthorizedConnectApp to retrieve</param>
 public IAsyncOperation <AuthorizedConnectApp> GetAuthorizedConnectAppAsync(string authorizedConnectAppSid)
 {
     return((IAsyncOperation <AuthorizedConnectApp>)AsyncInfo.Run((System.Threading.CancellationToken ct) => GetAuthorizedConnectAppAsyncInternal(authorizedConnectAppSid)));
 }
コード例 #18
0
        public HohoemaVideoListingPageViewModelBase(HohoemaApp app, PageManager pageManager, bool isRequireSignIn = true, bool useDefaultPageTitle = true)
            : base(app, pageManager, useDefaultPageTitle: useDefaultPageTitle)
        {
            var SelectionItemsChanged = SelectedItems.ToCollectionChanged().ToUnit();

#if DEBUG
            SelectedItems.CollectionChangedAsObservable()
            .Subscribe(x =>
            {
                Debug.WriteLine("Selected Count: " + SelectedItems.Count);
            })

            .AddTo(_CompositeDisposable);
#endif


            PlayAllCommand = SelectionItemsChanged
                             .Select(_ => SelectedItems.Count > 0)
                             .ToReactiveCommand(false)
                             .AddTo(_CompositeDisposable);

            PlayAllCommand
            .SubscribeOnUIDispatcher()
            .Subscribe(_ =>
            {
                // TODO: プレイリストに登録
                // プレイリストを空にしてから選択動画を登録

                //				SelectedVideoInfoItems.First()?.PlayCommand.Execute();
            })
            .AddTo(_CompositeDisposable);

            CancelCacheDownloadRequest = SelectionItemsChanged
                                         .Select(_ => SelectedItems.Count > 0)
                                         .ToReactiveCommand(false)
                                         .AddTo(_CompositeDisposable);

            CancelCacheDownloadRequest
            .SubscribeOnUIDispatcher()
            .Subscribe(async _ =>
            {
                var items  = EnumerateCacheRequestedVideoItems().ToList();
                var action = AsyncInfo.Run <uint>(async(cancelToken, progress) =>
                {
                    uint count = 0;
                    foreach (var item in items)
                    {
                        foreach (var quality in item.CachedQualityVideos.ToArray())
                        {
                            await HohoemaApp.CacheManager.CancelCacheRequest(item.RawVideoId, quality.Quality);
                        }

                        ++count;
                        progress.Report(count);
                    }

                    ClearSelection();
                });

                await PageManager.StartNoUIWork("キャッシュリクエストをキャンセル中", items.Count, () => action);
            }
                       )
            .AddTo(_CompositeDisposable);


            // クオリティ指定無しのキャッシュDLリクエスト
            RequestCacheDownload = SelectionItemsChanged
                                   .Select(_ => SelectedItems.Count > 0 && CanDownload)
                                   .ToReactiveCommand(false)
                                   .AddTo(_CompositeDisposable);

            RequestCacheDownload
            .SubscribeOnUIDispatcher()
            .Subscribe(async _ =>
            {
                foreach (var item in SelectedItems)
                {
                    await HohoemaApp.CacheManager.RequestCache(item.RawVideoId, NicoVideoQuality.Smile_Original);
                }

                ClearSelection();
                await UpdateList();
            })
            .AddTo(_CompositeDisposable);



            RegistratioMylistCommand = SelectionItemsChanged
                                       .Select(x => SelectedItems.Count > 0)
                                       .ToReactiveCommand(false)
                                       .AddTo(_CompositeDisposable);
            RegistratioMylistCommand
            .SubscribeOnUIDispatcher()
            .Subscribe(async _ =>
            {
                var targetMylist = await HohoemaApp.ChoiceMylist();

                if (targetMylist == null)
                {
                    return;
                }

                var items  = SelectedItems.ToList();
                var action = AsyncInfo.Run <uint>(async(cancelToken, progress) =>
                {
                    uint progressCount = 0;

                    Debug.WriteLine($"一括マイリストに追加を開始...");
                    int successCount = 0;
                    int existCount   = 0;
                    int failedCount  = 0;
                    foreach (var video in SelectedItems)
                    {
                        var registrationResult = await HohoemaApp.AddMylistItem(targetMylist, video.Label, video.RawVideoId);

                        switch (registrationResult)
                        {
                        case Mntone.Nico2.ContentManageResult.Success: successCount++; break;

                        case Mntone.Nico2.ContentManageResult.Exist: existCount++; break;

                        case Mntone.Nico2.ContentManageResult.Failed: failedCount++; break;

                        default:
                            break;
                        }

                        Debug.WriteLine($"{video.Label}[{video.RawVideoId}]:{registrationResult.ToString()}");

                        progressCount++;
                        progress.Report(progressCount);
                    }


                    if (targetMylist.Origin == PlaylistOrigin.LoginUser)
                    {
                        var mylistGroup = targetMylist as MylistGroupInfo;
                        await mylistGroup.Refresh();

                        // マイリストに追加に失敗したものを残すように
                        // 登録済みのアイテムを選択アイテムリストから削除
                        foreach (var item in SelectedItems.ToArray())
                        {
                            if (mylistGroup.CheckRegistratedVideoId(item.RawVideoId))
                            {
                                SelectedItems.Remove(item);
                            }
                        }
                    }

                    // リフレッシュ



                    // ユーザーに結果を通知

                    var titleText  = $"「{targetMylist.Label}」に {successCount}件 の動画を登録しました";
                    var resultText = $"";
                    if (existCount > 0)
                    {
                        resultText += $"重複:{existCount} 件";
                    }
                    if (failedCount > 0)
                    {
                        resultText += $"\n登録に失敗した {failedCount}件 は選択されたままです";
                    }

                    (App.Current as App).PublishInAppNotification(InAppNotificationPayload.CreateReadOnlyNotification(
                                                                      titleText,
                                                                      TimeSpan.FromSeconds(7)
                                                                      ));
                    //					ResetList();

                    Debug.WriteLine($"一括マイリストに追加を完了---------------");
                    ClearSelection();
                });

                await PageManager.StartNoUIWork("マイリストに追加", items.Count, () => action);
            }
                       )
            .AddTo(_CompositeDisposable);


            Playlists = HohoemaApp.Playlist.Playlists.ToReadOnlyReactiveCollection();
        }
コード例 #19
0
 public IAsyncOperation <AuthorizedConnectAppResult> ListAuthorizedConnectAppsAsync(int?pageNumber, int?count)
 {
     return((IAsyncOperation <AuthorizedConnectAppResult>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ListAuthorizedConnectAppsAsyncInternal(pageNumber, count)));
 }
コード例 #20
0
 public IAsyncOperation <bool> FlushAsync()
 {
     return(AsyncInfo.Run(_ => Task.FromResult(true)));
 }
コード例 #21
0
        }  // ReadAsync_AbstractStream

        #endregion ReadAsync implementations


        #region WriteAsync implementations

        internal static IAsyncOperationWithProgress <uint, uint> WriteAsync_AbstractStream(Stream stream, IBuffer buffer)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanWrite);
            Debug.Assert(buffer != null);

            // Choose the optimal writing strategy for the kind of buffer supplied:
            Func <CancellationToken, IProgress <uint>, Task <uint> > writeOperation;

            byte[] data;
            int    offset;

            // If buffer is backed by a managed array:
            if (buffer.TryGetUnderlyingData(out data, out offset))
            {
                writeOperation = async(cancelToken, progressListener) =>
                {
                    if (cancelToken.IsCancellationRequested)  // CancellationToken is non-nullable
                    {
                        return(0);
                    }

                    Debug.Assert(buffer.Length <= int.MaxValue);

                    int bytesToWrite = (int)buffer.Length;

                    await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false);

                    if (progressListener != null)
                    {
                        progressListener.Report((uint)bytesToWrite);
                    }

                    return((uint)bytesToWrite);
                };
                // Otherwise buffer is of an unknown implementation:
            }
            else
            {
                writeOperation = async(cancelToken, progressListener) =>
                {
                    if (cancelToken.IsCancellationRequested)  // CancellationToken is non-nullable
                    {
                        return(0);
                    }

                    uint   bytesToWrite = buffer.Length;
                    Stream dataStream   = buffer.AsStream();

                    int buffSize = 0x4000;
                    if (bytesToWrite < buffSize)
                    {
                        buffSize = (int)bytesToWrite;
                    }

                    await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false);

                    if (progressListener != null)
                    {
                        progressListener.Report((uint)bytesToWrite);
                    }

                    return((uint)bytesToWrite);
                };
            }  // if-else

            // Construct and run the async operation:
            return(AsyncInfo.Run <uint, uint>(writeOperation));
        }  // WriteAsync_AbstractStream
コード例 #22
0
        public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            return(AsyncInfo.Run(async(c) =>
            {
                if (CurrentIndex + count >= MaxNum)
                {
                    uint ItemNeedNum = MaxNum - CurrentIndex;
                    if (ItemNeedNum == 0)
                    {
                        HasMoreItems = false;
                        return new LoadMoreItemsResult {
                            Count = 0
                        };
                    }
                    else
                    {
                        IEnumerable <T> Result;

                        if (MoreItemsNeed == null)
                        {
                            Result = await MoreFolderNeed(CurrentIndex, ItemNeedNum, FolderQuery).ConfigureAwait(true);
                        }
                        else
                        {
                            Result = await MoreItemsNeed(CurrentIndex, ItemNeedNum, ItemQuery).ConfigureAwait(true);
                        }

                        for (int i = 0; i < Result.Count() && HasMoreItems; i++)
                        {
                            Add(Result.ElementAt(i));
                        }

                        CurrentIndex = MaxNum;
                        HasMoreItems = false;
                        return new LoadMoreItemsResult {
                            Count = ItemNeedNum
                        };
                    }
                }
                else
                {
                    IEnumerable <T> Result;

                    if (MoreItemsNeed == null)
                    {
                        Result = await MoreFolderNeed(CurrentIndex, count, FolderQuery).ConfigureAwait(true);
                    }
                    else
                    {
                        Result = await MoreItemsNeed(CurrentIndex, count, ItemQuery).ConfigureAwait(true);
                    }

                    for (int i = 0; i < Result.Count() && HasMoreItems; i++)
                    {
                        Add(Result.ElementAt(i));
                    }

                    CurrentIndex += count;
                    HasMoreItems = true;
                    return new LoadMoreItemsResult {
                        Count = count
                    };
                }
            }));
        }
コード例 #23
0
        /// <summary>
        /// 指定したテキスト、キャプション、ボタン、およびアイコンを表示するメッセージ ボックスを表示します。
        /// </summary>
        /// <param name="text">メッセージ ボックスに表示するテキスト。</param>
        /// <param name="caption">メッセージ ボックスのタイトル バーに表示するテキスト。</param>
        /// <param name="buttons">メッセージ ボックスに表示するボタンを指定する <see cref="MessageBoxButtons"/> 値の 1 つ。</param>
        /// <param name="icon">メッセージ ボックスに表示するアイコンを指定する <see cref="MessageBoxIcon"/> 値の 1 つ。互換性のために残しているもので実際には意味はありません。</param>
        /// <returns><see cref="DialogResult"/> 値のいずれか 1 つ。</returns>
        public static IAsyncOperation <DialogResult> ShowAsync(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            if (rootPage == null)
            {
                if (ApplicationSetting.rootPage != null)
                {
                    rootPage = ApplicationSetting.rootPage;
                }
                else
                {
                    throw new NullReferenceException("Tools.MessageBox.rootPage に 表示するページ(通常は this)を入れてください。");
                }
            }
            return(AsyncInfo.Run((token) => {
                return Task.Run(async() => {
                    DialogResult dr = DialogResult.Null;
                    await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => {
                        var msg = new MessageDialog(text, caption);
                        switch (buttons)
                        {
                        case MessageBoxButtons.OKCancel:
                            msg.Commands.Add(new UICommand("OK", null, DialogResult.OK));
                            msg.Commands.Add(new UICommand("キャンセル", null, DialogResult.Cancel));
                            msg.DefaultCommandIndex = 0;
                            msg.CancelCommandIndex = 1;
                            break;

                        case MessageBoxButtons.AbortRetryIgnore:
                            msg.Commands.Add(new UICommand("中止", null, DialogResult.Abort));
                            msg.Commands.Add(new UICommand("再試行", null, DialogResult.Retry));
                            msg.Commands.Add(new UICommand("無視", null, DialogResult.Ignore));
                            msg.DefaultCommandIndex = 1;
                            msg.CancelCommandIndex = 0;
                            break;

                        case MessageBoxButtons.YesNoCancel:
                            msg.Commands.Add(new UICommand("はい", null, DialogResult.Yes));
                            msg.Commands.Add(new UICommand("いいえ", null, DialogResult.No));
                            msg.Commands.Add(new UICommand("キャンセル", null, DialogResult.Cancel));
                            msg.DefaultCommandIndex = 0;
                            msg.CancelCommandIndex = 2;
                            break;

                        case MessageBoxButtons.YesNo:
                            msg.Commands.Add(new UICommand("はい", null, DialogResult.Yes));
                            msg.Commands.Add(new UICommand("いいえ", null, DialogResult.No));
                            msg.DefaultCommandIndex = 0;
                            msg.CancelCommandIndex = 1;
                            break;

                        case MessageBoxButtons.RetryCancel:
                            msg.Commands.Add(new UICommand("再試行", null, DialogResult.Retry));
                            msg.Commands.Add(new UICommand("キャンセル", null, DialogResult.Cancel));
                            msg.DefaultCommandIndex = 0;
                            msg.CancelCommandIndex = 1;
                            break;

                        default:
                            msg.Commands.Add(new UICommand("OK", null, DialogResult.OK));
                            msg.DefaultCommandIndex = 0;
                            break;
                        }

                        var res = await msg.ShowAsync();
                        dr = (DialogResult)res.Id;
                    });

                    while (dr == DialogResult.Null)
                    {
                        Task.WaitAll(Task.Delay(1000));
                    }
                    return dr;
                });
            }));
        }
コード例 #24
0
 /// <summary>
 /// Initializes incremental loading from the view.
 /// </summary>
 /// <param name="count">The number of items to load</param>
 /// <returns>The wrapped results of the load operation.</returns>
 public Windows.Foundation.IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
 {
     return(AsyncInfo.Run((c) => LoadMoreItemsAsync(c, count)));
 }
コード例 #25
0
 /// <summary>
 /// Changes the status of a subaccount. You must be authenticated as the master account to call this method on a subaccount.
 /// WARNING: When closing an account, Twilio will release all phone numbers assigned to it and shut it down completely.
 /// You can't ever use a closed account to make and receive phone calls or send and receive SMS messages.
 /// It's closed, gone, kaput. It will still appear in your accounts list, and you will still have access to historical
 /// data for that subaccount, but you cannot reopen a closed account.
 /// </summary>
 /// <param name="subAccountSid">The subaccount to change the status on</param>
 /// <param name="status">The status to change the subaccount to</param>
 public IAsyncOperation <Account> ChangeSubAccountStatusAsync(string subAccountSid, AccountStatus status)
 {
     return((IAsyncOperation <Account>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ChangeSubAccountStatusAsyncInternal(subAccountSid, status)));
 }
コード例 #26
0
 /// <summary>
 /// Returns a set of Transcriptions that includes paging information, sorted by 'DateUpdated', with most recent transcripts first.
 /// Makes a GET request to the Transcriptions List resource.
 /// </summary>
 public IAsyncOperation <TranscriptionResult> ListTranscriptionsAsync()
 {
     return((IAsyncOperation <TranscriptionResult>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ListTranscriptionsAsyncInternal(null, null)));
 }
コード例 #27
0
 /// <summary>
 /// List all subaccounts created for the authenticated account. Makes a GET request to the Account List resource.
 /// </summary>
 public IAsyncOperation <AccountResult> ListSubAccountsAsync()
 {
     return((IAsyncOperation <AccountResult>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ListSubAccountsAsyncInternal()));
 }
コード例 #28
0
 /// <summary>
 /// Returns a set of Transcriptions for a specific recording that includes paging information, sorted by 'DateUpdated',
 /// with most recent transcripts first. Makes a GET request to a Recording Transcriptions List resource.
 /// </summary>
 /// <param name="recordingSid">The Sid of the recording to retrieve transcriptions for</param>
 /// <param name="pageNumber">The page to start retrieving results from</param>
 /// <param name="count">The number of results to retrieve</param>
 public IAsyncOperation <TranscriptionResult> ListTranscriptionsAsync(string recordingSid, int?pageNumber, int?count)
 {
     return((IAsyncOperation <TranscriptionResult>)AsyncInfo.Run((System.Threading.CancellationToken ct) => ListTranscriptionsAsyncInternal(recordingSid, pageNumber, count)));
 }
コード例 #29
0
 /// <summary>
 /// Initializes incremental loading from the view.
 /// </summary>
 /// <param name="count">
 /// The number of items to load.
 /// </param>
 /// <returns>
 /// An object of the <see cref="LoadMoreItemsAsync(uint)"/> that specifies how many items have been actually retrieved.
 /// </returns>
 public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
 => AsyncInfo.Run((c) => LoadMoreItemsAsync(count, c));
コード例 #30
0
 /// <summary>
 /// Purchase/provision a local phone number
 /// </summary>
 /// <param name="options">Optional parameters to use when purchasing number</param>
 public IAsyncOperation <IncomingPhoneNumber> AddIncomingPhoneNumberAsync(PhoneNumberOptions options)
 {
     return((IAsyncOperation <IncomingPhoneNumber>)AsyncInfo.Run((System.Threading.CancellationToken ct) => AddIncomingPhoneNumberAsyncInternal(options)));
 }