Beispiel #1
0
        // ======================================== fk_doc === fk_code ==========================

        public async Task <ResultCrmDb> LoadFkDocxFormat(byte[] fileData, ImportParam importParam)
        {
            var result = new ResultCrmDb();

            importParam.TypeImp = ImportType.None;
            try
            {
                var parserFile = AutoFac.ResolveNamed <IParseFile>("FKDOCX");
                parserFile.FileData    = fileData;
                parserFile.ImportParam = importParam;
                var parserResult = await parserFile.ParseFile();

                if (!parserResult.Succeeded)
                {
                    return(parserResult);
                }

                var parserFormat = AutoFac.ResolveNamed <IParserFormat>("FKDOCX00");
                var fkCodes      = (List <fk_code>) await parserFormat.ParserFormat(parserResult.Result, importParam);
                await WriteFkCode(fkCodes);
            }
            catch (Exception ex)
            {
                result.AddError(Constant.ErrCodeImport, ex.Message);
                result.AddError(Constant.ErrCodeStackTrace, ex.StackTrace);
            }
            return(result);
        }
Beispiel #2
0
        public AuthorizeTest()
        {
            var confFileName = Path.Combine(
                Path.GetDirectoryName(GetType().Assembly.Location) ?? string.Empty,
                $"Monica.Crm.WebApi.dll.config");
            var build           = new ConfigurationBuilder().AddXmlFile(confFileName);
            var configiguration = build.Build();

            var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            foreach (var file in files)
            {
                if (file.IndexOf("testhost.dll", StringComparison.Ordinal) > -1)
                {
                    continue;
                }

                System.Runtime.Loader.AssemblyLoadContext.Default
                .LoadFromAssemblyPath(file);
            }

            AutoFac.Init(DataBaseName.MySql, builder =>
            {
                builder.RegisterInstance(configiguration).As <IConfiguration>();
            });
            _monicaAuthorizeDataAdapter = AutoFac.Resolve <IMonicaAuthorizeDataAdapter>();
        }
Beispiel #3
0
        public async Task <ResultCrmDb> PreviewFile(byte[] fileData, ImportParam importParam)
        {
            var result = new ResultCrmDb();

            importParam.TypeImp = ImportType.Preview;
            try
            {
                // TheOktmo потом перенести в Settings
                _dohodDbContext.SetTheOktmo(importParam, result);
                if (!result.Succeeded)
                {
                    return(result);
                }

                var parserFile = AutoFac.ResolveNamed <IParseFile>(importParam.FormatGroup);
                parserFile.FileData    = fileData;
                parserFile.ImportParam = importParam;
                var parserResult = await parserFile.ParseFile();

                if (!parserResult.Succeeded)
                {
                    return(parserResult);
                }

                var previewFormat = AutoFac.ResolveNamed <IPreviewFormat>(importParam.FormatGroup + importParam.Format);
                result.Result = (ImpPreviewData)await previewFormat.PreviewFormat(parserResult.Result, importParam);
            }
            catch (Exception ex)
            {
                result.AddError(Constant.ErrCodeImport, ex.Message);
                result.AddError(Constant.ErrCodeStackTrace, ex.StackTrace);
            }
            return(result);
        }
        public async Task GetRoles()
        {
            var roleManager = AutoFac.Resolve <RoleManager <ApplicationRole> >();
            var ss          = roleManager.Roles.Select(s => s.Name);

            Assert.IsNotEmpty(ss);
        }
Beispiel #5
0
        /// <summary>
        /// Получить данные для списка
        /// </summary>
        /// <param name="parametr"></param>
        /// <returns></returns>
        public async Task <ReportResultData> GetEditModel(BaseModelReportParam parametr)
        {
            var resultData = new ReportResultData();
            var accessForm = await _accessManager.GetAccessFormAsync(parametr.UserName, parametr.FormId);

            if (accessForm != null && (int)accessForm.TypeAccec < 2)
            {
                throw new UserMessageException("Вы запросили данные режима, на который у вас не открыты права");
            }
            var formModelDto =
                Mapper.Map <FormModelDto>((
                                              await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == parametr.FormId)));

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }

            resultData.FormModel   = formModelDto;
            resultData.FieldAccess = await _reportManager.GetFieldsFormWithProfileAsync(parametr.UserName, parametr.FormId, false, fields => fields.Where(f => f.IsDetail ?? false));

            // resultData.Buttons = await _reportManager.GetButtonsAsync(parametr.UserName, parametr.FormId, false);
            var report = AutoFac.ResolveNamed <IReportEngineData>(formModelDto.NameClassDataEngine);
            var resultDataFieldAccess = resultData.FieldAccess as FieldAccessDto[] ?? resultData.FieldAccess.ToArray();

            resultData.Data = report == null ? "" : GetModelAccess(await report.GetDataEditModel(parametr), resultDataFieldAccess);
            return(resultData);
        }
