protected void UpdateComponentProperies(Component component, List <Api.ExtentionPropertyDto> properties, Guid accountId)
        {
            var accountDbContext = Context.GetAccountDbContext(accountId);

            // удаляем
            var forDelete = component.Properties.Where(x => properties.All(y => y.Name != x.Name)).ToArray();

            foreach (var componentProperty in forDelete)
            {
                component.Properties.Remove(componentProperty);
                accountDbContext.ComponentProperties.Remove(componentProperty);
            }

            // обновляем или вставляем
            foreach (var property in properties)
            {
                var componentProperty = component.Properties.FirstOrDefault(x => x.Name == property.Name);
                if (componentProperty == null)
                {
                    // вставляем
                    componentProperty           = ApiConverter.GetComponentProperty(property);
                    componentProperty.Component = component;
                    component.Properties.Add(componentProperty);
                }
                else
                {
                    // обновляем
                    componentProperty.DataType = property.Type;
                    componentProperty.Value    = property.Value;
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Takes the snapshot of the window owned by a process
        /// </summary>
        /// <param name="name">The process name</param>
        /// <returns>Bitmap object</returns>
        public static Bitmap ProcessSnapshot(string name)
        {
            IntPtr hwnd = IntPtr.Zero;

            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName(name))
            {
                if (p.MainWindowHandle != IntPtr.Zero)
                {
                    hwnd = p.MainWindowHandle;
                    break;
                }
            }

            if (hwnd == IntPtr.Zero)
            {
                return(null);
            }
            else
            {
                USER32.RECT rc;
                USER32.GetWindowRect(hwnd, out rc);
                Rectangle r      = ApiConverter.ToRectangle(rc);
                Bitmap    bitmap = new Bitmap(r.Width, r.Height, PixelFormat.Format24bppRgb);
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    IntPtr hdcBitmap = g.GetHdc();
                    USER32.PrintWindow(hwnd, hdcBitmap, 0);
                }
                return(bitmap);
            }
        }
Beispiel #3
0
        public IActionResult PlayQuiz(string id)
        {
            string quizDetailUri = $"{BaseUri}/{id}";
            Quiz   quizDetail    = ApiConverter.GetApiResult <Quiz>(quizDetailUri);

            return(quizDetail == null?View("Error") : View(quizDetail));
        }
Beispiel #4
0
        public IActionResult Index()
        {
            ViewBag.UserId = _userManager.GetUserId(HttpContext.User);
            string           quizUri   = $"{BaseUri}/basic";
            List <QuizBasic> quizBasic = ApiConverter.GetApiResult <List <QuizBasic> >(quizUri);

            return(quizBasic == null?View("Error") : View(quizBasic));
        }
Beispiel #5
0
        public IActionResult EditQuiz(string id)
        {
            ViewBag.UserId = _userManager.GetUserId(HttpContext.User);
            ViewBag.Mode   = "Edit";
            string quizDetailUri = $"{BaseUri}/{id}";
            Quiz   quizDetail    = ApiConverter.GetApiResult <Quiz>(quizDetailUri);

            return(quizDetail == null?View("Error") : View(quizDetail));
        }
Beispiel #6
0
        protected Event CreateEvent(
            Guid accountId,
            DateTime?startDate,
            DateTime?endDate,
            int?count,
            string version,
            EventImportance?importance,
            TimeSpan?actualTime,
            string message,
            List <Api.ExtentionPropertyDto> properties,
            EventType eventType,
            Guid componentId,
            long joinKeyHash)
        {
            // вычисляем значения по умолчанию, если они не указаны явно
            startDate = startDate ?? DateTime.Now;
            endDate   = endDate ?? startDate;
            count     = count ?? 1;
            if (count < 1)
            {
                count = 1;
            }

            if (EventIsOld(eventType.OldVersion, version))
            {
                importance = eventType.ImportanceForOld ?? importance;
            }
            else
            {
                importance = eventType.ImportanceForNew ?? importance;
            }

            var now    = DateTime.Now;
            var result = new Event()
            {
                Id                   = Guid.NewGuid(),
                EventTypeId          = eventType.Id,
                Importance           = importance ?? EventImportance.Unknown,
                CreateDate           = now,
                OwnerId              = componentId,
                Count                = count.Value,
                EndDate              = endDate.Value,
                LastUpdateDate       = now,
                LastNotificationDate = null,
                JoinKeyHash          = joinKeyHash,
                StartDate            = startDate.Value,
                ActualDate           = startDate.Value + (actualTime ?? TimeSpan.Zero),
                Message              = message,
                Version              = version,
                Category             = eventType.Category,
                Properties           = ApiConverter.GetEventProperties(properties),
                IsUserHandled        = false,
                VersionLong          = VersionHelper.FromString(version)
            };

            return(result);
        }
Beispiel #7
0
        public void SaveLogMessages(Guid accountId, SendLogData[] messages)
        {
            // Проверка на наличие необходимых параметров
            if (messages == null)
            {
                throw new ParameterRequiredException("Request.Messages");
            }

            // Проверим лимиты
            var accountDbContext = Context.GetAccountDbContext(accountId);
            var checker          = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);

            var totalSize = messages.Sum(t => t.GetSize());

            checker.CheckLogSizePerDay(accountDbContext, totalSize);

            // Проверим лимит размера хранилища
            checker.CheckStorageSize(accountDbContext, totalSize);

            var componentService = Context.ComponentService;
            var logRepository    = Context.DbContext.GetAccountDbContext(accountId).GetLogRepository();

            // Добавим все записи в одной транзакции
            foreach (var message in messages)
            {
                if (message.Message == null)
                {
                    throw new ParameterRequiredException("Request.Message.Message"); //todo надо переименовать
                }

                if (message.Message.Length > 4000)
                {
                    message.Message = message.Message.Substring(0, 4000);
                }

                if (message.Context != null && message.Context.Length > 255)
                {
                    message.Context = message.Context.Substring(0, 255);
                }

                var component = componentService.GetComponentById(accountId, message.ComponentId.Value);

                var log = ApiConverter.GetLog(component.Id, message);
                logRepository.Add(log);
            }

            Context.SaveChanges();

            checker.AddLogSizePerDay(accountDbContext, totalSize);
        }
        protected Event CreateUnitTestResultEvent(
            IUnitTestCacheReadObject unitTest,
            SendUnitTestResultRequestData data,
            DateTime processDate)
        {
            data.Message = data.Message ?? string.Empty;

            if (data.Message.Length > 255)
            {
                data.Message = data.Message.Substring(0, 255);
            }

            var importance = EventImportanceHelper.Get(data.Result ?? UnitTestResult.Unknown);

            var cache        = new AccountCache(unitTest.AccountId);
            var unittestType = cache.UnitTestTypes.Read(unitTest.TypeId);

            var actualInterval = unitTest.ActualTime                                        // сначала берем из настроек проверки в ЛК
                                 ?? TimeSpanHelper.FromSeconds(unittestType.ActualTimeSecs) // потом из настроек типа проверки в ЛК
                                 ?? TimeSpanHelper.FromSeconds(data.ActualIntervalSeconds)  // потом из сообщения
                                 ?? TimeSpan.FromMinutes(5);                                // по умолчанию 5 мин

            var actualDate = processDate + actualInterval;

            var joinKeyHash = data.ReasonCode ?? 0;

            var result = new Event()
            {
                Id             = Guid.NewGuid(),
                Count          = 1,
                JoinKeyHash    = joinKeyHash,
                Importance     = importance,
                OwnerId        = unitTest.Id,
                ActualDate     = actualDate,
                CreateDate     = DateTime.Now,
                LastUpdateDate = processDate,
                StartDate      = processDate,
                EndDate        = processDate,
                Message        = data.Message,
                EventTypeId    = SystemEventType.UnitTestResult.Id,
                Category       = EventCategory.UnitTestResult
            };

            if (data.Properties != null)
            {
                result.Properties = ApiConverter.GetEventProperties(data.Properties);
            }
            return(result);
        }
