Пример #1
0
        static void Main(string[] args)
        {
            try
            {
                var configuration = ConfigurationLoader.Load();
                var generator     = new ContentGenerator(configuration, Console.Out);
                generator.StartAsync().GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error!");
                Console.WriteLine("Message:");
                Console.WriteLine($"\t{ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine("InnerMessage:");
                    Console.WriteLine($"\t{ex.InnerException.Message}");

                    if (ex.InnerException.InnerException != null)
                    {
                        Console.WriteLine("InnerMessage2:");
                        Console.WriteLine($"\t{ex.InnerException.InnerException.Message}");
                    }
                }
            }

            Console.WriteLine("Process completed");
            Console.ReadLine();
        }
Пример #2
0
        private void DoAddBackground(string pdfFile, string tmpFile,  ConversionProfile profile)
        {
            _logger.Debug("Start adding background.");

            var copyOptions = CopyOption.CopyLinks | CopyOption.CopyAnnotations | CopyOption.CopyFormFields | CopyOption.CopyOutlines | CopyOption.CopyLogicalStructure | CopyOption.CopyNamedDestinations | CopyOption.FlattenAnnotations | CopyOption.FlattenFormFields | CopyOption.FlattenSignatureAppearances | CopyOption.OptimizeResources;

            var conformance = DeterminePdfVersionConformance(profile);

            using (Stream backgroundStream = new FileStream(profile.BackgroundPage.File, FileMode.Open, FileAccess.Read))
            using (var backgroundDoc = Document.Open(backgroundStream, null))
            using (Stream docStream = new FileStream(tmpFile, FileMode.Open, FileAccess.Read))
            using (var doc = Document.Open(docStream, ""))
            using (Stream outStream = new FileStream(pdfFile, FileMode.Create, FileAccess.ReadWrite))
            using (var outDoc = Document.Create(outStream, conformance, new EncryptionParams()))
            {
                CopyMetadata(outDoc, doc.Metadata);

                var coverPages = GetNumberOfCoverPages(profile.CoverPage);
                var attachmentPages = GetNumberOfAttachmentPages(profile.AttachmentPage);

                var backgroundPageMapper = new BackgroundPageMapper(backgroundDoc.Pages.Count, profile.BackgroundPage, coverPages, attachmentPages);

                for (int i=0; i< doc.Pages.Count; i++)
                {
                    var page = doc.Pages[i];
                    var pageCopy = outDoc.CopyPage(page, copyOptions);

                    int backgroundPageNumber;
                    if (backgroundPageMapper.GetBackgroundPageNumber(i + 1, doc.Pages.Count, out backgroundPageNumber))
                    {
                        using (var gen = new ContentGenerator(pageCopy.Content, true))
                        {
                            var backgroundPage = backgroundDoc.Pages[backgroundPageNumber - 1];
                            var background = outDoc.CopyPageAsForm(backgroundPage, copyOptions);
                            var scaleWidth = pageCopy.Size.Width / backgroundPage.Size.Width;
                            var scaleHeight = pageCopy.Size.Height / backgroundPage.Size.Height;
                            var scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;

                            var backgroundHeight = backgroundPage.Size.Height*scale;
                            var backgroundWidth = backgroundPage.Size.Width*scale;

                            var offsetHeight = (pageCopy.Size.Height - backgroundHeight)/2;
                            var offsetWidth = (pageCopy.Size.Width - backgroundWidth)/2;

                            var backgroundRect = new Rectangle()
                            {
                                Top = backgroundHeight + offsetHeight,
                                Bottom = offsetHeight,
                                Right = backgroundWidth + offsetWidth,
                                Left = offsetWidth,
                            };
                            
                            gen.PaintForm(background, backgroundRect);
                        }
                    }

                    outDoc.Pages.Add(pageCopy);
                }
            }
        }
Пример #3
0
 protected override void BulkInsert()
 {
     recs = recs ?? ContentGenerator.CreateListings(o.Sample);
     using (var bulkInsert = store.BulkInsert())
     {
         recs.ForEach(r => bulkInsert.Store(r));
     }
 }
