Beispiel #1
0
 public void Test2()
 {
     var th = new TaskHelper<int>();
     var t = th.Task;
     Assert.IsNotNull(t);
     var e =new InvalidProgramException();
     th.RunTask(null, e);
     Assert.IsTrue(t.IsFaulted);
     Assert.AreEqual(t.Exception.InnerException, e);
 }
Beispiel #2
0
        public void Test1()
        {
            var th = new TaskHelper<int>();
            var t = th.Task;

            Assert.IsNotNull(t);
            th.RunTask(10, null);
            Assert.IsTrue(t.IsCompleted);
            Assert.AreEqual(t.Result, 10);
        }
Beispiel #3
0
 private void FetchCommentsInStatuesList(List<Statuses> statuesList)
 {
     List<CommentMan> manList = new List<CommentMan>();
     m_taskHelper = new TaskHelper(
         delegate()
         {
             m_fetchCommentManListCompleted(manList);
         }, 5000);
     foreach (Statuses statues in statuesList)
     {
         m_taskHelper.PushTask();
         App.DoubanAPI.GetComments(statues.id,100, (args) =>
         {
             if (args.errorCode == DoubanSdkErrCode.SUCCESS && args.comments != null)
             {
                 foreach (DoubanSDK.Comment comment in args.comments)
                 {
                     // 去掉关注对象自己
                     if (comment.user.id != PreferenceHelper.GetPreference("Douban_FollowerID")
                         && comment.user.id != PreferenceHelper.GetPreference("Douban_ID"))
                     {
                         CommentMan man = new CommentMan
                         {
                             name = comment.user.screen_name,
                             id = comment.user.id
                         };
                         manList.Add(man);
                     }
                 }
                 m_taskHelper.PopTask();
             }
             else
             {
                 m_taskHelper.PopTask();
             }
         });
     }
 }
Beispiel #4
0
        public Task<ObservableCollection<double>> GetRandomData()
        {
            var th = new TaskHelper<NpvServiceClient, ObservableCollection<double>>(new NpvServiceClient());
            return th.GetTask<ObservableCollection<double>>(null);

            var tcs = new TaskCompletionSource<ObservableCollection<double>>();

            var client = new NpvServiceClient();

            client.GetRandomDataCompleted += (s, e) =>
            {
                if (e.Error != null)
                    tcs.TrySetException(e.Error);
                else if (e.Cancelled)
                    tcs.TrySetCanceled();
                else
                    tcs.TrySetResult(e.Result);
            };

            client.GetRandomDataAsync();

            return tcs.Task;
        }
Beispiel #5
0
        public Task<ObservableCollection<double>> GetRandomData(bool loadKnownValues)
        {
            var th = new TaskHelper<NpvServiceClient, ObservableCollection<double>>(new NpvServiceClient());
            return th.GetTask<ObservableCollection<double>>(new object[] { loadKnownValues});

            //var tcs = new TaskCompletionSource<ObservableCollection<double>>();

            //var client = new NpvServiceClient();

            //client.GetRandomDataCompleted += (s, e) =>
            //{
            //    if (e.Error != null)
            //        tcs.TrySetException(e.Error);
            //    else if (e.Cancelled)
            //        tcs.TrySetCanceled();
            //    else
            //        tcs.TrySetResult(e.Result);
            //};

            //client.GetRandomDataAsync();

            //return tcs.Task;
        }
Beispiel #6
0
 public Task<string> DoWork()
 {
     var th = new TaskHelper<NpvServiceClient, string>(new NpvServiceClient());
     return th.GetTask<string>(null);
 }
 protected IMapper GetMappingClient(RowSet rowset, MappingConfiguration config = null)
 {
     return(GetMappingClient(() => TaskHelper.ToTask(rowset), config));
 }
Beispiel #8
0
        private static async Task <IBackgroundTaskRegistration> RegisterSessionConnectedTask(TaskHelper helper)
        {
            var sessionConnTask = helper.GetTask(nameof(SessionConnectedTask)) ??
                                  await helper.RegisterTask(nameof(SessionConnectedTask),
                                                            typeof(SessionConnectedTask).FullName,
                                                            new SystemTrigger(SystemTriggerType.InternetAvailable, oneShot : false),
                                                            removeIfRegistered : false);

            return(sessionConnTask);
        }
Beispiel #9
0
        public override bool TakeAction()
        {
            //int maxEquNum = ConfigEnvSet.GetInt("UserQueue.EquStrengMaxNum");
            //int coldTime = ConfigEnvSet.GetInt("UserItem.EquColdTime");

            //铜钱不足
            var package = UserItemPackage.Get(Uid);

            userItem = package.ItemPackage.Find(m => !m.IsRemove && m.UserItemID.Equals(userItemID)) ?? new UserItemInfo();
            if (ops == StrongOnce)
            {
                // 强化 1 次用钱
                strongMoney = new UserItemHelper(userItem, 1).StrongMoney;
            }
            else if (ops == StrongTenTimes)
            {
                // 强化 10 次用钱
                strongMoney = new UserItemHelper(userItem, 10).StrongMoney;
            }
            short strongMaxLv = (ContextUser.UserLv * 3).ToShort(); //MathUtils.Addition(ContextUser.UserLv, 1.ToShort()); //强化最高等级

            if (ContextUser.GameCoin < strongMoney)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St_GameCoinNotEnough;
                return(false);
            }

            //UserGeneral userGeneral = new GameDataCacheSet<UserGeneral>().FindKey(ContextUser.UserID, userItem.GeneralID);
            //if (userGeneral != null && userItem.ItemLv >= strongMaxLv)
            //{
            //    ErrorCode = LanguageManager.GetLang().ErrorCode;
            //    ErrorInfo = LanguageManager.GetLang().St1204_EquGeneralMaxLv;
            //    return false;
            //}

            if (userItem.ItemLv >= strongMaxLv)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St1204_EquMaxLv;
                return(false);
            }

            itemInfo = new ConfigCacheSet <ItemBaseInfo>().FindKey(userItem.ItemID);
            if (itemInfo != null)
            {
                itemEquArray = new ConfigCacheSet <ItemEquAttrInfo>().FindAll(m => m.ItemID == itemInfo.ItemID);
            }

            if (strongMoney > ContextUser.GameCoin)
            {
                isStrong = 1;
            }
            else if (userItem.ItemLv >= strongMaxLv)
            {
                isStrong = 2;
            }


            UpdateUserItem(ContextUser, userItem, strongMoney);
            //日常任务-强化
            TaskHelper.TriggerDailyTask(Uid, 4001);

            UserGeneral general = new GameDataCacheSet <UserGeneral>().FindKey(ContextUser.UserID, userItem.GeneralID);

            if (general != null)
            {
                general.RefreshMaxLife();
            }
            return(true);
        }
        public async Task <object> ExecuteAsync(CancellationToken cancellationToken)
        {
            // Do you enoy the app?
            ContentDialogResult dialogResult = await _windowManager.ShowMessageDialogAsync(
                LanguageManager.Instance.RateAndReviewApp.EnjoyingMessage,
                LanguageManager.Instance.RateAndReviewApp.EnjoyingCloseButtonText,
                LanguageManager.Instance.RateAndReviewApp.EnjoyingPrimaryButtonText,
                title : LanguageManager.Instance.RateAndReviewApp.EnjoyingTitle,
                defaultButton : ContentDialogButton.Primary)
                                               .ConfigureAwait(true);

            if (dialogResult == ContentDialogResult.Primary)
            {
                // Yes!
                // Would you mind rating it?
                dialogResult = await _windowManager.ShowMessageDialogAsync(
                    LanguageManager.Instance.RateAndReviewApp.RateMessage,
                    LanguageManager.Instance.RateAndReviewApp.RateCloseButtonText,
                    LanguageManager.Instance.RateAndReviewApp.RatePrimaryButtonText,
                    LanguageManager.Instance.RateAndReviewApp.RateSecondaryButtonText,
                    LanguageManager.Instance.RateAndReviewApp.RateTitle,
                    defaultButton : ContentDialogButton.Primary)
                               .ConfigureAwait(true);

                if (dialogResult == ContentDialogResult.Primary)
                {
                    // Yes!
                    StoreContext storeContext = StoreContext.GetDefault();

                    StoreRateAndReviewResult result = await TaskHelper.RunOnUIThreadAsync(async() =>
                    {
                        return(await storeContext.RequestRateAndReviewAppAsync());
                    }).ConfigureAwait(false);

                    if (result.Status == StoreRateAndReviewStatus.Succeeded)
                    {
                        // do not ask again.
                        _settingsProvider.SetSetting(SettingsDefinitions.UserRatedAndReviewedTheApp, true);
                    }
                }
                else if (dialogResult == ContentDialogResult.Secondary)
                {
                    // Maybe later
                }
                else
                {
                    // No, thanks
                    // do not ask again.
                    _settingsProvider.SetSetting(SettingsDefinitions.UserRatedAndReviewedTheApp, true);
                }
            }
            else
            {
                // Not really
                // Would you give a feedback?
                dialogResult = await _windowManager.ShowMessageDialogAsync(
                    LanguageManager.Instance.RateAndReviewApp.FeedbackMessage,
                    LanguageManager.Instance.RateAndReviewApp.FeedbackCloseButtonText,
                    LanguageManager.Instance.RateAndReviewApp.FeedbackPrimaryButtonText,
                    title : LanguageManager.Instance.RateAndReviewApp.FeedbackTitle,
                    defaultButton : ContentDialogButton.Primary)
                               .ConfigureAwait(true);

                if (dialogResult == ContentDialogResult.Primary)
                {
                    // Ok, sure
                    await TaskHelper.RunOnUIThreadAsync(async() =>
                    {
                        await Launcher.LaunchUriAsync(new Uri("https://github.com/veler/pazword/issues/new/choose"));
                    }).ConfigureAwait(false);
                }

                // do not ask again.
                _settingsProvider.SetSetting(SettingsDefinitions.UserRatedAndReviewedTheApp, true);
            }

            return(null);
        }