Beispiel #6
0
 protected void Application_Start()
 {
     AutoFac.Setup();
     Ef4.Setup();
     Mvc.Setup();
     Solr.Setup();
 }
Beispiel #7
0
        /// <summary>
        /// Получить данные для списка
        /// </summary>
        /// <param name="parametr"></param>
        /// <returns></returns>
        public async Task <ReportResultData> GetDataList(BaseModelReportParam parametr)
        {
            var resultData = new ReportResultData();
            var accessForm = await _accessManager.GetAccessFormAsync(parametr.UserName, parametr.FormId);

            if (accessForm != null && (int)accessForm.TypeAccec < 2)
            {
                throw new UserMessageException("Вы запросили данные режима, на который у вас не открыты права");
            }
            var formModelDto =
                (await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == parametr.FormId)).Map <FormModelDto>();

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }
            resultData.FormModel   = formModelDto;
            resultData.FieldAccess = await _reportManager.GetFieldsFormWithProfileAsync(parametr.UserName, parametr.FormId, false,
                                                                                        fields => fields.Where(f => (f.IsVisibleList ?? false) || string.IsNullOrWhiteSpace(f.Express)));

            var report = AutoFac.ResolveNamed <IReportEngineData>(string.IsNullOrWhiteSpace(formModelDto.NameClassDataEngine) ? nameof(ReportEngineDefaultData) : formModelDto.NameClassDataEngine);

            var resultDataFieldAccess = resultData.FieldAccess as FieldAccessDto[] ?? resultData.FieldAccess.ToArray();

            resultData.Data    = GetDataAccess(report == null ? null : await report.GetDataList(parametr), resultDataFieldAccess);
            resultData.Columns = await _columnCreater.GetColumns(resultDataFieldAccess);

            resultData.KeyField     = resultDataFieldAccess.FirstOrDefault(f => f.IsKey ?? false)?.Name;
            resultData.FormProperty = await _columnCreater.GetProperty(resultDataFieldAccess, formModelDto);

            return(resultData);
        }
        public async Task InvokeAsync(HttpContext context)
        {
            var auth = AutoFac.ResolveNamed <IAuthUserEngine>(_configuration["AuthSchema"], true);

            if (auth != null)
            {
                await auth.SetAuthUser(context);
            }

            await _next(context);
        }
Beispiel #9
0
        /// <summary>
        /// Проверка сохранеяемой модели по предоставленным правилам
        /// </summary>
        /// <param name="saveModel">Модель для сохранения</param>
        /// <param name="formModelId">Системный номер модели данных</param>
        /// <returns></returns>
        public async Task <ResultCrmDb> ValidateModel(dynamic saveModel, int formModelId)
        {
            var formModelDto =
                (await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == formModelId)).Map <FormModelDto>();

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }
            var report = AutoFac.ResolveNamed <IReportEngineData>(string.IsNullOrWhiteSpace(formModelDto.NameClassDataEngine) ? nameof(ReportEngineDefaultData) : formModelDto.NameClassDataEngine);

            return(await report.ValidateModel(saveModel, formModelDto));
        }
        public async Task ParserRtf_Normal()
        {
            var loaderFile = AutoFac.Resolve <ILoaderFile>();

            foreach (var f in Directory.GetFiles(_pathDir))
            {
                var file = await File.ReadAllBytesAsync(f);

                var fileRtf = await Service.ParseDocument(file);

                var documentLoader = await loaderFile.SaveDocumentLoader(fileRtf);

                await loaderFile.RunAotParser(documentLoader);

                Assert.IsNotNull(fileRtf);
            }
        }