Пример #4
0
        /// <summary>
        /// This method is used to execute the plug-in during the build process
        /// </summary>
        /// <param name="executionContext">The current execution context</param>
        public void Execute(ExecutionContext executionContext)
        {
            _buildProcess.ReportProgress(Resources.PlugInBuildProgress);
            var messageReporter = new MessageReporter(_buildProcess);
            var configuration   = new Configuration
            {
                OutputFolderPath     = _buildProcess.WorkingFolder,
                DocumentRootSchemas  = _configuration.DocumentRootSchemas,
                DocumentRootElements = _configuration.DocumentRootElements,
                DocumentConstraints  = _configuration.DocumentConstraints,
                DocumentSchemas      = _configuration.DocumentSchemas,
                DocumentSyntax       = _configuration.DocumentSyntax,
                UseTypeDocumentationForUndocumentedAttributes = _configuration.UseTypeDocumentationForUndocumentedAttributes,
                UseTypeDocumentationForUndocumentedElements   = _configuration.UseTypeDocumentationForUndocumentedElements,
                SchemaSetContainer          = _configuration.SchemaSetContainer,
                SchemaSetTitle              = _configuration.SchemaSetTitle,
                NamespaceContainer          = _configuration.NamespaceContainer,
                IncludeLinkUriInKeywordK    = _configuration.IncludeLinkUriInKeywordK,
                AnnotationTransformFileName = _configuration.AnnotationTransformFilePath.ExpandedPath,
                SchemaFileNames             = ExpandFiles(_configuration.SchemaFilePaths),
                SchemaDependencyFileNames   = ExpandFiles(_configuration.SchemaDependencyFilePaths),
                DocFileNames = ExpandFiles(_configuration.DocFilePaths)
            };

            var contentGenerator = new ContentGenerator(messageReporter, configuration);

            contentGenerator.Generate();

            var contentFileProfider = new ContentFileProvider(_buildProcess.CurrentProject);

            var contentLayoutFile = contentFileProfider.Add(BuildAction.ContentLayout, contentGenerator.ContentFile);

            contentLayoutFile.SortOrder = _configuration.SortOrder;
            _buildProcess.ConceptualContent.ContentLayoutFiles.Add(contentLayoutFile);

            foreach (var topicFileName in contentGenerator.TopicFiles)
            {
                contentFileProfider.Add(BuildAction.None, topicFileName);
            }

            _buildProcess.ConceptualContent.Topics.Add(new TopicCollection(contentLayoutFile));

            foreach (var mediaItem in contentGenerator.MediaItems)
            {
                var imageFilePath  = new FilePath(mediaItem.FileName, _buildProcess.CurrentProject);
                var imageReference = new ImageReference(imageFilePath, mediaItem.ArtItem.Id)
                {
                    AlternateText = mediaItem.ArtItem.AlternateText
                };
                _buildProcess.ConceptualContent.ImageFiles.Add(imageReference);
            }

            var componentConfig = GetComponentConfiguration(contentGenerator.IndexFile);

            _buildProcess.CurrentProject.ComponentConfigurations.Add(GetComponentId(), true, componentConfig);
        }
Пример #5
0
 /// <summary>
 /// Performs an HTTP POST Request
 /// </summary>
 /// <typeparam name="TRequestBody">Request body's type</typeparam>
 /// <param name="obj">Request body</param>
 /// <returns>Pure response message</returns>
 public async Task <HttpResponseMessage> PostRespnseAsync <TRequestBody>(TRequestBody obj)
 {
     using (HttpClient client = new HttpClient())
     {
         foreach (UnicornHeader header in Config.Headers)
         {
             client.DefaultRequestHeaders.Add(header.Name, header.Value);
         }
         return(await client.PostAsync(Config.Url, ContentGenerator.Generate(obj)));
     }
 }
        public void HappyPath_EveryThinkWorks()
        {
            var engine = fixture.Freeze <Mock <IEngine> >();

            sut = fixture.Create <ContentGenerator>();
            sut.Run();

            engine.Verify(e => e.LoadData(), Times.Once);
            engine.Verify(e => e.GenerateLinks(), Times.Once);
            engine.Verify(e => e.GenerateDescription(), Times.Once);
            engine.Verify(e => e.GenerateWeekSummary(), Times.Once);
        }
