Exemplo n.º 1
0
        private static void BuildDocumentation(string content, IEnumerable <string> matches)
        {
            PGDatabase database = DbProcessor.GetDatabase();

            content = content.Replace("[DBName]", Program.Database.ToUpperInvariant());
            content = content.Replace("[DBComment]", database.Comment);

            foreach (string match in matches)
            {
                string comment = HtmlHelper.RemoveComment(match);

                if (!comment.StartsWith("PostgreSQLDatabase"))
                {
                    continue;
                }

                comment = comment.Replace("PostgreSQLDatabase", "");

                StringBuilder items = new StringBuilder();

                foreach (PGDatabase.PGDatabaseSetting setting in database.Settings)
                {
                    items.Append(comment.Replace("[Name]", setting.Name)
                                 .Replace("[Setting]", setting.Setting)
                                 .Replace("[Description]", setting.Description));
                }

                content = content.Replace(match, items.ToString());
            }

            FileHelper.WriteFile(content, OutputPath);
            Console.WriteLine("Writing schemas.");
            SchemasRunner.Run();
        }
Exemplo n.º 2
0
        private dynamic GetServerMatches(dynamic parameters)
        {
            string endpoint       = GetCannonicalEndpoint(parameters);
            var    matchInfoModel = DbProcessor.FindMatchInfo(endpoint, parameters.timestamp);

            return(JsonOrErrorCode <MatchInfo>(matchInfoModel));
        }
 public void Process()
 {
     DbProcessor.ForEachAccount(data => ProcessAccount(data));
     if (CreatedNotificationsCount > 0)
     {
         Logger.Info("Обработано уведомлений: " + CreatedNotificationsCount);
     }
 }
Exemplo n.º 4
0
        private dynamic GetPopularServers(dynamic parameters)
        {
            int count = GetCannonicalCount(parameters.count);

            return(Response.AsJson(DbProcessor.GetServerRates()
                                   .OrderByDescending(r => r.AverageMatchesPerDay)
                                   .Take(count)));
        }
Exemplo n.º 5
0
        private dynamic GetBestPlayers(dynamic parameters)
        {
            int count = GetCannonicalCount(parameters.count);

            return(Response.AsJson(DbProcessor.GetPlayerRates()
                                   .OrderByDescending(playerRate => playerRate.KillToDeathRatio)
                                   .Take(count).ToArray()));
        }
Exemplo n.º 6
0
        private dynamic GetServerStats(dynamic parameters)
        {
            string endpoint    = parameters.ipOrHostname + "-" + parameters.port;
            var    serverModel = Db.FindById <GameServer>(endpoint);

            if (serverModel == null)
            {
                return(HttpStatusCode.NotFound);
            }
            return(Response.AsJson(DbProcessor.GetServerStats(endpoint)));
        }
        public void ProcessAll()
        {
            ResetCounters();

            DbProcessor.ForEachAccount(x => ProcessAccount(
                                           x.Account.Id,
                                           x.AccountDbContext,
                                           x.Logger,
                                           x.Account.DisplayName,
                                           x.CancellationToken));
        }
Exemplo n.º 8
0
        private dynamic GetPlayerStats(dynamic parameters)
        {
            string playerName    = parameters.name;
            var    isNullOrEmpty = DbProcessor.GetAllScores()
                                   .Where(s => s.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase))
                                   .IsNullOrEmpty();

            if (isNullOrEmpty)
            {
                return(HttpStatusCode.NotFound);
            }
            return(Response.AsJson(DbProcessor.GetPlayerStats(playerName)));
        }
Exemplo n.º 9
0
        public void Start()
        {
            var reqpro = new RequestProcessor();

            _listener.Start();

            while (true)
            {
                try
                {
                    HttpListenerContext  context  = _listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;
                    //Создаем ответ
                    Stream       inputStream = request.InputStream;
                    Encoding     encoding    = request.ContentEncoding;
                    StreamReader reader      = new StreamReader(inputStream, encoding);
                    var          requestBody = reader.ReadToEnd();

                    Console.WriteLine("{0} request was caught: {1}",
                                      request.HttpMethod, request.Url);
                    var    urlParts = request.Url.AbsolutePath.Split('/');
                    string msg;

                    try
                    {
                        if (urlParts[1] != "register")
                        {
                            DbProcessor.CheckAuth(urlParts[2], urlParts[3]);
                        }
                        msg = reqpro.GetResponseData(request.HttpMethod, urlParts, requestBody);
                        response.StatusCode = (int)HttpStatusCode.OK;
                    }
                    catch (Exception e)
                    {
                        msg = "Request error! " + e.Message;
                        Console.WriteLine(msg);
                        response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }


                    byte[] b = Encoding.UTF8.GetBytes(msg);
                    context.Response.ContentLength64 = b.Length;
                    context.Response.OutputStream.Write(b, 0, b.Length);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Net trouble\r\n" + exception.Message);
                }
            }
        }
 public void Process(Guid accountId, Guid componentId)
 {
     DbProcessor.ForEachAccount(data =>
     {
         if (data.Account.Id == accountId)
         {
             ProcessAccount(data, componentId);
         }
     });
     if (CreatedNotificationsCount > 0)
     {
         Logger.Info("Обработано уведомлений: " + CreatedNotificationsCount);
     }
 }