Beispiel #11
0
        public async Task <ResultCrmDb> AfterSaveModel(int formId, int idModel, string userName)
        {
            var formModelDto =
                (await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == formId)).Map <FormModelDto>();

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }
            var report = AutoFac.ResolveNamed <IActionAfterSave>(formModelDto.TableName, true);

            if (report == null)
            {
                return(new ResultCrmDb());
            }
            return(await report.BeforeSave(idModel, userName));
        }
Beispiel #12
0
        public async Task <ResultCrmDb> Action(int formId, int[] idModel, string userName, ActionArgs otherInfo, string sysname)
        {
            var formModelDto =
                (await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == formId)).Map <FormModelDto>();

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }
            var report = AutoFac.ResolveNamed <IActionBtnFormModel>(sysname);

            if (report == null)
            {
                return(new ResultCrmDb());
            }
            return(await report.Action(otherInfo, userName, formId, idModel));
        }
Beispiel #13
0
        private static IContainer BuildContainer()
        {
            var mockConfigurationProvider = new Mock <IAppConfigurationProvider>();
            var nvCol = new NameValueCollection {
                { ServerConfiguration.WebApplication.AppSettingKeys.TaskScheduleTrigger, "1" }
            };

            mockConfigurationProvider.SetupGet(cp => cp.Settings).Returns(nvCol);
            var autofac = new AutoFac(mockConfigurationProvider.Object)
            {
                SkipRavenDbInitialization = true
            };

            autofac.Configure();
            //capture DocumentStore for manual disposal during test tear down.  Otherwise, subsequent tests will fail with concurrency exceptions
            _documentStore = autofac.Container.Resolve <IDocumentStore>();
            return(autofac.Container);
        }
Beispiel #14
0
        protected BaseServiceTest()
        {
            var mockDataBaseMain = new Mock <IDataBaseMain>();
            var mockDataBaseIs4  = new Mock <IDataBaseIs4>();
            var logger           = new Mock <ILogger>();

            var configiguration     = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            var connectionString    = configiguration.ConnectionStrings.ConnectionStrings["MySqlDatabase"].ConnectionString;
            var connectionStringIs4 = configiguration.ConnectionStrings.ConnectionStrings["MySqlDatabaseIS4"].ConnectionString;

            GlobalSettingsApp.CurrentAppDirectory =
                Path.GetDirectoryName(Assembly.GetAssembly(typeof(BaseEfTest)).Location);
            mockDataBaseMain.Setup(main => main.ConntectionString).Returns(connectionString);
            mockDataBaseIs4.Setup(main => main.ConntectionString).Returns(connectionStringIs4);
            var events   = new OnStartupEvents();
            var services = new ServiceCollection();

            services.AddSingleton(mockDataBaseMain.Object);
            services.AddSingleton(mockDataBaseIs4.Object);
            events.OnConfigureServicesAfterAddMvc(services, null);


            var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            foreach (var file in files)
            {
                if (file.IndexOf("testhost.dll", StringComparison.Ordinal) > -1)
                {
                    continue;
                }

                System.Runtime.Loader.AssemblyLoadContext.Default
                .LoadFromAssemblyPath(file);
            }

            AutoFac.Init(DataBaseName.MySql, builder =>
            {
                builder.Populate(services);
                builder.RegisterInstance(logger.Object);
                //builder.RegisterInstance(mockDataBaseIs4);
                //builder.RegisterInstance(mockDataBaseMain);
            });
            Service = AutoFac.Resolve <TService>();
        }
Beispiel #15
0
        /// <summary>
        /// Удаление моделей данных
        /// </summary>
        /// <param name="formModel">Сущность для которой нужно удалить данные</param>
        /// <param name="userName">Пользователь, который удаляет данные</param>
        /// <param name="key">Список ключей сущности, которые нужно удалить</param>
        /// <returns></returns>
        public async Task <ResultCrmDb> RemoveEntity(int formModel, string userName, string[] key)
        {
            var accessForm = await _accessManager.GetAccessFormAsync(userName, formModel);

            if (accessForm != null && (int)accessForm.TypeAccec < 2)
            {
                throw new UserMessageException("Вы запросили данные режима, на который у вас не открыты права");
            }
            var formModelDto =
                (await _reportDbContext.FormModel.FirstOrDefaultAsync(f => f.Id == formModel)).Map <FormModelDto>();

            if (formModelDto == null)
            {
                throw new UserMessageException("Не удалось определить форму");
            }
            var report = AutoFac.ResolveNamed <IReportEngineData>(string.IsNullOrWhiteSpace(formModelDto.NameClassDataEngine) ? nameof(ReportEngineDefaultData) : formModelDto.NameClassDataEngine);

            return(await report.RemoveEntity(formModelDto, userName, key));
        }