Пример #7
0
 public void Load()
 {
     Modifier.LoadModifiers();
     //Engine.Game = Deserialize();
     LoadTypes();
     LoadNames();
     LoadIdeologies();
     ContentGenerator.Run();
     LoadParties();
     LoadPlayers();
     LoadPersons();
 }
Пример #8
0
 /// <summary>
 /// Performs an HTTP PUT Request
 /// </summary>
 /// <typeparam name="T">Model's type</typeparam>
 /// <param name="obj">Model</param>
 /// <param name="key">Identifier</param>
 /// <returns>Pure response message</returns>
 public async Task <HttpResponseMessage> PutResponseAsync <T>(T obj, object key)
 {
     using (HttpClient client = new HttpClient())
     {
         foreach (UnicornHeader header in Config.Headers)
         {
             client.DefaultRequestHeaders.Add(header.Name, header.Value);
         }
         return(await client
                .PutAsync(Config.Url + "/" + key,
                          ContentGenerator.Generate(obj)));
     }
 }
 private float ShowProp(
     MaterialEditor materialEditor, MaterialProperty prop,
     ContentGenerator contentGenerator = null)
 {
     if (contentGenerator != null)
     {
         materialEditor.ShaderProperty(prop, contentGenerator(prop));
     }
     else
     {
         materialEditor.ShaderProperty(prop, prop.displayName);
     }
     return(prop.floatValue);
 }
Пример #10
0
        static int Main(string[] args)
        {
            ParsedArguments parsedArgs = null;

            try
            {
                parsedArgs = ArgumentParser.Parse(args);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("An error occured when trying to parse command line arguments: ");
                Console.Error.WriteLine(e.ToString());
                return(-1);
            }

            if (Path.GetFileName(parsedArgs.SDVContentRootDirectory) != "Content")
            {
                Console.Error.WriteLine($"\"{parsedArgs.SDVContentRootDirectory}\" doesn't look like a valid SDV Content Directory: ");
                Console.Error.WriteLine($"It doesn't point to a Content folder.");
                return(-1);
            }

            MappedDirectory mapping = DirectoryMapper.TryMapDirectories(parsedArgs.SDVContentRootDirectory, parsedArgs.ModRootDirectory, out IDictionary <string, string> errors);

            if (mapping == null)
            {
                Console.Error.WriteLine($"An error occured when trying to map the mod to the game's Content folder: ");
                foreach (KeyValuePair <string, string> errorinfo in errors)
                {
                    Console.Error.WriteLine($"{errorinfo.Key} is invalid because: ${errorinfo.Value}");
                }
                return(-1);
            }

            ContentPack p = new ContentPack(Path.Combine(Directory.GetCurrentDirectory(), "CP"));

            if (Directory.Exists(p.RootDirectory))
            {
                Directory.Delete(p.RootDirectory, true);
            }
            Directory.CreateDirectory(p.RootDirectory);
            Console.WriteLine(p.RootDirectory);

            p.GenerateManifest(parsedArgs);

            ContentGenerator.GenerateContent(p.RootDirectory, mapping);

            return(0);
        }
        public void DeleteThisWhenTheServiceIsRunning_generatePages()
        {
            var contentGenerator = new ContentGenerator();

            var filesystemRepository = new HtmlWriter(baseUrl);

            var documentParser = new DocumentParser();

            var siteGenerator = new SiteGenerator(
                contentGenerator,
                filesystemRepository,
                documentParser,
                new MarkDownMutator(filesystemRepository, contentGenerator));

            siteGenerator.GenerateSite(new ReadWritePaths(readPath, writePath), baseUrl, editBaseUrl);
        }
