Skip to content

Commit b369aed

Browse files
committed
add code generate
1 parent edc5175 commit b369aed

File tree

3 files changed

+126
-15
lines changed

3 files changed

+126
-15
lines changed

src/BlazorAdmin/BlazorAdmin.Core/Data/DatabaseExtension.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ public static void InitialData(this BlazorAdminDbContext dbContext, bool isCreat
135135

136136
dbContext.Menus.Add(new Menu { ParentId = entry3.Entity.Id, Name = "配置", Type = 1, Route = "/setting", Order = 1, Icon = Icons.Material.Filled.Settings });
137137
dbContext.Menus.Add(new Menu { ParentId = entry3.Entity.Id, Name = "指标", Type = 1, Route = "/appmetric", Order = 2, Icon = Icons.Material.Filled.AutoGraph });
138+
//dbContext.Menus.Add(new Menu { ParentId = entry3.Entity.Id, Name = "代码生成", Type = 1, Route = "/setting/code-generator", Order = 3, Icon = Icons.Material.Filled.Code });
138139
dbContext.SaveChanges();
139140

140141
//var aiConfigPage = dbContext.Menus.Add(new Menu { ParentId = aiEntry.Entity.Id, Name = "Ai配置", Type = 1, Route = "/ai/config", Order = 3, Icon = Icons.Material.Filled.SettingsInputComponent });

src/BlazorAdmin/BlazorAdmin.Modules/BlazorAdmin.Setting/Pages/CodeGenerator.razor renamed to src/BlazorAdmin/BlazorAdmin.Modules/BlazorAdmin.Setting/Pages/Codes/CodeGenerator.razor

Lines changed: 102 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
@using BlazorAdmin.Core.Dynamic
66
@using BlazorAdmin.Data.Entities
77
@using System.ComponentModel.DataAnnotations.Schema
8+
@using System.IO.Compression
89
@using static BlazorAdmin.Component.Pages.PagePagination
910
@rendermode RenderMode.InteractiveServer
1011
@inject IDbContextFactory<BlazorAdminDbContext> _dbFactory
@@ -19,7 +20,8 @@
1920
}
2021
</MudSelect>
2122
</div>
22-
<MudButton Color="Color.Primary" OnClick="GenerateCode" Class="mr-2">生成代码</MudButton>
23+
<MudButton Color="Color.Primary" OnClick="GenerateCode" Class="mr-2" Variant="Variant.Filled">生成代码</MudButton>
24+
<MudButton Color="Color.Primary" OnClick="DownloadZip" Class="mr-2" Variant="Variant.Filled">打包下载</MudButton>
2325
</PageHeader>
2426

2527
<MudPaper Class="pa-4 mb-4 flex-1" Style="overflow:auto">
@@ -30,29 +32,21 @@
3032
@_pageSrc
3133
</MudText>
3234
}
33-
@if (!string.IsNullOrEmpty(_createDialogSrc))
34-
{
35-
<MudText Style="white-space: pre; font-family: monospace; " Class="border mt-2">
36-
@_createDialogSrc
37-
</MudText>
38-
}
3935
@if (!string.IsNullOrEmpty(_editDialogSrc))
4036
{
4137
<MudText Style="white-space: pre; font-family: monospace; " Class="border mt-2">
4238
@_editDialogSrc
4339
</MudText>
4440
}
45-
</MudPaper>
41+
</MudPaper>
4642

