示例#1
0
        public async Task <IActionResult> GetAllShortPages()
        {
            var result = await _pageRepository.GetAllShortPagesAsync();

            _logger.Info("All short pages: {@result}", result);
            return(Ok(result));
        }
示例#2
0
        public async Task <IActionResult> GetOne(string id)
        {
            var result = await _standardRepository.GetOneAsync(id);

            _logger.Info("Found standard component: {@result}", result);
            return(Ok(result));
        }
示例#3
0
        public async Task <IActionResult> Upload(IFormFile formFile)
        {
            _logger.Info("Upload file with name = {name} size = {size}", formFile.FileName, formFile.Length);
            var result = await _fileService.UploadFileAsync(formFile, "", false);

            _logger.Info("Uploaded file: {@result}", result);
            return(Ok(result));
        }
        public Task <DynamicListResponseDataModel> Query(DatabaseConnection databaseConnection, DynamicList dynamicList, DynamicListFetchDataModel fetchDataModel)
        {
            var response = new DynamicListResponseDataModel();
            var hasRows  = false;

            using (var sqlDbConnection = new SqlConnection(databaseConnection.ConnectionString))
            {
                var combinedQuery =
                    _builder
                    .Init(
                        dynamicList.ListDatasource.DatabaseConnectionOptions.Query,
                        fetchDataModel.FilledParameterOptions.FilledParameters,
                        options =>
                {
                    options.ContainsOperatorFormat = " LIKE '%' + {0} + '%'";
                    options.PaginationFormat       = "OFFSET {1} ROWS FETCH NEXT {0} ROWS ONLY";
                    options.FieldFormat            = "[{0}]";
                    options.DateCompareFormat      = "cast({0} as date){1}cast({2} as date) {3}";
                })
                    .AddTextSearch(fetchDataModel.TextSearch, dynamicList.ColumnsList.ColumnDefs.Where(a => a.SearchOptions.AllowTextSearch).Select(b => b.Name))
                    .AddFilter(fetchDataModel.FilterGroupOptions.FilterGroups)
                    .AddSort(fetchDataModel.SortOptions.SortableFields)
                    .AddPagination(fetchDataModel.PaginationOptions.PageNumber, fetchDataModel.PaginationOptions.PageSize)
                    .Build();

                sqlDbConnection.Open();
                _serviceLogger.Info("Current executed query {query}", combinedQuery.CombinedQuery);
                _serviceLogger.Info("Current parameters {@parameters}", combinedQuery.Parameters);
                using (var cmd = new SqlCommand(combinedQuery.CombinedQuery, sqlDbConnection))
                {
                    foreach (var param in combinedQuery.Parameters)
                    {
                        if (param.IsReplacedValue)
                        {
                            var castObject = _cSharpMapper.GetCSharpObjectByType(param.Value, param.ReplaceValueType);
                            cmd.Parameters.Add(
                                new SqlParameter(
                                    param.Name, _sqlServerMapper.GetSqlDbType(param.ReplaceValueType))
                            {
                                Value     = castObject,
                                Direction = System.Data.ParameterDirection.Input
                            });
                        }
                        else
                        {
                            cmd.Parameters.Add(
                                new SqlParameter(
                                    param.Name, GetSqlDbType(param, out var castObject))
                            {
                                Value     = castObject,
                                Direction = System.Data.ParameterDirection.Input
                            });
示例#5
0
        public async Task <IActionResult> GetOne(string databaseId, string entityName)
        {
            _logger.Info("Get one entity schema in database id = {databaseId}, entity name = {entityName}", databaseId, entityName);
            var result = await _entitySchemaRepository.GetOneEntitySchemaAsync(databaseId, entityName);

            _logger.Info("Found entity schemas: {@result}", result);
            if (result != null)
            {
                return(Ok(result));
            }

            return(NotFound());
        }
示例#6
0
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var methodName = input.Target.GetType().FullName + "." + input.MethodBase.Name;

            _logger.Info(string.Format("Method '{0}' called", methodName));
            var result = getNext()(input, getNext);

            _logger.Info(result.Exception == null
                             ? string.Format("Call '{0}' complete", methodName)
                             : string.Format("Call '{0}' completes with exception: {1}", methodName, result.Exception.GetType()));

            return(result);
        }
        public async Task <IActionResult> GetOne(string appId, string localeId)
        {
            var result = await _localizationRepository.GetByLocaleId(localeId, appId);

            _logger.Info("Found localization: {@result}", result);
            return(Ok(result));
        }
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var flexiblePage = new FlexiblePageModel
            {
                Sections = _siteRequest.Current.PageTemplate.Sections.Select(a => new SectionPartModel {
                    Name = a.ThemePartRef, BindingType = a.BindingType, TemplateKey = a.Key
                }).ToList(),
                GoogleMetadata = _siteRequest.Current.Page.GoogleMetadata
            };

            _logger.Info("The current flexible page {@flexiblePage}", flexiblePage);
            var pageVersion = _siteRequest.Current.PageVersion;

            if (flexiblePage.Sections != null && flexiblePage.Sections.Any())
            {
                foreach (var section in flexiblePage.Sections)
                {
                    if (section.BindingType == BindingType.Datasource)
                    {
                        var foundPartVersion = pageVersion.Manifests.FirstOrDefault(a => a.TemplateKey == section.TemplateKey);
                        if (foundPartVersion != null)
                        {
                            section.DatasourceName = foundPartVersion.DatasourceKey;
                        }
                    }
                }
            }

            _siteRequest.Current.RenderedPageModel = flexiblePage;

            await next.Invoke(context);
        }
        public override Task <ServiceConfigurationResponse> Pull(ServiceConfigurationRequest request, ServerCallContext context)
        {
            _logger.Info("Client is sending request", request);
            var fileContent = _configuration.GetSection($"{request.ServiceName}:{request.Version}").Value;

            return(Task.FromResult(new ServiceConfigurationResponse {
                ConfigurationContent = fileContent
            }));
        }
示例#10
0
 public DeployService(IDeployServiceFactory dsFactory, IConfFactory cFactory)
 {
     _dsFactory = dsFactory;
     _cFactory = cFactory;
     _logger = _dsFactory.CreateLoggerObj();
     _logger.Info("Service instance is created");
     if (OperationContext.Current != null)
         OperationContext.Current.Channel.Closing += ClearLocks;
 }
示例#11
0
 public DeployService(IDeployServiceFactory dsFactory, IConfFactory cFactory)
 {
     _dsFactory = dsFactory;
     _cFactory  = cFactory;
     _logger    = _dsFactory.CreateLoggerObj();
     _logger.Info("Service instance is created");
     if (OperationContext.Current != null)
     {
         OperationContext.Current.Channel.Closing += ClearLocks;
     }
 }
示例#12
0
 public void HandleDeploy(DeployException ex, IDeployEvents callback, List <IDeployer> deploySteps, Action <IDeployer> rollbackExecutor)
 {
     _logger.Error("Deploy exception is catched", ex);
     HandleException(ex);
     foreach (var installStep in deploySteps)
     {
         try {
             rollbackExecutor(installStep);
             _logger.Info("Rollback is complete");
         } catch (RollbackException rollbackEx) {
             HandleException(rollbackEx);
         }
     }
        public async Task Invoke(
            HttpContext httpContext,
            IOptionsMonitor <MonitorOptions> monitorOption,
            IMonitorHealthCheck monitorHealthCheck,
            IServiceLogger <AddRequestMonitorMiddleware> serviceLogger)
        {
            if (monitorOption.CurrentValue.Enable)
            {
                var requestMonitor = new RequestMonitor
                {
                    BeginDateTime = DateTime.UtcNow
                };
                var startTime     = DateTime.UtcNow;
                var startCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
                var stopWatch     = new Stopwatch();
                stopWatch.Start();
                await _next.Invoke(httpContext);

                stopWatch.Stop();
                var endTime     = DateTime.UtcNow;
                var endCpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
                requestMonitor.ElapsedTime = stopWatch.ElapsedMilliseconds;
                requestMonitor.EndDateTime = DateTime.UtcNow;
                var cpuUsedMs     = (endCpuUsage - startCpuUsage).TotalMilliseconds;
                var totalMsPassed = (endTime - startTime).TotalMilliseconds;
                var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed);
                requestMonitor.CpuUsage = cpuUsageTotal * 100;
                if (requestMonitor.CpuUsage > 100)
                {
                    requestMonitor.CpuUsage = 100;
                }
                requestMonitor.StatusCode = httpContext.Response.StatusCode;
                requestMonitor.MemoryUsed = Process.GetCurrentProcess().WorkingSet64 / 1024;
                monitorHealthCheck.AddRequestMonitor(requestMonitor);
                httpContext.Items[Constants.RequestMonitor] = requestMonitor;
                serviceLogger.Info("Request complete with these usages {$Monitor}", requestMonitor.ToJson());
            }
            else
            {
                await _next.Invoke(httpContext);
            }
        }
示例#14
0
        public async Task <IActionResult> GetOne(string id)
        {
            _logger.Info("Getting Chart with Id = {id}", id);
            var result = await _chartRepository.GetOneAsync(id);

            if (result == null)
            {
                return(NotFound());
            }

            // Hide infos when datasource is database
            result.DatabaseOptions.Query =
                string.Join(';',
                            StringUtil
                            .GetAllDoubleCurlyBraces(
                                result.DatabaseOptions.Query, true,
                                new List <string> {
                "{{REAL_TIME}}", "{{FILTER}}"
            }));
            _logger.Info("Found chart: {@result}", result);
            return(Ok(result));
        }
        public async Task <IActionResult> GetAll()
        {
            var result = await _dynamicListRepository.GetAllAsync(isRequiredDiscriminator : true);

            _logger.Info("Found dynamic lists {@result}", result);
            if (result != null)
            {
                return(Ok(result));
            }

            return(NotFound());
        }
        public async Task <TokenModel> SignInAsync(LoginModel loginModel)
        {
            _serviceLogger.Info("User Login {$loginModel}", loginModel.ToJson());
            var user = await _userManager.FindByNameAsync(loginModel.Username);

            if (user != null)
            {
                var validationResult = await _signInManager.PasswordSignInAsync(user, loginModel.Password, false, true);

                if (validationResult.Succeeded)
                {
                    var userClaims = await _userManager.GetClaimsAsync(user);

                    var token = SignedToken(userClaims);

                    // Create UserSession
                    var userSession = new UserSession
                    {
                        Id = DataUtil.GenerateUniqueId(),
                        RequestIpAddress = loginModel.ClientIp,
                        SoftwareAgent    = loginModel.SoftwareAgent,
                        InstalledVersion = loginModel.VersionInstalled,
                        SignInDate       = DateTime.UtcNow,
                        UserId           = user.Id,
                        Username         = user.Username,
                        UserActivities   = new List <UserActivity>
                        {
                            new UserActivity
                            {
                                Id           = DataUtil.GenerateUniqueId(),
                                ActivityName = "USER_SIGNIN",
                                Content      = "Signin successfully",
                                ActivityDate = DateTime.UtcNow,
                                ActivityType = ActivityType.Info
                            }
                        }
                    };
                    await _userSessionRepository.AddAsync(userSession);

                    // Create refresh token
                    var expToken        = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.TokenExpiration);
                    var expRefreshToken = DateTime.UtcNow.AddMinutes(_jwtBearerOptions.CurrentValue.RefreshTokenExpiration);
                    var issuedToken     = new IssuedToken
                    {
                        Id                  = DataUtil.GenerateUniqueId(),
                        UserId              = user.Id,
                        JwtToken            = token,
                        ExpiredJwtToken     = expToken,
                        ExpiredRefreshToken = expRefreshToken,
                        RefreshToken        = CryptoUtil.ToSHA256(Guid.NewGuid().ToString()),
                        UserSessionId       = userSession.Id,
                        Deactive            = false
                    };

                    await _issuedTokenRepository.AddAsync(issuedToken);

                    _serviceLogger.Info("User Login Successfully {$issuedToken}", issuedToken.ToJson());
                    return(new TokenModel
                    {
                        Token = token,
                        Exp = ((DateTimeOffset)expToken).ToUnixTimeSeconds(),
                        ExpRefresh = ((DateTimeOffset)expRefreshToken).ToUnixTimeSeconds(),
                        RefreshToken = issuedToken.RefreshToken,
                        UserSessionId = userSession.Id
                    });
                }
            }

            throw new IdentityException(ErrorCodes.CannotSignIn);
        }
示例#17
0
        public async Task <IActionResult> Get()
        {
            var result = await _databaseRepository.GetAllAsync();

            _logger.Info("Found database connections: {@result}", result);
            if (!result.Any())
            {
                return(NotFound());
            }

            // Empty all connection strings for security risks
            foreach (var databaseConnection in result)
            {
                databaseConnection.ConnectionString = string.Empty;
                databaseConnection.DataSource       = string.Empty;
            }
            return(Ok(result));
        }
 public async Task <Post> GetByUrlPathAsync(string urlPath)
 {
     _logger.Info("Get post by url path " + urlPath);
     return(await Collection.AsQueryable().FirstAsync(a => a.UrlPath == urlPath));
 }
示例#19
0
        public async Task <IActionResult> GetOne(string id, string localeId)
        {
            _logger.Info("Getting App with Id = {id}", id);
            var result = await _appRepository.GetOneAsync(id);

            _logger.Info("Found app: {@result}", result);

            var languageKeys = await _localizationRepository.GetAppLangues(id, localeId);

            if (languageKeys != null && languageKeys.Any())
            {
                TranslateApp(result, languageKeys);
            }
            if (result == null)
            {
                return(NotFound());
            }

            return(Ok(result));
        }
示例#20
0
 protected void ClearLocks(object sender, EventArgs e)
 {
     FoldersLocks.RemoveForSession(_sessionKey);
     _logger.Info(string.Format("Lock for folder '{0}' is released", _updatedForlder));
 }