Пример #12
0
        /// <summary>
        /// Shows how to add data to an existing series.
        /// Data is structured as CSV where each line represent one sample.
        /// Each sample have a timestamp and a value, where timestamp is in nanoseconds since EPOCH.
        /// Value can be number or text data.
        /// </summary>
        private async Task AddDataToTimeSeries(string timeSeriesId)
        {
            Guid fileId;

            await using (var timeSeriesContent = ContentGenerator.GenerateRandomSeries(DateTimeOffset.UtcNow, 1, 12))
            {
                fileId = await _file.Upload(timeSeriesContent);
            }

            Console.WriteLine($"{fileId} uploaded. Waiting for processing ready...");

            await _file.WaitForFileProcessed(fileId);

            Console.WriteLine($"Appending {fileId} to {timeSeriesId}...");
            await _timeSeries.AddData(fileId, timeSeriesId);
        }
Пример #13
0
        public void GenerateSite(Configuration configuration, FilesystemRepository filesystemRepository)
        {
            var contentGenerator     = new ContentGenerator();
            var extractor            = new TagsExtractor(filesystemRepository);
            var htmlTransformer      = new MarkdownToHtml();
            var expandTagsToMarkdown = new ExpandTagsToMarkdown(filesystemRepository);
            var readMdAndWriteHtml   = new ReadMdAndWriteHtml(filesystemRepository, contentGenerator, htmlTransformer, expandTagsToMarkdown);

            var siteGenerator = new SiteGenerator(
                contentGenerator,
                filesystemRepository,
                extractor,
                readMdAndWriteHtml,
                htmlTransformer);

            siteGenerator.Execute(configuration, baseUrl, editBaseUrl);
        }
Пример #14
0
 void Start()
 {
     ContentManager = GetComponent <ContentManager>();
     TerrainInfo    = new TerrainInfo(GetComponent <Terrain>());
     if (UseCustomTerrainSizeDefinitions)
     {
         TerrainInfo.TerrainWidth  = TerrainWidth;
         TerrainInfo.TerrainHeight = TerrainHeight;
         TerrainInfo.TerrainDepth  = TerrainDepth;
     }
     // Figure out how to do this better, for now info has "manager" info (so we can use it elsewhere)
     TerrainInfo.ContentManager = ContentManager;
     ContentGenerator           = GetComponent <ContentGenerator>();
     // Initialize manager, need to handle path for different platforms (OSX, Windows)
     SerializationManager.InitializeManager();
     // You can deserialize here and take the first NoiseParameter from the list if you dont want the default values
     InitializeTerrain();
 }
Пример #15
0
        internal async Task CreateEnumContentAsync(PhysicalFile physicalFile, ContentGenerator generator)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var language = physicalFile.AsProjectItem().ContainingProject.CodeModel.Language;

            var codePath = Path.ChangeExtension(physicalFile.FullPath,
                                                CodeModelLanguageConstants.vsCMLanguageVB == language
                    ? ".dv.vb"
                    : ".dv.cs"
                                                );

            var codeProvider = CodeModelLanguageConstants.vsCMLanguageVB == language
                ? CodeDomProvider.CreateProvider("VisualBasic")
                : CodeDomProvider.CreateProvider("C#");

            var fileNamespace = GenerateNamespace(physicalFile);

            var enumContent = generator.GetEnumCode(codeProvider, fileNamespace);

            if (string.IsNullOrWhiteSpace(enumContent))
            {
                var vsFile = await PhysicalFile.FromFileAsync(codePath);

                if (vsFile != null)
                {
                    await vsFile.TryRemoveAsync();
                }

                return;
            }

            var file = await WriteFileAsync(enumContent, codePath, physicalFile.ContainingProject);

            if (file == null)
            {
                return;
            }

            await file.SetAsChildItemAsync(physicalFile);

            await physicalFile.ContainingProject.SaveAsync();
        }