47-
@code {
43+
@code {
4844

4945
private List<Type> entityTypes = new();
5046
private Type? selectedEntity;
5147

5248
private string _pageSrc = string.Empty;
5349

54-
private string _createDialogSrc = string.Empty;
55-
5650
private string _editDialogSrc = string.Empty;
5751

5852
protected override async Task OnInitializedAsync()
@@ -128,6 +122,7 @@
128122
@using BlazorAdmin.Core.Dynamic
129123
@using BlazorAdmin.Data.Entities
130124
@using static BlazorAdmin.Component.Pages.PagePagination
125+
@using BlazorAdmin.Component.Dialogs
131126
132127
@using {selectedEntity.Namespace}
133128
@@ -140,6 +135,9 @@
140135
<MudIconButton Size=""MudBlazor.Size.Medium"" Icon = ""@Icons.Material.Filled.SearchOff""
141136
OnClick=""SearchReset"" Variant = ""Variant.Outlined"" Color = ""Color.Primary"" ></MudIconButton >
142137
</MudTooltip>
138+
<MudIconButton Size=""MudBlazor.Size.Medium"" Icon =""@Icons.Material.Filled.Add"" OnClick=""AddClick""
139+
Variant=""Variant.Outlined"" Color=""Color.Primary"" >
140+
</MudIconButton>
143141
</PageHeader>
144142
145143
<MudDataGrid Dense=PageDataGridConfig.Dense
@@ -160,6 +158,10 @@
160158
{tableColumns}
161159
<TemplateColumn Title=""操作"" HeaderStyle="" white-space:nowrap;"">
162160
<CellTemplate>
161+
<MudIconButton Size=""@MudBlazor.Size.Small"" Icon =""@Icons.Material.Outlined.Delete"" Color=""Color.Error""
162+
OnClick=""() =>DeleteClick(context.Item.Id)"" />
163+
<MudIconButton Size=""@MudBlazor.Size.Small"" Icon =""@Icons.Material.Outlined.Edit"" Color=""Color.Primary""
164+
OnClick=""() =>EditClick(context.Item.Id)"" />
163165
</CellTemplate>
164166
</TemplateColumn>
165167
</Columns>
@@ -224,6 +226,57 @@
224226
dataGrid.ReloadServerData();
225227
}}
226228
229+
private async Task AddClick()
230+
{{
231+
var parameters = new DialogParameters<Edit{entityName}Dialog> {{ }};
232+
var options = new DialogOptions() {{CloseButton = true,MaxWidth = MaxWidth.ExtraLarge}};
233+
var dialog = await _dialogService.ShowAsync<Edit{entityName}Dialog>(""创建"", parameters, options);
234+
var result = await dialog.Result;
235+
if (!result.Canceled)
236+
{{
237+
_snackbarService.Add(""创建成功"", Severity.Success);
238+
await dataGrid.ReloadServerData();
239+
}}
240+
}}
241+
242+
private async Task EditClick(int id)
243+
{{
244+
var parameters = new DialogParameters<Edit{entityName}Dialog>
245+
{{
246+
{{ x=> x.Id, id}}
247+
}};
248+
var options = new DialogOptions() {{CloseButton = true,MaxWidth = MaxWidth.ExtraLarge}};
249+
var dialog = await _dialogService.ShowAsync<Edit{entityName}Dialog>(""编辑"", parameters, options);
250+
var result = await dialog.Result;
251+
if (!result.Canceled)
252+
{{
253+
_snackbarService.Add(""修改成功"", Severity.Success);
254+
await dataGrid.ReloadServerData();
255+
}}
256+
}}
257+
258+
private async Task DeleteClick(int id)
259+
{{
260+
await _dialogService.ShowDeleteDialog(""确定是否删除"", null,
261+
async (e) =>
262+
{{
263+
using var context = await _dbFactory.CreateDbContextAsync();
264+
var data = context.Set<{entityName}>().Find(id);
265+
if (data != null)
266+
{{
267+
context.Remove(data);
268+
context.SaveChanges();
269+
270+
_snackbarService.Add(""删除成功!"", Severity.Success);
271+
}}
272+
else
273+
{{
274+
_snackbarService.Add(""信息不存在!"", Severity.Error);
275+
}}
276+
await dataGrid.ReloadServerData();
277+
}});
278+
}}
279+
227280
private record SearchObject : PaginationModel
228281
{{
229282
{searchProperties}
@@ -242,7 +295,7 @@
242295
var formFields = string.Join("\n", properties.Select(p =>
243296
$" <MudTextField T=\"{GetCSharpTypeName(p.PropertyType)}\" @bind-Value=\"EditModel.{p.Name}\"\n " +
244297
$" Label=\"{p.Name}\" Variant=\"Variant.Outlined\" For=\"()=>EditModel.{p.Name}\"/>"));
245-
298+
246299
var setEditModelProperties = string.Join(",\n", properties
247300
.Select(p =>
248301
$" {p.Name} = entity.{p.Name}"));
@@ -320,15 +373,49 @@
320373
}}
321374
}}";
322375