Beispiel #9
0
        public void SaveLogMessage(Guid accountId, Guid componentId, SendLogData message)
        {
            // Проверка на наличие необходимых параметров
            if (message == null)
            {
                throw new ParameterRequiredException("Request.Message");
            }
            if (message.Message == null)
            {
                throw new ParameterRequiredException("Request.Message.Message"); //todo надо переименовать
            }

            if (message.Message.Length > 4000)
            {
                message.Message = message.Message.Substring(0, 4000);
            }

            if (message.Context != null && message.Context.Length > 255)
            {
                message.Context = message.Context.Substring(0, 255);
            }

            // Проверим лимиты
            var accountDbContext = Context.GetAccountDbContext(accountId);
            var checker          = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);

            var size = message.GetSize();

            checker.CheckLogSizePerDay(accountDbContext, size);

            // Проверим лимит размера хранилища
            checker.CheckStorageSize(accountDbContext, size);

            // Получим компонент
            var componentService = Context.ComponentService;
            var component        = componentService.GetComponentById(accountId, componentId);

            var logRepository = Context.DbContext.GetAccountDbContext(accountId).GetLogRepository();
            var log           = ApiConverter.GetLog(component.Id, message);

            logRepository.Add(log);

            Context.SaveChanges();

            checker.AddLogSizePerDay(accountDbContext, size);
        }