Пример #16
0
    void Start()
    {
        contentGenerator = Component.FindObjectOfType <ContentGenerator> ();

        _currentProject = new Project(filename);

        Dictionary <BuildingProperty, MetricMapping> mappings = new Dictionary <BuildingProperty, MetricMapping>();

        List <string> metricNames = currentProject.metricNames;

        mappings.Add(BuildingProperty.Height, new MetricMapping(metricNames[7], BuildingProperty.Height, new ValueConverter(0, 1, 0, 1f, false), null));
        mappings.Add(BuildingProperty.Width, new MetricMapping(metricNames[10], BuildingProperty.Width, new ValueConverter(0, 1, 0, 10, false), null));

        ColorGradient col = new ColorGradient(new ColorGradient.ColorPoint(0, new Vector3(1, 0, 0)), new ColorGradient.ColorPoint(1, new Vector3(0, 1, 0)));

        mappings.Add(BuildingProperty.Red, new MetricMapping(metricNames[4], BuildingProperty.Red, new ValueConverter(0, 100, 0, 1, true), col));
        mappings.Add(BuildingProperty.Green, new MetricMapping(metricNames[4], BuildingProperty.Green, new ValueConverter(0, 100, 0, 1, true), col));
        mappings.Add(BuildingProperty.Blue, new MetricMapping(metricNames[4], BuildingProperty.Blue, new ValueConverter(0, 100, 0, 1, true), col));

        OnMappingChanged(mappings);
    }
Пример #17
0
        public async Task <Response <HospitalAppointmentModel> > CreateForNonRegisteredUserAsync(HospitalAppointmentModel modelToCreate)
        {
            var response = InitErrorResponse();

            if (Validate(modelToCreate))
            {
                int nextNumber = await _unitOfWork.HospitalAppointmentRepository.GetMaxQueueNumberAsync(modelToCreate.HospitalId, modelToCreate.MedicalStaffId, modelToCreate.AppointmentDate);

                DateTime estimateTime = await GetEstimateTimeAsync(modelToCreate, nextNumber);

                var userId = GetUserId();
                var en     = GetEntityFromModel(modelToCreate);
                en.UserId            = null;
                en.CreatedById       = en.UpdatedById = userId;
                en.CreatedDate       = en.UpdatedDate = DateTime.UtcNow;
                en.AppointmentStatus = AppointmentStatus.Pending;
                en.QueueNumber       = nextNumber;
                en.AppointmentDate   = estimateTime;
                _unitOfWork.HospitalAppointmentRepository.Add(this.RemoveChildEntity(en));
                _unitOfWork.Commit();

                var current = await _unitOfWork.HospitalAppointmentRepository.GetHospitalAppointmentDetailAsync(en.Id);

                var content = ContentGenerator.BookingDoctor(GetModelFromEntity <HospitalAppointment, HospitalAppointmentModel>(current));

                ISender sender = _senderFact.Create(SenderFactory.SMS);
                var     result = await sender.SendAsync(en.PhoneNumber, content.Title, content.Body);

                response      = InitSuccessResponse(MessageConstant.Create);
                response.Item = GetModelFromEntity(en);
            }
            else
            {
                response.Message = MessageConstant.ValidationError;
            }


            return(response);
        }
Пример #18
0
        internal async Task CreateSqlContentAsync(PhysicalFile physicalFile, ContentGenerator generator)
        {
            var sqlPath = Path.ChangeExtension(physicalFile.FullPath, ".dv.sql");

            var solution = physicalFile.GetSolution();

            var relativePath = physicalFile.FullPath.Replace(Path.GetDirectoryName(solution.FullPath), string.Empty);

            var sqlContent = generator.GetSqlCode(relativePath);

            var file = await WriteFileAsync(sqlContent, sqlPath, physicalFile.ContainingProject);

            if (file == null)
            {
                return;
            }

            await file.SetAsChildItemAsync(physicalFile);

            if (!string.IsNullOrWhiteSpace(generator.CopySql))
            {
                var targetItem = FindSolutionItem(solution, generator.CopySql.Split('\\').ToArray());

                if (targetItem is PhysicalFolder folder)
                {
                    var copyPath = Path.Combine(folder.FullPath, Path.GetFileName(sqlPath));

                    var copyFile = await WriteFileAsync(sqlContent, copyPath, folder.ContainingProject);

                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    copyFile.SetProperty("BuildAction", "None");
                }
            }

            await physicalFile.ContainingProject.SaveAsync();
        }
Пример #19
0
 void Start()
 {
     contentGenerator = GameObject.Find("ContentGenerator").GetComponent <ContentGenerator>();
 }
