Esempio n. 1
0
        ChatCommand(TwitchChatRoom room, string name, Action<SqlTwitchUser, string> action, string description, string[] aliases, bool modOnly, TimeSpan timeToThrottleFor, bool throttlePerUser, bool enabled)
            : base(room)
        {
            this.commandName = name;
            this.action = action;
            this.description = description;
            this.aliases = aliases;
            this.modOnly = modOnly;
            if(timeToThrottleFor > TimeSpan.FromSeconds(0)) {
                throttle = new Throttle(timeToThrottleFor);
            } else {
                throttle = null;
            }
            this.throttlePerUser = throttlePerUser;

            this.enabled = enabled;
        }
Esempio n. 2
0
        public static void Main() {
            var mainWindow = new MainWindow();
            var mongoToken = Token.ReadFromRessource(typeof(Program).Assembly, "twitter.frontend.mongohq.credentials.txt");
            var bitlyToken = Token.ReadFromRessource(typeof(Program).Assembly, "twitter.frontend.bitly.credentials.txt");
            var accessToken = Token.ReadFromFile("access.credentials.txt");

            var tweetStore = new TweetStore(mongoToken);
            var urlShortener = new UrlShortener(bitlyToken.Key, bitlyToken.Secret);
            var textCompressor = new TextCompressor(urlShortener);
            var throttle = new Throttle<string>(2000);
            var synchronizer = new Synchronizer<string>();

            mainWindow.TweettextChanged += throttle.Process;

            throttle.Result += t =>
            {
                var shortText = textCompressor.Compress(t);
                synchronizer.Process(shortText);
            };

            synchronizer.Result += mainWindow.ShowTweetText;


            mainWindow.Tweet += (text, veröffentlichen) => {
                var tweet = new Tweet {
                    AccessToken = accessToken.Key,
                    OAuthToken = accessToken.Secret,
                    Text = text,
                    Veröffentlichen = veröffentlichen
                };
                tweetStore.Speichern(tweet);
            };
            
            var app = new Application {
                MainWindow = mainWindow
            };
            app.Run(mainWindow);
        }
Esempio n. 3
0
        private void ConfigureInput()
        {
            var isFocusLocked = true;

            _renderTarget.Window.SetCursorPositionToCenter();
            _renderTarget.Window.LockCursor = true;
            _renderTarget.Window.ShowCursor = false;

            // Grasshopper uses Reactive Extensions to expose input events as an
            // observable stream. In your own projects, you'll need to make sure
            // the Reactive Extensions NuGet packages are referenced in order to
            // access all the extension methods for observables.

            // Handle the two possible results of pressing the ESC key
            _app.Input.KeyboardEvents
                .Where(ev => ev.Key == Key.Escape && ev.State == KeyState.Down)
                .Subscribe(ev =>
                {
                    if(isFocusLocked) // unlock the input controls from the view
                    {
                        _renderTarget.Window.LockCursor = false;
                        _renderTarget.Window.ShowCursor = true;
                        isFocusLocked = false;
                    }
                    else
                        _app.Exit();
                });

            // Create observables for keypresses that only trigger when the controls are locked to the view
            var whenKeyHeldDown = _app.Input.KeyboardEvents.Where(ev => ev.State == KeyState.Down && isFocusLocked);
            var whenKeyReleased = _app.Input.KeyboardEvents.Where(ev => ev.State == KeyState.Up && isFocusLocked);

            Func<KeyboardEvent, bool> isForwardKey = ev => ev.Key == Key.Up || ev.Key == Key.W;
            Func<KeyboardEvent, bool> isBackwardKey = ev => ev.Key == Key.Down || ev.Key == Key.S;
            Func<KeyboardEvent, bool> isRollLeftKey = ev => ev.Key == Key.Left || ev.Key == Key.A;
            Func<KeyboardEvent, bool> isRollRightKey = ev => ev.Key == Key.Right || ev.Key == Key.D;

            whenKeyHeldDown.Where(isForwardKey).Subscribe(ev => _throttle = Throttle.Forward);
            whenKeyHeldDown.Where(isBackwardKey).Subscribe(ev => _throttle = Throttle.Backward);
            whenKeyHeldDown.Where(isRollLeftKey).Subscribe(ev => _rotation = Rotation.Left);
            whenKeyHeldDown.Where(isRollRightKey).Subscribe(ev => _rotation = Rotation.Right);

            whenKeyReleased.Where(isForwardKey).Subscribe(ev => _throttle = Throttle.None);
            whenKeyReleased.Where(isBackwardKey).Subscribe(ev => _throttle = Throttle.None);
            whenKeyReleased.Where(isRollLeftKey).Subscribe(ev => _rotation = Rotation.None);
            whenKeyReleased.Where(isRollRightKey).Subscribe(ev => _rotation = Rotation.None);

            // Handle mouse events for looking around ("free look")
            var whenMouseMoved = _app.Input.MouseEvents
                .Where(ev => ev.Type == MouseEventType.Move && ev.Window == null && isFocusLocked);

            whenMouseMoved.Where(ev => ev.DeltaX != 0)
                .Subscribe(ev => _camera.Yaw(-(float)(ev.DeltaX * Math.PI / 180)/7.5f));

            whenMouseMoved.Where(ev => ev.DeltaY != 0)
                .Subscribe(ev => _camera.Pitch((float)(ev.DeltaY * Math.PI / 180)/7.5f));

            // Handle the two possible results of clicking the mouse button
            _app.Input.MouseEvents
                .Where(ev => ev.Type == MouseEventType.Button && ev.ButtonState == ButtonState.Down)
                .Subscribe(ev =>
                {
                    if(isFocusLocked) // reset the camera and position
                    {
                        _camera.Position = Vector3.Zero;
                        _camera.Direction = -Vector3.UnitZ;
                        _camera.Up = Vector3.UnitY;
                    }
                    else // lock the input controls back to the view
                    {
                        isFocusLocked = true;
                        _renderTarget.Window.LockCursor = true;
                        _renderTarget.Window.ShowCursor = false;
                        _renderTarget.Window.SetCursorPositionToCenter();
                    }
                });
        }