323-
_createDialogSrc = createDialogCode;
324376
_editDialogSrc = createDialogCode;
325377

326378
}
327379

328-
private record SearchObject : PaginationModel
380+
private async Task DownloadZip()
329381
{
330-
}
382+
if (selectedEntity == null || string.IsNullOrEmpty(_pageSrc) || string.IsNullOrEmpty(_editDialogSrc)) return;
383+
384+
var entityName = selectedEntity.Name;
385+
var tempPath = Path.Combine(Path.GetTempPath(), $"CodeGenerator_{DateTime.Now:yyyyMMddHHmmss}");
386+
Directory.CreateDirectory(tempPath);
387+
388+
try
389+
{
390+
// 保存页面文件
391+
var pageFilePath = Path.Combine(tempPath, $"{entityName}Page.razor");
392+
await File.WriteAllTextAsync(pageFilePath, _pageSrc);
393+
394+
// 保存对话框文件
395+
var dialogFilePath = Path.Combine(tempPath, $"Edit{entityName}Dialog.razor");
396+
await File.WriteAllTextAsync(dialogFilePath, _editDialogSrc);
397+
398+
// 创建zip文件
399+
var zipPath = Path.Combine(Path.GetTempPath(), $"{entityName}_{DateTime.Now:yyyyMMddHHmmss}.zip");
400+
ZipFile.CreateFromDirectory(tempPath, zipPath);
401+
402+
// 读取zip文件并转换为base64字符串
403+
var zipBytes = await File.ReadAllBytesAsync(zipPath);
404+
var base64String = Convert.ToBase64String(zipBytes);
405+
406+
// 通过JavaScript触发下载
407+
var commonModule = await _jsRuntime.InvokeAsync<IJSObjectReference>("import", "./js/common.js");
408+
await commonModule.InvokeVoidAsync("downloadFileFromBase64", base64String, $"{entityName}_Code.zip");
331409

410+
// 清理临时文件
411+
Directory.Delete(tempPath, true);
412+
File.Delete(zipPath);
413+
}
414+
catch (Exception ex)
415+
{
416+
_snackbarService.Add($"下载失败:{ex.Message}", Severity.Error);
417+
}
418+
}
332419
private class EntityInfo
333420
{
334421
public string EntityName { get; set; } = string.Empty;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export function downloadFileFromBase64(base64String, fileName) {
2+
// 将base64字符串转换为Blob对象
3+
const byteCharacters = atob(base64String);
4+
const byteNumbers = new Array(byteCharacters.length);
5+
for (let i = 0; i < byteCharacters.length; i++) {
6+
byteNumbers[i] = byteCharacters.charCodeAt(i);
7+
}
8+
const byteArray = new Uint8Array(byteNumbers);
9+
const blob = new Blob([byteArray]);
10+
11+
// 创建下载链接
12+
const downloadLink = document.createElement('a');
13+
downloadLink.href = URL.createObjectURL(blob);
14+
downloadLink.download = fileName;
15+
16+
// 添加到文档并触发点击
17+
document.body.appendChild(downloadLink);
18+
downloadLink.click();
19+
20+
// 清理
21+
document.body.removeChild(downloadLink);
22+
URL.revokeObjectURL(downloadLink.href);
23+
}

0 commit comments

Comments
 (0)