Exemplo n.º 11
0
        public void ProcessAccount(Guid accountId, Guid unitTestId)
        {
            ResetCounters();

            DbProcessor.ForEachAccount(x =>
            {
                if (x.Account.Id == accountId)
                {
                    ProcessAccount(
                        x.Account.Id,
                        x.AccountDbContext,
                        x.Logger,
                        x.Account.DisplayName,
                        x.CancellationToken,
                        unitTestId);
                }
            });
        }
        /// <summary>
        /// Отправка уведомлений из указанной StorageDb
        /// </summary>
        protected void ProcessAccount(ForEachAccountData data, Guid?componentId = null)
        {
            var notificationRepository = data.AccountDbContext.GetNotificationRepository();

            var notificationsQuery = notificationRepository.GetForSend(NotificationType);

            if (componentId.HasValue)
            {
                notificationsQuery = notificationsQuery.Where(t => t.Event.OwnerId == componentId.Value);
            }

            var notifications = notificationsQuery.OrderBy(t => t.CreationDate).Take(MaxNotificationCount).ToList();

            if (notifications.Count > 0)
            {
                data.Logger.Debug("Найдено уведомлений: " + notifications.Count);
                foreach (var notification in notifications)
                {
                    data.CancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        data.Logger.Debug("Обработка уведомления " + notification.Id);

                        Send(data.Logger,
                             notification,
                             data.AccountDbContext,
                             data.Account.SystemName, data.Account.Id);

                        notification.Status   = NotificationStatus.Sended;
                        notification.SendDate = DateTime.Now;
                        data.AccountDbContext.SaveChanges();

                        data.Logger.Info("Уведомление " + notification.Id + " отправлено на " + notification.Address);
                        Interlocked.Increment(ref CreatedNotificationsCount);
                    }
                    catch (NotificationNonImportantException exception)
                    {
                        // ошибка при отправке, которая не считается важной
                        data.Logger.Info(exception);

                        // обновим статус
                        notification.SendError = (exception.InnerException ?? exception).ToString();
                        notification.Status    = NotificationStatus.Error;
                        notification.SendDate  = DateTime.Now;
                        data.AccountDbContext.SaveChanges();

                        // TODO отправить ошибку в компонент аккаунта, чтобы её увидел админ аккаунта (а не админ Зидиума)
                    }
                    catch (Exception exception)
                    {
                        // залогируем ошибку
                        DbProcessor.SetException(exception);
                        data.Logger.Error(exception);

                        // обновим статус
                        notification.SendError = exception.ToString();
                        notification.Status    = NotificationStatus.Error;
                        notification.SendDate  = DateTime.Now;
                        data.AccountDbContext.SaveChanges();
                    }
                }
            }
            else
            {
                data.Logger.Trace("Новых уведомлений нет");
            }
        }
        protected override Core.Api.SendUnitTestResultRequestData GetResult(
            Guid accountId,
            AccountDbContext accountDbContext,
            UnitTest unitTest,
            ILogger logger,
            CancellationToken token)
        {
            if (unitTest == null)
            {
                throw new ArgumentNullException("unitTest");
            }
            if (unitTest.DomainNamePaymentPeriodRule == null)
            {
                // Правило ещё не создалось, бывает
                return(new Core.Api.SendUnitTestResultRequestData()
                {
                    Result = Core.Api.UnitTestResult.Unknown
                });
            }
            var rule = unitTest.DomainNamePaymentPeriodRule;

            if (string.IsNullOrWhiteSpace(rule.Domain))
            {
                throw new UserFriendlyException("Не указан домен для проверки");
            }

            var resultInfo = GetPaymentDate(rule.Domain);

            // Сервис недоступен
            if (resultInfo.Code == DomainNamePaymentPeriodErrorCode.Unavailable)
            {
                // Отмена выполнения
                logger.Warn(resultInfo.ErrorMessage);

                throw new OperationCanceledException();
            }

            if (resultInfo.Code == DomainNamePaymentPeriodErrorCode.UnknownError)
            {
                var logEvent = new LogEventInfo()
                {
                    Level   = NLog.LogLevel.Warn,
                    Message = "Произошла неизвестная ошибка"
                };
                logEvent.Properties["Html"] = resultInfo.Html;
                logger.Log(logEvent);

                DbProcessor.SetException(new UserFriendlyException(resultInfo.ErrorMessage));
            }

            if (resultInfo.Date == null)
            {
                rule.LastRunErrorCode = resultInfo.Code;
                return(new Core.Api.SendUnitTestResultRequestData()
                {
                    Result = Core.Api.UnitTestResult.Alarm,
                    Message = resultInfo.ErrorMessage
                });
            }

            var days = (int)((resultInfo.Date.Value - DateTime.Now.Date).TotalDays);

            rule.LastRunErrorCode = DomainNamePaymentPeriodErrorCode.Success;
            var result = new Core.Api.SendUnitTestResultRequestData()
            {
                Message = string.Format(
                    "Осталось {0} дней до окончания срока оплаты. Домен оплачен до {1}",
                    days,
                    resultInfo.Date.Value.ToString("dd.MM.yyyy"))
            };

            if (days <= rule.AlarmDaysCount)
            {
                result.Result = Core.Api.UnitTestResult.Alarm;
            }
            else if (days <= rule.WarningDaysCount)
            {
                result.Result = Core.Api.UnitTestResult.Warning;
            }
            else
            {
                result.Result = Core.Api.UnitTestResult.Success;
            }
            return(result);
        }