Beispiel #10
0
        private int SetUp(DllArgs args)
        {
            const string dateFormat = @"yyyy-MM-dd";

            if (!DateTime.TryParseExact(args.From, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _) ||
                !DateTime.TryParseExact(args.To, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime _))
            {
                Logger.LogToConsole($"Date inputs must match '{dateFormat}'");
                return(1);
            }

            IAzureDevOpsRequest request    = new AzureDevOpsRequest(WebRequest, args);
            IApiConverter       converter  = new ApiConverter(args.ChangesetIdField, args.ClosedDateField);
            ITimeKeeper         timeKeeper = new TimeKeeper(TimeSpan.FromSeconds(30));

            azureDevOps = AzureDevOpsFactory.GetAzureDevOps(Logger, request, converter, timeKeeper);
            return(0);
        }
Beispiel #11
0
        public void TestApiConversionDeserialize()
        {
            var converter = new ApiConverter();
            var settings  = new JsonSerializerSettings {
                Converters = new List <JsonConverter>(new[] { converter })
            };
            var serializer = JsonSerializer.Create(settings);
            var json       = new JObject {
                { "flashBriefing", new JObject() }, { "householdList", new JObject() }
            };

            using (var obj = new JsonTextReader(new StringReader(json.ToString(Formatting.None))))
            {
                var res = serializer.Deserialize <List <IApi> >(obj);
                Assert.Equal(res.Count, 2);
                Assert.IsType <FlashBriefingApi>(res.First());
                Assert.IsType <HouseholdListApi>(res.Skip(1).First());
            }
        }
Beispiel #12
0
        public void TestApiConversionSerialize()
        {
            var converter = new ApiConverter();
            var settings  = new JsonSerializerSettings {
                Converters = new List <JsonConverter>(new[] { converter })
            };
            var serializer = JsonSerializer.Create(settings);

            var list = new List <IApi> {
                new FlashBriefingApi(), new HouseholdListApi()
            };
            var source = JObject.FromObject(list, serializer);

            var target = new JObject {
                { "flashBriefing", JObject.FromObject(new FlashBriefingApi()) }, { "householdList", JObject.FromObject(new HouseholdListApi()) }
            };

            Assert.True(JToken.DeepEquals(source, target));
        }
