public override async Task RunExampleAsync() { PreviewSms previewClient = new PreviewSms(BASIC_AUTH_CONFIGURATION); PreviewRequest request = new PreviewRequest() { Text = "Artık Ulusal Dil Tanımlayıcısı ile Türkçe karakterli smslerinizi rahatlıkla iletebilirsiniz.", LanguageCode = "TR", Transliteration = "TURKISH" }; PreviewResponse response = await previewClient.ExecuteAsync(request); Console.WriteLine("Original text: "); Console.WriteLine("\t" + response.OriginalText); Console.WriteLine("Previews:"); foreach (Preview preview in response.Previews) { Console.WriteLine("\t------------------------------------------------"); Console.WriteLine("\tText preview: " + preview.TextPreview); Console.WriteLine("\tNumber of messages: " + preview.MessageCount); Console.WriteLine("\tCharacters remaining: " + preview.CharactersRemaining); Console.WriteLine("\tConfiguration: " + JsonConvert.SerializeObject(preview.Configuration)); } Console.WriteLine("\t------------------------------------------------"); }
public void PreviewRequestSendBKK() { //var previewRequest = new PreviewRequest(); //Debug.Log("Host Type: " + previewRequest.HostId.Type + " " + "HostId: " + previewRequest.HostId.Value); //string jsonString = previewRequest.SerializePreviewRequest(previewRequest); //Debug.Log(jsonString); string jsonString = new PreviewRequest().SerializePreviewRequest(new PreviewRequest()); string url = ConfigDat.URL + "/preview_request"; //string url = ("https://flex13005-uat.compliance.flexnetoperations.eu/api/1.0/instances/YLR8N2Y7DQS1/preview_request"); Debug.Log(url); byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString); Debug.Log("Number of Byes in Request: " + System.Text.ASCIIEncoding.ASCII.GetByteCount(jsonString)); var unityWebRequest = new UnityWebRequest(url, "POST"); unityWebRequest.uploadHandler = new UploadHandlerRaw(bodyRaw); string getByte = Encoding.ASCII.GetString(bodyRaw); unityWebRequest.downloadHandler = new DownloadHandlerBuffer(); unityWebRequest.timeout = -1; unityWebRequest.SetRequestHeader("Content-Type", "application/json"); unityWebRequest.SetRequestHeader("Authorization", "Bearer " + ConfigDat.BearerToken); Debug.Log(ConfigDat.BearerToken); StartCoroutine(NetworkManager(unityWebRequest)); StopCoroutine(NetworkManager(unityWebRequest)); }
public async Task <ActionResult <PreviewResult> > Preview([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, MenuUtils.SitePermissions.MaterialMessage)) { return(Unauthorized()); } var(success, token, errorMessage) = await _wxManager.GetAccessTokenAsync(request.SiteId); if (success) { foreach (var wxName in ListUtils.GetStringList(request.WxNames, Constants.Newline)) { var mediaId = await _wxManager.PushMaterialAsync(token, MaterialType.Message, request.MaterialId); if (string.IsNullOrEmpty(mediaId)) { return(this.Error("操作失败,素材未能上传")); } await _wxManager.PreviewSendAsync(token, MaterialType.Message, mediaId, wxName); } } return(new PreviewResult { Success = success, ErrorMessage = errorMessage }); }
public async Task <ActionResult <StringResult> > Preview([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, Types.SitePermissions.Templates)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); if (site == null) { return(NotFound()); } var template = await _templateRepository.GetAsync(request.TemplateId); await _parseManager.InitAsync(site, request.ChannelId, request.ContentId, template); var parsedContent = await _parseManager.ParseTemplatePreviewAsync(request.Content); return(new StringResult { Value = parsedContent }); }
public static void Run() { var configuration = new Configuration(Common.MyAppSid, Common.MyAppKey); var apiInstance = new DocumentApi(configuration); try { var fileInfo = new FileInfo { FilePath = "WordProcessing/four-pages.docx" }; var options = new PreviewOptions() { FileInfo = fileInfo, OutputPath = "Output/preview-page", Pages = new List <int?> { 1, 3 }, Format = PreviewOptions.FormatEnum.Png }; var request = new PreviewRequest(options); var response = apiInstance.Preview(request); foreach (var document in response.Documents) { Console.WriteLine("Output file path: " + document.Path); } } catch (Exception e) { Console.WriteLine("Exception while calling api: " + e.Message); } }
public async Task <PreviewResponse> ExecuteAsync(PreviewRequest bodyObject) { using (var client = HttpClientProvider.GetHttpClient(configuration)) { string endpoint = path; string requestJson = JsonConvert.SerializeObject(bodyObject, Settings); HttpContent content = new StringContent(requestJson, Encoding.UTF8, "application/json"); var response = await client.PostAsync(endpoint, content); string contents = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <PreviewResponse>(contents, Settings)); } else { throw new InfobipApiException( response.StatusCode, JsonConvert.DeserializeObject <ApiErrorResponse>(contents, Settings) ); } } }
public async Task <ActionResult <BoolResult> > Submit([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, MenuUtils.SitePermissions.Templates)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); if (site == null) { return(NotFound()); } var template = await _templateRepository.GetAsync(request.TemplateId); await _pathManager.WriteContentToTemplateFileAsync(site, template, request.Content, _authManager.AdminId); await CreatePagesAsync(template); await _authManager.AddSiteLogAsync(site.Id, $"修改{template.TemplateType.GetDisplayName()}", $"模板名称:{template.TemplateName}"); return(new BoolResult { Value = true }); }
private async Task <Build> CheckDatasetValidAggregations(PreviewRequest previewRequest) { Build build = null; IEnumerable <string> aggregateParameters = SourceCodeHelpers.GetDatasetAggregateFunctionParameters(previewRequest.SourceCode); if (aggregateParameters.IsNullOrEmpty()) { return(build); } string cacheKey = $"{CacheKeys.DatasetRelationshipFieldsForSpecification}{previewRequest.SpecificationId}"; IEnumerable <DatasetSchemaRelationshipModel> datasetSchemaRelationshipModels = Enumerable.Empty <DatasetSchemaRelationshipModel>(); datasetSchemaRelationshipModels = await _cacheProvider.GetAsync <List <DatasetSchemaRelationshipModel> >(cacheKey); if (datasetSchemaRelationshipModels.IsNullOrEmpty()) { ApiResponse <IEnumerable <Common.ApiClient.DataSets.Models.DatasetSchemaRelationshipModel> > datasetsApiClientResponse = await _datasetsApiClientPolicy.ExecuteAsync(() => _datasetsApiClient.GetDatasetSchemaRelationshipModelsForSpecificationId(previewRequest.SpecificationId)); if (!datasetsApiClientResponse.StatusCode.IsSuccess()) { string message = $"No dataset schema relationship found for specificationId '{previewRequest.SpecificationId}'."; _logger.Error(message); throw new RetriableException(message); } if (datasetsApiClientResponse.Content != null) { datasetSchemaRelationshipModels = _mapper.Map <IEnumerable <DatasetSchemaRelationshipModel> >(datasetsApiClientResponse.Content); } await _cacheProvider.SetAsync <List <DatasetSchemaRelationshipModel> >(cacheKey, datasetSchemaRelationshipModels.ToList()); } HashSet <string> compilerErrors = new HashSet <string>(); IEnumerable <string> datasetAggregationFields = datasetSchemaRelationshipModels?.SelectMany(m => m.Fields?.Where(f => f.IsAggregable).Select(f => f.FullyQualifiedSourceName)); foreach (string aggregateParameter in aggregateParameters) { if (datasetAggregationFields.IsNullOrEmpty() || !datasetAggregationFields.Any(m => string.Equals(m.Trim(), aggregateParameter.Trim(), StringComparison.CurrentCultureIgnoreCase))) { compilerErrors.Add($"{aggregateParameter} is not an aggregable field"); } } if (compilerErrors.Any()) { build = new Build { CompilerMessages = compilerErrors.Select(m => new CompilerMessage { Message = m, Severity = Severity.Error }).ToList() }; } return(build); }
public async Task <ApiResponse <PreviewResponse> > PreviewCompile(PreviewRequest previewRequest) { Guard.ArgumentNotNull(previewRequest, nameof(previewRequest)); string url = $"{UrlRoot}/compile-preview"; return(await PostAsync <PreviewResponse, PreviewRequest>(url, previewRequest)); }
public static void PreviewRequestSend() { string uri = ConfigDat.URL + "/preview_request"; string jsonString = new PreviewRequest().SerializePreviewRequest(new PreviewRequest()); CommunicationsBK communicationsScript = (GameObject.FindGameObjectWithTag("AppPanel")).AddComponent <CommunicationsBK>(); communicationsScript.StartCoroutine(NetworkManager(uri, jsonString, (value) => { JSON = value; Debug.Log(JSON); })); //communicationsScript.StartCoroutine(NetworkManager(uri, jsonString, (value) => { JSON = value; })); }
/// <summary> /// Load a preview scene into the preview game. /// </summary> /// <param name="previewScene">The scene to load as preview</param> /// <param name="logger">The logger to use in case of errors.</param> /// <returns>The result of the scene load</returns> public async Task <ResultStatus> LoadPreviewScene(Scene previewScene, GraphicsCompositor graphicsCompositor, ILogger logger) { lock (requestLock) { previewRequest = new PreviewRequest(previewScene, graphicsCompositor, logger); } return(await previewRequest.RequestCompletion.Task); }
public void TestSimpleAddition() { // 1. Create code block node with value of 123. // 2. Create "Add" function node. // 3. Drag to connect from output of code block node to first input of add function node. // string commands = @" CreateCodeBlockNode|d:15381.0|d:15112.0|s:Your code goes here BeginNodeEdit|u:0x10000001|e:DesignScriptStudio.Graph.Core.NodePart,Text EndNodeEdit|u:0x10000001|s:3|b:True CreateCodeBlockNode|d:15339.0|d:15196.0|s:Your code goes here BeginNodeEdit|u:0x10000002|e:DesignScriptStudio.Graph.Core.NodePart,Text EndNodeEdit|u:0x10000002|s:5|b:True CreateFunctionNode|d:15497.0|d:15135.0|s:Special Nodes|s:+|s:double,double MouseDown|e:System.Windows.Input.MouseButton,Left|u:0x10000001|e:DesignScriptStudio.Graph.Core.NodePart,OutputSlot|i:0|e:System.Windows.Input.ModifierKeys,None BeginDrag|e:System.Windows.Input.MouseButton,Left|u:0x10000001|e:DesignScriptStudio.Graph.Core.NodePart,OutputSlot|i:0|e:System.Windows.Input.ModifierKeys,None|d:15343.0|d:15113.0 EndDrag|e:System.Windows.Input.MouseButton,Left|u:0x10000003|e:DesignScriptStudio.Graph.Core.NodePart,InputSlot|i:0|e:System.Windows.Input.ModifierKeys,None|d:15449.0|d:15129.0 MouseUp|e:System.Windows.Input.MouseButton,Left|u:0x10000003|e:DesignScriptStudio.Graph.Core.NodePart,InputSlot|i:0|e:System.Windows.Input.ModifierKeys,None MouseDown|e:System.Windows.Input.MouseButton,Left|u:0x10000002|e:DesignScriptStudio.Graph.Core.NodePart,OutputSlot|i:0|e:System.Windows.Input.ModifierKeys,None BeginDrag|e:System.Windows.Input.MouseButton,Left|u:0x10000002|e:DesignScriptStudio.Graph.Core.NodePart,OutputSlot|i:0|e:System.Windows.Input.ModifierKeys,None|d:15301.0|d:15199.0 EndDrag|e:System.Windows.Input.MouseButton,Left|u:0x10000003|e:DesignScriptStudio.Graph.Core.NodePart,InputSlot|i:1|e:System.Windows.Input.ModifierKeys,None|d:15436.0|d:15147.0 MouseUp|e:System.Windows.Input.MouseButton,Left|u:0x10000003|e:DesignScriptStudio.Graph.Core.NodePart,InputSlot|i:1|e:System.Windows.Input.ModifierKeys,None"; GraphController controller = new GraphController(null); // Indicate that the test case is interested in the values of // all these nodes whose IDs are represented by the input array. controller.RegisterPreviewRequest(new uint[] { 0x10000001, 0x10000002, 0x10000003 }); bool result = controller.RunCommands(commands); Assert.AreEqual(true, result); // WaitForPreviewRequestCompletion method internally creates a Task and // blocks on its 'Result' property until either it timed out, or all the // requested node values are computed. Assert.AreEqual(true, controller.WaitForPreviewRequestCompletion(100000)); // These calls are just to validate requested node values. PreviewRequest requestedData = controller.GetPreviewRequest(); ProtoCore.DSASM.StackValue value = requestedData.GetNodeValue(0x10000003); Assert.AreEqual(8, value.opdata); value = requestedData.GetNodeValue(0x10000001); Assert.AreEqual(3, value.opdata); value = requestedData.GetNodeValue(0x10000002); Assert.AreEqual(5, value.opdata); }
private async Task ProcessPreviewRequestsTask() { while (IsRunning) { await Script.NextFrame(); PreviewRequest request; lock (requestLock) { request = previewRequest; previewRequest = null; } if (request != null) { try { MicrothreadLocalDatabases.MountCommonDatabase(); Faulted = false; previewScene.Children.Clear(); if (SceneSystem.GraphicsCompositor != request.GraphicsCompositor) { SceneSystem.GraphicsCompositor?.Dispose(); SceneSystem.GraphicsCompositor = request.GraphicsCompositor; } if (request.Scene != null) { previewScene.Children.Add(request.Scene); } request.RequestCompletion.SetResult(ResultStatus.Successful); } catch (Exception e) { // end the thumbnail build task request.Logger.Error("An exception occurred while loading the preview scene.", e); request.RequestCompletion.SetResult(ResultStatus.Failed); } } if (previewScene.Children.Count != 0) { var handler = UpdateSceneCallback; if (handler != null) { var renderingMode = handler(); } } } }
IEnumerator PreviewRequestManager(Communications communicationsScript) { var jsonPreviewRequest = new PreviewRequest().SerializePreviewRequest(new PreviewRequest()); PreviewRequest.InjectSelectorsDictionary(jsonPreviewRequest); while (true) { Communications.SendPreviewRequest(communicationsScript, jsonPreviewRequest); yield return(new WaitForSeconds(5)); } }
public async Task <ActionResult <PreviewResult> > ChangeMode([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, MenuUtils.SitePermissions.Templates)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); if (site == null) { return(NotFound()); } var template = await _templateRepository.GetAsync(request.TemplateId); await _parseManager.InitAsync(EditMode.Preview, site, request.ChannelId, request.ContentId, template); var parsedContent = await _parseManager.ParseTemplateWithCodesHtmlAsync(request.Content); var baseUrl = string.Empty; if (template.TemplateType == TemplateType.IndexPageTemplate) { baseUrl = await _pathManager.GetIndexPageUrlAsync(site, false); } else if (template.TemplateType == TemplateType.ChannelTemplate) { var channel = await _channelRepository.GetAsync(request.ChannelId); baseUrl = await _pathManager.GetChannelUrlAsync(site, channel, false); } else if (template.TemplateType == TemplateType.ContentTemplate) { var content = await _contentRepository.GetAsync(site, request.ChannelId, request.ContentId); baseUrl = await _pathManager.GetContentUrlByIdAsync(site, content, false); } else if (template.TemplateType == TemplateType.FileTemplate) { baseUrl = await _pathManager.GetFileUrlAsync(site, template.Id, false); } return(new PreviewResult { BaseUrl = baseUrl, Html = parsedContent }); }
private async Task <Build> CheckDatasetValidAggregations(PreviewRequest previewRequest) { Build build = null; IEnumerable <string> aggregateParameters = SourceCodeHelpers.GetDatasetAggregateFunctionParameters(previewRequest.SourceCode); if (aggregateParameters.IsNullOrEmpty()) { return(build); } string cacheKey = $"{CacheKeys.DatasetRelationshipFieldsForSpecification}{previewRequest.SpecificationId}"; IEnumerable <DatasetSchemaRelationshipModel> datasetSchemaRelationshipModels = Enumerable.Empty <DatasetSchemaRelationshipModel>(); datasetSchemaRelationshipModels = await _cacheProvider.GetAsync <List <DatasetSchemaRelationshipModel> >(cacheKey); if (datasetSchemaRelationshipModels.IsNullOrEmpty()) { datasetSchemaRelationshipModels = await _datasetRepository.GetDatasetSchemaRelationshipModelsForSpecificationId(previewRequest.SpecificationId); await _cacheProvider.SetAsync <List <DatasetSchemaRelationshipModel> >(cacheKey, datasetSchemaRelationshipModels.ToList()); } HashSet <string> compilerErrors = new HashSet <string>(); IEnumerable <string> datasetAggregationFields = datasetSchemaRelationshipModels?.SelectMany(m => m.Fields?.Where(f => f.IsAggregable).Select(f => f.FullyQualifiedSourceName)); foreach (string aggregateParameter in aggregateParameters) { if (datasetAggregationFields.IsNullOrEmpty() || !datasetAggregationFields.Any(m => string.Equals(m.Trim(), aggregateParameter.Trim(), StringComparison.CurrentCultureIgnoreCase))) { compilerErrors.Add($"{aggregateParameter} is not an aggregable field"); } } if (compilerErrors.Any()) { build = new Build { CompilerMessages = compilerErrors.Select(m => new CompilerMessage { Message = m, Severity = Severity.Error }).ToList() }; } return(build); }
private Calculation GenerateTemporaryCalculationForPreview(PreviewRequest previewRequest) { return(new Calculation { Id = TempCalculationId, SpecificationId = previewRequest.SpecificationId, Current = new CalculationVersion { Name = !string.IsNullOrWhiteSpace(previewRequest.Name) ? previewRequest.Name : TempCalculationName, CalculationId = TempCalculationId, SourceCodeName = _typeIdentifierGenerator.GenerateIdentifier(!string.IsNullOrWhiteSpace(previewRequest.Name) ? previewRequest.Name : TempCalculationName), SourceCode = previewRequest.SourceCode, Namespace = CalculationNamespace.Additional, CalculationType = CalculationType.Additional, DataType = CalculationDataType.Decimal, ValueType = CalculationValueType.Number, WasTemplateCalculation = false, } }); }
public async Task <ActionResult <BoolResult> > Preview([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, Types.SitePermissions.WxSend)) { return(Unauthorized()); } var(success, token, errorMessage) = await _wxManager.GetAccessTokenAsync(request.SiteId); if (!success) { return(this.Error(errorMessage)); } if (request.MaterialType == MaterialType.Text) { foreach (var wxName in ListUtils.GetStringList(request.WxNames, Constants.Newline)) { await _wxManager.PreviewSendAsync(token, request.MaterialType, request.Text, wxName); } } else { var mediaId = await _wxManager.PushMaterialAsync(token, request.MaterialType, request.MaterialId); if (string.IsNullOrEmpty(mediaId)) { return(this.Error("操作失败,素材未能上传")); } foreach (var wxName in ListUtils.GetStringList(request.WxNames, Constants.Newline)) { await _wxManager.PreviewSendAsync(token, request.MaterialType, mediaId, wxName); } } return(new BoolResult { Value = true }); }
public static object Preview(PreviewRequest previewRequest) { try { return(Render(new DeninaSharpModel { Commands = previewRequest.Commands, Template = previewRequest.Template })); } catch (DeninaUmbracoException ex) { return(new { originalException = ex.InnerException, ex.CurrentCommandName, ex.CurrentCommandText, ex.LogData, ex.Message }); } }
public async Task <IActionResult> CompilePreview([FromRoute] string specificationId, [FromRoute] string calculationId , [FromBody] PreviewCompileRequestViewModel vm) { if (!ModelState.IsValid) { PreviewResponse errorResponse = new PreviewResponse(); foreach (var modelStateValue in ModelState.Values) { errorResponse.CompilerOutput = new Build { CompilerMessages = new List <CompilerMessage> { new CompilerMessage { Message = modelStateValue.Errors[0].ErrorMessage } } }; } return(BadRequest(errorResponse)); } PreviewRequest request = _mapper.Map <PreviewRequest>(vm); request.CalculationId = calculationId; request.SpecificationId = specificationId; request.ProviderId = vm.ProviderId; ApiResponse <PreviewResponse> response = await _calcClient.PreviewCompile(request); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest) { return(Ok(response.Content)); } throw new InvalidOperationException($"An error occurred while compiling calculation. Status code={response.StatusCode}"); }
public CalculationEditModelValidator( IPreviewService previewService, ICalculationsRepository calculationRepository) { Guard.ArgumentNotNull(previewService, nameof(previewService)); Guard.ArgumentNotNull(calculationRepository, nameof(calculationRepository)); _previewService = previewService; _calculationRepository = calculationRepository; RuleFor(model => model.SpecificationId) .NotEmpty() .NotNull() .WithMessage("Null or empty specification id provided."); RuleFor(model => model.ValueType) .NotNull() .WithMessage("Null value type was provided."); RuleFor(model => model.CalculationId) .NotEmpty() .NotNull() .WithMessage("Null or empty calculation id provided."); RuleFor(model => model.Name) .Custom((name, context) => { CalculationEditModel calculationEditModel = context.ParentContext.InstanceToValidate as CalculationEditModel; if (string.IsNullOrWhiteSpace(calculationEditModel.Name)) { context.AddFailure("Null or empty calculation name provided."); } else { if (!string.IsNullOrWhiteSpace(calculationEditModel.SpecificationId)) { Calculation calculation = _calculationRepository.GetCalculationsBySpecificationIdAndCalculationName(calculationEditModel.SpecificationId, calculationEditModel.Name).Result; if (calculation != null && calculation.Id != calculationEditModel.CalculationId) { context.AddFailure($"A calculation already exists with the name: '{calculationEditModel.Name}' for this specification"); } } } }); RuleFor(model => model.SourceCode) .Custom((sc, context) => { CalculationEditModel calculationEditModel = context.ParentContext.InstanceToValidate as CalculationEditModel; if (string.IsNullOrWhiteSpace(calculationEditModel.SourceCode)) { context.AddFailure("Null or empty source code provided."); } else { PreviewRequest previewRequest = new PreviewRequest { SpecificationId = calculationEditModel.SpecificationId, CalculationId = calculationEditModel.CalculationId, Name = calculationEditModel.Name, SourceCode = calculationEditModel.SourceCode, DataType = calculationEditModel.DataType }; IActionResult result = _previewService.Compile(previewRequest).Result; OkObjectResult okObjectResult = result as OkObjectResult; if (okObjectResult.Value is PreviewResponse response) { if (!response.CompilerOutput.CompilerMessages.IsNullOrEmpty()) { context.AddFailure("There are errors in the source code provided"); } } } }); }
public string SerializePreviewRequest(PreviewRequest previewRequest) { return(JsonConvert.SerializeObject(previewRequest)); }
private void OnNUnitNodeValueReady(object sender, NodeValueReadyEventArgs e) { PreviewRequest request = controller.GetPreviewRequest(); request.AppendPreviewValue(e.NodeId, e.RuntimeMirror.GetData()); }
private void Tick(UpdateEventArgs obj) { if (_current == null) { if (!_queue.TryDequeue(out _current)) { return; } if (_current.ResourceType.Code != 0) { Application.Current.ResourceCache.BackgroundLoadResource(_current.ResourceType, _current.ResourceName, false); } } if (!_current.Ready) { if (Application.Current.ResourceCache.NumBackgroundLoadResources == 0) { if (File.Exists(_current.ImagePath)) { _current.Container.ImageSource = BitmapFrame.Create(new Uri(_current.ImagePath)); _current = null; } _current.Ready = true; var scene = _current.PreviewScene.Value; _renderTexture.RenderSurface.SetViewport(0, new Viewport(Application.CurrentContext, scene.Scene, scene.Camera)); _renderTexture.RenderSurface.UpdateMode = RenderSurfaceUpdateMode.Updatealways; } return; } if (_current.TimeoutCounter > 0) { --_current.TimeoutCounter; return; } var size = _renderTexture.GetDataSize(_previewSize, _previewSize); if (size != 0) { var buf = new byte[size]; var pinnedArray = GCHandle.Alloc(buf, GCHandleType.Pinned); var pointer = pinnedArray.AddrOfPinnedObject(); _renderTexture.GetData(0, pointer); pinnedArray.Free(); var image = BitmapSource.Create( _previewSize, _previewSize, 96, 96, PixelFormats.Rgb24, BitmapPalettes.Halftone256, buf, _previewSize * 3); using (var stream = new FileStream(_current.ImagePath, FileMode.Create)) { var encoder = new PngBitmapEncoder(); encoder.Interlace = PngInterlaceOption.On; encoder.Frames.Add(BitmapFrame.Create(image)); encoder.Save(stream); } _current.Container.ImageSource = BitmapFrame.Create(new Uri(_current.ImagePath)); } _current = null; }
public async Task <ActionResult <PreviewResult> > Preview([FromBody] PreviewRequest request) { if (!await _authManager.HasSitePermissionsAsync(request.SiteId, Types.SitePermissions.Contents) || !await _authManager.HasContentPermissionsAsync(request.SiteId, request.ChannelId, Types.ContentPermissions.Add)) { return(Unauthorized()); } var site = await _siteRepository.GetAsync(request.SiteId); var channel = await _channelRepository.GetAsync(request.ChannelId); if (site == null) { return(this.Error("指定的站点不存在")); } if (channel == null) { return(this.Error("指定的栏目不存在")); } //var styleList = await TableStyleManager.GetContentStyleListAsync(site, channel); //var dict = BackgroundInputTypeParser.SaveAttributesAsync(site, styleList, request.Content, ContentAttribute.AllAttributes.Value); //var contentInfo = new Content(dict) //{ // ChannelId = channelId, // SiteId = siteId, // AddUserName = AuthRequest.AdminName, // LastEditUserName = AuthRequest.AdminName, // LastEditDate = DateTime.Now //}; var content = request.Content; content.SiteId = site.Id; content.ChannelId = channel.Id; content.AdminId = _authManager.AdminId; content.Checked = true; content.Id = await _contentRepository.InsertPreviewAsync(site, channel, content); return(new PreviewResult { Url = _pathManager.GetPreviewContentUrl(request.SiteId, request.ChannelId, content.Id, true) }); ////contentInfo.GroupNameCollection = ControlUtils.SelectedItemsValueToStringCollection(CblContentGroups.Items); //var tagCollection = ContentTagUtils.ParseTagsString(form["TbTags"]); //contentInfo.Title = form["TbTitle"]; //var formatString = TranslateUtils.ToBool(form[ContentAttribute.Title + "_formatStrong"]); //var formatEm = TranslateUtils.ToBool(form[ContentAttribute.Title + "_formatEM"]); //var formatU = TranslateUtils.ToBool(form[ContentAttribute.Title + "_formatU"]); //var formatColor = form[ContentAttribute.Title + "_formatColor"]; //var theFormatString = ContentUtility.GetTitleFormatString(formatString, formatEm, formatU, formatColor); //contentInfo.Set(ContentAttribute.GetFormatStringAttributeName(ContentAttribute.Title), theFormatString); ////foreach (ListItem listItem in CblContentAttributes.Items) ////{ //// var value = listItem.Selected.ToString(); //// var attributeName = listItem.Value; //// contentInfo.Set(attributeName, value); ////} ////contentInfo.LinkUrl = TbLinkUrl.Text; //contentInfo.AddDate = TranslateUtils.ToDateTime(form["TbAddDate"]); //contentInfo.Checked = false; //contentInfo.Tags = TranslateUtils.ObjectCollectionToString(tagCollection, " "); //foreach (var service in PluginManager.GetServicesAsync()) //{ // try // { // service.OnContentFormSubmit(new ContentFormSubmitEventArgs(siteId, channelId, contentInfo.Id, TranslateUtils.ToDictionary(form), contentInfo)); // } // catch (Exception ex) // { // LogUtils.AddErrorLogAsync(service.PluginId, ex, nameof(IService.ContentFormSubmit)); // } //} //contentInfo.Id = _contentRepository.InsertPreviewAsync(site, channelInfo, contentInfo); //return new //{ // previewUrl = ApiRoutePreview.GetContentPreviewUrl(siteId, channelId, contentId, contentInfo.Id) //}; }
private async Task <IActionResult> GenerateAndCompile(BuildProject buildProject, Calculation calculationToPreview, IEnumerable <Calculation> calculations, CompilerOptions compilerOptions, PreviewRequest previewRequest) { PreviewProviderCalculationResponseModel previewProviderCalculation = null; Build compilerOutput = _sourceCodeService.Compile(buildProject, calculations, compilerOptions); if (compilerOutput.SourceFiles != null) { await _sourceCodeService.SaveSourceFiles(compilerOutput.SourceFiles, buildProject.SpecificationId, SourceCodeType.Preview); } if (compilerOutput.Success) { _logger.Information($"Build compiled successfully for calculation id {calculationToPreview.Id}"); string calculationIdentifier = $"{_typeIdentifierGenerator.GenerateIdentifier(calculationToPreview.Namespace)}.{_typeIdentifierGenerator.GenerateIdentifier(calculationToPreview.Name)}"; IDictionary <string, string> functions = _sourceCodeService.GetCalculationFunctions(compilerOutput.SourceFiles); IDictionary <string, string> calculationIdentifierMap = calculations .Select(_ => new { Identifier = $"{_typeIdentifierGenerator.GenerateIdentifier(_.Namespace)}.{_typeIdentifierGenerator.GenerateIdentifier(_.Name)}", CalcName = _.Name }) .ToDictionary(d => d.Identifier, d => d.CalcName); if (!functions.ContainsKey(calculationIdentifier)) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"{calculationIdentifier} is not an aggregable field", Severity = Severity.Error }); } else { if (previewRequest != null) { if (!SourceCodeHelpers.HasReturn(previewRequest.SourceCode)) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"{calculationIdentifier} must have a return statement so that a calculation result will be returned", Severity = Severity.Error }); } else { IEnumerable <string> aggregateParameters = SourceCodeHelpers.GetCalculationAggregateFunctionParameters(previewRequest.SourceCode); bool continueChecking = true; if (!aggregateParameters.IsNullOrEmpty()) { foreach (string aggregateParameter in aggregateParameters) { if (!functions.ContainsKey(aggregateParameter)) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"{aggregateParameter} is not an aggregable field", Severity = Severity.Error }); continueChecking = false; break; } if (calculationIdentifierMap.ContainsKey(aggregateParameter)) { Calculation calculation = calculations.SingleOrDefault(_ => _.Name == calculationIdentifierMap[aggregateParameter]); if (calculation.Current.DataType != CalculationDataType.Decimal) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"Only decimal fields can be used on aggregation. {aggregateParameter} has data type of {calculation.Current.DataType}", Severity = Severity.Error }); continueChecking = false; break; } } } if (continueChecking) { if (SourceCodeHelpers.IsCalcReferencedInAnAggregate(functions, calculationIdentifier)) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"{calculationIdentifier} is already referenced in an aggregation that would cause nesting", Severity = Severity.Error }); } else if (SourceCodeHelpers.CheckSourceForExistingCalculationAggregates(functions, previewRequest.SourceCode)) { compilerOutput.Success = false; compilerOutput.CompilerMessages.Add(new CompilerMessage { Message = $"{calculationIdentifier} cannot reference another calc that is being aggregated", Severity = Severity.Error }); } } } } } } } else { _logger.Information($"Build did not compile successfully for calculation id {calculationToPreview.Id}"); } LogMessages(compilerOutput, buildProject, calculationToPreview); if (!string.IsNullOrEmpty(previewRequest.ProviderId)) { CalculationSummaryModel calculationSummaryModel = calculationToPreview.ToSummaryModel(); CalcEngineModels.CalculationSummaryModel model = _mapper.Map <CalcEngineModels.CalculationSummaryModel>(calculationSummaryModel); CalcEngineModels.PreviewCalculationRequest previewCalculationRequest = new CalcEngineModels.PreviewCalculationRequest { AssemblyContent = compilerOutput.Assembly, PreviewCalculationSummaryModel = model }; ApiResponse <CalcEngineProviderResult> previewCalcResultApiResponse = await _calcEngineApiClientPolicy.ExecuteAsync( () => _calcEngineApiClient.PreviewCalculationResults( previewRequest.SpecificationId, previewRequest.ProviderId, previewCalculationRequest)); if (previewCalcResultApiResponse.StatusCode.IsSuccess()) { CalcEngineProviderResult calcEngineProviderResult = previewCalcResultApiResponse.Content; previewProviderCalculation = new PreviewProviderCalculationResponseModel { ProviderName = calcEngineProviderResult.Provider.Name, CalculationResult = _mapper.Map <CalculationResult>( calcEngineProviderResult.CalculationResults.SingleOrDefault(_ => _.Calculation?.Id == calculationToPreview.Id)), }; } } return(new OkObjectResult(new PreviewResponse { Calculation = calculationToPreview.ToResponseModel(), CompilerOutput = compilerOutput, PreviewProviderCalculation = previewProviderCalculation })); }
private static void ApplyChangesToCurrentCalculationForPreview(PreviewRequest previewRequest, Calculation calculationToPreview) { calculationToPreview.Current.SourceCode = previewRequest.SourceCode; }
public async Task <IActionResult> Compile(PreviewRequest previewRequest) { if (previewRequest == null) { _logger.Error("A null preview request was supplied"); return(new BadRequestObjectResult("A null preview request was provided")); } FluentValidation.Results.ValidationResult validationResult = await _previewRequestValidator.ValidateAsync(previewRequest); if (!validationResult.IsValid) { string errors = string.Join(";", validationResult.Errors.Select(m => m.ErrorMessage).ToArraySafe()); _logger.Warning($"The preview request failed to validate with errors: {errors}"); return(new BadRequestObjectResult("The preview request failed to validate")); } Task <IEnumerable <Calculation> > calculationsTask = _calculationsRepository.GetCalculationsBySpecificationId(previewRequest.SpecificationId); Task <BuildProject> buildProjectTask = _buildProjectsService.GetBuildProjectForSpecificationId(previewRequest.SpecificationId); Task <CompilerOptions> compilerOptionsTask = _calculationsRepository.GetCompilerOptions(previewRequest.SpecificationId); await TaskHelper.WhenAllAndThrow(calculationsTask, buildProjectTask, compilerOptionsTask); BuildProject buildProject = buildProjectTask.Result; if (buildProject == null) { _logger.Warning($"Build project for specification '{previewRequest.SpecificationId}' could not be found"); return(new PreconditionFailedResult($"Build project for specification '{previewRequest.SpecificationId}' could not be found")); } List <Calculation> allSpecCalculations = new List <Calculation>(calculationsTask.Result); Calculation calculationToPreview = allSpecCalculations.SingleOrDefault(m => m.Id == previewRequest.CalculationId); if (calculationToPreview == null) { calculationToPreview = GenerateTemporaryCalculationForPreview(previewRequest); allSpecCalculations.Add(calculationToPreview); } else { ApplyChangesToCurrentCalculationForPreview(previewRequest, calculationToPreview); } Build buildForDatasetAggregationCheck = await CheckDatasetValidAggregations(previewRequest); if (buildForDatasetAggregationCheck != null && buildForDatasetAggregationCheck.CompilerMessages.Any(m => m.Severity == Severity.Error)) { PreviewResponse response = new PreviewResponse { Calculation = calculationToPreview.ToResponseModel(), CompilerOutput = buildForDatasetAggregationCheck }; return(new OkObjectResult(response)); } CompilerOptions compilerOptions = compilerOptionsTask.Result ?? new CompilerOptions { SpecificationId = buildProject.SpecificationId }; return(await GenerateAndCompile(buildProject, calculationToPreview, allSpecCalculations, compilerOptions, previewRequest)); }
public CalculationCreateModelValidator( ICalculationsRepository calculationRepository, IPreviewService previewService, ISpecificationsApiClient specificationsApiClient, ICalcsResiliencePolicies calcsResiliencePolicies) { Guard.ArgumentNotNull(calculationRepository, nameof(calculationRepository)); Guard.ArgumentNotNull(previewService, nameof(previewService)); Guard.ArgumentNotNull(specificationsApiClient, nameof(specificationsApiClient)); Guard.ArgumentNotNull(calcsResiliencePolicies, nameof(calcsResiliencePolicies)); Guard.ArgumentNotNull(calcsResiliencePolicies?.SpecificationsApiClient, nameof(calcsResiliencePolicies.SpecificationsApiClient)); _calculationRepository = calculationRepository; _previewService = previewService; _specificationsApiClient = specificationsApiClient; _specificationsApiClientPolicy = calcsResiliencePolicies.SpecificationsApiClient; CascadeMode = CascadeMode.StopOnFirstFailure; RuleFor(model => model.SpecificationId) .NotEmpty() .NotNull() .WithMessage("Null or empty specification id provided."); RuleFor(model => model.ValueType) .NotNull() .WithMessage("Null value type was provided."); RuleFor(model => model.Name) .Custom((name, context) => { CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel; if (string.IsNullOrWhiteSpace(calculationCreateModel.Name)) { context.AddFailure("Null or empty calculation name provided."); } else { if (!string.IsNullOrWhiteSpace(calculationCreateModel.SpecificationId)) { Calculation calculation = _calculationRepository.GetCalculationsBySpecificationIdAndCalculationName(calculationCreateModel.SpecificationId, calculationCreateModel.Name).Result; if (calculation != null) { context.AddFailure($"A calculation already exists with the name: '{calculationCreateModel.Name}' for this specification"); } } } }); RuleFor(model => model.SourceCode) .Custom((sc, context) => { CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel; if (string.IsNullOrWhiteSpace(calculationCreateModel.SourceCode)) { context.AddFailure("Null or empty source code provided."); } else { if (calculationCreateModel.CalculationType == CalculationType.Additional) { PreviewRequest previewRequest = new PreviewRequest { SpecificationId = calculationCreateModel.SpecificationId, CalculationId = calculationCreateModel.Id, Name = calculationCreateModel.Name, SourceCode = calculationCreateModel.SourceCode }; IActionResult result = _previewService.Compile(previewRequest).Result; OkObjectResult okObjectResult = result as OkObjectResult; PreviewResponse response = okObjectResult.Value as PreviewResponse; if (response != null) { if (!response.CompilerOutput.CompilerMessages.IsNullOrEmpty()) { context.AddFailure("There are errors in the source code provided"); } } } } }); RuleFor(model => model.FundingStreamId) .Custom((fs, context) => { CalculationCreateModel calculationCreateModel = context.ParentContext.InstanceToValidate as CalculationCreateModel; //only validate funding stream id for template calcs var isTemplateCalculation = calculationCreateModel.CalculationType == CalculationType.Template; if (isTemplateCalculation && string.IsNullOrWhiteSpace(calculationCreateModel.FundingStreamId)) { context.AddFailure("Null or empty funding stream id provided."); } else { ApiResponse <SpecModel.SpecificationSummary> specificationApiResponse = _specificationsApiClientPolicy.ExecuteAsync(() => _specificationsApiClient.GetSpecificationSummaryById(calculationCreateModel.SpecificationId)).GetAwaiter().GetResult(); if (specificationApiResponse == null || !specificationApiResponse.StatusCode.IsSuccess() || specificationApiResponse.Content == null) { context.AddFailure("Failed to find specification for provided specification id."); } else { SpecModel.SpecificationSummary specificationSummary = specificationApiResponse.Content; //I don't want to have to fetch the spec summary again outside of this method to get the name and funding stream so we set them on input model here calculationCreateModel.SpecificationName = specificationSummary.Name; //only validate funding stream ids for template calcs if (!isTemplateCalculation) { return; } Reference fundingStream = specificationSummary.FundingStreams.FirstOrDefault(m => m.Id == calculationCreateModel.FundingStreamId); if (fundingStream == null) { context.AddFailure("The funding stream id provided is not associated with the provided specification."); } else { calculationCreateModel.FundingStreamName = fundingStream.Name; } } } }); }
public Task <IActionResult> CompilePreview([FromBody] PreviewRequest previewRequest) => _previewService.Compile(previewRequest);