Beispiel #11
0
 public bool WaitForLock(Guid resource, TimeSpan?lockTimeout, TimeSpan waitTime, out LockInfo lockInfo)
 {
     EnsureNotDisposed();
     lockInfo = TaskHelper.GetResultSafeSync(() => this.WaitForLockAsync(resource, lockTimeout, waitTime));
     return(lockInfo.AsImmutable().HasLock());
 }
        /// <summary>
        /// Returns a private scene (requires a token obtained from strong authentication with the Stormancer API).
        /// </summary>
        /// <remarks>
        /// The effective connection happens when "Connect" is called on the scene. Note that when you call GetScene,
        /// a connection token is requested from the Stormancer API.this token is only valid for a few minutes: Don't get scenes
        /// a long time before connecting to them.
        /// </remarks>
        /// <param name="token">The token securing the connection.</param>
        /// <returns>A task returning the scene object on completion.</returns>
        private Task <Scene> GetScene(string sceneId, SceneEndpoint ci)
        {
            return(TaskHelper.If(_serverConnection == null, () =>
            {
                return TaskHelper.If(!_transport.IsRunning, () =>
                {
                    _cts = new CancellationTokenSource();
                    return _transport.Start("client", new ConnectionHandler(), _cts.Token, null, (ushort)(_maxPeers + 1));
                })
                .Then(() =>
                {
                    UnityEngine.Debug.Log("Connecting transport...");
                    return _transport.Connect(ci.TokenData.Endpoints[_transport.Name]);
                })
                .Then(connection =>
                {
                    this.Logger.Log(Stormancer.Diagnostics.LogLevel.Trace, sceneId, string.Format("Trying to connect to scene '{0}' through endpoint : '{1}' on application : '{2}' with id : '{3}'", sceneId, ci.TokenData.Endpoints[_transport.Name], ci.TokenData.Application, ci.TokenData.AccountId));
                    _serverConnection = connection;
                    connection.ConnectionClosed += reason =>
                    {
                        var action = OnDisconnected;
                        if (action != null)
                        {
                            action(reason);
                        }
                    };

                    foreach (var kvp in _metadata)
                    {
                        _serverConnection.Metadata[kvp.Key] = kvp.Value;
                    }
                    return this.UpdateServerMetadata();
                })
                .Then(() =>
                {
                    if (ci.TokenData.Version > 0)
                    {
                        StartSyncClock();
                    }
                });
            }).Then(() =>
            {
                var parameter = new Stormancer.Dto.SceneInfosRequestDto {
                    Metadata = _serverConnection.Metadata, Token = ci.Token
                };
                return SendSystemRequest <Stormancer.Dto.SceneInfosRequestDto, Stormancer.Dto.SceneInfosDto>((byte)SystemRequestIDTypes.ID_GET_SCENE_INFOS, parameter);
            }).Then(result =>
            {
                if (_serverConnection.GetComponent <ISerializer>() == null)
                {
                    if (result.SelectedSerializer == null)
                    {
                        this.Logger.Error("No serializer selected");
                        throw new InvalidOperationException("No serializer selected.");
                    }
                    _serverConnection.RegisterComponent(_serializers[result.SelectedSerializer]);
                    _serverConnection.Metadata.Add("serializer", result.SelectedSerializer);
                    this.Logger.Info("Serializer selected: " + result.SelectedSerializer);
                }
                return UpdateServerMetadata().Then(() =>
                {
                    var scene = new Scene(this._serverConnection, this, sceneId, ci.Token, result, _pluginCtx, DependencyResolver);

                    var ev = _pluginCtx.SceneCreated;
                    if (ev != null)
                    {
                        ev(scene);
                    }

                    return scene;
                });
            }));


            //if (_serverConnection == null)
            //{
            //    if (!_transport.IsRunning)
            //    {
            //        cts = new CancellationTokenSource();
            //        await _transport.Start("client", new ConnectionHandler(), cts.Token, null, (ushort)(_maxPeers + 1));
            //    }
            //    _serverConnection = await _transport.Connect(ci.TokenData.Endpoints[_transport.Name]);
            //}


            //var parameter = new Stormancer.Dto.SceneInfosRequestDto { Metadata = _metadata, Token = ci.Token };

            //var result = await SendSystemRequest<Stormancer.Dto.SceneInfosRequestDto, Stormancer.Dto.SceneInfosDto>((byte)MessageIDTypes.ID_GET_SCENE_INFOS, parameter);

            //if (!_serverConnection.Components.ContainsKey("serializer"))
            //{
            //    if (result.SelectedSerializer == null)
            //    {
            //        throw new InvalidOperationException("No seralizer selected.");
            //    }
            //    _serverConnection.Components["serializer"] = _serializers[result.SelectedSerializer];
            //}
            //var scene = new Scene(this._serverConnection, this, sceneId, ci.Token, result);
            //_scenesDispatcher.AddScene(scene);
            //return scene;
        }
Beispiel #13
0
        public async Task <string> GetHashMd5(string kernelPath)
        {
            var hashProvider = new HashProvider();

            return(await TaskHelper <string> .AsyncPattern(hashProvider.CalculateMD5, kernelPath));
        }
Beispiel #14
0
 public async Task <bool> DirectoryExists(string siteName)
 {
     return(await TaskHelper <bool> .AsyncPattern(Directory.Exists, siteName));
 }