Beispiel #16
0
        }                                                                  // Initiated only once in Application_Start()

        protected void Application_Start()
        {
            // Initiate NHibernate session factory, this should be done once for every application start.
            // Creating a session factory is an time-consuming operation (all mapping files are processed for example)
            SessionFactory = NHibernateHelper.SessionFactory;

            NHibernateProfiler.Initialize();

            AreaRegistration.RegisterAllAreas();

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AutoFac.Setup();

            // Avoids unexpected required attributes on value types like integer.
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
        }
Beispiel #17
0
        public async Task <ResultCrmDb> ImportFile(byte[] fileData, ImportParam importParam)
        {
            var result = new ResultCrmDb();

            importParam.TypeImp = ImportType.Import;
            try
            {
                // TheOktmo потом перенести в Settings
                _dohodDbContext.SetTheOktmo(importParam, result);
                if (!result.Succeeded)
                {
                    return(result);
                }

                var parserFile = AutoFac.ResolveNamed <IParseFile>(importParam.FormatGroup);
                parserFile.FileData    = fileData;
                parserFile.ImportParam = importParam;
                var parserResult = await parserFile.ParseFile();

                if (!parserResult.Succeeded)
                {
                    return(parserResult);
                }


                var parserFormat = AutoFac.ResolveNamed <IParserFormat>(importParam.FormatGroup + importParam.Format);
                var dohods       = (List <t_dohod>) await parserFormat.ParserFormat(parserResult.Result, importParam);
                await WriteImportedData(dohods);

                await parserFormat.AfterDataWrited(dohods, importParam);

                result.Result = ImportInfo(parserFormat.PreviewData, importParam);
            }
            catch (Exception ex)
            {
                result.AddError(Constant.ErrCodeImport, ex.Message);
                result.AddError(Constant.ErrCodeStackTrace, ex.StackTrace);
            }
            //_dohodDbContext.TruncateDbTable("t_dohorig");
            //dohodDbContext.TruncateDbTable("t_dohod");
            return(result);
        }
Beispiel #18
0
        public GenerateFieldsMySqlTest()
        {
            var mockDataBaseMain = new Mock <IDataBaseMain>();
            var mockDataBaseIs4  = new Mock <IDataBaseIs4>();
            var logger           = new Mock <ILogger>();

            var configiguration     = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            var connectionString    = configiguration.ConnectionStrings.ConnectionStrings["MySqlDatabase"].ConnectionString;
            var connectionStringIs4 = configiguration.ConnectionStrings.ConnectionStrings["MySqlDatabaseIS4"].ConnectionString;

            mockDataBaseMain.Setup(main => main.ConntectionString).Returns(connectionString);
            mockDataBaseIs4.Setup(main => main.ConntectionString).Returns(connectionStringIs4);

            var services = new ServiceCollection();

            services.AddSingleton(mockDataBaseMain.Object);
            services.AddSingleton(mockDataBaseIs4.Object);
            services.AddDbContextCore();


            var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            foreach (var file in files)
            {
                if (file.IndexOf("testhost.dll", StringComparison.Ordinal) > -1)
                {
                    continue;
                }

                System.Runtime.Loader.AssemblyLoadContext.Default
                .LoadFromAssemblyPath(file);
            }

            AutoFac.Init(DataBaseName.MySql, builder =>
            {
                builder.Populate(services);
                builder.RegisterInstance(logger.Object);
                //builder.RegisterInstance(mockDataBaseIs4);
                //builder.RegisterInstance(mockDataBaseMain);
            });
            Service = AutoFac.ResolveNamed <IGenerateField>(nameof(GenerateFieldMySql));
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            LoaderExtensions.OnConfigureServicesBeforeAddMvc(services);
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                {
                    builder.AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithOrigins("*")
                    .WithMethods("*")
                    .WithHeaders("*")
                    .DisallowCredentials();
                });
            });
            IMvcBuilder mvcBuilder = MvcServiceCollectionExtensions.AddMvc(services).AddNewtonsoftJson();

            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new AuthorizeFilter("CorsPolicyAll"));
            //});
            services.AddControllers(mvcOtions =>
            {
                mvcOtions.EnableEndpointRouting = false;
            });
            mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddScoped <IDataBaseMain, DataBaseMain>();
            services.AddScoped <IDataBaseIs4, DataBaseIs4>();
            LoaderExtensions.OnConfigureServicesAfterAddMvc(services, mvcBuilder, Configuration);
            LoaderExtensions.LoadMvc(mvcBuilder, GlobalSettingsApp.CurrentAppDirectory);
            LoaderExtensions.OnInitBackendService(services);

            ApplicationContainer = AutoFac.Init(DataBaseName.MySql, cb =>
            {
                cb.Populate(services);
            });
            return(new AutofacServiceProvider(ApplicationContainer));
        }