Пример #20
0
 public Task <IPageContent <TResult> > GetPageContent() => ContentGenerator.GeneratePageContent();
Пример #21
0
 private void GenContent()
 {
     Logg($"Generating {o.Sample:N0} random records, please wait... ");
     recs = ContentGenerator.CreateListings(o.Sample);
     Ok();
 }
Пример #22
0
        // asyncronous method for sending appointment
        async Task <IList <Notification> > SendPendingAppointment(HospitalAppointment currentAppointment)
        {
            //get all pending appointment related to the current appointment
            var currentDate        = DateTime.UtcNow;
            var pendingAppointment = await _unitOfWork.HospitalAppointmentRepository
                                     .FindByAsync(x => x.AppointmentStatus == AppointmentStatus.Pending &&
                                                  x.HospitalId == currentAppointment.HospitalId && x.MedicalStaffId == currentAppointment.MedicalStaffId &&
                                                  x.QueueNumber > currentAppointment.QueueNumber &&
                                                  x.AppointmentDate >= currentDate.StartOfDay() && x.AppointmentDate <= currentDate.EndOfDay());

            //define setting
            var setting = await _unitOfWork.HospitalMedicalStaffRepository.GetSingleAsync(x => x.HospitalId == currentAppointment.HospitalId &&
                                                                                          x.MedicalStaffId == currentAppointment.MedicalStaffId, x => x.OperatingHours);

            //get detail staff and hospital
            var medicalStaff = await _unitOfWork.MedicalStaffRepository.GetStaffWithHospitalDetailAsync(currentAppointment.MedicalStaffId, false);

            var hospital = await _unitOfWork.HospitalRepository.GetSingleAsync(currentAppointment.HospitalId);

            var notifications = new List <Notification>();

            // Convert PendingAppointment to PendingList Model
            // to make entities untracked, because if not
            // entities will doing arbitary insert
            var pendingList = GetModelFromEntity(pendingAppointment.ToList());

            foreach (var appt in pendingList)
            {
                // just send pending appointment FCM
                // to registered user
                var item = GetEntityFromModel(appt);
                if (item.UserId != null)
                {
                    //update estime time
                    item.AppointmentDate    = GetNextPatientEstimateTime(setting.EstimateTimeForPatient ?? 15, currentDate, item.QueueNumber);
                    item.Hospital           = hospital;
                    item.MedicalStaff       = medicalStaff;
                    item.CurrentQueueNumber = currentAppointment.QueueNumber;

                    var option = new FCMOption
                    {
                        TargetScreen = NotificationModel.APPOINTMENT_QUEUE_SCREEN,
                        JsonData     = JsonConvert.SerializeObject(item, new JsonSerializerSettings()
                        {
                            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                            ReferenceLoopHandling      = ReferenceLoopHandling.Ignore,
                            Formatting       = Formatting.None,
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        }),
                        Priority = FCMOption.PriorityHigh
                    };


                    //send notification for all user devices
                    var content       = ContentGenerator.CurrentAppointment(GetModelFromEntity <HospitalAppointment, HospitalAppointmentModel>(item));
                    var userDeviceIds = await _unitOfWork.FirebaseUserMapRepository.FindByAsync(x => x.UserId == item.UserId);


                    ISender sender = _senderFact.Create(SenderFactory.FCM);
                    await sender.SendMultipleAsync(userDeviceIds.Select(x => x.DeviceToken).ToList(),
                                                   content.Title, content.Body, option);

                    notifications.Add(new Notification
                    {
                        Id           = 0,
                        TargetScreen = option.TargetScreen,
                        JsonData     = option.JsonData,
                        Title        = content.Title,
                        Message      = content.Body,
                        ObjectId     = item.Id,
                        UserId       = item.UserId ?? 0,
                        IsRead       = false,
                        CreatedById  = GetUserId(),
                        UpdatedById  = GetUserId(),
                        CreatedDate  = DateTime.UtcNow,
                        UpdatedDate  = DateTime.UtcNow
                    });
                }
            }

            return(notifications);
        }