public void SetTitle(string pageTitle) { JSRuntime.InvokeVoidAsync("setTitle", pageTitle); }
protected async Task SavePost(PostAction postAction) { try { var content = await JSRuntime.InvokeAsync <string>("commonJsFunctions.getEditorValue", ""); Post.Content = content; if (string.IsNullOrEmpty(Post.Title)) { Toaster.Error("Post title required"); } else if (string.IsNullOrEmpty(Post.Content)) { Toaster.Error("Post content required"); } else { PostItem saved; if (Post.Id == 0) { var authState = await AuthenticationStateTask; var author = await DataService.Authors.GetItem( a => a.AppUserName == authState.User.Identity.Name); Post.Author = author; Post.Slug = Post.Title.ToSlug(); Post.Description = Post.Title; saved = await DataService.BlogPosts.SaveItem(Post); } else { var item = await DataService.BlogPosts.GetItem(p => p.Id == Post.Id); item.Content = Post.Content; item.Title = Post.Title; item.Description = Post.Description; item.Categories = Post.Categories; if (postAction == PostAction.Unpublish) { item.Published = DateTime.MinValue; } saved = await DataService.BlogPosts.SaveItem(item); } DataService.Complete(); if (postAction == PostAction.Publish && !AppSettings.DemoMode) { var section = Configuration.GetSection(Constants.ConfigSectionKey); if (section != null) { var apiKey = section.GetValue <string>("SendGridApiKey"); if (!string.IsNullOrEmpty(apiKey) && apiKey != "YOUR-SENDGRID-API-KEY") { var pager = new Pager(1, 10000); var items = await DataService.Newsletters.GetList(e => e.Id > 0, pager); var emails = items.Select(i => i.Email).ToList(); var blogPost = DataService.BlogPosts.Single(p => p.Id == saved.Id); int count = await EmailService.SendNewsletters(blogPost, emails, NavigationManager.BaseUri); if (count > 0) { Toaster.Success(string.Format(Localizer["email-sent-count"], count)); } } } } Toaster.Success("Saved"); Post = saved; PostId = Post.Id; StateHasChanged(); } } catch (Exception ex) { Toaster.Error(ex.Message); } }
[JSInvokable] public async Task QuillContentChanged() { OneQuiz.Description = await JSRuntime.InvokeAsync <string>("QuillFunctions.getQuillHTML", divEditorElement); }
/// <summary> /// 弹窗状态切换方法 /// </summary> public async Task Toggle() { Dialogs.ForEach(d => d.IsShown = Dialogs.IndexOf(d) == 0); await JSRuntime.Invoke(ModalElement, "modal", "toggle"); }
protected async Task GoBack() { await JSRuntime.InvokeVoidAsync("History.goBack"); }
public static ObjectCache GetObjectCache(JSRuntime rt) { return(_runtime.GetObjectCache()); }
public async Task SendBill(string BillId) { var bill = await appDBContext.Billings .Include(a => a.propertyDirectory) .ThenInclude(b => b.property) .Include(a => a.propertyDirectory) .ThenInclude(b => b.tenant) .Include(a => a.billingLineItems) .Where(a => a.billId.Equals(Guid.Parse(BillId))).FirstOrDefaultAsync(); var user = await userManager.FindByNameAsync(UserName); var preparedBy = $"{user.firstName} {user.lastName}"; var path = Path.Combine(_env.WebRootPath, "Templates"); var resultPath = Path.Combine(_env.WebRootPath, "Uploaded", "SOA"); var templateFile = string.Empty; var template = string.Empty; var fullName = string.Empty; var rentalDate = string.Empty; var unit = string.Empty; var billItems = new StringBuilder(); var fileName = string.Empty; var fileAttachment = string.Empty; var email = string.Empty; var ownerEmail = string.Empty; switch (CompanyId.ToUpper()) { case "ASRC": templateFile = Path.Combine(path, "template_asrc.html"); template = File.ReadAllText(templateFile); fullName = $"{bill.propertyDirectory.tenant.lastName} {bill.propertyDirectory.tenant.firstName} {bill.propertyDirectory.tenant.middleName}"; rentalDate = bill.dateDue.ToString("yyyy-MM-01"); template = template.Replace("[@Tenant]", fullName); template = template.Replace("[@BillDocumentId]", bill.documentId); unit = bill.propertyDirectory.property.description; template = template.Replace("[@Unit]", unit); template = template.Replace("[@TransactionDate]", bill.transactionDate.ToString("yyyy-MM-dd")); template = template.Replace("[@RentalPeriod]", rentalDate); template = template.Replace("[@DueDate]", bill.dateDue.ToString("yyyy-MM-dd")); template = template.Replace("[@TotalAmount]", bill.totalAmount.ToString("#,##0.00;(#,##0.00)")); template = template.Replace("[@PreparedBy]", preparedBy); template = template.Replace("[@PenaltyPct]", $"{bill.propertyDirectory.penaltyPct.ToString("0.00")}%"); foreach (var item in bill.billingLineItems) { var vat = 0m; var penalty = 0m; var wt = 0m; var total = 0m; var lineItem = string.Empty; switch (item.billLineType) { case Constants.BillLineTypes.MONTHLYBILLITEM: vat = bill.billingLineItems.Where(a => a.billLineType.Equals(Constants.BillLineTypes.MONTHLYBILLITEM_VAT)).Sum(a => a.amount); penalty = bill.billingLineItems.Where(a => a.billLineType.Equals(Constants.BillLineTypes.MONTHLYBILLITEMPENALTY)).Sum(a => a.amount); wt = bill.billingLineItems.Where(a => a.billLineType.Equals(Constants.BillLineTypes.MONTHLYBILLITEM_WT)).Sum(a => a.amount); total = item.amount + vat + penalty + wt; lineItem = $"<tr><td colspan = \"3\">Rental Due payable to ASRC</td><td>{unit}</td><td>{bill.propertyDirectory.property.areaInSqm.ToString()}</td><td>{item.amount.ToString("#,##0.00;(#,##0.00)")}</td><td>{vat.ToString("#,##0.00;(#,##0.00)")}</td><td>{penalty.ToString("#,##0.00;(#,##0.00)")}</td><td>{wt.ToString("#,##0.00;(#,##0.00)")}</td><td> {total.ToString("#,##0.00;(#,##0.00)")} </td></tr>"; billItems.AppendLine(lineItem); break; case Constants.BillLineTypes.MONTHLYASSOCDUE: vat = bill.billingLineItems.Where(a => a.billLineType.Equals(Constants.BillLineTypes.MONTHLYASSOCDUE_VAT)).Sum(a => a.amount); penalty = bill.billingLineItems.Where(a => a.billLineType.Equals(Constants.BillLineTypes.MONTHLYASSOCDUEPENALTY)).Sum(a => a.amount); total = item.amount + vat + penalty + wt; lineItem = $"<tr><td colspan = \"3\">Assoc Due Payable to ADBCA ({bill.dateDue.ToString("MMM yyyy")})</td><td>{unit}</td><td>{bill.propertyDirectory.property.areaInSqm.ToString()}</td><td>{item.amount.ToString("#,##0.00;(#,##0.00)")}</td><td>{vat.ToString("#,##0.00;(#,##0.00)")}</td><td>{penalty.ToString("#,##0.00;(#,##0.00)")}</td><td> </td><td> {total.ToString("#,##0.00;(#,##0.00)")} </td ></tr>"; billItems.AppendLine(lineItem); break; case Constants.BillLineTypes.MONTHLYBILLITEMPENALTY: case Constants.BillLineTypes.MONTHLYBILLITEM_VAT: case Constants.BillLineTypes.MONTHLYBILLITEM_WT: case Constants.BillLineTypes.MONTHLYASSOCDUEPENALTY: case Constants.BillLineTypes.MONTHLYASSOCDUE_VAT: break; default: lineItem = $"<tr><td colspan = \"3\">{item.description}</td><td>{unit}</td><td>{bill.propertyDirectory.property.areaInSqm.ToString()}</td><td></td><td></td><td></td><td> </td><td> {item.amount.ToString("#,##0.00;(#,##0.00)")} </td ></tr>"; billItems.AppendLine(lineItem); break; } } template = template.Replace("[@BillItems]", billItems.ToString()); template = template.Replace("[@PreparedBy]", preparedBy); fileName = $"{BillId}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.html"; fileAttachment = Path.Combine(resultPath, fileName); File.WriteAllText(fileAttachment, template); email = bill.propertyDirectory.tenant.emailAddress; ownerEmail = bill.propertyDirectory.property.ownerEmailAdd; if ((!string.IsNullOrEmpty(email) || !string.IsNullOrEmpty(ownerEmail))) { var subject = $"Statement of account - {bill.dateDue.ToString("MMM yyyy")}"; var body = new StringBuilder(); body.AppendLine($"Dear {bill.propertyDirectory.tenant.firstName} {bill.propertyDirectory.tenant.lastName},"); body.AppendLine("<br/><br/>"); body.AppendLine($"Please see attached billing for the month of {bill.dateDue.ToString("MMM yyyy")}."); body.AppendLine("<br/><br/><br/>"); body.AppendLine("Thanks"); var send = await emailService.SendEmail($"{email};{ownerEmail}", "", subject, body.ToString(), fileAttachment); if (send) { await JSRuntime.InvokeVoidAsync("alert", $"Bill successfully sent to {email};{ownerEmail}."); } else { await JSRuntime.InvokeVoidAsync("alert", $"Bill sending failed. Please contact your system administrator."); } } else { await JSRuntime.InvokeVoidAsync("alert", $"The tenant do not have a email address."); } break; case "ADBCA": templateFile = Path.Combine(path, "template_adbca.html"); template = File.ReadAllText(templateFile); fullName = $"{bill.propertyDirectory.tenant.lastName} {bill.propertyDirectory.tenant.firstName} {bill.propertyDirectory.tenant.middleName}"; rentalDate = bill.dateDue.ToString("yyyy-MM-01"); template = template.Replace("[@Tenant]", fullName); template = template.Replace("[@OwnerName]", bill.propertyDirectory.property.ownerFullName); template = template.Replace("[@BillDocumentId]", bill.documentId); unit = bill.propertyDirectory.property.description; var area = bill.propertyDirectory.property.areaInSqm.ToString("0.00"); var rate = bill.propertyDirectory.ratePerSQMAssocDues.ToString("#,##0.00;(#,##0.00)"); template = template.Replace("[@Unit]", unit); template = template.Replace("[@Area]", area); template = template.Replace("[@Rate]", rate); template = template.Replace("[@TransactionDate]", bill.transactionDate.ToString("yyyy-MM-dd")); template = template.Replace("[@RentalPeriod]", rentalDate); template = template.Replace("[@DueDate]", bill.dateDue.ToString("yyyy-MM-dd")); template = template.Replace("[@TotalAmount]", bill.totalAmount.ToString("#,##0.00;(#,##0.00)")); template = template.Replace("[@PreparedBy]", preparedBy); foreach (var item in bill.billingLineItems) { var lineItem = $"<tr><td style=\"border: 1px solid #000000;\">{item.description}</td><td style=\"width: 50px; border: 1px solid #000000;text-align: center;\">PHP</td><td style=\"width: 200px; border: 1px solid #000000; text-align: right;\">{item.amount.ToString("#,##0.00;(#,##0.00)")}</td></tr>"; billItems.AppendLine(lineItem); } template = template.Replace("[@BillItems]", billItems.ToString()); template = template.Replace("[@PreparedBy]", preparedBy); fileName = $"{BillId}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.html"; fileAttachment = Path.Combine(resultPath, fileName); File.WriteAllText(fileAttachment, template); email = bill.propertyDirectory.tenant.emailAddress; if (!string.IsNullOrEmpty(email)) { var subject = $"Statement of account - {bill.dateDue.ToString("MMM yyyy")}"; var body = new StringBuilder(); body.AppendLine($"Dear {bill.propertyDirectory.tenant.firstName} {bill.propertyDirectory.tenant.lastName},"); body.AppendLine("<br/><br/>"); body.AppendLine($"Please see attached billing for the month of {bill.dateDue.ToString("MMM yyyy")}."); body.AppendLine("<br/><br/><br/>"); body.AppendLine("Thanks"); var send = await emailService.SendEmail(email, "", subject, body.ToString(), fileAttachment); if (send) { await JSRuntime.InvokeVoidAsync("alert", $"Bill successfully sent to {email}."); } else { await JSRuntime.InvokeVoidAsync("alert", $"Bill sending failed. Please contact your system administrator."); } } else { await JSRuntime.InvokeVoidAsync("alert", $"The tenant do not have a email address."); } break; case "APMI": templateFile = Path.Combine(path, "template_apmi.html"); break; } //template }
public void Dispose() { JSRuntime.InvokeVoidAsync("panoramicData.hideMenu", Id); }
public BlazorHybridRenderer(IPC ipc, IServiceProvider serviceProvider, ILoggerFactory loggerFactory, JSRuntime jsRuntime, Dispatcher dispatcher) : base(serviceProvider, loggerFactory) { _ipc = ipc ?? throw new ArgumentNullException(nameof(ipc)); _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher)); _jsRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime)); var rootComponent = new RenderFragmentComponent(); var rootComponentId = AssignRootComponentId(rootComponent); RootRenderHandle = rootComponent.RenderHandle; var initTask = _jsRuntime.InvokeAsync <object>( "Blazor._internal.attachRootComponentToElement", "app", rootComponentId, _rendererId); CaptureAsyncExceptions(initTask); }
/// <summary> /// OnAfterRenderAsync 方法 /// </summary> /// <param name="firstRender"></param> /// <returns></returns> protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); await JSRuntime.InvokeVoidAsync(ConsoleElement, "bb_console_log"); }
public DotNetObjectReferenceJsonConverterFactory(JSRuntime jsRuntime) { JSRuntime = jsRuntime; }
public async Task PlaySound() { await JSRuntime.InvokeVoidAsync("playSound"); }
private void LoadJsModule() { _module = _module ?? JSRuntime .InvokeAsync <IJSObjectReference>("import", "./js/demo.js") .AsTask(); }
private async System.Threading.Tasks.Task HandleKeyPress(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs args, bool isFilter = false) { if (Disabled) { return; } var items = (LoadData.HasDelegate ? Data != null ? Data : Enumerable.Empty <object>() : (View != null ? View : Enumerable.Empty <object>())).Cast <object>(); var key = args.Code != null ? args.Code : args.Key; if (!args.AltKey && (key == "ArrowDown" || key == "ArrowLeft" || key == "ArrowUp" || key == "ArrowRight")) { try { var newSelectedIndex = await JSRuntime.InvokeAsync <int>("Radzen.focusListItem", search, list, key == "ArrowDown" || key == "ArrowRight", selectedIndex); if (!Multiple) { if (newSelectedIndex != selectedIndex && newSelectedIndex >= 0 && newSelectedIndex <= items.Count() - 1) { selectedIndex = newSelectedIndex; await OnSelectItem(items.ElementAt(selectedIndex), true); } } else { selectedIndex = await JSRuntime.InvokeAsync <int>("Radzen.focusListItem", search, list, key == "ArrowDown", selectedIndex); } } catch (Exception) { // } } else if (Multiple && key == "Space") { if (selectedIndex >= 0 && selectedIndex <= items.Count() - 1) { await JSRuntime.InvokeAsync <string>("Radzen.setInputValue", search, $"{searchText}".Trim()); await OnSelectItem(items.ElementAt(selectedIndex), true); } } else if (key == "Enter" || (args.AltKey && key == "ArrowDown")) { await OpenPopup(key, isFilter); } else if (key == "Escape" || key == "Tab") { await JSRuntime.InvokeVoidAsync("Radzen.closePopup", PopupID); } else if (key == "Delete") { if (!Multiple && selectedItem != null) { selectedIndex = -1; await OnSelectItem(null, true); } if (AllowFiltering && isFilter) { Debounce(DebounceFilter, FilterDelay); } } else if (AllowFiltering && isFilter) { Debounce(DebounceFilter, FilterDelay); } }
private async Task Clear() { await JSRuntime.InvokeVoidAsync(QRCodeElement, "bb_qrcode", "clear"); }
public static ObjectCache GetObjectCache(JSRuntime rt) { return(GetRuntime(rt).GetObjectCache()); }
public ScriptCompiler() { _rt = JSApi.JS_NewRuntime(); _ctx = JSApi.JS_NewContext(_rt); JSApi.JS_AddIntrinsicOperators(_ctx); }
protected async Task HandleViewCommandAsync(ViewCommand command) { try { if (command == null) { return; } if (command is ReturnCommand) { if (_previousParameterCommand != null) { command = _previousParameterCommand; } else { command = new NavigateBackCommand(); } } switch (command) { case NavigateCommand navigateCommand: NavigationManager.NavigateTo(navigateCommand.Uri); break; case NavigateBackCommand navigateBackCommand: // TODO: improve this await JSRuntime.InvokeAsync <bool>("history.back"); break; case UpdateParameterCommand parameterCommand: _previousParameterCommand = new UpdateParameterCommand { Action = Action, CollectionAlias = CollectionAlias, Id = Id, ParentPath = Path, VariantAlias = VariantAlias }; var data = new Dictionary <string, object>() { { nameof(Action), parameterCommand.Action }, { nameof(CollectionAlias), parameterCommand.CollectionAlias } }; if (parameterCommand.VariantAlias != null) { data.Add(nameof(VariantAlias), parameterCommand.VariantAlias); } if (parameterCommand.Id != null) { data.Add(nameof(Id), parameterCommand.Id); } if (parameterCommand.ParentPath != null) { data.Add(nameof(Path), parameterCommand.ParentPath); } var update = ParameterView.FromDictionary(data); await SetParametersAsync(update); break; case ReloadCommand reloadCommand: await LoadDataAsync(reloadCommand.EntityId); break; case NoOperationCommand _: default: StateHasChanged(); break; } } catch (Exception ex) { HandleException(ex); } }
public static ScriptRuntime GetRuntime(JSRuntime rt) { return(_runtime); }
void IDisposable.Dispose() { JSRuntime.InvokeVoidAsync("DestroyActivePlayer"); }
public static void StartElectronProcess(Func <Task> callback) { var projectRoot = GetProjectRoot(); Directory.SetCurrentDirectory(projectRoot); var applicationBaseDir = Path.GetDirectoryName(typeof(Launcher).Assembly.Location); var electronEntryPoint = Path.Combine( applicationBaseDir, "electron-js", "main.js"); var electronPort = SelectPort(); Log($"Launching Electron on port {electronPort}"); var electronFilename = Path.Combine(projectRoot, "node_modules", "electron", "dist", GetElectronPath()); var electronProcess = ElectronProcess.Start(new ProcessStartInfo { FileName = electronFilename, Arguments = $"\"{electronEntryPoint}\" {electronPort}" }); // TODO - this is a gross hack because Electron.NET's bridge connector doesn't let us configure the port any other way. WebHostBuilderExtensions.UseElectron(new FakeWebHostBuilder(), new[] { $"/electronport={electronPort}" }); var current = SynchronizationContext.Current; var electronSynchronizationContext = new ElectronSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(electronSynchronizationContext); ElectronNET.API.Electron.IpcMain.On("BeginInvokeDotNetFromJS", args => { electronSynchronizationContext.Send(state => { JSRuntime.SetCurrentJSRuntime(ElectronJSRuntime); var argsArray = (JArray)state; JSInterop.DotNetDispatcher.BeginInvoke( (string)argsArray[0], (string)argsArray[1], (string)argsArray[2], (long)argsArray[3], (string)argsArray[4]); }, args); }); try { Task.Factory.StartNew(async() => { try { await callback(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); //Electron.App.Exit(1); } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); electronProcess.Process.WaitForExit(); electronSynchronizationContext.Stop(); } finally { SynchronizationContext.SetSynchronizationContext(current); } }
private async Task OnDownload() { var text = BuildText(); await JSRuntime.InvokeVoidAsync("downloadFile", text, _fileName); }
protected async Task LoadYouTubeVideo(Episode OneEpisode) { await JSRuntime.InvokeVoidAsync("Player.loadYouTubeVideo", OneEpisode.VideoId); }
/// <summary> /// 顯示提示信息 /// </summary> /// <param name="text"></param> /// <param name="ret"></param> protected void ShowMessage(string text, bool ret = true) => JSRuntime?.ShowToast("網站設置", ret ? $"{text}成功" : $"{text}失败", ret ? ToastCategory.Success : ToastCategory.Error);
public ByteArrayJsonConverter(JSRuntime jSRuntime) { JSRuntime = jSRuntime; }
private async ValueTask <bool> IsLoaded() { // Make sure both QuillJs is loaded return(await JSRuntime.InvokeAsync <bool>("eval", "(function(){ return typeof Quill !== 'undefined' })()")); }
protected override async Task OnAfterRenderAsync(bool firstRender) { await JSRuntime.InvokeVoidAsync("BlazorFabricBaseComponent.initializeFocusRects"); await base.OnAfterRenderAsync(firstRender); }
public ByteArrayJsonConverterTest() { JSRuntime = new TestJSRuntime(); }
protected override async Task OnAfterRenderAsync(bool firstRender) { _jSModule = await JSRuntime.InvokeAsync <IJSObjectReference>("import", "./_content/KristofferStrube.Blazor.SVGEditor/KristofferStrube.Blazor.SVGEditor.js"); BBox = await GetBoundingBox(SVGElementReference); }
public void SetKeywords(List <string> keywords) { JSRuntime.InvokeVoidAsync("setKeywords", string.Join(",", keywords)); }