Beispiel #13
0
 /// <summary>
 /// Takes a snaphot of a window
 /// </summary>
 /// <param name="hwnd">Handle to the window</param>
 /// <returns>Bitmap object</returns>
 public static Bitmap WindowSnapshot(IntPtr hwnd)
 {
     if (hwnd == IntPtr.Zero)
     {
         return(null);
     }
     else
     {
         USER32.RECT rc;
         USER32.GetWindowRect(hwnd, out rc);
         Rectangle r      = ApiConverter.ToRectangle(rc);
         Bitmap    bitmap = new Bitmap(r.Width, r.Height, PixelFormat.Format24bppRgb);
         using (Graphics g = Graphics.FromImage(bitmap))
         {
             IntPtr hdcBitmap = g.GetHdc();
             USER32.PrintWindow(hwnd, hdcBitmap, 0);
         }
         return(bitmap);
     }
 }
Beispiel #14
0
 public ConverterManager(Dictionary <string, string> knownTypes)
 {
     _structConverter = new StructConverter(knownTypes);
     _apiConverter    = new ApiConverter(knownTypes);
 }
        public Component GetOrCreateComponentInternal(Guid accountId, GetOrCreateComponentRequestData data, bool createNew)
        {
            if (data == null)
            {
                throw new ParameterRequiredException("Request.Data");
            }
            if (data.TypeId == null)
            {
                throw new ParameterRequiredException("Request.Data.TypeId");
            }
            if (string.IsNullOrEmpty(data.SystemName))
            {
                throw new ParameterRequiredException("data.SystemName");
            }

            if (data.ParentComponentId == null)
            {
                data.ParentComponentId = GetRootId(accountId);
            }

            var componentId = data.NewId ?? Guid.NewGuid();
            var systemName  = data.SystemName;

            var properties = ApiConverter.GetComponentProperties(data.Properties);

            var accountDbContext    = Context.GetAccountDbContext(accountId);
            var componentRepository = accountDbContext.GetComponentRepository();
            var lockObj             = LockObject.ForComponent(systemName);

            lock (lockObj)
            {
                // ищем в детях
                var  component = componentRepository.GetChild(data.ParentComponentId.Value, systemName);
                bool isExists  = true;
                if (component == null)
                {
                    // ищем в папках
                    var parent = componentRepository.GetById(data.ParentComponentId.Value);
                    component = FindBySystemName(parent, systemName);
                    if (component == null)
                    {
                        // Проверим лимит
                        var checker          = AccountLimitsCheckerManager.GetCheckerForAccount(accountId);
                        var limitCheckResult = checker.CheckMaxComponents(accountDbContext);
                        if (!limitCheckResult.Success)
                        {
                            throw new OverLimitException(limitCheckResult.Message);
                        }

                        // создаем новый
                        component = Add(
                            accountId,
                            componentId,
                            data.ParentComponentId.Value,
                            data.DisplayName ?? systemName,
                            systemName,
                            data.TypeId.Value);

                        isExists = false;
                        checker.RefreshComponentsCount();
                    }
                }

                if (isExists && createNew)
                {
                    throw new ResponseCodeException(
                              ResponseCode.ParameterError,
                              "Компонент с таким системным именем уже существует");
                }

                // обновим версию
                if (string.IsNullOrEmpty(data.Version) == false)
                {
                    component.Version = data.Version;
                }

                // обновим свойства
                foreach (var property in properties)
                {
                    component.SetProperty(property);
                }
                accountDbContext.SaveChanges();
                return(component);
            }
        }
Beispiel #16
0
        public IEnumerable <CurrencyModel> GetAllCurrenciesForNationalBank()
        {
            string response = ApiAccess.GetDataFromApi(ApiRequestUrlModel.GetAllCurrenciesUrl);

            return(ApiConverter.ToCurrencyListConverter(response));
        }