protected ImageLoader(ImageConfig imageConfig) : this() { if (imageConfig == null) { throw new ArgumentException("Can not initialize ImageLoader with empty configuration"); } }
public static Character CreateDefaultCharacter(CharacterConfig.CHARACTERS character, CharacterConfig.BUTTONS button) { var c = new Character(); c.characterType = character; ByteStreamPair bsp = CharacterConfig.GetByteStreamPair(character, button); PaletteConfig spriteConfig = PaletteConfig.GenerateSpriteConfig(character); PaletteConfig portraitConfig = PaletteConfig.GeneratePortraitConfig(character); Palette s = Palette.PaletteFromConfig(spriteConfig); Palette p = Palette.PaletteFromConfig(portraitConfig); c.sprite = s; c.portrait = p; s.LoadStream(bsp.spriteStream); p.LoadStream(bsp.portraitStream); AssignImage(s, ImageConfig.GenerateNeutralBasePalette(character), "neutral"); AssignImage(p, ImageConfig.GenerateVictoryBasePalette(character), "victory"); if (character != CharacterConfig.CHARACTERS.Gouki) { AssignImage(p, ImageConfig.GenerateLossBasePalette(character), "loss"); } if (character == CharacterConfig.CHARACTERS.Dictator) { AssignDicatatorSpriteImages(s); } if (character == CharacterConfig.CHARACTERS.Gouki) { AssignGoukiSpriteImages(s); } return(c); }
public ConfigWindow(WordConfig wordsConfig, ImageConfig imageConfig, TagsCloudCreator tagsCloudProcessor, IServiceFactory <ITextFilter> filtersFactory, IServiceFactory <IWordConverter> convertersFactory, IServiceFactory <ITagsGenerator> tagsGeneratorFactory, IServiceFactory <IRectanglesLayouter> layouterFactory) { InitializeComponent(); this.wordsConfig = wordsConfig; this.imageConfig = imageConfig; this.tagsGeneratorFactory = tagsGeneratorFactory; this.layouterFactory = layouterFactory; this.tagsCloudProcessor = tagsCloudProcessor; this.filtersFactory = filtersFactory; this.convertersFactory = convertersFactory; colorDialog = new ColorDialog(); fontDialog = new FontDialog(); saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Изображение (*.png)||Изображение (*.jpg)||Изображение (*.bmp)|"; openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Текстовые файлы (*.txt)|"; widthNumeric = new NumericUpDown(); heightNumeric = new NumericUpDown(); tableLayoutPanel = new TableLayoutPanel(); tableLayoutPanel.Dock = DockStyle.Fill; tableLayoutPanel.AutoSize = true; Controls.Add(tableLayoutPanel); InitView(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrEmpty(env)) { env = "Development"; } // Read configuration var builder = new ConfigurationBuilder() .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)) .AddJsonFile($"appsettings.json", optional: false) .AddJsonFile($"appsettings.{env}.json", optional: true); Configuration = builder.Build(); // Connection string for using in DBContext var connectionString = Configuration.GetConnectionString("DefaultConnection"); var imageConfig = new ImageConfig(); Configuration.Bind(imageConfig); services .AddDbContext <SimpleCatalogDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient, ServiceLifetime.Transient) .AddTransient <IProductCategoryService, ProductCategoryService>() .AddTransient <IProductService, ProductService>() .AddTransient <IImageService, ImageService>() .AddSingleton(imageConfig) .AddSingleton(new LoggerFactory().AddNLog()) .AddLogging() .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); var provider = services.BuildServiceProvider(); _logger = provider.GetService <ILogger <Startup> >(); _logger.LogInformation("Start the project"); try { //Apply database migrations. (It will create DB if not exist) using (var dbCntx = provider.GetService <SimpleCatalogDbContext>()) { dbCntx.Database.Migrate(); } } catch (Exception ex) { _logger.LogError(ex, "Migration error"); throw; } }
public ImageDataBlobStorage(ImageConfig settings) { _connectionString = settings.ConnectionString;//TODO остальное тоже в конфиги? string dbGuid = "8e188595-ae55-42f6-bca2-a88814e5f2b8"; _containerImagesName = "menuimages-"; _containerUploadedImagesName = _containerImagesName + "uploads-" + dbGuid; _containerImagesName += dbGuid; }
public ImageConfig GetConfiguration(bool fresh = false) { if (!fresh && null != _containerConfigCache) { return(_containerConfigCache); } _containerConfigCache = DockerHost.InspectImage(Id, Certificates).Data; return(_containerConfigCache); }
private ImageSize AddImage(ImageConfig imageConfig, ItemDataModel itemDataModelFile, string propertName, IList <Stream> streams, byte[] contents) { // Si c'est une image, créer un aperçu minuscule var imageFormat = ImageUtility.GetImageFormat(Input.FileData.ContentType); if (imageFormat != null) { var fileDataModel = new FileDataModel(); using (var memoryStream = new MemoryStream(contents)) { var stream = ImageUtility.ResizeGdi(memoryStream, imageConfig, imageFormat); string contentType; string filename = null; if (!string.IsNullOrEmpty(imageConfig.TypeMime)) { contentType = imageConfig.TypeMime; var fileNames = Input.FileData.Filename.Split('.'); if (fileNames.Length == 2) { filename = string.Concat(fileNames[0], ".", ImageUtility.GetImageExtention(imageConfig.TypeMime)); } } else { contentType = Input.FileData.ContentType; filename = Input.FileData.Filename; } var imageBusinessModel = new ImageBusinessModel(); imageBusinessModel.Size = new ImageSize { Heigth = stream.Height, Width = stream.With }; fileDataModel.Module = "ImageData"; fileDataModel.PropertyName = propertName; fileDataModel.SiteId = Input.SiteId; fileDataModel.FileData.ContentType = contentType; fileDataModel.FileData.FileName = filename; fileDataModel.FileData.Stream = stream.Stream; itemDataModelFile.Files.Add(fileDataModel); _dataFactory.Add(fileDataModel); streams.Add(stream.Stream); return(new ImageSize { Heigth = stream.Height, Width = stream.With }); } } return(null); }
public static ImageLoader Initialize(ImageConfig imageConfig) { if (imageConfig == null) { throw new ArgumentException("Can not initialize ImageLoader with empty configuration"); } if (ImageConfig.Default != null) { return ImageLoader.Instance; } ImageConfig.Default = imageConfig; return ImageLoader.Instance; }
public PhotoService(IFileService fileService, IRepository <Photo> photoRepository, IFilePathHelper filePathHelper, IMapper mapper, IOptions <ImageConfig> imageOptions, ILogger <PhotoService> logger) { _fileService = fileService; _photoRepository = photoRepository; _filePathHelper = filePathHelper; _mapper = mapper; _imageConfig = imageOptions.Value; _logger = logger; }
public static ImageLoader Initialize(ImageConfig imageConfig, bool isLogEnabled = false) { if (imageConfig == null) { throw new ArgumentException("Can not initialize ImageLoader with empty configuration"); } if (ImageLoader.Instance._ImageConfig != null) { return ImageLoader.Instance; } IsLogEnabled = isLogEnabled; ImageLoader.Instance._ImageConfig = imageConfig; return ImageLoader.Instance; }
public void SetUp() { var path = TestContext.CurrentContext.TestDirectory; textPath = Path.Combine(path, "Resources", "text.txt"); imagePath = Path.Combine(path, "Resources", "test.png"); expectedImagePath = Path.Combine(path, "Resources", "expected.png"); tagsCloudCreator = container.GetService <TagsCloudCreator>(); wordsConfig = container.GetService <WordConfig>(); ConfigureWordsConfig(textPath); imageConfig = container.GetService <ImageConfig>(); ConfigureImageConfig(imagePath); }
private ImageConfig GetImageConfig() { ImageConfig imageConfig; if (!string.IsNullOrEmpty(Input.ConfigJson)) { imageConfig = JsonConvert.DeserializeObject <ImageConfig>(Input.ConfigJson); } else { imageConfig = new ImageConfig { MaxHeigth = 600, MaxWidth = 800 }; } return(imageConfig); }
private void AddImageConfigToFileSystem(MockFileSystem fileSystem, string name, string tag = "1.0") { var directory = $"{ImageSourceManager.InternalSourcesPath}/{name.ToLower()}"; var imageConfig = new ImageConfig { Name = name, Versions = new[] { new ImageVersion { Tag = tag } } }; fileSystem.AddFile($"{directory}/ImageConfig.json", JsonHelper.Serialise(imageConfig)); fileSystem.AddFile($"{directory}/Dockerfile", "NOT even a real Dockerfile"); }
private MockFileSystem CreateFileSystem() { var configOne = new ImageConfig { Name = "Steve", Versions = new[] { new ImageVersion { Tag = "1.0" } } }; return(new MockFileSystem(new Dictionary <string, MockFileData> { [$"{ImageSourceManager.InternalSourcesPath}/testing/ImageConfig.json"] = new MockFileData(JsonHelper.Serialise(configOne)), [$"{ImageSourceManager.InternalSourcesPath}/testing/Dockerfile"] = new MockFileData("LABEL this is a real Dockerfile") })); }
/// <summary> /// 注册其他的Image Loader,便于不同策略使用 /// </summary> /// <param name="key"></param> /// <param name="imageLoader"></param> public static void Register(string key, ImageConfig imageConfig) { Collection.Add(key, new ImageLoader(imageConfig)); }
public ImageSaverFactory(ImageConfig imageConfig) { this.imageConfig = imageConfig; }
public ImageService(ImageConfig imageConfig, ILogger <ImageService> logger) { _imageConfig = imageConfig; _logger = logger; }
public Config() { this.LayerOpacity = 0.5; this.BackgroundImage = new ImageConfig(); }
async Task <TestResponse> CompileInNewContainer(ImageConfig imageConfig, TestRequest request) { try { DockerClient client = new DockerClientConfiguration().CreateClient(); var createRes = await client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = imageConfig.Name, ExposedPorts = new Dictionary <string, EmptyStruct> { { "80/tcp", default(EmptyStruct) } }, HostConfig = new HostConfig { PublishAllPorts = true }, Env = new List <string> { "db_connection=" + _config.DatabaseInfo.GetConnectionStringFrom(null) } }).ConfigureAwait(false); var id = createRes.ID; //await Task.Delay(3000); var startRes = await client.Containers.StartContainerAsync(id, null).ConfigureAwait(false); if (startRes) { var inspectRes = await client.Containers.InspectContainerAsync(id).ConfigureAwait(false); if (inspectRes.State.Running) { var port = inspectRes.NetworkSettings.Ports["80/tcp"][0].HostPort; var serviceName = inspectRes.Name; var result = await CompilationRequest(port, imageConfig.TestActionLink, request); await client.Containers.KillContainerAsync(id, new ContainerKillParameters()).ConfigureAwait(false); await client.Containers.RemoveContainerAsync(id, new ContainerRemoveParameters()).ConfigureAwait(false); return(result); } } return(new TestResponse { OK = false, Message = "Couldn't start new compiler container!", Result = ResultCode.IE, TestId = request.TestId, }); } catch (Exception e) { return(new TestResponse { OK = false, Message = "Error occured: " + e.Message + (e.InnerException is null ? "" : " Inner: " + e.InnerException.Message), Result = ResultCode.IE, TestId = request.TestId, });
public FilePathHelper(IOptions <ImageConfig> imageOptions) { _imageConfig = imageOptions.Value; }
public bool Open(XmlNode argNode, string argBasePath, bool argIsRemote) { Debug.Assert(null != argNode && !string.IsNullOrEmpty(argBasePath)); try { m_basePath = argBasePath; m_isRemote = argIsRemote; Log.ResourceManager.LogDebugFormat("Prepare for opening a resource service [{0}]", m_language); if (!argIsRemote) { XmlAttribute cfgAttri = null; //Load image config XmlNode imgNode = argNode.SelectSingleNode(s_ImageNode); if (null != imgNode && imgNode.NodeType == XmlNodeType.Element) { string imgCfg = null; cfgAttri = imgNode.Attributes[s_cfgAttri]; if (null != cfgAttri && !string.IsNullOrEmpty(cfgAttri.Value)) { imgCfg = string.Format(@"{0}\{1}\{2}", argBasePath, imgNode.Name, cfgAttri.Value); ImageConfig.Load(imgCfg); } } //Load voice config XmlNode voiceNode = argNode.SelectSingleNode(s_VoiceNode); if (null != voiceNode && voiceNode.NodeType == XmlNodeType.Element) { string voiceCfg = null; cfgAttri = voiceNode.Attributes[s_cfgAttri]; if (null != cfgAttri && !string.IsNullOrEmpty(cfgAttri.Value)) { voiceCfg = string.Format(@"{0}\{1}\{2}", argBasePath, voiceNode.Name, cfgAttri.Value); VoiceConfig.Load(voiceCfg); } } //Load video config XmlNode videoNode = argNode.SelectSingleNode(s_VideoNode); if (null != videoNode && videoNode.NodeType == XmlNodeType.Element) { string videoCfg = null; cfgAttri = videoNode.Attributes[s_cfgAttri]; if (null != cfgAttri && !string.IsNullOrEmpty(cfgAttri.Value)) { videoCfg = string.Format(@"{0}\{1}\{2}", argBasePath, videoNode.Name, cfgAttri.Value); VideoConfig.Load(videoCfg); } } //load text content string textNodePath = string.Format("{0}/{1}", s_textNode, s_categoryNode); XmlNodeList listNodes = argNode.SelectNodes(textNodePath); XmlAttribute nameAttri = null; string textFilePath = null; XmlDocument textDoc = null; foreach (XmlNode node in listNodes) { nameAttri = node.Attributes[s_nameAttri]; if (null == nameAttri || string.IsNullOrEmpty(nameAttri.Value)) { continue; } try { textFilePath = string.Format(@"{0}\{1}\{2}\{3}.xml", argBasePath, s_textNode, m_language, nameAttri.Value); if (!File.Exists(textFilePath)) { Log.ResourceManager.LogWarnFormat("The file[{0}] isn't exist", textFilePath); continue; } textDoc = new XmlDocument(); textDoc.Load(textFilePath); TextCategories.Add(nameAttri.Value, textDoc); } catch (System.Exception ex) { Log.ResourceManager.LogWarn(string.Format("Failed to open text file[{0}]", textFilePath), ex); } } } } catch (System.Exception ex) { m_imageConfig = null; m_voiceConfig = null; m_videoConfig = null; if (null != m_dicTextCategories) { m_dicTextCategories.Clear(); m_dicTextCategories = null; } Log.ResourceManager.LogError("Failed to open a resource service", ex); return(false); } return(true); }
public static ResizeGdiResult ResizeGdi(Stream stream, ImageConfig size, ImageFormat imageFormat) { size ??= new ImageConfig { Heigth = 400, Width = 800 }; var resizeGdiResult = new ResizeGdiResult(); var image = Image.FromStream(stream); var width = image.Width; var height = image.Height; const int sourceX = 0; const int sourceY = 0; const int destX = 0; const int destY = 0; var destW = 0; var destH = 0; if (size.MaxHeigth.HasValue && size.MaxWidth.HasValue) { float percent = 0, percentWidth = 0, percentHeight = 0; percentWidth = (size.MaxWidth.Value / (float)width); percentHeight = (size.MaxHeigth.Value / (float)height); if (percentWidth > 1) { percentWidth = 1; } if (percentHeight > 1) { percentHeight = 1; } if (percentHeight < percentWidth) { percent = percentHeight; } else { percent = percentWidth; } destW = (int)(width * percent); destH = (int)(height * percent); } else if (size.Width.HasValue && size.Heigth.HasValue) { destW = size.Width.Value; destH = size.Heigth.Value; } else { destW = width; destH = height; } var outputImageFormat = imageFormat; if (!string.IsNullOrEmpty(size.TypeMime)) { outputImageFormat = GetImageFormat(size.TypeMime); } var mStream = new MemoryStream(); resizeGdiResult.Stream = mStream; if (destW == 0 && destH == 0) { image.Save(mStream, outputImageFormat); resizeGdiResult.With = width; resizeGdiResult.Height = height; return(resizeGdiResult); } using (var bitmap = new Bitmap(destW, destH, PixelFormat.Format32bppRgb)) { using (var graphics = Graphics.FromImage(bitmap)) { graphics.InterpolationMode = InterpolationMode.Default; graphics.DrawImage(image, new Rectangle(destX, destY, destW, destH), new Rectangle(sourceX, sourceY, width, height), GraphicsUnit.Pixel); } bitmap.Save(mStream, outputImageFormat); } mStream.Position = 0; resizeGdiResult.With = destW; resizeGdiResult.Height = destH; return(resizeGdiResult); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddDbContext <MenuDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); // services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"), new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true })); // Add the processing server as IHostedService services.AddHangfireServer(); //конфигурируем encoders(HtmlEncoder и тд) что бы они не ломали русские буквы services.Configure <WebEncoderOptions>(options => { options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); }); services.AddSignalR(); var menuAppInitializer = new MenuAppInitializer(); var wordsCardsAppInitializer = new WordsCardsAppInitializer(); var planitPokerInitializer = new PlanitPokerInitializer(); //repositories services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IImageRepository, ImageRepository>(); menuAppInitializer.RepositoriesInitialize(services); wordsCardsAppInitializer.RepositoriesInitialize(services); planitPokerInitializer.RepositoriesInitialize(services); //services.AddScoped<IPlanitPokerRepository, PlanitPokerRepository>(); //healpers services.AddScoped <IApiHelper, ApiHelper>(); //services.AddScoped<IReturnContainer, ReturnContainer>(); //var returnContainer = new ReturnContainer(); //InitReturnTypeContainer(returnContainer); services.AddSingleton <MultiThreadHelper, MultiThreadHelper>(); services.AddSingleton <IStringValidator, StringValidator>(); //services services.AddSingleton <IFileService, PhysicalFileService>(); services.AddScoped <IErrorService, ErrorService>(); services.AddScoped <IImageService, ImageService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IWorker, Worker>(); menuAppInitializer.ServicesInitialize(services); wordsCardsAppInitializer.ServicesInitialize(services); planitPokerInitializer.ServicesInitialize(services); //cache //services.AddStackExchangeRedisCache(options => //{ // options.Configuration = Configuration.GetValue<string>("CacheSettings:Redis:ConnectionString"); //}); var imageConfig = new ImageConfig(); Configuration.GetSection("ImageSettings").Bind(imageConfig); if (imageConfig.TypeOfStorage == "blob") { services.AddSingleton <IImageDataStorage, ImageDataBlobStorage>(x => new ImageDataBlobStorage(imageConfig)); } else { services.AddSingleton <IImageDataStorage, ImageDataIOStorage>(); } //& var errorContainer = new ErrorContainer(); planitPokerInitializer.ErrorContainerInitialize(errorContainer); services.AddSingleton <IErrorContainer, ErrorContainer>(x => errorContainer); //auth services.InjectJwtAuth(Configuration); services.AddScoped <IAuthService, AuthService>(); services.Configure <ApiBehaviorOptions>(options => { //отключаем автоответ если modelstate not valide, для формирования ответа ошибок в общем-кастомном формате options.SuppressModelStateInvalidFilter = true; }); }
public CircularCloudLayouterCreator(ImageConfig imageConfig) { this.imageConfig = imageConfig; }
public ImageBuilder(ImageConfig imageConfig, WordConfig wordsConfig) { this.imageConfig = imageConfig; this.wordsConfig = wordsConfig; }
public UploadImageModel(IOptionsSnapshot <ImageConfig> imageConfig) { _imageConfig = imageConfig.Value; }