Beispiel #20
0
 public EngineParser(List <WordNotPersistent> wordNotPersistents)
 {
     _wordDbContext        = AutoFac.Resolve <WordDbContext>();
     VocalabryFirstBigramm = wordNotPersistents?.Where(f => f.IsFirst);
     VocalabryEndBigramm   = wordNotPersistents?.Where(f => !f.IsFirst);
 }
 //  protected IEnumerable<EncodingWord> _encodingWords;
 public InputLayer()
 {
     _wordDbContext = AutoFac.Resolve <WordDbContext>();
     // _outputCodeWordsArray = outputCodeWords;
 }
Beispiel #22
0
 /// <summary>
 /// Конструктор
 /// </summary>
 public CrmDesignerController(IReportManager reportManager) : base(ModuleName)
 {
     _reportManager = reportManager;
     _generateField = AutoFac.ResolveNamed <IGenerateField>(nameof(GenerateFieldMySql));
 }
Beispiel #23
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
            {
                //builder.AllowAnyMethod()
                //    .AllowAnyHeader()
                //    .WithOrigins("*")
                //    .WithMethods("*")
                //    .WithHeaders("*")
                //.DisallowCredentials();
                builder.WithOrigins("http://localhost:4200", "http://localhost:4200/", "https://barbuuuda.ru", "https://barbuuuda.ru/")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
            }));

            #region ПРОД.
            //    services.AddDbContext<ApplicationDbContext>(options =>
            //      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));

            //    services.AddEntityFrameworkNpgsql().AddDbContext<PostgreDbContext>(opt =>
            //opt.UseNpgsql(Configuration.GetConnectionString("PostgreConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));

            //    services.AddDbContext<IdentityDbContext>(options =>
            //        options.UseNpgsql(Configuration.GetConnectionString("PostgreConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));
            #endregion

            #region ТЕСТ.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("TestMsSqlConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));

            services.AddEntityFrameworkNpgsql().AddDbContext <PostgreDbContext>(opt =>
                                                                                opt.UseNpgsql(Configuration.GetConnectionString("TestNpgSqlConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));

            services.AddDbContext <IdentityDbContext>(options =>
                                                      options.UseNpgsql(Configuration.GetConnectionString("TestNpgSqlConnection"), b => b.MigrationsAssembly("Barbuuuda.Core").EnableRetryOnFailure()));
            #endregion

            services.AddIdentity <UserEntity, IdentityRole>(opts =>
            {
                opts.Password.RequiredLength         = 5;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase       = false;
                opts.Password.RequireUppercase       = false;
                opts.Password.RequireDigit           = false;
            })
            .AddEntityFrameworkStores <IdentityDbContext>()
            .AddDefaultTokenProviders();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Barbuuuda", Version = "v1"
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = AuthOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });

            services.AddSignalR();

            ApplicationContainer = AutoFac.Init(cb =>
            {
                cb.Populate(services);
            });

            return(new AutofacServiceProvider(ApplicationContainer));
        }
Beispiel #24
0
 /// <summary>
 /// AutoFac 配置
 /// </summary>
 /// <param name="builder"></param>
 public void ConfigureContainer(ContainerBuilder builder)
 {
     AutoFac.AutoFacLoad(builder);
 }