Beispiel #15
0
 public async Task <bool> RenameDirectory(string oldFileFullPath, string newFullPath)
 {
     return(await TaskHelper <bool> .AsyncPattern(RenameDirectorySync, oldFileFullPath, newFullPath));
 }
 public override Task ProcessAsync(EventContext ctx)
 {
     return(TaskHelper.Completed());
 }
 public Task Write(IContent content, Stream outputStream)
 {
     return(TaskHelper.Completed());
 }
        public void RunSync20()
        {
            _ = TaskHelper.RunSync(() => this.FireWithReturn(nameof(this.RunSync20)));

            Assert.AreEqual(this._fireResult, nameof(this.RunSync20));
        }
        public void RunSync10()
        {
            TaskHelper.RunSync(() => this.Fire(nameof(this.RunSync10)));

            Assert.AreEqual(this._fireResult, nameof(this.RunSync10));
        }
        public async Task <(IEnumerable <PublishedProviderResult>, IEnumerable <PublishedProviderResultExisting>)> GeneratePublishedProviderResultsToSave(IEnumerable <PublishedProviderResult> providerResults, IEnumerable <PublishedProviderResultExisting> existingResults)
        {
            Guard.ArgumentNotNull(providerResults, nameof(providerResults));
            Guard.ArgumentNotNull(existingResults, nameof(existingResults));

            ConcurrentBag <PublishedProviderResult> publishedProviderResultsToSave = new ConcurrentBag <PublishedProviderResult>();

            ConcurrentDictionary <string, ConcurrentDictionary <string, PublishedProviderResultExisting> > existingProviderResults = new ConcurrentDictionary <string, ConcurrentDictionary <string, PublishedProviderResultExisting> >();

            foreach (PublishedProviderResultExisting providerResult in existingResults)
            {
                if (!existingProviderResults.ContainsKey(providerResult.ProviderId))
                {
                    existingProviderResults.TryAdd(providerResult.ProviderId, new ConcurrentDictionary <string, PublishedProviderResultExisting>());
                }

                existingProviderResults[providerResult.ProviderId].TryAdd(providerResult.AllocationLineId, providerResult);
            }

            List <Task> allTasks = new List <Task>();

            SemaphoreSlim throttler = new SemaphoreSlim(initialCount: 30);

            foreach (PublishedProviderResult providerResult in providerResults)
            {
                await throttler.WaitAsync();

                allTasks.Add(
                    Task.Run(async() =>
                {
                    try
                    {
                        if (existingProviderResults.ContainsKey(providerResult.ProviderId))
                        {
                            ConcurrentDictionary <string, PublishedProviderResultExisting> existingResultsForProvider = existingProviderResults[providerResult.ProviderId];

                            if (existingResultsForProvider.TryGetValue(providerResult.FundingStreamResult.AllocationLineResult.AllocationLine.Id, out PublishedProviderResultExisting existingResult))
                            {
                                existingResultsForProvider.TryRemove(providerResult.FundingStreamResult.AllocationLineResult.AllocationLine.Id, out var removedExistingResult);

                                if (!existingResultsForProvider.Any())
                                {
                                    existingProviderResults.TryRemove(providerResult.ProviderId, out var removedProviderResult);
                                }

                                if (providerResult.FundingStreamResult.AllocationLineResult.Current.Value == existingResult.Value)
                                {
                                    existingProviderResults.TryRemove(providerResult.ProviderId, out var removedProviderResult);

                                    return;
                                }

                                providerResult.FundingStreamResult.AllocationLineResult.Current.Version =
                                    await _allocationResultsVersionRepository.GetNextVersionNumber(providerResult.FundingStreamResult.AllocationLineResult.Current, existingResult.Version, incrementFromCurrentVersion: true);

                                providerResult.FundingStreamResult.AllocationLineResult.HasResultBeenVaried = existingResult.HasResultBeenVaried;

                                if (existingResult.Status != AllocationLineStatus.Held)
                                {
                                    providerResult.FundingStreamResult.AllocationLineResult.Current.Status = AllocationLineStatus.Updated;
                                }

                                if (existingResult.Published != null)
                                {
                                    providerResult.FundingStreamResult.AllocationLineResult.Published = existingResult.Published;
                                }

                                providerResult.FundingStreamResult.AllocationLineResult.Current.Major = existingResult.Major;
                                providerResult.FundingStreamResult.AllocationLineResult.Current.Minor = existingResult.Minor;
                            }
                            else
                            {
                                providerResult.FundingStreamResult.AllocationLineResult.Current.Version = 1;
                            }
                        }
                        else
                        {
                            providerResult.FundingStreamResult.AllocationLineResult.Current.Version = 1;
                        }

                        publishedProviderResultsToSave.Add(providerResult);
                    }
                    finally
                    {
                        throttler.Release();
                    }
                }));
            }
            await TaskHelper.WhenAllAndThrow(allTasks.ToArray());

            // Need to remove results that have been varied
            List <PublishedProviderResult> publishedProviderResultsToSaveList = publishedProviderResultsToSave.ToList();

            publishedProviderResultsToSaveList.RemoveAll(r => r.FundingStreamResult.AllocationLineResult.HasResultBeenVaried);

            List <PublishedProviderResultExisting> existingRecordsExclude = new List <PublishedProviderResultExisting>(existingProviderResults.Values.Count);

            foreach (ConcurrentDictionary <string, PublishedProviderResultExisting> existingList in existingProviderResults.Values)
            {
                existingRecordsExclude.AddRange(existingList.Values.Where(r => !r.HasResultBeenVaried));
            }

            return(publishedProviderResultsToSaveList, existingRecordsExclude);
        }
Beispiel #21
0
 public async Task <Dictionary <string, DriveType> > GetDrives()
 {
     return(await TaskHelper <Dictionary <string, DriveType> > .AsyncPattern(GetDrivesSync));
 }
Beispiel #22
0
 public bool TryRenewLock(LockInfo lockInfo, TimeSpan?renewTimeout = null, bool retryLock = false)
 {
     EnsureNotDisposed();
     return(TaskHelper.GetResultSafeSync(() => TryRenewLockAsync(lockInfo, renewTimeout, retryLock)));
 }
Beispiel #23
0
 public async Task <string> GetDirectoryName(string directoryPath)
 {
     return(await TaskHelper <string> .AsyncPattern(GetDirectoryNameSync, directoryPath));
 }
Beispiel #24
0
 public bool TryLock(Guid resource, TimeSpan?lockTimeout, out LockInfo lockInfo)
 {
     EnsureNotDisposed();
     lockInfo = TaskHelper.GetResultSafeSync(() => TryLockAsync(resource, lockTimeout));
     return(lockInfo.AsImmutable().HasLock());
 }
Beispiel #25
0
 public async Task <bool> CreateDirectory(string directoryPath)
 {
     return(await TaskHelper <bool> .AsyncPattern(CreateDirectorySync, directoryPath));
 }
Beispiel #26
0
        private Task <IHTMLBinding> Navigate(Uri uri, object iViewModel, JavascriptBindingMode iMode = JavascriptBindingMode.TwoWay)
        {
            if (uri == null)
            {
                throw ExceptionHelper.GetArgument($"ViewModel not registered: {iViewModel.GetType()}");
            }

            _Navigating = true;

            var oldvm = Binding?.Root as INavigable;

            if (_UseINavigable && (oldvm != null))
            {
                oldvm.Navigation = null;
            }

            var wh = new WindowHelper(new HTMLLogicWindow());

            if (_CurrentWebControl != null)
            {
                _CurrentWebControl.HTMLWindow.Crashed -= Crashed;
            }

            var closetask = (_CurrentWebControl != null) ? _Window.CloseAsync() : TaskHelper.Ended();

            _NextWebControl = _WebViewLifeCycleManager.Create();
            _NextWebControl.HTMLWindow.ConsoleMessage += ConsoleMessage;

            var moderWindow = _NextWebControl.HTMLWindow as IModernWebBrowserWindow;

            if (moderWindow != null)
            {
                var debugContext = _WebViewLifeCycleManager.DebugContext;
                EventHandler <BeforeJavascriptExcecutionArgs> before = null;
                before = (o, e) =>
                {
                    moderWindow.BeforeJavascriptExecuted -= before;
                    e.JavascriptExecutor(_javascriptFrameworkManager.GetMainScript(debugContext));
                };
                moderWindow.BeforeJavascriptExecuted += before;
            }

            var tcs = new TaskCompletionSource <IHTMLBinding>();

            EventHandler <LoadEndEventArgs> sourceupdate = null;

            sourceupdate = (o, e) =>
            {
                var injectorFactory = GetInjectorFactory(uri);
                _NextWebControl.HTMLWindow.LoadEnd -= sourceupdate;
                var engine = new HTMLViewEngine(_NextWebControl, injectorFactory, _webSessionLogger);

                HTML_Binding.Bind(engine, iViewModel, iMode, wh).WaitWith(closetask, t => Switch(t, wh.__window__, tcs));
            };

            Url = uri;
            _NextWebControl.HTMLWindow.LoadEnd += sourceupdate;
            _NextWebControl.HTMLWindow.NavigateTo(uri);

            return(tcs.Task);
        }