Esempio n. 4
0
 public ThrottleCommand(Throttle throttle)
     : base(throttle.StartTime, throttle.Duration)
 {
     _targetThrottle = throttle.TargetThrottle;
 }
Esempio n. 5
0
 private void Startup()
 {
     callCount = 0;
     headers = new Dictionary<string, string>();
     parameters = new Dictionary<string, string>();
     throttle = new Throttle();
 }
        public override async Task Translate(ITranslationSession translationSession)
        {
            try
            {
                var authenticationKey = AuthenticationKey;

                if (string.IsNullOrEmpty(authenticationKey))
                {
                    translationSession.AddMessage("Azure Translator requires subscription secret.");
                    return;
                }

                var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey, translationSession.CancellationToken).ConfigureAwait(false);

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Authorization", token);

                    var throttle = new Throttle(MaxCharactersPerMinute, translationSession.CancellationToken);

                    var itemsByLanguage = translationSession.Items.GroupBy(item => item.TargetCulture);

                    foreach (var languageGroup in itemsByLanguage)
                    {
                        var cultureKey     = languageGroup.Key;
                        var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage;

                        var itemsByTextType = languageGroup.GroupBy(GetTextType);

                        foreach (var textTypeGroup in itemsByTextType)
                        {
                            var textType = textTypeGroup.Key;

                            foreach (var sourceItems in SplitIntoChunks(translationSession, textTypeGroup))
                            {
                                if (!sourceItems.Any())
                                {
                                    break;
                                }

                                var sourceStrings = sourceItems
                                                    .Select(item => item.Source)
                                                    .Select(RemoveKeyboardShortcutIndicators)
                                                    .ToList();

                                await throttle.Tick(sourceItems);

                                if (translationSession.IsCanceled)
                                {
                                    return;
                                }

                                var uri = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={translationSession.SourceLanguage.IetfLanguageTag}&to={targetLanguage.IetfLanguageTag}&textType={textType}");

                                var response = await client.PostAsync(uri, CreateRequestContent(sourceStrings), translationSession.CancellationToken).ConfigureAwait(false);

                                if (response.IsSuccessStatusCode)
                                {
                                    var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                                    {
                                        var translations = JsonConvert.DeserializeObject <List <AzureTranslationResponse> >(reader.ReadToEnd());
                                        if (translations != null)
                                        {
                                            await translationSession.MainThread.StartNew(() => ReturnResults(sourceItems, translations));
                                        }
                                    }
                                }
                                else
                                {
                                    var errorMessage = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                                    translationSession.AddMessage("Azure translator reported a problem: " + errorMessage);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                translationSession.AddMessage("Azure translator reported a problem: " + ex);
            }
        }
		/// <summary>
		/// Initializes this instance before the start thread.
		/// </summary>
		protected override void Initialize()
		{
			if (string.IsNullOrEmpty(QueuePath))
				throw new WorkerException("QueuePath", Name);

			_throttle = ThrottleLimit > 0 ? new Throttle(new TimeSpan(0, 0, 1), ThrottleLimit) : Throttle.DisabledThrottle;

			this.Queue = new MessageQueue(QueuePath)
			{
				Formatter = new XmlMessageFormatter
				{
					TargetTypes = MessageTypes
				}
			};

			Logger.Info("Queue " + QueuePath);
			Logger.Info("Queue can read {0}", Queue.CanRead);

			base.Initialize();
		}
Esempio n. 8
0
        public void Execute(
            ScheduleTask task,
            IDictionary <string, string> taskParameters = null,
            bool throwOnError = false)
        {
            if (AsyncRunner.AppShutdownCancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (task.LastHistoryEntry == null)
            {
                // The task was started manually.
                task.LastHistoryEntry = _scheduledTaskService.GetLastHistoryEntryByTaskId(task.Id);
            }

            if (task?.LastHistoryEntry?.IsRunning == true)
            {
                return;
            }

            bool      faulted   = false;
            bool      canceled  = false;
            string    lastError = null;
            ITask     instance  = null;
            string    stateName = null;
            Type      taskType  = null;
            Exception exception = null;

            var historyEntry = new ScheduleTaskHistory
            {
                ScheduleTask_Id = task.Id,
                IsRunning       = true,
                MachineName     = Environment.MachineName,
                StartedOnUtc    = DateTime.UtcNow
            };

            try
            {
                taskType = Type.GetType(task.Type);
                if (taskType == null)
                {
                    Logger.DebugFormat("Invalid scheduled task type: {0}", task.Type.NaIfEmpty());
                }

                if (taskType == null)
                {
                    return;
                }

                task.ScheduleTaskHistory.Add(historyEntry);
                _scheduledTaskService.UpdateTask(task);
            }
            catch
            {
                return;
            }

            try
            {
                // Task history entry has been successfully added, now we execute the task.
                // Create task instance.
                instance  = _taskResolver(taskType);
                stateName = task.Id.ToString();

                // Create & set a composite CancellationTokenSource which also contains the global app shoutdown token.
                var cts = CancellationTokenSource.CreateLinkedTokenSource(AsyncRunner.AppShutdownCancellationToken, new CancellationTokenSource().Token);
                _asyncState.SetCancelTokenSource <ScheduleTask>(cts, stateName);

                var ctx = new TaskExecutionContext(_componentContext, historyEntry)
                {
                    ScheduleTaskHistory = historyEntry.Clone(),
                    CancellationToken   = cts.Token,
                    Parameters          = taskParameters ?? new Dictionary <string, string>()
                };

                Logger.DebugFormat("Executing scheduled task: {0}", task.Type);
                instance.Execute(ctx);
            }
            catch (Exception ex)
            {
                exception = ex;
                faulted   = true;
                canceled  = ex is OperationCanceledException;
                lastError = ex.ToAllMessages(true);

                if (canceled)
                {
                    Logger.Warn($"La tarea planificada { task.Name} ha sido cancelado", ex);
                }
                else
                {
                    Logger.Error($"Error al ejecutar la tarea programada {task.Name}", ex);
                }
            }
            finally
            {
                var now        = DateTime.UtcNow;
                var updateTask = false;

                historyEntry.IsRunning       = false;
                historyEntry.ProgressPercent = null;
                historyEntry.ProgressMessage = null;
                historyEntry.Error           = lastError;
                historyEntry.FinishedOnUtc   = now;

                if (faulted)
                {
                    if (!canceled && task.StopOnError || instance == null)
                    {
                        task.Enabled = false;
                        updateTask   = true;
                    }
                }
                else
                {
                    historyEntry.SucceededOnUtc = now;
                }

                try
                {
                    Logger.DebugFormat("Executed scheduled task: {0}. Elapsed: {1} ms.", task.Type, (now - historyEntry.StartedOnUtc).TotalMilliseconds);

                    // Remove from AsyncState.
                    if (stateName.HasValue())
                    {
                        _asyncState.Remove <ScheduleTask>(stateName);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }

                if (task.Enabled)
                {
                    task.NextRunUtc = _scheduledTaskService.GetNextSchedule(task);
                    updateTask      = true;
                }

                _scheduledTaskService.UpdateHistoryEntry(historyEntry);

                if (updateTask)
                {
                    _scheduledTaskService.UpdateTask(task);
                }

                Throttle.Check("Delete old schedule task history entries", TimeSpan.FromDays(1), () => _scheduledTaskService.DeleteHistoryEntries() > 0);
            }

            if (throwOnError && exception != null)
            {
                throw exception;
            }
        }
        protected override Task ProcessRequestAsync(HttpContext context)
        {
            var checker = Throttle.check("sssPutDel", Global.throttle, context);

            if (!checker.CheckResult)
            {
                Errors.GetError().p406(context);
                return(context.Response.Output.WriteAsync(string.Empty));
            }

            context.Response.ContentType = "application/json";

            var appKey = context.Request.Headers["U-ApiKey"];

            if (appKey != "appkey")
            {
                Errors.GetError().p412(context);
                return(context.Response.Output.WriteAsync(string.Empty));
            }

            var    meth        = context.Request.HttpMethod;
            var    routeValues = context.Request.RequestContext.RouteData.Values;
            string dvid        = routeValues["dvid"].ToString();
            string ssid        = routeValues["ssid"].ToString();

            //判断是否有模拟put,delete请求
            var req = context.Request.QueryString["method"];

            if (!string.IsNullOrEmpty(req))
            {
                var mt = req.ToUpper();
                if (Enum.GetNames(typeof(em_HttpMeth)).Contains(mt))
                {
                    meth = mt;
                }
                else
                {
                    Errors.GetError().p417(context);
                    return(context.Response.Output.WriteAsync(string.Empty));
                }
            }

            //查看设备信息
            if (meth == "GET")
            {
                int dv;
                int ss;
                if (int.TryParse(dvid, out dv) && int.TryParse(ssid, out ss))
                {
                    return(context.Response.Output.WriteAsync(
                               Controller.SensorsController.GetSensors().GetOne(dv, ss)));
                }
                else
                {
                    return(context.Response.Output.WriteAsync(Errors.e7002));
                }
            }

            //修改设备信息
            if (meth == "PUT")
            {
                if (context.Request.InputStream.Length == 0)
                {
                    Errors.GetError().p204(context);
                    return(context.Response.Output.WriteAsync(string.Empty));
                }
                using (var reader = new StreamReader(context.Request.InputStream))
                {
                    int dv;
                    int ss;
                    if (int.TryParse(dvid, out dv) && int.TryParse(ssid, out ss))
                    {
                        if (!DataDV.GetDV().CheckConnected())
                        {
                            return(context.Response.Output.WriteAsync(Errors.e7006));
                        }
                        var obj = Controller.SensorsController.GetSensors().GetOne(dv, ss);
                        if (obj != null)
                        {
                            SensorModel model;
                            try
                            {
                                model = BsonSerializer.Deserialize <SensorModel>(reader.ReadToEnd());
                                if (string.IsNullOrEmpty(model.title))
                                {
                                    return(context.Response.Output.WriteAsync(Errors.e7001));
                                }
                                return(context.Response.Output.WriteAsync(
                                           Controller.SensorsController.GetSensors().Edit(dv, ss, model.ToBsonDocument())));
                            }
                            catch
                            {
                                return(context.Response.Output.WriteAsync(Errors.e7005));
                            }
                        }
                        else
                        {
                            return(context.Response.Output.WriteAsync(Errors.e7004));
                        }
                    }
                    else
                    {
                        return(context.Response.Output.WriteAsync(Errors.e7002));
                    }
                }
            }

            //删除设备
            if (meth == "DELETE")
            {
                int dv;
                int ss;
                if (int.TryParse(dvid, out dv) && int.TryParse(ssid, out ss))
                {
                    var obj = Controller.SensorsController.GetSensors().GetOne(dv, ss);
                    if (obj != null)
                    {
                        return(context.Response.Output.WriteAsync(
                                   Controller.SensorsController.GetSensors().Delete(dv, ss)));
                    }
                    else
                    {
                        return(context.Response.Output.WriteAsync(Errors.e7004));
                    }
                }
                else
                {
                    return(context.Response.Output.WriteAsync(Errors.e7002));
                }
            }

            Errors.GetError().p404(context);
            return(context.Response.Output.WriteAsync(string.Empty));
        }