Beispiel #27
0
    // Use this for initialization
    void Start()
    {
        currentScore = GameObject.Find("CurrentScore").GetComponent<CurrentScore>();
        fullScore = GameObject.FindObjectOfType<FullScore>();
        score = GetComponent<Score>();
        energy = GetComponent<Energy>();
        energyLine = GameObject.FindObjectOfType<EnergyLine>();
        inputController = GameObject.FindObjectOfType<InputController>();
        timerScript = GameObject.FindObjectOfType<TimerScript>();
        timerUI = GameObject.FindObjectOfType<TimerUI>();
        info = GetComponent<Info>();
        taskStrings = GetComponent<TaskStrings>();
        pauseButton = GameObject.FindObjectOfType<PauseButton>().gameObject;
        pauseMenu = GameObject.Find("Canvas").GetComponentInChildren<PauseMenu>();
          //  endMenu = GameObject.FindObjectOfType<EndMenu>();
        taskHelper = GameObject.FindObjectOfType<TaskHelper>();
        globalController = GetComponent<GlobalController>();
        cam = GameObject.Find("MainCamera");
        secondCamera = GameObject.Find("SecondCamera");
        wordRideCanvas = GameObject.FindObjectOfType<WordRideCanvas>();

        metalSparksPrefab = Resources.Load("Prefabs/Particles/MetalSpark") as GameObject;
        carUserParametres = GetComponent<CarUserParametres>();
        gameUI = GameObject.FindObjectOfType<GameUI>();
        canvasController = GameObject.FindObjectOfType<CanvasController>();

        particleCanvas = GameObject.Find("ParticleCanvas");
        carCreator = GameObject.FindObjectOfType<CarCreator>();

        mainBonus = GameObject.FindObjectOfType<MainBonus>();

        waitBackground = GameObject.FindObjectOfType<WaitBackground>();
    }
Beispiel #28
0
        private static async Task <IBackgroundTaskRegistration> RegisterSignalingTask(TaskHelper helper, bool registerAgain = true)
        {
            var signalingTask = helper.GetTask(nameof(SignalingTask)) ??
                                await helper.RegisterTask(nameof(SignalingTask), typeof(SignalingTask).FullName,
                                                          new SocketActivityTrigger(), registerAgain).AsTask();

            return(signalingTask);
        }
Beispiel #29
0
        protected override void OnReceived(byte[] data)
        {
            Actived = DateTimeHelper.Now;

            if (data != null)
            {
                this.UserToken.Unpacker.Unpack(data, (s) =>
                {
                    if (s.Content != null)
                    {
                        try
                        {
                            var cm = ConvertHelper.PBDeserialize <ChatMessage>(s.Content);

                            switch (cm.Type)
                            {
                            case ChatMessageType.LoginAnswer:
                                this.Logined = true;
                                _autoResetEvent.Set();
                                break;

                            case ChatMessageType.SubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _subscribed = true;
                                }
                                else
                                {
                                    _subscribed = false;
                                }
                                _autoResetEvent.Set();
                                break;

                            case ChatMessageType.UnSubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _unsubscribed = true;
                                }
                                else
                                {
                                    _unsubscribed = false;
                                }
                                _autoResetEvent.Set();
                                break;

                            case ChatMessageType.ChannelMessage:
                                TaskHelper.Start(() => OnChannelMessage?.Invoke(cm.GetIMessage <ChannelMessage>()));
                                break;

                            case ChatMessageType.PrivateMessage:
                                TaskHelper.Start(() => OnPrivateMessage?.Invoke(cm.GetIMessage <PrivateMessage>()));
                                break;

                            case ChatMessageType.GroupMessage:
                                TaskHelper.Start(() => OnGroupMessage?.Invoke(cm.GetIMessage <GroupMessage>()));
                                break;

                            case ChatMessageType.PrivateMessageAnswer:
                                _autoResetEvent.Set();
                                break;

                            case ChatMessageType.CreateGroupAnswer:
                            case ChatMessageType.RemoveGroupAnswer:
                            case ChatMessageType.AddMemberAnswer:
                            case ChatMessageType.RemoveMemberAnswer:
                                _autoResetEvent.Set();
                                break;

                            case ChatMessageType.GroupMessageAnswer:
                                _autoResetEvent.Set();
                                break;

                            default:
                                ConsoleHelper.WriteLine("cm.Type", cm.Type);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            RaiseOnError("", ex);
                        }
                    }
                }, null, null);
            }
        }
Beispiel #30
0
 public async Task <bool> DeleteFile(string directory)
 {
     return(await TaskHelper <bool> .AsyncPattern(DeleteFileSync, directory));
 }
Beispiel #31
0
        protected async Task <Tuple <bool, IBaseEventTriggerModel> > TriggerProcess <T>(T model, ProcessConfigModel processConfigModel) where T : BaseEventTriggerModel <T>
        {
            var isExcute = false;

            var hWnd            = IntPtr.Zero;
            var applciationData = ObjectExtensions.GetInstance <ApplicationDataManager>().Find(model.ProcessInfo.ProcessName) ?? new ApplicationDataModel();

            for (int i = 0; i < processConfigModel.Processes.Count; ++i)
            {
                var factor = CalculateFactor(processConfigModel.Processes[i].MainWindowHandle, model, applciationData.IsDynamic);

                if (string.IsNullOrEmpty(applciationData.HandleName))
                {
                    hWnd = processConfigModel.Processes[i].MainWindowHandle;
                }
                else
                {
                    var item = NativeHelper.GetChildHandles(processConfigModel.Processes[i].MainWindowHandle).Where(r => r.Item1.Equals(applciationData.HandleName)).FirstOrDefault();

                    if (item != null)
                    {
                        hWnd = item.Item2;
                    }
                    else
                    {
                        hWnd = processConfigModel.Processes[i].MainWindowHandle;
                    }
                }

                if (model.RepeatInfo.RepeatType == RepeatType.Search && model.SubEventTriggers.Count > 0)
                {
                    var count = model.RepeatInfo.Count;
                    while (DisplayHelper.ProcessCapture(processConfigModel.Processes[i], out Bitmap bmp, applciationData.IsDynamic) && count-- > 0)
                    {
                        var targetBmp  = model.Image.Resize((int)Math.Truncate(model.Image.Width * factor.Item1.Item1), (int)Math.Truncate(model.Image.Height * factor.Item1.Item1));
                        var similarity = OpenCVHelper.Search(bmp, targetBmp, out Point location, processConfigModel.SearchImageResultDisplay);
                        LogHelper.Debug($"RepeatType[Search : {count}] : >>>> Similarity : {similarity} % max Loc : X : {location.X} Y: {location.Y}");
                        CaptureImage(bmp);
                        if (!await TaskHelper.TokenCheckDelayAsync(model.AfterDelay, processConfigModel.Token) || similarity > processConfigModel.Similarity)
                        {
                            break;
                        }
                        for (int ii = 0; ii < model.SubEventTriggers.Count; ++ii)
                        {
                            await TriggerProcess(model.SubEventTriggers[ii], processConfigModel);

                            if (processConfigModel.Token.IsCancellationRequested)
                            {
                                break;
                            }
                        }
                        factor = CalculateFactor(processConfigModel.Processes[i].MainWindowHandle, model, applciationData.IsDynamic);
                    }
                }
                else
                {
                    if (DisplayHelper.ProcessCapture(processConfigModel.Processes[i], out Bitmap bmp, applciationData.IsDynamic))
                    {
                        var targetBmp  = model.Image.Resize((int)Math.Truncate(model.Image.Width * factor.Item1.Item1), (int)Math.Truncate(model.Image.Height * factor.Item1.Item2));
                        var similarity = OpenCVHelper.Search(bmp, targetBmp, out Point location, processConfigModel.SearchImageResultDisplay);
                        LogHelper.Debug($"Similarity : {similarity} % max Loc : X : {location.X} Y: {location.Y}");
                        if (model.SameImageDrag == false)
                        {
                            CaptureImage(bmp);
                        }
                        if (similarity > processConfigModel.Similarity)
                        {
                            if (model.SubEventTriggers.Count > 0)
                            {
                                if (model.RepeatInfo.RepeatType == RepeatType.Count || model.RepeatInfo.RepeatType == RepeatType.Once)
                                {
                                    for (int ii = 0; ii < model.RepeatInfo.Count; ++ii)
                                    {
                                        if (!await TaskHelper.TokenCheckDelayAsync(model.AfterDelay, processConfigModel.Token))
                                        {
                                            break;
                                        }
                                        for (int iii = 0; iii < model.SubEventTriggers.Count; ++iii)
                                        {
                                            await TriggerProcess(model.SubEventTriggers[iii], processConfigModel);

                                            if (processConfigModel.Token.IsCancellationRequested)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (model.RepeatInfo.RepeatType == RepeatType.NoSearch)
                                {
                                    while (await TaskHelper.TokenCheckDelayAsync(model.AfterDelay, processConfigModel.Token))
                                    {
                                        isExcute = false;
                                        for (int ii = 0; ii < model.SubEventTriggers.Count; ++ii)
                                        {
                                            var childResult = await TriggerProcess(model.SubEventTriggers[ii], processConfigModel);

                                            if (processConfigModel.Token.IsCancellationRequested)
                                            {
                                                break;
                                            }
                                            if (isExcute == false && childResult.Item1)
                                            {
                                                isExcute = childResult.Item1;
                                            }
                                        }
                                        if (!isExcute)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                isExcute = true;
                                if (model.EventType == EventType.Mouse)
                                {
                                    location.X = applciationData.OffsetX;
                                    location.Y = applciationData.OffsetY;
                                    MouseTriggerProcess(hWnd, location, model, factor.Item2);
                                }
                                else if (model.EventType == EventType.Image)
                                {
                                    if (model.SameImageDrag == true)
                                    {
                                        //Todo
                                        for (int ii = 0; ii < model.MaxSameImageCount; ++ii)
                                        {
                                            var locations = OpenCVHelper.MultipleSearch(bmp, targetBmp, processConfigModel.Similarity, 2, processConfigModel.SearchImageResultDisplay);
                                            if (locations.Count > 1)
                                            {
                                                CaptureImage(bmp);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var percentage = _random.NextDouble();

                                        location.X = ((location.X + applciationData.OffsetX) / factor.Item2.Item1) + (targetBmp.Width / factor.Item2.Item1 * percentage);
                                        location.Y = ((location.Y + applciationData.OffsetY) / factor.Item2.Item2) + (targetBmp.Height / factor.Item2.Item1 * percentage);
                                        ImageTriggerProcess(hWnd, location, model);
                                    }
                                }
                                else if (model.EventType == EventType.RelativeToImage)
                                {
                                    location.X = ((location.X + applciationData.OffsetX) / factor.Item2.Item1) + (targetBmp.Width / factor.Item2.Item1 / 2);
                                    location.Y = ((location.Y + applciationData.OffsetY) / factor.Item2.Item2) + (targetBmp.Height / factor.Item2.Item2 / 2);
                                    ImageTriggerProcess(hWnd, location, model);
                                }

                                else if (model.EventType == EventType.Keyboard)
                                {
                                    KeyboardTriggerProcess(processConfigModel.Processes[i].MainWindowHandle, model);
                                }
                                if (!await TaskHelper.TokenCheckDelayAsync(model.AfterDelay, processConfigModel.Token))
                                {
                                    break;
                                }

                                if (model.EventToNext > 0 && model.TriggerIndex != model.EventToNext)
                                {
                                    IBaseEventTriggerModel nextModel = null;
                                    if (model is GameEventTriggerModel)
                                    {
                                        nextModel = ObjectExtensions.GetInstance <CacheDataManager>().GetGameEventTriggerModel(model.EventToNext);
                                    }
                                    else if (model is EventTriggerModel)
                                    {
                                        nextModel = ObjectExtensions.GetInstance <CacheDataManager>().GetEventTriggerModel(model.EventToNext);
                                    }

                                    if (nextModel != null)
                                    {
                                        LogHelper.Debug($">>>>Next Move Event : CurrentIndex [ {model.TriggerIndex} ] NextIndex [ {nextModel.TriggerIndex} ] ");
                                        return(Tuple.Create(isExcute, nextModel));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            await TaskHelper.TokenCheckDelayAsync(processConfigModel.ItemDelay, processConfigModel.Token);

            return(Tuple.Create <bool, IBaseEventTriggerModel>(isExcute, null));
        }
        /// <summary>
        /// Switches the GUI into "waiting" mode, then calls <paramref name="taskCreation"/> to create
        /// the task.
        /// If another task is started before the previous task finishes running, the previous task is cancelled.
        /// </summary>
        public Task <T> RunWithCancellation <T>(Func <CancellationToken, Task <T> > taskCreation)
        {
            if (!waitAdorner.IsVisible)
            {
                waitAdorner.IsVisible = true;
                // Work around a WPF bug by setting IsIndeterminate only while the progress bar is visible.
                // https://github.com/icsharpcode/ILSpy/issues/593
                progressBar.IsIndeterminate = true;
                //waitAdorner.BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(0.5)), FillBehavior.Stop));
                //var taskBar = MainWindow.Instance.TaskbarItemInfo;
                //if (taskBar != null) {
                //	taskBar.ProgressState = Avalonia.Shell.TaskbarItemProgressState.Indeterminate;
                //}
            }
            CancellationTokenSource previousCancellationTokenSource = currentCancellationTokenSource;
            var myCancellationTokenSource = new CancellationTokenSource();

            currentCancellationTokenSource = myCancellationTokenSource;
            // cancel the previous only after current was set to the new one (avoid that the old one still finishes successfully)
            if (previousCancellationTokenSource != null)
            {
                previousCancellationTokenSource.Cancel();
            }

            var      tcs = new TaskCompletionSource <T>();
            Task <T> task;

            try {
                task = taskCreation(myCancellationTokenSource.Token);
            } catch (OperationCanceledException) {
                task = TaskHelper.FromCancellation <T>();
            } catch (Exception ex) {
                task = TaskHelper.FromException <T>(ex);
            }
            Action continuation = delegate {
                try {
                    if (currentCancellationTokenSource == myCancellationTokenSource)
                    {
                        currentCancellationTokenSource = null;
                        waitAdorner.IsVisible          = false;
                        progressBar.IsIndeterminate    = false;
                        //var taskBar = MainWindow.Instance.TaskbarItemInfo;
                        //if (taskBar != null) {
                        //	taskBar.ProgressState = Avalonia.Shell.TaskbarItemProgressState.None;
                        //}
                        if (task.IsCanceled)
                        {
                            AvaloniaEditTextOutput output = new AvaloniaEditTextOutput();
                            output.WriteLine("The operation was canceled.");
                            ShowOutput(output);
                        }
                        tcs.SetFromTask(task);
                    }
                    else
                    {
                        tcs.SetCanceled();
                    }
                } finally {
                    myCancellationTokenSource.Dispose();
                }
            };

            task.ContinueWith(delegate { Dispatcher.UIThread.InvokeAsync(continuation, DispatcherPriority.Normal); });
            return(tcs.Task);
        }
Beispiel #33
0
        public override bool TakeAction()
        {
            //if (ContextUser.EnergyNum <= 0)
            //{
            //    ErrorCode = LanguageManager.GetLang().ErrorCode;
            //    ErrorInfo = LanguageManager.GetLang().St_EnergyNotEnough;
            //    return false;
            //}
            //if (ContextUser.EnergyNum <= 0 && ContextUser.TempEnergyNum == 0)
            //{
            //    ErrorCode = LanguageManager.GetLang().ErrorCode;
            //    ErrorInfo = LanguageManager.GetLang().St_EnergyNotEnough;
            //    return false;
            //}
            if (ContextUser.UserStatus == UserStatus.SaoDang)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St4007_Saodanging;
                return(false);
            }
            if (ContextUser.UseMagicID == 0)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St4004_NoUseMagic;
                return(false);
            }
            if (new PersonalCacheStruct <UserEmbattle>().FindAll(Uid, m => m.MagicID == ContextUser.UseMagicID).Count == 0)
            {
                ErrorCode = LanguageManager.GetLang().ErrorCode;
                ErrorInfo = LanguageManager.GetLang().St4004_EmbattleEmpty;
                return(false);
            }

            //if (ContextUser.TempEnergyNum == 0)
            //{
            //    ErrorCode = LanguageManager.GetLang().ErrorCode;
            //    ErrorInfo = LanguageManager.GetLang().St_EnergyNotEnough;
            //    return false;
            //}

            ContextUser.UserStatus = UserStatus.Combat;
            try
            {
                //触发战斗
                PlotNPCInfo npcInfo = new ShareCacheStruct <PlotNPCInfo>().FindKey(PlotNpcID);

                //原因:碰npc时掉线,再请求战斗详情
                if (npcInfo == null)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().LoadDataError;
                    return(false);
                }

                //原因:最后一个npc时,清空玩家保存副本
                if (ContextUser.UserExtend != null && ContextUser.UserExtend.MercenarySeq > npcInfo.NpcSeqNo)
                {
                    ContextUser.UserStatus = UserStatus.Normal;
                    ContextUser.UserExtend.UpdateNotify(obj =>
                    {
                        ContextUser.UserExtend.PlotStatusID = 0;
                        ContextUser.UserExtend.PlotNpcID    = -1;
                        ContextUser.UserExtend.MercenarySeq = 1;
                        ContextUser.UserExtend.IsBoss       = false;
                        return(true);
                    });
                    //ErrorCode = LanguageManager.GetLang().ErrorCode;
                    //ErrorInfo = LanguageManager.GetLang().St4011_NoMonster;
                    //return false;
                }

                PlotInfo plotInfo = new ShareCacheStruct <PlotInfo>().FindKey(npcInfo.PlotID);
                if (plotInfo == null)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().LoadDataError;
                    return(false);
                }

                var cacheSetUserPlot = new PersonalCacheStruct <UserPlotPackage>();
                var cacheSetItemInfo = new ShareCacheStruct <ItemBaseInfo>();
                var cacheSet         = new PersonalCacheStruct <UserPlotCombat>();
                var userPlotPack     = cacheSetUserPlot.FindKey(ContextUser.UserID);
                var userPlot         = userPlotPack != null?userPlotPack.PlotPackage.Find(s => s.PlotID == npcInfo.PlotID) : null;

                //PlotHelper.IsKill(ContextUser.UserID, plotInfo.PlotID, plotInfo.CityID)
                if (userPlot != null && userPlot.PlotNum >= plotInfo.ChallengeNum)
                {
                    if (plotInfo.PlotType == PlotType.Elite)
                    {
                        ErrorCode = LanguageManager.GetLang().ErrorCode;
                        ErrorInfo = LanguageManager.GetLang().St4002_EliteUsed;
                        return(false);
                    }
                    else if (plotInfo.PlotType == PlotType.HeroPlot)
                    {
                        ErrorCode = LanguageManager.GetLang().ErrorCode;
                        ErrorInfo = LanguageManager.GetLang().St4002_HeroPlotNum;
                        return(false);
                    }
                }

                //if (userPlot != null && userPlot.ItemList != null)
                //{
                //    userPlot.UpdateNotify(obj =>
                //    {
                //        userPlot.ItemList.Clear();
                //        return true;
                //    });
                //}
                if (npcInfo.NpcSeqNo == 1)
                {
                    userPlot.ItemList.Clear();
                    ContextUser.IsItem = false;
                }
                userPlotCombat = cacheSet.FindKey(ContextUser.UserID, PlotNpcID);
                if (userPlotCombat != null && userPlotCombat.IsWin && ContextUser.UserExtend != null &&
                    PlotNpcID == ContextUser.UserExtend.PlotNpcID && !ContextUser.IsItem)
                {
                    prizeItems = PlotHelper.GetPlotMonsterItems(Uid, npcInfo.PlotNpcID);
                }
                else
                {
                    ISingleCombat plotCombater = CombatFactory.TriggerPlot(ContextUser, PlotNpcID);
                    if (plotCombater == null)
                    {
                        ErrorCode = LanguageManager.GetLang().ErrorCode;
                        ErrorInfo = LanguageManager.GetLang().LoadDataError;
                        return(false);
                    }
                    if (userPlotCombat == null)
                    {
                        userPlotCombat = new UserPlotCombat()
                        {
                            UserID    = ContextUser.UserID,
                            PlotNpcID = PlotNpcID
                        };
                        cacheSet.Add(userPlotCombat);
                        userPlotCombat = cacheSet.FindKey(ContextUser.UserID, PlotNpcID);
                    }
                    userPlotCombat.PlotID     = npcInfo.PlotID;
                    userPlotCombat.CombatDate = DateTime.Now;
                    userPlotCombat.IsWin      = plotCombater.Doing();
                    if (!userPlotCombat.IsWin)
                    {
                        userPlotCombat.OverNum += 1;
                    }
                    ContextUser.IsItem            = npcInfo.NpcSeqNo == 1 ? false : ContextUser.IsItem;
                    combatProcessList             = (CombatProcessContainer)plotCombater.GetProcessResult();
                    userPlotCombat.GeneralNum     = combatProcessList.AttackList.Count;
                    userPlotCombat.GeneralOverNum = GetOverGeneralNum(combatProcessList.AttackList.ToList());
                    //userPlotCombat.CombatProcess = JsonUtils.Serialize(combatProcessList);
                    int generalNum = combatProcessList.DefenseList.FindAll(s => s.LiveNum > 0).Count;
                    if (userPlotCombat.IsWin)
                    {
                        if (ContextUser.UserExtend != null)
                        {
                            ContextUser.UserExtend.UpdateNotify(obj =>
                            {
                                ContextUser.UserExtend.PlotStatusID = npcInfo.PlotID;
                                ContextUser.UserExtend.PlotNpcID    = PlotNpcID;
                                ContextUser.UserExtend.MercenarySeq = MathUtils.Addition(npcInfo.NpcSeqNo, (short)1);
                                ContextUser.UserExtend.IsBoss       = npcInfo.IsBoss; //是否最后一个副本npc
                                return(true);
                            });
                        }
                        //玩家通过一个城市的所有副本时,增加聊天频道系统提示
                        if (userPlot.PlotStatus != PlotStatus.Completed && npcInfo.IsBoss)      //玩家此副本胜利
                        {
                            var city     = new ShareCacheStruct <CityInfo>().FindKey(plotInfo.CityID);
                            var nextPlot = new ShareCacheStruct <PlotInfo>().FindKey(plotInfo.AftPlotID);
                            if (city != null && nextPlot != null && nextPlot.CityID != plotInfo.CityID)            //此城市的最后一个副本
                            {
                                string content = string.Format(LanguageManager.GetLang().St_systemprompts, ContextUser.NickName,
                                                               city.CityName);
                                new TjxChatService().SystemSend(ChatType.World, content);
                            }
                        }
                        PlotHelper.DoPlotPrize(Uid, npcInfo, userPlotCombat, generalNum, out _honourNum);
                        if (npcInfo.NpcSeqNo == 1)
                        {
                            ContextUser.EnergyNum = MathUtils.Subtraction(ContextUser.EnergyNum, ContextUser.TempEnergyNum).ToShort();
                            //原因:刷晶石BUG
                            ContextUser.TempEnergyNum = 0;
                        }
                        if (!ContextUser.IsItem)
                        {
                            prizeItems = PlotHelper.GetPlotMonsterItems(Uid, npcInfo.PlotNpcID);
                        }
                        TaskHelper.KillPlotMonster(Uid, npcInfo.PlotID, PlotNpcID);

                        //var stroyTaskList = new ShareCacheStruct<StoryTaskInfo>().FindAll(s => s.PlotID == plotInfo.AftPlotID);
                        //foreach (var story in stroyTaskList)
                        //{
                        //    var usertask = new PersonalCacheStruct<UserTask>().FindKey(ContextUser.UserID, story.PlotID);
                        //    if (usertask != null)
                        //    {
                        PlotHelper.EnablePlot(Uid, plotInfo.AftPlotID);
                        //    }
                        //}

                        if (plotInfo.PlotType == PlotType.Elite)
                        {
                            EliteDailyRestrain(npcInfo);
                            NoviceHelper.ElitePlotFestivalList(ContextUser); //通关精英副本获得奖励
                        }
                        else if (plotInfo.PlotType == PlotType.Kalpa)
                        {
                            KalpaDailyRestrain(npcInfo);
                        }
                        else if (plotInfo.PlotType == PlotType.HeroPlot)
                        {
                            PlotHelper.EnableHeroPlot(ContextUser.UserID, plotInfo.PlotID);
                            PlotHelper.HeroDailyRestrain(ContextUser.UserID, plotInfo.PlotID, plotInfo.CityID);
                        }
                    }
                    else
                    {
                        ContextUser.GeneralAllCount  = 0;
                        ContextUser.GeneralKillCount = 0;
                    }


                    var restrain = new PersonalCacheStruct <UserDailyRestrain>().FindKey(Uid);
                    if (restrain != null)
                    {
                        var restrainSet = new ShareCacheStruct <DailyRestrainSet>().FindKey(RestrainType.PlotGoto);
                        if (restrainSet != null)
                        {
                            GotoNum = MathUtils.Subtraction(restrainSet.MaxNum, restrain.Funtion14, 0);
                        }
                    }
                }
                //原因:最后一个npc时,清空玩家保存副本
                if (ContextUser.UserExtend != null && ContextUser.UserExtend.IsBoss)
                {
                    ContextUser.UserExtend.UpdateNotify(obj =>
                    {
                        ContextUser.UserExtend.PlotStatusID = 0;
                        ContextUser.UserExtend.PlotNpcID    = -1;
                        ContextUser.UserExtend.MercenarySeq = 0;
                        ContextUser.UserExtend.IsBoss       = npcInfo.IsBoss;
                        return(true);
                    });
                }

                if (!ContextUser.IsItem)
                {
                    foreach (var prize in prizeItems)
                    {
                        if (prize.Type == 0 && userPlot != null)
                        {
                            var           itemInfo      = cacheSetItemInfo.FindKey(prize.ItemID);
                            UniversalInfo universalInfo = new UniversalInfo();
                            universalInfo.HeadID    = itemInfo != null ? itemInfo.HeadID : string.Empty;
                            universalInfo.ItemID    = itemInfo != null ? itemInfo.ItemID : 0;
                            universalInfo.ItemDesc  = itemInfo != null ? itemInfo.ItemDesc : string.Empty;
                            universalInfo.MaxHeadID = itemInfo != null ? itemInfo.MaxHeadID : string.Empty;
                            universalInfo.Name      = itemInfo != null ? itemInfo.ItemName : string.Empty;
                            universalInfo.Num       = prize.Num;
                            if (userPlot.ItemList != null && userPlot.ItemList.Count > 0)
                            {
                                var item = userPlot.ItemList.Find(s => s.ItemID == prize.ItemID);
                                if (item != null)
                                {
                                    item.UpdateNotify(obj =>
                                    {
                                        item.Num = MathUtils.Addition(item.Num, prize.Num);
                                        return(true);
                                    });
                                }
                                else
                                {
                                    userPlot.UpdateNotify(obj =>
                                    {
                                        userPlot.ItemList.Add(universalInfo);
                                        return(true);
                                    });
                                }
                            }
                            else
                            {
                                userPlot.UpdateNotify(obj =>
                                {
                                    userPlot.ItemList.Add(universalInfo);
                                    return(true);
                                });
                            }
                        }
                        ContextUser.IsItem = true;
                    }
                }
                var a = userPlot.ItemList;
            }
            finally
            {
                ContextUser.UserStatus = UserStatus.Normal;
            }
            //日志
            UserCombatLog log = new UserCombatLog();

            log.CombatLogID   = Guid.NewGuid().ToString("N");
            log.UserID        = userPlotCombat.UserID;
            log.CityID        = ContextUser.CityID;
            log.PlotID        = userPlotCombat.PlotID;
            log.NpcID         = userPlotCombat.PlotNpcID;
            log.CombatType    = CombatType.Plot;
            log.HostileUser   = string.Empty;
            log.IsWin         = userPlotCombat.IsWin;
            log.CombatProcess = JsonUtils.Serialize(combatProcessList);
            log.PrizeItem     = prizeItems;
            log.CreateDate    = DateTime.Now;
            var sender = DataSyncManager.GetDataSender();

            sender.Send(log);

            UserHelper.GetGeneralLife(ContextUser.UserID);
            UserHelper.RegainGeneralLife(ContextUser.UserID);

            //var userEmbattleList = EmbattleHelper.CurrEmbattle(ContextUser.UserID, true);
            //           foreach (var userEmbattle in userEmbattleList)
            //           {
            //               _userTalPriority = MathUtils.Addition(_userTalPriority, PriorityHelper.GeneralTotalPriority(ContextUser.UserID, userEmbattle.GeneralID));
            //           }
            selfAbilityEffectList = UserAbilityHelper.GetSelfAbilityEffectList(ContextUser.UserID, 0);
            //var userEmbattleList = EmbattleHelper.CurrEmbattle(ContextUser.UserID, true);

            _userTalPriority = CombatHelper.TotalPriorityNum(ContextUser.UserID, 0);

            return(true);
        }
Beispiel #34
0
        //public Task<double> CalculateNpv(IList<Cashflow> npvData, double rate, RolloverType rolloverType, bool useXnpvFormula)
        //{
        //    // Would be good to use a ServiceResolver<> here to get an INpvService. This allow service changes without having to Update Service Reference...
        //    var th = new TaskHelper<NpvServiceClient, double>(new NpvServiceClient());
        //    return th.GetTask<double>(new object[] { npvData, rate, rolloverType, useXnpvFormula });
        //}

        public Task<NpvResponse> CalculateNpvForNpvRequest(NpvRequest request, bool useXnpvFormula)
        {
            var th = new TaskHelper<NpvServiceClient, double>(new NpvServiceClient());
            return th.GetTask<NpvResponse>(new object[] { request, useXnpvFormula });
        }
        public async Task <IActionResult> OnGetAsync(string providerId, int?pageNumber, string searchTerm = null, string fundingPeriodId = null, string specificationId = null)
        {
            Guard.IsNullOrWhiteSpace(providerId, nameof(providerId));

            ProviderId = providerId;

            SearchRequestViewModel searchRequest = new SearchRequestViewModel()
            {
                PageNumber    = pageNumber,
                IncludeFacets = false,
                SearchTerm    = "",
                Filters       = new Dictionary <string, string[]>
                {
                    { "providerId", new[] { providerId } },
                    { "specificationId", new[] { specificationId } },
                }
            };

            Task populatePeriodsTask = PopulateFundingPeriods(fundingPeriodId);

            Task <ApiResponse <Provider> > apiResponseTask = _resultsApiClient.GetProviderByProviderId(providerId);


            await TaskHelper.WhenAllAndThrow(populatePeriodsTask, apiResponseTask);

            if (string.IsNullOrWhiteSpace(fundingPeriodId))
            {
                fundingPeriodId = FundingPeriods?.First().Value;
            }

            FundingPeriodId = fundingPeriodId;

            await PopulateSpecifications(providerId, specificationId);

            SpecificationId = specificationId;

            ApiResponse <Provider> apiResponse = apiResponseTask.Result;

            if (apiResponse != null && apiResponse.StatusCode == HttpStatusCode.OK && apiResponse.Content != null)
            {
                Provider response = apiResponse.Content;

                ProviderViewModel providerViewModel = _mapper.Map <ProviderViewModel>(apiResponse.Content);

                ProviderInfoModel = providerViewModel;
            }
            else
            {
                _logger.Error("Provider response content is null");
                return(new StatusCodeResult(500));
            }

            if (!string.IsNullOrWhiteSpace(specificationId))
            {
                TestScenarioSearchResults = await _testScenarioSearchService.PerformSearch(searchRequest);

                if (TestScenarioSearchResults != null)
                {
                    Passed  = TestScenarioSearchResults.TestScenarios.Where(c => c.TestResult == "Passed").Count();
                    Failed  = TestScenarioSearchResults.TestScenarios.Where(c => c.TestResult == "Failed").Count();
                    Ignored = TestScenarioSearchResults.TestScenarios.Where(c => c.TestResult == "Ignored").Count();

                    int totalRecords = Passed + Failed + Ignored;
                    if (totalRecords > 0)
                    {
                        TestCoverage = Math.Round((decimal)(Passed + Failed) / totalRecords * 100, 1);
                    }
                }
            }

            return(Page());
        }
Beispiel #36
0
 public Task<ObservableCollection<DateTime>> GetDates(RolloverType period)
 {
     var th = new TaskHelper<NpvDateServiceClient, ObservableCollection<DateTime>>(new NpvDateServiceClient());
     return th.GetTask<ObservableCollection<DateTime>>(new object[]{period});
 }
 public void AddTask(string searchLine, KnownConverter converter, string searchDir)
 {
     TaskHelper.AddTask(Items, searchLine, converter, searchDir);
     OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
 }
Beispiel #38
0
 public Task<ObservableCollection<Customer>> GetCustomers(Customer customer)
 {
     var th = new TaskHelper<NpvServiceClient, ObservableCollection<Customer>>(new NpvServiceClient());
     return th.GetTask<ObservableCollection<Customer>>(new object[] { customer });
 }
Beispiel #39
0
        private void _client_OnReceive(byte[] data)
        {
            Actived = DateTimeHelper.Now;

            if (data != null)
            {
                this._messageContext.Unpacker.Unpack(data, (s) =>
                {
                    if (s.Content != null)
                    {
                        try
                        {
                            var cm = SerializeHelper.PBDeserialize <ChatMessage>(s.Content);

                            switch (cm.Type)
                            {
                            case ChatMessageType.LoginAnswer:
                                this.Logined = true;
                                break;

                            case ChatMessageType.SubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _subscribed = true;
                                }
                                else
                                {
                                    _subscribed = false;
                                }
                                break;

                            case ChatMessageType.UnSubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _unsubscribed = true;
                                }
                                else
                                {
                                    _unsubscribed = false;
                                }
                                break;

                            case ChatMessageType.ChannelMessage:
                                TaskHelper.Run(() => OnChannelMessage?.Invoke(cm.GetIMessage <ChannelMessage>()));
                                break;

                            case ChatMessageType.PrivateMessage:
                                TaskHelper.Run(() => OnPrivateMessage?.Invoke(cm.GetIMessage <PrivateMessage>()));
                                break;

                            case ChatMessageType.GroupMessage:
                                TaskHelper.Run(() => OnGroupMessage?.Invoke(cm.GetIMessage <GroupMessage>()));
                                break;

                            case ChatMessageType.PrivateMessageAnswer:
                                break;

                            case ChatMessageType.CreateGroupAnswer:
                            case ChatMessageType.RemoveGroupAnswer:
                            case ChatMessageType.AddMemberAnswer:
                            case ChatMessageType.RemoveMemberAnswer:
                                break;

                            case ChatMessageType.GroupMessageAnswer:
                                break;

                            default:
                                ConsoleHelper.WriteLine("cm.Type", cm.Type);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            OnError?.Invoke(_messageContext.UserToken.ID, ex);
                        }
                    }
                }, null, null);
            }
        }
Beispiel #40
0
        private void LoadSinaWeiboCommentMen(WStatuses statuses)
        {
            List<CommentMan> manList = new List<CommentMan>();
            m_taskHelper = new TaskHelper(
                delegate()
                {
                    m_fetchCommentManListCompleted(manList);
                }, 5000);
            App.Test1 = 0;
            App.Test2 = 0;
            App.Test3 = 0;
            foreach (WStatus status in statuses.statuses)
            {
                m_taskHelper.PushTask();
                List<String> commentIDList = new List<String>();

                ++App.Test1;
                System.Diagnostics.Debug.WriteLine("Test1: " + App.Test1);
                LoadSinaWeiboCommentByStatusID(status.id,
                    delegate(Comments comments)
                    {
                        if (comments != null)
                        {
                            foreach (Comment comment in comments.comments)
                            {
                                // 微博版要区分姓别
                                // 要去掉她自己啊!!!!你个2货
                                if (comment.user.id != status.user.id
                                    && comment.user.id != PreferenceHelper.GetPreference("SinaWeibo_ID")
                                    && comment.user.gender != status.user.gender)
                                {
                                    CommentMan man = new CommentMan
                                    {
                                        name = comment.user.screen_name,
                                        id = comment.user.id
                                    };
                                    manList.Add(man);
                                }
                            }
                        }
                        m_taskHelper.PopTask();
                    });

            }
        }
Beispiel #41
0
        private static Dictionary <Assembly, HashSet <Type> > GetAssemblyTypes(List <Assembly> assemblies, bool allowMultithreadedInitialization = false)
        {
            // Important note: only allow explicit multithreaded initialization

            var dictionary = new Dictionary <Assembly, HashSet <Type> >();

            if (allowMultithreadedInitialization)
            {
                // We try to use multiple threads since GetAllTypesSafely() is an expensive operation, try to multithread
                // without causing to much expansive context switching going on. Using .AsParallel wasn't doing a lot.
                //
                // After some manual performance benchmarking, the optimum for UWP apps (the most important for performance)
                // is between 15 and 25 threads
                const int PreferredNumberOfThreads = 20;

                var tasks     = new List <Task <List <KeyValuePair <Assembly, HashSet <Type> > > > >();
                var taskLists = new List <List <Assembly> >();

                var assemblyCount      = assemblies.Count;
                var assembliesPerBatch = (int)Math.Ceiling(assemblyCount / (double)PreferredNumberOfThreads);
                var batchCount         = (int)Math.Ceiling(assemblyCount / (double)assembliesPerBatch);

                for (var i = 0; i < batchCount; i++)
                {
                    var taskList = new List <Assembly>();

                    var startIndex = (assembliesPerBatch * i);
                    var endIndex   = Math.Min(assembliesPerBatch * (i + 1), assemblyCount);

                    for (var j = startIndex; j < endIndex; j++)
                    {
                        taskList.Add(assemblies[j]);
                    }

                    taskLists.Add(taskList);
                }

                for (var i = 0; i < taskLists.Count; i++)
                {
                    var taskList = taskLists[i];

                    var task = TaskHelper.Run(() =>
                    {
                        var taskResults = new List <KeyValuePair <Assembly, HashSet <Type> > >();

                        foreach (var assembly in taskList)
                        {
                            var assemblyTypes = assembly.GetAllTypesSafely();
                            taskResults.Add(new KeyValuePair <Assembly, HashSet <Type> >(assembly, new HashSet <Type>(assemblyTypes)));
                        }

                        return(taskResults);
                    });

                    tasks.Add(task);
                }

                var waitTask = TaskShim.WhenAll(tasks);
                waitTask.Wait();

                foreach (var task in tasks)
                {
                    var results = task.Result;

                    foreach (var result in results)
                    {
                        dictionary[result.Key] = result.Value;
                    }
                }
            }
            else
            {
                var types = (from assembly in assemblies
                             select new KeyValuePair <Assembly, HashSet <Type> >(assembly, new HashSet <Type>(assembly.GetAllTypesSafely())));

                var results = types.AsParallel();

                return(results.ToDictionary(p => p.Key, p => p.Value));
            }

            return(dictionary);
        }