├── .gitignore ├── AutoMapperExercise ├── AutoMapperExercise.csproj ├── MappingProfile.cs ├── PersonInfo.cs ├── PersonInfoDto.cs └── Program.cs ├── BenchmarkDotNetExercise ├── BenchmarkDotNetExercise.csproj ├── DataSetDeduplicationBenchmark.cs ├── HashFunctionsBenchmark.cs ├── HashFunctionsBenchmarkV2.cs ├── ParamsBenchmark.cs ├── Program.cs └── StringConcatenationBenchmark.cs ├── BouncyCastleExercise ├── BouncyCastleExercise.csproj └── Program.cs ├── ChartjsExercise ├── App.razor ├── ChartjsExercise.csproj ├── Layout │ ├── MainLayout.razor │ ├── MainLayout.razor.css │ ├── NavMenu.razor │ └── NavMenu.razor.css ├── Model │ ├── Colors.cs │ └── DataItem.cs ├── Pages │ ├── BarSimple.razor │ ├── BarSimple.razor.cs │ ├── Home.razor │ ├── LineSimple.razor │ ├── LineSimple.razor.cs │ ├── PieSimple.razor │ └── PieSimple.razor.cs ├── Program.cs ├── Properties │ └── launchSettings.json ├── _Imports.razor └── wwwroot │ ├── css │ ├── app.css │ └── bootstrap │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ ├── favicon.png │ ├── icon-192.png │ ├── index.html │ └── sample-data │ └── weather.json ├── CsvHelperExercise ├── CsvHelperExercise.csproj ├── Program.cs └── StudentInfo.cs ├── DotNetExercises.sln ├── DotnetSpiderExercise ├── DotnetSpiderExercise.csproj ├── Program.cs ├── RecommendedRankingModel.cs └── RecommendedRankingSpider.cs ├── EtoFormsExercise ├── EtoFormsExercise.csproj └── Program.cs ├── FileCompDecompExercise ├── FileCompDecompExercise.csproj ├── FileCompressionHelper.cs └── Program.cs ├── FusionCacheExercise ├── FusionCacheExercise.csproj ├── FusionCacheService.cs ├── PersonInfo.cs └── Program.cs ├── GenericRepositoryExercise ├── GenericRepositoryExercise.csproj ├── Program.cs ├── TestDbContext.cs ├── UserInfo.cs └── UserInfoService.cs ├── IdGeneratorExercise ├── IdGeneratorExercise.csproj └── Program.cs ├── LICENSE ├── MLNETExercise ├── ImageAnalysis.Designer.cs ├── ImageAnalysis.cs ├── ImageAnalysis.resx ├── ImageAnalysis │ ├── 家电 │ │ ├── jd-1.jpg │ │ ├── jd-2.jpg │ │ ├── jd-3.jpg │ │ ├── jd-4.jpg │ │ └── jd-5.png │ ├── 玩具 │ │ ├── wj-1.jpg │ │ ├── wj-2.jpg │ │ ├── wj-3.jpg │ │ ├── wj-4.jpg │ │ └── wj-5.jpg │ └── 食物 │ │ ├── sw-1.jpg │ │ ├── sw-2.jpg │ │ ├── sw-3.jpg │ │ ├── sw-4.jpg │ │ └── sw-5.jpg ├── MLImageAnalysis.consumption.cs ├── MLImageAnalysis.mbconfig ├── MLImageAnalysis.mlnet ├── MLImageAnalysis.training.cs ├── MLNETExercise.csproj └── Program.cs ├── MapsuiExercise ├── App.razor ├── Layout │ ├── MainLayout.razor │ ├── MainLayout.razor.css │ ├── NavMenu.razor │ └── NavMenu.razor.css ├── MapsuiExercise.csproj ├── Pages │ ├── Counter.razor │ ├── Home.razor │ └── Weather.razor ├── Program.cs ├── Properties │ └── launchSettings.json ├── _Imports.razor └── wwwroot │ ├── css │ ├── app.css │ └── bootstrap │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ ├── favicon.png │ ├── icon-192.png │ ├── index.html │ └── sample-data │ └── weather.json ├── MethodTimerExercise ├── FodyWeavers.xml ├── FodyWeavers.xsd ├── MethodTimerExercise.csproj └── Program.cs ├── MoqExercise ├── IUserInfo.cs ├── MoqExercise.csproj ├── Program.cs └── VerifyServiceClient.cs ├── QrCodeGeneratorExercise ├── Program.cs ├── QrCodeBitmapExtensions.cs └── QrCodeGeneratorExercise.csproj ├── QuestPDFExercise ├── CreateInvoiceDetails.cs ├── CreateInvoiceDocument.cs ├── InvoiceModel.cs ├── Program.cs ├── QuestPDFExercise.csproj └── dotnetguide.png ├── README.md ├── ScottPlotWinFormsExercise ├── BarChart.Designer.cs ├── BarChart.cs ├── BarChart.resx ├── Home.Designer.cs ├── Home.cs ├── Home.resx ├── LineChart.Designer.cs ├── LineChart.cs ├── LineChart.resx ├── PieChart.Designer.cs ├── PieChart.cs ├── PieChart.resx ├── Program.cs ├── ScatterChart.Designer.cs ├── ScatterChart.cs ├── ScatterChart.resx └── ScottPlotWinFormsExercise.csproj ├── SpectreExercise ├── Program.cs └── SpectreExercise.csproj ├── SqidsExercise ├── Program.cs └── SqidsExercise.csproj ├── TerminalGuiExercise ├── Program.cs └── TerminalGuiExercise.csproj └── TimeCrontabExercise ├── Program.cs └── TimeCrontabExercise.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /AutoMapperExercise/AutoMapperExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /AutoMapperExercise/MappingProfile.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace AutoMapperExercise 9 | { 10 | public class MappingProfile : Profile 11 | { 12 | public MappingProfile() 13 | { 14 | CreateMap(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /AutoMapperExercise/PersonInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoMapperExercise 8 | { 9 | public class PersonInfo 10 | { 11 | public string FirstName { get; set; } 12 | public string LastName { get; set; } 13 | public int Age { get; set; } 14 | public string Nationality { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /AutoMapperExercise/PersonInfoDto.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoMapperExercise 8 | { 9 | public class PersonInfoDto 10 | { 11 | public string FirstName { get; set; } 12 | public string LastName { get; set; } 13 | public int Age { get; set; } 14 | public string Nationality { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /AutoMapperExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | 3 | namespace AutoMapperExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | var configuration = new MapperConfiguration(cfg => { 10 | cfg.AddProfile(); 11 | //或者下面这种方式 12 | //cfg.CreateMap(); 13 | }); 14 | var mapper = configuration.CreateMapper(); 15 | 16 | var personInfo = new PersonInfo 17 | { 18 | FirstName = "大东", 19 | LastName = "陈", 20 | Age = 18, 21 | Nationality = "中国" 22 | }; 23 | var personInfoDto = mapper.Map(personInfo); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/BenchmarkDotNetExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/DataSetDeduplicationBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace BenchmarkDotNetExercise 4 | { 5 | [MemoryDiagnoser]//记录内存分配情况 6 | public class DataSetDeduplicationBenchmark 7 | { 8 | private List dataSource; 9 | 10 | public DataSetDeduplicationBenchmark() 11 | { 12 | // 生成大量重复数据 13 | dataSource = Enumerable.Repeat(Enumerable.Range(1, 100), 10000).SelectMany(x => x).ToList(); 14 | } 15 | 16 | /// 17 | /// 使用HashSet去重 18 | /// TODO:HashSet是一个集合类,它的特点是不允许重复元素,可以方便地实现去重功能。 19 | /// 20 | [Benchmark] 21 | public void HashSetDuplicate() 22 | { 23 | HashSet uniqueData = new HashSet(dataSource); 24 | } 25 | 26 | /// 27 | /// 直接循环遍历去重 28 | /// 29 | [Benchmark] 30 | public void LoopTraversalDuplicate() 31 | { 32 | var uniqueData = new List(); 33 | foreach (var item in dataSource) 34 | { 35 | //if (!uniqueData.Any(x => x == item)) 36 | //if (!uniqueData.Exists(x => x == item)) 37 | if (!uniqueData.Contains(item)) 38 | { 39 | uniqueData.Add(item); 40 | } 41 | } 42 | } 43 | 44 | /// 45 | /// 使用Linq的Distinct()方法去重 46 | /// 47 | [Benchmark] 48 | public void DistinctDuplicate() 49 | { 50 | var uniqueData = dataSource.Distinct().ToList(); 51 | } 52 | 53 | /// 54 | /// 使用Linq的GroupBy()方法去重 55 | /// 56 | [Benchmark] 57 | public void GroupByDuplicate() 58 | { 59 | //GroupBy()方法将原始集合中的元素进行分组,根据指定的键或条件进行分组。每个分组都会有一个唯一的键,通过将原始集合分组并选择每个分组中的第一个元素,实现了去重的效果。 60 | var uniqueData = dataSource.GroupBy(item => item).Select(group => group.First()).ToList(); 61 | } 62 | 63 | /// 64 | /// 使用自定义的比较器和循环遍历 65 | /// 66 | [Benchmark] 67 | public void CustomEqualityComparerDuplicate() 68 | { 69 | var uniqueData = new List(); 70 | foreach (var item in dataSource) 71 | { 72 | if (!uniqueData.Contains(item, new CustomEqualityComparer())) 73 | { 74 | uniqueData.Add(item); 75 | } 76 | } 77 | } 78 | 79 | /// 80 | /// 自定义的比较器 81 | /// 82 | public class CustomEqualityComparer : IEqualityComparer 83 | { 84 | public bool Equals(int x, int y) 85 | { 86 | return x == y; 87 | } 88 | 89 | public int GetHashCode(int obj) 90 | { 91 | return obj.GetHashCode(); 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/HashFunctionsBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using BenchmarkDotNet.Exporters; 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | namespace BenchmarkDotNetExercise 7 | { 8 | /// 9 | /// 测试目的:为了验证每个哈希函数在频繁调用情况下的性能 10 | /// 11 | [MemoryDiagnoser]//记录内存分配情况 12 | [MarkdownExporter, AsciiDocExporter, HtmlExporter, CsvExporter, RPlotExporter] 13 | public class HashFunctionsBenchmark 14 | { 15 | private readonly byte[] _inputDataBytes; 16 | 17 | public HashFunctionsBenchmark() 18 | { 19 | // 使用一个较长的字符串作为输入,以更好地反映哈希函数的性能 20 | var generateData = new string('y', 1000000); 21 | _inputDataBytes = Encoding.UTF8.GetBytes(generateData); 22 | } 23 | 24 | [Benchmark] 25 | public byte[] MD5Hash() 26 | { 27 | using (MD5 md5 = MD5.Create()) 28 | { 29 | return md5.ComputeHash(_inputDataBytes); 30 | } 31 | } 32 | 33 | [Benchmark] 34 | public byte[] SHA256Hash() 35 | { 36 | using (SHA256 sha256 = SHA256.Create()) 37 | { 38 | return sha256.ComputeHash(_inputDataBytes); 39 | } 40 | } 41 | 42 | [Benchmark] 43 | public byte[] SHA1Hash() 44 | { 45 | using (SHA1 sha1 = SHA1.Create()) 46 | { 47 | return sha1.ComputeHash(_inputDataBytes); 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/HashFunctionsBenchmarkV2.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Security.Cryptography; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace BenchmarkDotNetExercise 10 | { 11 | public class HashFunctionsBenchmarkV2 12 | { 13 | private const int N = 10000; 14 | private readonly byte[] data; 15 | 16 | private readonly SHA256 sha256 = SHA256.Create(); 17 | private readonly MD5 md5 = MD5.Create(); 18 | private readonly SHA1 sha1 = SHA1.Create(); 19 | 20 | public HashFunctionsBenchmarkV2() 21 | { 22 | data = new byte[N]; 23 | new Random(42).NextBytes(data); 24 | } 25 | 26 | [Benchmark] 27 | public byte[] Sha256() => sha256.ComputeHash(data); 28 | 29 | [Benchmark] 30 | public byte[] Md5() => md5.ComputeHash(data); 31 | 32 | [Benchmark] 33 | public byte[] Sha1() => sha1.ComputeHash(data); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/ParamsBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | 3 | namespace BenchmarkDotNetExercise 4 | { 5 | [MemoryDiagnoser]//记录内存分配情况 6 | [MarkdownExporter, AsciiDocExporter, HtmlExporter, CsvExporter, RPlotExporter] 7 | public class ParamsBenchmark 8 | { 9 | private List dataList = new(); 10 | 11 | /// 12 | /// 初始化测试数据 13 | /// 如创建大型数据集、分配内存资源等,避免在每次基准测试迭代中重复初始化带来的性能干扰 14 | /// 15 | [GlobalSetup] 16 | public void Setup() 17 | { 18 | dataList = new List { 1, 2, 3, 4, 5, 6, 7, 9, 10, 22, 55, 66, 88, 44, 66, 33, 77, 54, 24, 8789, 24, 54, 244, 377, 26, 99, 888, 1000 }; 19 | } 20 | 21 | [Benchmark] 22 | public int CalculateOldSum() 23 | { 24 | return OldSumArray(dataList.ToArray()); 25 | } 26 | 27 | [Benchmark] 28 | public int CalculateNewSumList() 29 | { 30 | return NewSumList(dataList); 31 | } 32 | 33 | /// 34 | /// C# 13 之前 35 | /// 36 | /// datas 37 | /// 38 | public int OldSumArray(params int[] datas) 39 | { 40 | return datas.Sum(); 41 | } 42 | 43 | /// 44 | /// C# 13 中 45 | /// 46 | /// datas 47 | /// 48 | public int NewSumList(params List datas) 49 | { 50 | return datas.Sum(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | namespace BenchmarkDotNetExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | 10 | var paramsBenchmark = BenchmarkRunner.Run(); 11 | //var hashFunctionsBenchmark = BenchmarkRunner.Run(); 12 | //var hashFunctionsBenchmarkV2 = BenchmarkRunner.Run(); 13 | //var dataSetDeduplicationBenchmark = BenchmarkRunner.Run(); 14 | //var stringConcatenationBenchmark = BenchmarkRunner.Run(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /BenchmarkDotNetExercise/StringConcatenationBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using System.Text; 3 | 4 | namespace BenchmarkDotNetExercise 5 | { 6 | [MemoryDiagnoser]//记录内存分配情况 7 | public class StringConcatenationBenchmark 8 | { 9 | private const int IterationCount = 1000; 10 | private const string StringPart1 = "追逐时光者"; 11 | private const string StringPart2 = "DotNetGuide"; 12 | private const string StringPart3 = "DotNetGuide技术社区"; 13 | private readonly string[] _stringPartsArray = { "追逐时光者", "DotNetGuide", "DotNetGuide技术社区" }; 14 | 15 | #region 少量字符串拼接 16 | 17 | /// 18 | /// 使用 + 操作符拼接字符串 19 | /// 20 | /// 21 | [Benchmark] 22 | public string PlusOperator() 23 | { 24 | string result = StringPart1 + " " + StringPart2 + " " + StringPart3; 25 | return result; 26 | } 27 | 28 | /// 29 | /// 使用 $ 内插字符串拼接字符串 30 | /// 31 | /// 32 | [Benchmark] 33 | public string InterpolatedString() 34 | { 35 | string result = $"{StringPart1} {StringPart2} {StringPart3}"; 36 | return result; 37 | } 38 | 39 | /// 40 | /// 使用string.Format()拼接字符串 41 | /// 42 | /// 43 | [Benchmark] 44 | public string StringFormat() 45 | { 46 | string result = string.Format("{0} {1} {2}", StringPart1, StringPart2, StringPart3); 47 | return result; 48 | } 49 | 50 | /// 51 | /// 使用string.Concat()拼接字符串 52 | /// 53 | /// 54 | [Benchmark] 55 | public string StringConcat() 56 | { 57 | string result = string.Concat(StringPart1, " ", StringPart2, " ", StringPart3); 58 | return result; 59 | } 60 | 61 | /// 62 | /// 使用string.Join()拼接字符串 63 | /// 64 | /// 65 | [Benchmark] 66 | public string StringJoin() 67 | { 68 | string result = string.Join(" ", _stringPartsArray); 69 | return result; 70 | } 71 | 72 | /// 73 | /// 使用StringBuilder.Append拼接字符串 74 | /// 75 | /// 76 | [Benchmark] 77 | public string StringBuilderAppend() 78 | { 79 | StringBuilder stringBuilder = new StringBuilder(); 80 | stringBuilder.Append(StringPart1); 81 | stringBuilder.Append(" "); 82 | stringBuilder.Append(StringPart2); 83 | stringBuilder.Append(" "); 84 | stringBuilder.Append(StringPart3); 85 | return stringBuilder.ToString(); 86 | } 87 | 88 | /// 89 | /// 使用StringBuilder.AppendFormat拼接字符串 90 | /// 91 | /// 92 | [Benchmark] 93 | public string StringBuilderAppendFormat() 94 | { 95 | StringBuilder stringBuilder = new StringBuilder(); 96 | stringBuilder.AppendFormat("{0} {1} {2}", StringPart1, StringPart2, StringPart3); 97 | return stringBuilder.ToString(); 98 | } 99 | 100 | #endregion 101 | 102 | #region 大量字符串拼接 103 | 104 | /// 105 | /// 使用 + 操作符拼接字符串 106 | /// 107 | /// 108 | [Benchmark] 109 | public string BigDataPlusOperator() 110 | { 111 | string result = string.Empty; 112 | for (int i = 0; i < IterationCount; i++) 113 | { 114 | result += StringPart1 + " " + StringPart2 + " " + StringPart3; 115 | } 116 | return result; 117 | } 118 | 119 | /// 120 | /// 使用StringBuilder.Append拼接字符串 121 | /// 122 | /// 123 | [Benchmark] 124 | public string BigDataStringBuilderAppend() 125 | { 126 | StringBuilder stringBuilder = new StringBuilder(); 127 | for (int i = 0; i < IterationCount; i++) 128 | { 129 | stringBuilder.Append(StringPart1); 130 | stringBuilder.Append(" "); 131 | stringBuilder.Append(StringPart2); 132 | stringBuilder.Append(" "); 133 | stringBuilder.Append(StringPart3); 134 | } 135 | return stringBuilder.ToString(); 136 | } 137 | 138 | #endregion 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /BouncyCastleExercise/BouncyCastleExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ChartjsExercise/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /ChartjsExercise/ChartjsExercise.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /ChartjsExercise/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 |
3 | 6 | 7 |
8 |
9 | About 10 |
11 | 12 |
13 | @Body 14 |
15 |
16 |
17 | -------------------------------------------------------------------------------- /ChartjsExercise/Layout/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row { 41 | justify-content: space-between; 42 | } 43 | 44 | .top-row ::deep a, .top-row ::deep .btn-link { 45 | margin-left: 0; 46 | } 47 | } 48 | 49 | @media (min-width: 641px) { 50 | .page { 51 | flex-direction: row; 52 | } 53 | 54 | .sidebar { 55 | width: 250px; 56 | height: 100vh; 57 | position: sticky; 58 | top: 0; 59 | } 60 | 61 | .top-row { 62 | position: sticky; 63 | top: 0; 64 | z-index: 1; 65 | } 66 | 67 | .top-row.auth ::deep a:first-child { 68 | flex: 1; 69 | text-align: right; 70 | width: 0; 71 | } 72 | 73 | .top-row, article { 74 | padding-left: 2rem !important; 75 | padding-right: 1.5rem !important; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /ChartjsExercise/Layout/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  9 | 10 | 34 | 35 | @code { 36 | private bool collapseNavMenu = true; 37 | 38 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 39 | 40 | private void ToggleNavMenu() 41 | { 42 | collapseNavMenu = !collapseNavMenu; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /ChartjsExercise/Layout/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .bi { 15 | display: inline-block; 16 | position: relative; 17 | width: 1.25rem; 18 | height: 1.25rem; 19 | margin-right: 0.75rem; 20 | top: -1px; 21 | background-size: cover; 22 | } 23 | 24 | .bi-house-door-fill-nav-menu { 25 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E"); 26 | } 27 | 28 | .bi-plus-square-fill-nav-menu { 29 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E"); 30 | } 31 | 32 | .bi-list-nested-nav-menu { 33 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); 34 | } 35 | 36 | .nav-item { 37 | font-size: 0.9rem; 38 | padding-bottom: 0.5rem; 39 | } 40 | 41 | .nav-item:first-of-type { 42 | padding-top: 1rem; 43 | } 44 | 45 | .nav-item:last-of-type { 46 | padding-bottom: 1rem; 47 | } 48 | 49 | .nav-item ::deep a { 50 | color: #d7d7d7; 51 | border-radius: 4px; 52 | height: 3rem; 53 | display: flex; 54 | align-items: center; 55 | line-height: 3rem; 56 | } 57 | 58 | .nav-item ::deep a.active { 59 | background-color: rgba(255,255,255,0.37); 60 | color: white; 61 | } 62 | 63 | .nav-item ::deep a:hover { 64 | background-color: rgba(255,255,255,0.1); 65 | color: white; 66 | } 67 | 68 | @media (min-width: 641px) { 69 | .navbar-toggler { 70 | display: none; 71 | } 72 | 73 | .collapse { 74 | /* Never collapse the sidebar for wide screens */ 75 | display: block; 76 | } 77 | 78 | .nav-scrollable { 79 | /* Allow sidebar to scroll for tall menus */ 80 | height: calc(100vh - 3.5rem); 81 | overflow-y: auto; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /ChartjsExercise/Model/Colors.cs: -------------------------------------------------------------------------------- 1 | namespace ChartjsExercise.Model 2 | { 3 | public static class Colors 4 | { 5 | public static List Palette1 = new List() 6 | { 7 | "rgba(255, 99, 132, 0.2)", 8 | "rgba(255, 159, 64, 0.2)", 9 | "rgba(255, 205, 86, 0.2)", 10 | "rgba(75, 192, 192, 0.2)", 11 | "rgba(54, 162, 235, 0.2)", 12 | "rgba(153, 102, 255, 0.2)", 13 | "rgba(201, 203, 207, 0.2)" 14 | }; 15 | 16 | public static List PaletteBorder1 = new List() 17 | { 18 | "rgb(255, 99, 132)", 19 | "rgb(255, 159, 64)", 20 | "rgb(255, 205, 86)", 21 | "rgb(75, 192, 192)", 22 | "rgb(54, 162, 235)", 23 | "rgb(153, 102, 255)", 24 | "rgb(201, 203, 207)" 25 | }; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ChartjsExercise/Model/DataItem.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace ChartjsExercise.Model 4 | { 5 | public class DataItem 6 | { 7 | /// 8 | /// Gets or sets the group. 9 | /// 10 | /// 11 | /// The group. 12 | /// 13 | [JsonPropertyName("group")] 14 | public string? Group { get; set; } 15 | 16 | /// 17 | /// Gets or sets the name of the attribute 18 | /// 19 | /// 20 | /// The name of the attribute 21 | /// 22 | [JsonPropertyName("name")] 23 | public string? Name { get; set; } 24 | 25 | /// 26 | /// Gets or sets the value. 27 | /// 28 | /// 29 | /// The value 30 | /// 31 | [JsonPropertyName("value")] 32 | public decimal? Value { get; set; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/BarSimple.razor: -------------------------------------------------------------------------------- 1 | @page "/BarSimple" 2 | @using ChartjsExercise.Model 3 |

柱状图

4 | 5 | 6 | 7 | @code { 8 | private BarChartConfig? _config; 9 | private Chart? _chart; 10 | 11 | protected override async Task OnInitializedAsync() 12 | { 13 | _config = new BarChartConfig() 14 | { 15 | Options = new Options() 16 | { 17 | Responsive = true, 18 | MaintainAspectRatio = false, 19 | Plugins = new Plugins() 20 | { 21 | Legend = new Legend() 22 | { 23 | Align = Align.Center, 24 | Display = true, 25 | Position = LegendPosition.Right 26 | } 27 | }, 28 | Scales = new Dictionary() 29 | { 30 | { 31 | Scales.XAxisId, new Axis() 32 | { 33 | Stacked = true, 34 | Ticks = new Ticks() 35 | { 36 | MaxRotation = 0, 37 | MinRotation = 0 38 | } 39 | } 40 | }, 41 | { 42 | Scales.YAxisId, new Axis() 43 | { 44 | Stacked = true 45 | } 46 | } 47 | } 48 | } 49 | }; 50 | 51 | _config.Data.Labels = BarSimpleData.SimpleBarText; 52 | _config.Data.Datasets.Add(new BarDataset() 53 | { 54 | Label = "Value", 55 | Data = BarSimpleData.SimpleBar.Select(l => l.Value).ToList(), 56 | BackgroundColor = Colors.Palette1, 57 | BorderColor = Colors.PaletteBorder1, 58 | BorderWidth = 1 59 | }); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/BarSimple.razor.cs: -------------------------------------------------------------------------------- 1 | using ChartjsExercise.Model; 2 | 3 | namespace ChartjsExercise.Pages 4 | { 5 | partial class BarSimple 6 | { 7 | } 8 | 9 | public class BarSimpleData 10 | { 11 | public static List SimpleBarText = new List() { "一月", "二月", "三月", "四月", "五月", "六月", "七月" }; 12 | public static List SimpleBar = new List() 13 | { 14 | new DataItem() { Name = "一月", Value = 65 }, 15 | new DataItem() { Name = "二月", Value = 59 }, 16 | new DataItem() { Name = "三月", Value = 80 }, 17 | new DataItem() { Name = "四月", Value = 81 }, 18 | new DataItem() { Name = "五月", Value = 56 }, 19 | new DataItem() { Name = "六月", Value = 55 }, 20 | new DataItem() { Name = "七月", Value = 40 } 21 | }; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/Home.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | Home 4 | 5 |

在Blazor中使用Chart.js快速创建图表

6 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/LineSimple.razor: -------------------------------------------------------------------------------- 1 | @page "/LineSimple" 2 | @using ChartjsExercise.Model 3 | 4 |

折线图

5 | 6 | 7 | 8 | @code { 9 | private LineChartConfig? _config; 10 | private Chart? _chart; 11 | 12 | protected override async Task OnInitializedAsync() 13 | { 14 | _config = new LineChartConfig() 15 | { 16 | }; 17 | 18 | _config.Data.Labels = LineSimpleData.SimpleLineText; 19 | _config.Data.Datasets.Add(new LineDataset() 20 | { 21 | Label = "数据集", 22 | Data = LineSimpleData.SimpleLine.ToList(), 23 | BorderColor = Colors.PaletteBorder1.FirstOrDefault(), 24 | Tension = 0.1M, 25 | Fill = false, 26 | PointRadius = 15, 27 | PointStyle = PointStyle.Cross 28 | }); 29 | } 30 | 31 | private void AddValue() 32 | { 33 | Random rd = new Random(); 34 | _chart.AddData(new List() { "August" }, 0, new List() { rd.Next(0, 200) }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/LineSimple.razor.cs: -------------------------------------------------------------------------------- 1 | namespace ChartjsExercise.Pages 2 | { 3 | partial class LineSimple 4 | { 5 | } 6 | 7 | public class LineSimpleData 8 | { 9 | public static List SimpleLineText = new List() { "一月", "二月", "三月", "四月", "五月", "六月", "七月" }; 10 | public static List SimpleLine = new List() { 65, 59, 80, 81, 86, 55, 40 }; 11 | public static List SimpleLine2 = new List() { 33, 25, 35, 51, 54, 76, 60 }; 12 | public static List SimpleLine3 = new List() { 53, 91, 39, 61, 39, 87, 23 }; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ChartjsExercise/Pages/PieSimple.razor: -------------------------------------------------------------------------------- 1 | @page "/PieSimple" 2 | @using ChartjsExercise.Model 3 |

饼图

4 | 5 | 6 | 7 | @code { 8 | private PieChartConfig? _config; 9 | private Chart? _chart; 10 | 11 | protected override async Task OnInitializedAsync() 12 | { 13 | _config = new PieChartConfig() 14 | { 15 | Options = new PieOptions() 16 | { 17 | Responsive = true, 18 | MaintainAspectRatio = false 19 | } 20 | }; 21 | 22 | _config.Data.Labels = PieSimpleData.SimplePieText; 23 | _config.Data.Datasets.Add(new PieDataset() 24 | { 25 | Label = "数据集", 26 | Data = PieSimpleData.SimplePie.ToList(), 27 | BackgroundColor = Colors.PaletteBorder1, 28 | HoverOffset = 4 29 | }); 30 | } 31 | } -------------------------------------------------------------------------------- /ChartjsExercise/Pages/PieSimple.razor.cs: -------------------------------------------------------------------------------- 1 | namespace ChartjsExercise.Pages 2 | { 3 | partial class PieSimple 4 | { 5 | } 6 | 7 | public class PieSimpleData 8 | { 9 | public static List SimplePieText = new List() { "一月", "二月", "三月", "四月" }; 10 | public static List SimplePie = new List() { 300, 50, 100, 20 }; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ChartjsExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Web; 2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 3 | 4 | namespace ChartjsExercise 5 | { 6 | public class Program 7 | { 8 | public static async Task Main(string[] args) 9 | { 10 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 11 | builder.RootComponents.Add("#app"); 12 | builder.RootComponents.Add("head::after"); 13 | 14 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 15 | 16 | await builder.Build().RunAsync(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ChartjsExercise/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:13749", 8 | "sslPort": 44360 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 17 | "applicationUrl": "http://localhost:5103", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "https": { 23 | "commandName": "Project", 24 | "dotnetRunMessages": true, 25 | "launchBrowser": true, 26 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 27 | "applicationUrl": "https://localhost:7288;http://localhost:5103", 28 | "environmentVariables": { 29 | "ASPNETCORE_ENVIRONMENT": "Development" 30 | } 31 | }, 32 | "IIS Express": { 33 | "commandName": "IISExpress", 34 | "launchBrowser": true, 35 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 36 | "environmentVariables": { 37 | "ASPNETCORE_ENVIRONMENT": "Development" 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /ChartjsExercise/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 8 | @using Microsoft.JSInterop 9 | @using ChartjsExercise 10 | @using ChartjsExercise.Layout 11 | 12 | 13 | @using PSC.Blazor.Components.Chartjs 14 | @using PSC.Blazor.Components.Chartjs.Enums 15 | @using PSC.Blazor.Components.Chartjs.Models 16 | @using PSC.Blazor.Components.Chartjs.Models.Common 17 | @using PSC.Blazor.Components.Chartjs.Models.Bar 18 | @using PSC.Blazor.Components.Chartjs.Models.Bubble 19 | @using PSC.Blazor.Components.Chartjs.Models.Doughnut 20 | @using PSC.Blazor.Components.Chartjs.Models.Line 21 | @using PSC.Blazor.Components.Chartjs.Models.Pie 22 | @using PSC.Blazor.Components.Chartjs.Models.Polar 23 | @using PSC.Blazor.Components.Chartjs.Models.Radar 24 | @using PSC.Blazor.Components.Chartjs.Models.Scatter -------------------------------------------------------------------------------- /ChartjsExercise/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | h1:focus { 6 | outline: none; 7 | } 8 | 9 | a, .btn-link { 10 | color: #0071c1; 11 | } 12 | 13 | .btn-primary { 14 | color: #fff; 15 | background-color: #1b6ec2; 16 | border-color: #1861ac; 17 | } 18 | 19 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 20 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 21 | } 22 | 23 | .content { 24 | padding-top: 1.1rem; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid red; 33 | } 34 | 35 | .validation-message { 36 | color: red; 37 | } 38 | 39 | #blazor-error-ui { 40 | background: lightyellow; 41 | bottom: 0; 42 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 43 | display: none; 44 | left: 0; 45 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 46 | position: fixed; 47 | width: 100%; 48 | z-index: 1000; 49 | } 50 | 51 | #blazor-error-ui .dismiss { 52 | cursor: pointer; 53 | position: absolute; 54 | right: 0.75rem; 55 | top: 0.5rem; 56 | } 57 | 58 | .blazor-error-boundary { 59 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 60 | padding: 1rem 1rem 1rem 3.7rem; 61 | color: white; 62 | } 63 | 64 | .blazor-error-boundary::after { 65 | content: "An error has occurred." 66 | } 67 | 68 | .loading-progress { 69 | position: relative; 70 | display: block; 71 | width: 8rem; 72 | height: 8rem; 73 | margin: 20vh auto 1rem auto; 74 | } 75 | 76 | .loading-progress circle { 77 | fill: none; 78 | stroke: #e0e0e0; 79 | stroke-width: 0.6rem; 80 | transform-origin: 50% 50%; 81 | transform: rotate(-90deg); 82 | } 83 | 84 | .loading-progress circle:last-child { 85 | stroke: #1b6ec2; 86 | stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; 87 | transition: stroke-dasharray 0.05s ease-in-out; 88 | } 89 | 90 | .loading-progress-text { 91 | position: absolute; 92 | text-align: center; 93 | font-weight: bold; 94 | inset: calc(20vh + 3.25rem) 0 auto 0.2rem; 95 | } 96 | 97 | .loading-progress-text:after { 98 | content: var(--blazor-load-percentage-text, "Loading"); 99 | } 100 | 101 | code { 102 | color: #c02d76; 103 | } 104 | -------------------------------------------------------------------------------- /ChartjsExercise/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/ChartjsExercise/wwwroot/favicon.png -------------------------------------------------------------------------------- /ChartjsExercise/wwwroot/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/ChartjsExercise/wwwroot/icon-192.png -------------------------------------------------------------------------------- /ChartjsExercise/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ChartjsExercise 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 |
22 |
23 | 24 |
25 | An unhandled error has occurred. 26 | Reload 27 | 🗙 28 |
29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /ChartjsExercise/wwwroot/sample-data/weather.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "date": "2022-01-06", 4 | "temperatureC": 1, 5 | "summary": "Freezing" 6 | }, 7 | { 8 | "date": "2022-01-07", 9 | "temperatureC": 14, 10 | "summary": "Bracing" 11 | }, 12 | { 13 | "date": "2022-01-08", 14 | "temperatureC": -13, 15 | "summary": "Freezing" 16 | }, 17 | { 18 | "date": "2022-01-09", 19 | "temperatureC": -16, 20 | "summary": "Balmy" 21 | }, 22 | { 23 | "date": "2022-01-10", 24 | "temperatureC": -2, 25 | "summary": "Chilly" 26 | } 27 | ] 28 | -------------------------------------------------------------------------------- /CsvHelperExercise/CsvHelperExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /CsvHelperExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using CsvHelper; 2 | using System.Globalization; 3 | 4 | namespace CsvHelperExercise 5 | { 6 | internal class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | var students = new List 11 | { 12 | new StudentInfo { ID = 1, Name = "张三", Age = 20, Class = "终极一班", Gender = "男", Address = "北京市东城区" }, 13 | new StudentInfo { ID = 2, Name = "李四", Age = 21, Class = "终极一班", Gender = "女", Address = "上海市黄浦区" }, 14 | new StudentInfo { ID = 3, Name = "王五", Age = 22, Class = "终极一班", Gender = "男", Address = "广州市越秀区" }, 15 | new StudentInfo { ID = 4, Name = "赵六", Age = 20, Class = "终极二班", Gender = "女", Address = "深圳市福田区" }, 16 | new StudentInfo { ID = 5, Name = "孙七", Age = 23, Class = "终极二班", Gender = "男", Address = "杭州市西湖区" }, 17 | new StudentInfo { ID = 6, Name = "周八", Age = 24, Class = "终极二班", Gender = "女", Address = "南京市玄武区" }, 18 | new StudentInfo { ID = 7, Name = "吴九", Age = 22, Class = "终极二班", Gender = "男", Address = "成都市锦江区" }, 19 | new StudentInfo { ID = 8, Name = "小袁", Age = 21, Class = "终极三班", Gender = "女", Address = "重庆市渝中区" }, 20 | new StudentInfo { ID = 9, Name = "大姚", Age = 20, Class = "终极三班", Gender = "男", Address = "武汉市武昌区" }, 21 | new StudentInfo { ID = 10, Name = "追逐时光者", Age = 23, Class = "终极三班", Gender = "女", Address = "长沙市天心区" } 22 | }; 23 | 24 | //写入CSV文件数据 25 | using var writer = new StreamWriter(@".\StudentInfoFile.csv"); 26 | using var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture); 27 | csvWriter.WriteRecords(students); 28 | 29 | //读取CSV文件数据 30 | using var reader = new StreamReader(@".\StudentInfoFile.csv"); 31 | using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture); 32 | var getStudentInfos = csvReader.GetRecords().ToList(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /CsvHelperExercise/StudentInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace CsvHelperExercise 8 | { 9 | public class StudentInfo 10 | { 11 | /// 12 | /// 学生学号 13 | /// 14 | public int ID { get; set; } 15 | 16 | /// 17 | /// 学生姓名 18 | /// 19 | public string Name { get; set; } 20 | 21 | /// 22 | /// 学生年龄 23 | /// 24 | public int Age { get; set; } 25 | 26 | /// 27 | /// 班级 28 | /// 29 | public string Class { get; set; } 30 | 31 | /// 32 | /// 性别 33 | /// 34 | public string Gender { get; set; } 35 | 36 | /// 37 | /// 住址 38 | /// 39 | public string Address { get; set; } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /DotnetSpiderExercise/DotnetSpiderExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /DotnetSpiderExercise/Program.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetSpiderExercise 2 | { 3 | public class Program 4 | { 5 | static async Task Main(string[] args) 6 | { 7 | Console.WriteLine("网页数据抓取开始..."); 8 | 9 | await RecommendedRankingSpider.RunAsync(); 10 | 11 | Console.WriteLine("网页数据抓取完成..."); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /DotnetSpiderExercise/RecommendedRankingModel.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetSpiderExercise 2 | { 3 | public class RecommendedRankingModel 4 | { 5 | /// 6 | /// 文章标题 7 | /// 8 | public string ArticleTitle { get; set; } 9 | 10 | /// 11 | /// 文章简介 12 | /// 13 | public string ArticleSummary { get; set; } 14 | 15 | /// 16 | /// 文章地址 17 | /// 18 | public string ArticleUrl { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DotnetSpiderExercise/RecommendedRankingSpider.cs: -------------------------------------------------------------------------------- 1 | using DotnetSpider.DataFlow.Parser; 2 | using DotnetSpider.DataFlow; 3 | using DotnetSpider.Downloader; 4 | using DotnetSpider.Http; 5 | using DotnetSpider.Scheduler.Component; 6 | using DotnetSpider.Selector; 7 | using DotnetSpider; 8 | using Microsoft.Extensions.Logging; 9 | using Microsoft.Extensions.Options; 10 | using Serilog; 11 | using DotnetSpider.Scheduler; 12 | using Microsoft.Extensions.Hosting; 13 | using System.Reflection; 14 | 15 | namespace DotnetSpiderExercise 16 | { 17 | public class RecommendedRankingSpider : Spider 18 | { 19 | public RecommendedRankingSpider(IOptions options, 20 | DependenceServices services, 21 | ILogger logger) : base(options, services, logger) 22 | { 23 | } 24 | 25 | public static async Task RunAsync() 26 | { 27 | var builder = Builder.CreateDefaultBuilder(); 28 | builder.UseSerilog(); 29 | builder.UseDownloader(); 30 | builder.UseQueueDistinctBfsScheduler(); 31 | await builder.Build().RunAsync(); 32 | } 33 | 34 | protected override async Task InitializeAsync(CancellationToken stoppingToken = default) 35 | { 36 | //添加自定义解析 37 | AddDataFlow(new Parser()); 38 | //使用控制台存储器 39 | AddDataFlow(new ConsoleStorage()); 40 | //添加采集请求:博客园10天推荐排行榜 41 | await AddRequestsAsync(new Request("https://www.cnblogs.com/aggsite/topdiggs") 42 | { 43 | //请求超时10秒 44 | Timeout = 10000 45 | }); 46 | } 47 | 48 | class Parser : DataParser 49 | { 50 | public override Task InitializeAsync() 51 | { 52 | return Task.CompletedTask; 53 | } 54 | 55 | protected override Task ParseAsync(DataFlowContext context) 56 | { 57 | var recommendedRankingList = new List(); 58 | // 网页数据解析 59 | var number = 1; 60 | var recommendedList = context.Selectable.SelectList(Selectors.XPath(".//article[@class='post-item']")); 61 | foreach (var news in recommendedList) 62 | { 63 | var articleTitle = news.Select(Selectors.XPath(".//a[@class='post-item-title']"))?.Value; 64 | var articleSummary = news.Select(Selectors.XPath(".//p[@class='post-item-summary']"))?.Value?.Replace("\n", "").Replace(" ", ""); 65 | var articleUrl = news.Select(Selectors.XPath(".//a[@class='post-item-title']/@href"))?.Value; 66 | 67 | Console.WriteLine($"第{number}篇文章 标题:{articleTitle}"); 68 | 69 | recommendedRankingList.Add(new RecommendedRankingModel 70 | { 71 | ArticleTitle = articleTitle, 72 | ArticleSummary = articleSummary, 73 | ArticleUrl = articleUrl 74 | }); 75 | 76 | number++; 77 | } 78 | 79 | using (StreamWriter sw = new StreamWriter("RecommendedRanking.txt")) 80 | { 81 | foreach (RecommendedRankingModel model in recommendedRankingList) 82 | { 83 | string line = $"文章标题:{model.ArticleTitle}\r\n文章简介:{model.ArticleSummary}\r\n文章地址:{model.ArticleUrl}"; 84 | sw.WriteLine(line + "\r\n ========================================================================================== \r\n"); 85 | } 86 | } 87 | return Task.CompletedTask; 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /EtoFormsExercise/EtoFormsExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | net8.0-windows 6 | enable 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /EtoFormsExercise/Program.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/EtoFormsExercise/Program.cs -------------------------------------------------------------------------------- /FileCompDecompExercise/FileCompDecompExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /FileCompDecompExercise/FileCompressionHelper.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Compression; 2 | 3 | namespace FileCompDecompExercise 4 | { 5 | /// 6 | /// 文件压缩帮助类(.zip文件) 7 | /// 8 | public class FileCompressionHelper 9 | { 10 | /// 11 | /// 指定文件目录压缩为zip文件 12 | /// 13 | /// 指定压缩的文件目录 14 | /// 压缩后文件存放路径 15 | public static void CompressZipFileDirectory(string sourceDirectory, string zipFilePath) 16 | { 17 | //确保指定的路径中的目录存在 18 | DirectoryInfo directoryInfo = new DirectoryInfo(zipFilePath); 19 | if (directoryInfo.Parent != null) 20 | { 21 | directoryInfo = directoryInfo.Parent; 22 | } 23 | 24 | if (!directoryInfo.Exists) 25 | { 26 | directoryInfo.Create(); 27 | } 28 | 29 | //创建一个新的 .zip 文件并将文件夹内容压缩进去 30 | ZipFile.CreateFromDirectory(sourceDirectory, zipFilePath, CompressionLevel.Optimal, false); 31 | Console.WriteLine("文件目录压缩完成"); 32 | } 33 | 34 | /// 35 | /// 指定文件压缩为zip文件 36 | /// 37 | /// 指定要压缩的文件路径 38 | /// 指定压缩后的zip文件路径 39 | public static void CompressZipFile(string sourceFilePath, string zipFilePath) 40 | { 41 | //确保指定的路径中的目录存在 42 | DirectoryInfo directoryInfo = new DirectoryInfo(zipFilePath); 43 | if (directoryInfo.Parent != null) 44 | { 45 | directoryInfo = directoryInfo.Parent; 46 | } 47 | 48 | if (!directoryInfo.Exists) 49 | { 50 | directoryInfo.Create(); 51 | } 52 | 53 | // 创建一个新的 Zip 存档并向其中添加指定的文件 54 | using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Update)) 55 | { 56 | archive.CreateEntryFromFile(sourceFilePath, Path.GetFileName(sourceFilePath)); 57 | } 58 | Console.WriteLine("文件压缩完成"); 59 | } 60 | 61 | /// 62 | /// 解压.zip文件到目标文件夹 63 | /// 64 | /// 要解压的.zip文件路径 65 | /// 解压目标文件夹路径 66 | public static void ExtractZipFile(string zipFilePath, string extractPath) 67 | { 68 | if (!Directory.Exists(extractPath)) 69 | { 70 | Directory.CreateDirectory(extractPath); 71 | } 72 | 73 | // 提取 .zip 文件到指定文件夹 74 | ZipFile.ExtractToDirectory(zipFilePath, extractPath); 75 | Console.WriteLine("文件解压完成"); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /FileCompDecompExercise/Program.cs: -------------------------------------------------------------------------------- 1 | namespace FileCompDecompExercise 2 | { 3 | internal class Program 4 | { 5 | static void Main(string[] args) 6 | { 7 | var sourceFilePath = @".\MySourceFile.xls"; //指定要压缩的文件路径(先创建对应.xls文件) 8 | var zipSourceFilePath = @".\OutputFolder\ZipSourceFilePath.zip"; //压缩后文件存放路径 9 | var zipFilePath = @".\OutputFolder\Archive.zip"; //压缩后文件存放路径 10 | string extractPath = @".\OutputFolder"; // 解压目标文件夹路径 11 | var sourceDirectory = @".\ZipFileDirectory";//指定压缩的文件目录(先在对应位置创建好) 12 | 13 | //指定文件压缩为zip文件 14 | FileCompressionHelper.CompressZipFile(sourceFilePath, zipSourceFilePath); 15 | 16 | //指定文件目录压缩为zip文件 17 | FileCompressionHelper.CompressZipFileDirectory(sourceDirectory, zipFilePath); 18 | 19 | //解压.zip文件到目标文件夹 20 | FileCompressionHelper.ExtractZipFile(zipFilePath, extractPath); 21 | 22 | Console.WriteLine("操作完成"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /FusionCacheExercise/FusionCacheExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /FusionCacheExercise/FusionCacheService.cs: -------------------------------------------------------------------------------- 1 | using ZiggyCreatures.Caching.Fusion; 2 | 3 | namespace FusionCacheExercise 4 | { 5 | public class FusionCacheService 6 | { 7 | private readonly IFusionCache _cache; 8 | 9 | public FusionCacheService(IFusionCache cache) 10 | { 11 | _cache = cache; 12 | } 13 | 14 | public async Task GetValueAsync(string key) 15 | { 16 | var cachedValue = await _cache.GetOrDefaultAsync(key).ConfigureAwait(false); 17 | if (cachedValue != null) 18 | { 19 | cachedValue.CacheMsg = "缓存中的值"; 20 | return cachedValue; 21 | } 22 | else 23 | { 24 | //从数据库或其他数据源获取值 25 | var value = GetValueFromDataSource(key); 26 | //将值存入缓存,设置过期时间等 27 | await _cache.SetAsync(key, value, TimeSpan.FromMinutes(10)).ConfigureAwait(false); 28 | return value; 29 | } 30 | } 31 | 32 | private PersonInfo GetValueFromDataSource(string key) 33 | { 34 | var personInfo = new PersonInfo 35 | { 36 | UserName = "追逐时光者", 37 | Age = 18, 38 | Nationality = "中国", 39 | CacheMsg = "默认值" 40 | }; 41 | return personInfo; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /FusionCacheExercise/PersonInfo.cs: -------------------------------------------------------------------------------- 1 | namespace FusionCacheExercise 2 | { 3 | public class PersonInfo 4 | { 5 | public string UserName { get; set; } 6 | 7 | public int Age { get; set; } 8 | 9 | public string Nationality { get; set; } 10 | 11 | public string CacheMsg { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /FusionCacheExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using ZiggyCreatures.Caching.Fusion; 3 | 4 | namespace FusionCacheExercise 5 | { 6 | internal class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | //创建服务集合 11 | var services = new ServiceCollection(); 12 | 13 | //服务注册 14 | services.AddScoped(); 15 | var entryOptions = new FusionCacheEntryOptions().SetDuration(TimeSpan.FromMinutes(10)); 16 | services.AddFusionCache() 17 | .WithDefaultEntryOptions(entryOptions) 18 | .WithPostSetup((sp, c) => 19 | { 20 | c.DefaultEntryOptions.Duration = TimeSpan.FromMinutes(5); 21 | }); 22 | 23 | using var serviceProvider = services.BuildServiceProvider(); 24 | 25 | var myService = serviceProvider.GetRequiredService(); 26 | 27 | for (int i = 0; i < 2; i++) 28 | { 29 | var value = myService.GetValueAsync("FusionCacheExerciseKey").Result; 30 | Console.WriteLine($"{value.CacheMsg} {value.UserName},{value.Age},{value.Nationality}"); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /GenericRepositoryExercise/GenericRepositoryExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /GenericRepositoryExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using TanvirArjel.EFCore.GenericRepository; 4 | 5 | namespace GenericRepositoryExercise 6 | { 7 | internal class Program 8 | { 9 | static async Task Main(string[] args) 10 | { 11 | //设置依赖注入容器 12 | IServiceCollection services = new ServiceCollection(); 13 | services.AddScoped(); 14 | 15 | var connectionString = "Server=.;Database=MyTestDB;User Id=test;Password=123456;trustServerCertificate=true;"; 16 | services.AddDbContext(option => option.UseSqlServer(connectionString)); 17 | 18 | //注册DbConext后立即调用它 19 | services.AddGenericRepository(); 20 | 21 | IServiceProvider serviceProvider = services.BuildServiceProvider(); 22 | 23 | //从容器中获取UserInfoService实例并执行操作 24 | var userInfoService = serviceProvider.GetRequiredService(); 25 | await userInfoService.UserInfoCRUD(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /GenericRepositoryExercise/TestDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace GenericRepositoryExercise 4 | { 5 | public class TestDbContext : DbContext 6 | { 7 | public TestDbContext(DbContextOptions options) : base(options) 8 | { 9 | } 10 | 11 | public DbSet UserInfo { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /GenericRepositoryExercise/UserInfo.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace GenericRepositoryExercise 5 | { 6 | [Table("UserInfo")] 7 | public class UserInfo 8 | { 9 | [Key] 10 | public int Id { get; set; } 11 | 12 | [Required] 13 | public string Name { get; set; } 14 | 15 | [Required] 16 | public int Age { get; set; } 17 | 18 | [Required] 19 | public string Email { get; set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /GenericRepositoryExercise/UserInfoService.cs: -------------------------------------------------------------------------------- 1 | using TanvirArjel.EFCore.GenericRepository; 2 | 3 | namespace GenericRepositoryExercise 4 | { 5 | public class UserInfoService 6 | { 7 | private readonly IRepository _repository; 8 | 9 | public UserInfoService(IRepository repository) 10 | { 11 | _repository = repository; 12 | } 13 | 14 | public async Task UserInfoCRUD() 15 | { 16 | // 创建一个新用户 17 | var newUser = new UserInfo { Name = "daydayup", Age = 28, Email = "daydayup@example.com" }; 18 | await _repository.AddAsync(newUser); 19 | await _repository.SaveChangesAsync(); 20 | 21 | // 更新用户信息 22 | newUser.Email = "new_updated@example.com"; 23 | _repository.Update(newUser); 24 | await _repository.SaveChangesAsync(); 25 | 26 | // 删除用户 27 | _repository.Remove(newUser); 28 | await _repository.SaveChangesAsync(); 29 | 30 | // 查询所有用户 31 | var users = await _repository.GetListAsync(); 32 | foreach (var user in users) 33 | { 34 | Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Age: {user.Age}, Email: {user.Email}"); 35 | } 36 | 37 | //查询总数 38 | var totalCount = await _repository.GetCountAsync(); 39 | 40 | // 根据条件查询用户 41 | var filteredUsers = await _repository.GetListAsync(u => u.Age > 25); 42 | foreach (var user in filteredUsers) 43 | { 44 | Console.WriteLine($"Id: {user.Id}, Name: {user.Name}, Age: {user.Age}, Email: {user.Email}"); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /IdGeneratorExercise/IdGeneratorExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /IdGeneratorExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Yitter.IdGenerator; 2 | 3 | namespace IdGeneratorExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | #region 第一步:全局初始化(应用程序启动时执行一次) 10 | 11 | // 创建 IdGeneratorOptions 对象,可在构造函数中输入 WorkerId: 12 | // options.WorkerIdBitLength = 10; // 默认值6,限定 WorkerId 最大值为2^6-1,即默认最多支持64个节点。 13 | // options.SeqBitLength = 6; // 默认值6,限制每毫秒生成的ID个数。若生成速度超过5万个/秒,建议加大 SeqBitLength 到 10。 14 | // options.BaseTime = Your_Base_Time; // 如果要兼容老系统的雪花算法,此处应设置为老系统的BaseTime。 15 | // WorkerId:WorkerId,机器码,最重要参数,无默认值,必须 全局唯一(或相同 DataCenterId 内唯一),必须 程序设定,缺省条件(WorkerIdBitLength取默认值)时最大值63,理论最大值 2^WorkerIdBitLength-1(不同实现语言可能会限定在 65535 或 32767,原理同 WorkerIdBitLength 规则)。不同机器或不同应用实例 不能相同,你可通过应用程序配置该值,也可通过调用外部服务获取值。 16 | // ...... 其它参数参考 IdGeneratorOptions 定义。 17 | var idGeneratorOptions = new IdGeneratorOptions(1) { WorkerIdBitLength = 6 }; 18 | // 保存参数(务必调用,否则参数设置不生效): 19 | YitIdHelper.SetIdGenerator(idGeneratorOptions); 20 | // 以上过程只需全局一次,且应在生成ID之前完成。 21 | 22 | #endregion 23 | 24 | #region 第二步:生成分布式ID 25 | 26 | for (int i = 0; i < 1000; i++) 27 | { 28 | // 初始化后,在任何需要生成ID的地方,调用以下方法: 29 | var newId = YitIdHelper.NextId(); 30 | Console.WriteLine($"Number{i},{newId}"); 31 | } 32 | 33 | #endregion 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 追逐时光者 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis.Designer.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Forms; 2 | 3 | namespace MLNETExercise 4 | { 5 | partial class ImageAnalysis 6 | { 7 | /// 8 | /// Required designer variable. 9 | /// 10 | private System.ComponentModel.IContainer components = null; 11 | 12 | /// 13 | /// Clean up any resources being used. 14 | /// 15 | /// true if managed resources should be disposed; otherwise, false. 16 | protected override void Dispose(bool disposing) 17 | { 18 | if (disposing && (components != null)) 19 | { 20 | components.Dispose(); 21 | } 22 | base.Dispose(disposing); 23 | } 24 | 25 | #region Windows Form Designer generated code 26 | 27 | /// 28 | /// Required method for Designer support - do not modify 29 | /// the contents of this method with the code editor. 30 | /// 31 | private void InitializeComponent() 32 | { 33 | Btn_SelectImage = new Button(); 34 | label1 = new Label(); 35 | txt_Box = new TextBox(); 36 | pictureBox = new PictureBox(); 37 | ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); 38 | SuspendLayout(); 39 | // 40 | // Btn_SelectImage 41 | // 42 | Btn_SelectImage.Location = new Point(103, 66); 43 | Btn_SelectImage.Name = "Btn_SelectImage"; 44 | Btn_SelectImage.Size = new Size(158, 50); 45 | Btn_SelectImage.TabIndex = 0; 46 | Btn_SelectImage.Text = "选择图片"; 47 | Btn_SelectImage.UseVisualStyleBackColor = true; 48 | Btn_SelectImage.Click += Btn_SelectImage_Click; 49 | // 50 | // label1 51 | // 52 | label1.AutoSize = true; 53 | label1.Location = new Point(103, 265); 54 | label1.Name = "label1"; 55 | label1.Size = new Size(68, 17); 56 | label1.TabIndex = 1; 57 | label1.Text = "分析结果:"; 58 | // 59 | // txt_Box 60 | // 61 | txt_Box.Location = new Point(177, 262); 62 | txt_Box.Name = "txt_Box"; 63 | txt_Box.Size = new Size(162, 23); 64 | txt_Box.TabIndex = 2; 65 | // 66 | // pictureBox 67 | // 68 | pictureBox.Location = new Point(418, 43); 69 | pictureBox.Name = "pictureBox"; 70 | pictureBox.Size = new Size(336, 303); 71 | pictureBox.TabIndex = 3; 72 | pictureBox.TabStop = false; 73 | // 74 | // ImageAnalysis 75 | // 76 | AutoScaleDimensions = new SizeF(7F, 17F); 77 | AutoScaleMode = AutoScaleMode.Font; 78 | ClientSize = new Size(800, 450); 79 | Controls.Add(pictureBox); 80 | Controls.Add(txt_Box); 81 | Controls.Add(label1); 82 | Controls.Add(Btn_SelectImage); 83 | Name = "ImageAnalysis"; 84 | Text = "图像分类"; 85 | ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); 86 | ResumeLayout(false); 87 | PerformLayout(); 88 | } 89 | 90 | private void Btn_SelectImage_Click(object sender, EventArgs e) 91 | { 92 | using (OpenFileDialog openFileDialog = new OpenFileDialog()) 93 | { 94 | openFileDialog.Title = "Select Image"; 95 | openFileDialog.Filter = "Image Files (*.jpg, *.png, *.bmp)|*.jpg;*.png;*.bmp|All Files (*.*)|*.*"; 96 | 97 | if (openFileDialog.ShowDialog() == DialogResult.OK) 98 | { 99 | // 获取用户选择的文件路径 100 | string selectedImagePath = openFileDialog.FileName; 101 | 102 | // 从文件加载图片 103 | Image img = Image.FromFile(openFileDialog.FileName); 104 | this.pictureBox.Image = img; 105 | 106 | var imageBytes = File.ReadAllBytes(selectedImagePath); 107 | MLImageAnalysis.ModelInput sampleData = new MLImageAnalysis.ModelInput() 108 | { 109 | ImageSource = imageBytes, 110 | }; 111 | 112 | //Load model and predict output 113 | var result = MLImageAnalysis.Predict(sampleData); 114 | this.txt_Box.Text = result.PredictedLabel; 115 | } 116 | } 117 | } 118 | 119 | #endregion 120 | 121 | private OpenFileDialog openFileDialog; 122 | private Button Btn_SelectImage; 123 | private Label label1; 124 | private TextBox txt_Box; 125 | private PictureBox pictureBox; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Forms; 2 | 3 | namespace MLNETExercise 4 | { 5 | public partial class ImageAnalysis : Form 6 | { 7 | public ImageAnalysis() 8 | { 9 | InitializeComponent(); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/家电/jd-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/家电/jd-1.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/家电/jd-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/家电/jd-2.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/家电/jd-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/家电/jd-3.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/家电/jd-4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/家电/jd-4.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/家电/jd-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/家电/jd-5.png -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/玩具/wj-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/玩具/wj-1.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/玩具/wj-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/玩具/wj-2.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/玩具/wj-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/玩具/wj-3.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/玩具/wj-4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/玩具/wj-4.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/玩具/wj-5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/玩具/wj-5.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/食物/sw-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/食物/sw-1.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/食物/sw-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/食物/sw-2.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/食物/sw-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/食物/sw-3.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/食物/sw-4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/食物/sw-4.jpg -------------------------------------------------------------------------------- /MLNETExercise/ImageAnalysis/食物/sw-5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/ImageAnalysis/食物/sw-5.jpg -------------------------------------------------------------------------------- /MLNETExercise/MLImageAnalysis.consumption.cs: -------------------------------------------------------------------------------- 1 | // This file was auto-generated by ML.NET Model Builder. 2 | using Microsoft.ML; 3 | using Microsoft.ML.Data; 4 | using System; 5 | using System.Linq; 6 | using System.IO; 7 | using System.Collections.Generic; 8 | namespace MLNETExercise 9 | { 10 | public partial class MLImageAnalysis 11 | { 12 | /// 13 | /// model input class for MLImageAnalysis. 14 | /// 15 | #region model input class 16 | public class ModelInput 17 | { 18 | [LoadColumn(0)] 19 | [ColumnName(@"Label")] 20 | public string Label { get; set; } 21 | 22 | [LoadColumn(1)] 23 | [ColumnName(@"ImageSource")] 24 | public byte[] ImageSource { get; set; } 25 | 26 | } 27 | 28 | #endregion 29 | 30 | /// 31 | /// model output class for MLImageAnalysis. 32 | /// 33 | #region model output class 34 | public class ModelOutput 35 | { 36 | [ColumnName(@"Label")] 37 | public uint Label { get; set; } 38 | 39 | [ColumnName(@"ImageSource")] 40 | public byte[] ImageSource { get; set; } 41 | 42 | [ColumnName(@"PredictedLabel")] 43 | public string PredictedLabel { get; set; } 44 | 45 | [ColumnName(@"Score")] 46 | public float[] Score { get; set; } 47 | 48 | } 49 | 50 | #endregion 51 | 52 | private static string MLNetModelPath = Path.GetFullPath("MLImageAnalysis.mlnet"); 53 | 54 | public static readonly Lazy> PredictEngine = new Lazy>(() => CreatePredictEngine(), true); 55 | 56 | 57 | private static PredictionEngine CreatePredictEngine() 58 | { 59 | var mlContext = new MLContext(); 60 | ITransformer mlModel = mlContext.Model.Load(MLNetModelPath, out var _); 61 | return mlContext.Model.CreatePredictionEngine(mlModel); 62 | } 63 | 64 | /// 65 | /// Use this method to predict scores for all possible labels. 66 | /// 67 | /// model input. 68 | /// 69 | public static IOrderedEnumerable> PredictAllLabels(ModelInput input) 70 | { 71 | var predEngine = PredictEngine.Value; 72 | var result = predEngine.Predict(input); 73 | return GetSortedScoresWithLabels(result); 74 | } 75 | 76 | /// 77 | /// Map the unlabeled result score array to the predicted label names. 78 | /// 79 | /// Prediction to get the labeled scores from. 80 | /// Ordered list of label and score. 81 | /// 82 | public static IOrderedEnumerable> GetSortedScoresWithLabels(ModelOutput result) 83 | { 84 | var unlabeledScores = result.Score; 85 | var labelNames = GetLabels(result); 86 | 87 | Dictionary labledScores = new Dictionary(); 88 | for (int i = 0; i < labelNames.Count(); i++) 89 | { 90 | // Map the names to the predicted result score array 91 | var labelName = labelNames.ElementAt(i); 92 | labledScores.Add(labelName.ToString(), unlabeledScores[i]); 93 | } 94 | 95 | return labledScores.OrderByDescending(c => c.Value); 96 | } 97 | 98 | /// 99 | /// Get the ordered label names. 100 | /// 101 | /// Predicted result to get the labels from. 102 | /// List of labels. 103 | /// 104 | private static IEnumerable GetLabels(ModelOutput result) 105 | { 106 | var schema = PredictEngine.Value.OutputSchema; 107 | 108 | var labelColumn = schema.GetColumnOrNull("Label"); 109 | if (labelColumn == null) 110 | { 111 | throw new Exception("Label column not found. Make sure the name searched for matches the name in the schema."); 112 | } 113 | 114 | // Key values contains an ordered array of the possible labels. This allows us to map the results to the correct label value. 115 | var keyNames = new VBuffer>(); 116 | labelColumn.Value.GetKeyValues(ref keyNames); 117 | return keyNames.DenseValues().Select(x => x.ToString()); 118 | } 119 | 120 | /// 121 | /// Use this method to predict on . 122 | /// 123 | /// model input. 124 | /// 125 | public static ModelOutput Predict(ModelInput input) 126 | { 127 | var predEngine = PredictEngine.Value; 128 | return predEngine.Predict(input); 129 | } 130 | 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /MLNETExercise/MLImageAnalysis.mbconfig: -------------------------------------------------------------------------------- 1 | { 2 | "Scenario": "ImageClassification", 3 | "DataSource": { 4 | "Type": "Folder", 5 | "Version": 1, 6 | "FolderPath": "D:\\Desktop\\ImageAnalysis" 7 | }, 8 | "Environment": { 9 | "Type": "LocalCPU", 10 | "Version": 1 11 | }, 12 | "RunHistory": { 13 | "Version": 3, 14 | "Type": "Result", 15 | "Trials": [ 16 | { 17 | "Version": 1, 18 | "Type": "Trial", 19 | "TrainerName": "ImageClassificationMulti", 20 | "Score": 0.0, 21 | "RuntimeInSeconds": 15.067, 22 | "Parameter": { 23 | "_SCHEMA_": "e0 * e1 * e2", 24 | "e0": { 25 | "OutputColumnName": "Label", 26 | "InputColumnName": "Label", 27 | "AddKeyValueAnnotationsAsText": false 28 | }, 29 | "e1": { 30 | "LabelColumnName": "Label", 31 | "ScoreColumnName": "Score", 32 | "FeatureColumnName": "ImageSource", 33 | "Arch": "ResnetV250", 34 | "BatchSize": 10, 35 | "Epoch": 200 36 | }, 37 | "e2": { 38 | "OutputColumnName": "PredictedLabel", 39 | "InputColumnName": "PredictedLabel" 40 | } 41 | } 42 | } 43 | ], 44 | "Estimators": { 45 | "e0": "MapValueToKey", 46 | "e1": "ImageClassificationMulti", 47 | "e2": "MapKeyToValue" 48 | }, 49 | "Schema": "e0 * e1 * e2", 50 | "MetricName": "MicroAccuracy", 51 | "ModelFilePath": "D:\\DotNetExercises\\MLNETExercise\\MLImageAnalysis.mlnet" 52 | }, 53 | "Type": "TrainingConfig", 54 | "Version": 4, 55 | "TrainingOption": { 56 | "Version": 1, 57 | "Type": "ClassificationTrainingOption", 58 | "TrainingTime": 2147483647, 59 | "ValidationOption": { 60 | "Version": 0, 61 | "Type": "TrainValidateSplitValidationOption", 62 | "SplitRatio": 0.2 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /MLNETExercise/MLImageAnalysis.mlnet: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MLNETExercise/MLImageAnalysis.mlnet -------------------------------------------------------------------------------- /MLNETExercise/MLImageAnalysis.training.cs: -------------------------------------------------------------------------------- 1 | // This file was auto-generated by ML.NET Model Builder. 2 | using System; 3 | using System.IO; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Microsoft.ML.Data; 9 | using Microsoft.ML.Vision; 10 | using Microsoft.ML; 11 | 12 | namespace MLNETExercise 13 | { 14 | public partial class MLImageAnalysis 15 | { 16 | 17 | 18 | /// 19 | /// Load an IDataView from a folder path. 20 | /// 21 | /// The common context for all ML.NET operations. 22 | /// Folder to the image data for training. 23 | public static IDataView LoadImageFromFolder(MLContext mlContext, string folder) 24 | { 25 | var res = new List(); 26 | var allowedImageExtensions = new[] { ".png", ".jpg", ".jpeg", ".gif" }; 27 | DirectoryInfo rootDirectoryInfo = new DirectoryInfo(folder); 28 | DirectoryInfo[] subDirectories = rootDirectoryInfo.GetDirectories(); 29 | 30 | if (subDirectories.Length == 0) 31 | { 32 | throw new Exception("fail to find subdirectories"); 33 | } 34 | 35 | foreach (DirectoryInfo directory in subDirectories) 36 | { 37 | var imageList = directory.EnumerateFiles().Where(f => allowedImageExtensions.Contains(f.Extension.ToLower())); 38 | if (imageList.Count() > 0) 39 | { 40 | res.AddRange(imageList.Select(i => new ModelInput 41 | { 42 | Label = directory.Name, 43 | ImageSource = File.ReadAllBytes(i.FullName), 44 | })); 45 | } 46 | } 47 | return mlContext.Data.LoadFromEnumerable(res); 48 | } 49 | 50 | /// 51 | /// Retrains model using the pipeline generated as part of the training process. 52 | /// 53 | /// 54 | /// 55 | /// 56 | public static ITransformer RetrainModel(MLContext mlContext, IDataView trainData) 57 | { 58 | var pipeline = BuildPipeline(mlContext); 59 | var model = pipeline.Fit(trainData); 60 | 61 | return model; 62 | } 63 | 64 | 65 | /// 66 | /// build the pipeline that is used from model builder. Use this function to retrain model. 67 | /// 68 | /// 69 | /// 70 | public static IEstimator BuildPipeline(MLContext mlContext) 71 | { 72 | // Data process configuration with pipeline data transformations 73 | var pipeline = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName:@"Label",inputColumnName:@"Label",addKeyValueAnnotationsAsText:false) 74 | .Append(mlContext.MulticlassClassification.Trainers.ImageClassification(labelColumnName:@"Label",scoreColumnName:@"Score",featureColumnName:@"ImageSource")) 75 | .Append(mlContext.Transforms.Conversion.MapKeyToValue(outputColumnName:@"PredictedLabel",inputColumnName:@"PredictedLabel")); 76 | 77 | return pipeline; 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /MLNETExercise/MLNETExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | WinExe 4 | net8.0-windows 5 | enable 6 | true 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | -------------------------------------------------------------------------------- /MLNETExercise/Program.cs: -------------------------------------------------------------------------------- 1 | namespace MLNETExercise 2 | { 3 | internal static class Program 4 | { 5 | /// 6 | /// The main entry point for the application. 7 | /// 8 | [STAThread] 9 | static void Main() 10 | { 11 | // To customize application configuration such as set high DPI settings or default font, 12 | // see https://aka.ms/applicationconfiguration. 13 | ApplicationConfiguration.Initialize(); 14 | Application.Run(new ImageAnalysis()); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /MapsuiExercise/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /MapsuiExercise/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 |
3 | 6 | 7 |
8 |
9 | About 10 |
11 | 12 |
13 | @Body 14 |
15 |
16 |
17 | -------------------------------------------------------------------------------- /MapsuiExercise/Layout/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row { 41 | justify-content: space-between; 42 | } 43 | 44 | .top-row ::deep a, .top-row ::deep .btn-link { 45 | margin-left: 0; 46 | } 47 | } 48 | 49 | @media (min-width: 641px) { 50 | .page { 51 | flex-direction: row; 52 | } 53 | 54 | .sidebar { 55 | width: 250px; 56 | height: 100vh; 57 | position: sticky; 58 | top: 0; 59 | } 60 | 61 | .top-row { 62 | position: sticky; 63 | top: 0; 64 | z-index: 1; 65 | } 66 | 67 | .top-row.auth ::deep a:first-child { 68 | flex: 1; 69 | text-align: right; 70 | width: 0; 71 | } 72 | 73 | .top-row, article { 74 | padding-left: 2rem !important; 75 | padding-right: 1.5rem !important; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /MapsuiExercise/Layout/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  9 | 10 | 19 | 20 | @code { 21 | private bool collapseNavMenu = true; 22 | 23 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 24 | 25 | private void ToggleNavMenu() 26 | { 27 | collapseNavMenu = !collapseNavMenu; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /MapsuiExercise/Layout/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .bi { 15 | display: inline-block; 16 | position: relative; 17 | width: 1.25rem; 18 | height: 1.25rem; 19 | margin-right: 0.75rem; 20 | top: -1px; 21 | background-size: cover; 22 | } 23 | 24 | .bi-house-door-fill-nav-menu { 25 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E"); 26 | } 27 | 28 | .bi-plus-square-fill-nav-menu { 29 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E"); 30 | } 31 | 32 | .bi-list-nested-nav-menu { 33 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); 34 | } 35 | 36 | .nav-item { 37 | font-size: 0.9rem; 38 | padding-bottom: 0.5rem; 39 | } 40 | 41 | .nav-item:first-of-type { 42 | padding-top: 1rem; 43 | } 44 | 45 | .nav-item:last-of-type { 46 | padding-bottom: 1rem; 47 | } 48 | 49 | .nav-item ::deep a { 50 | color: #d7d7d7; 51 | border-radius: 4px; 52 | height: 3rem; 53 | display: flex; 54 | align-items: center; 55 | line-height: 3rem; 56 | } 57 | 58 | .nav-item ::deep a.active { 59 | background-color: rgba(255,255,255,0.37); 60 | color: white; 61 | } 62 | 63 | .nav-item ::deep a:hover { 64 | background-color: rgba(255,255,255,0.1); 65 | color: white; 66 | } 67 | 68 | @media (min-width: 641px) { 69 | .navbar-toggler { 70 | display: none; 71 | } 72 | 73 | .collapse { 74 | /* Never collapse the sidebar for wide screens */ 75 | display: block; 76 | } 77 | 78 | .nav-scrollable { 79 | /* Allow sidebar to scroll for tall menus */ 80 | height: calc(100vh - 3.5rem); 81 | overflow-y: auto; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /MapsuiExercise/MapsuiExercise.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /MapsuiExercise/Pages/Counter.razor: -------------------------------------------------------------------------------- 1 | @page "/counter" 2 | 3 | Counter 4 | 5 |

Counter

6 | 7 |

Current count: @currentCount

8 | 9 | 10 | 11 | @code { 12 | private int currentCount = 0; 13 | 14 | private void IncrementCount() 15 | { 16 | currentCount++; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /MapsuiExercise/Pages/Home.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @using Mapsui.UI.Blazor 3 | 4 | MapsuiExercise 5 |
6 |
7 |
8 | 9 |
10 |
11 |
12 | 13 | 19 | 20 | @code 21 | { 22 | private MapControl? _mapControl; 23 | protected override void OnAfterRender(bool firstRender) 24 | { 25 | base.OnAfterRender(firstRender); 26 | if (firstRender) 27 | { 28 | if (_mapControl != null) 29 | _mapControl.Map?.Layers.Add(Mapsui.Tiling.OpenStreetMap.CreateTileLayer()); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MapsuiExercise/Pages/Weather.razor: -------------------------------------------------------------------------------- 1 | @page "/weather" 2 | @inject HttpClient Http 3 | 4 | Weather 5 | 6 |

Weather

7 | 8 |

This component demonstrates fetching data from the server.

9 | 10 | @if (forecasts == null) 11 | { 12 |

Loading...

13 | } 14 | else 15 | { 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | @foreach (var forecast in forecasts) 27 | { 28 | 29 | 30 | 31 | 32 | 33 | 34 | } 35 | 36 |
DateTemp. (C)Temp. (F)Summary
@forecast.Date.ToShortDateString()@forecast.TemperatureC@forecast.TemperatureF@forecast.Summary
37 | } 38 | 39 | @code { 40 | private WeatherForecast[]? forecasts; 41 | 42 | protected override async Task OnInitializedAsync() 43 | { 44 | forecasts = await Http.GetFromJsonAsync("sample-data/weather.json"); 45 | } 46 | 47 | public class WeatherForecast 48 | { 49 | public DateOnly Date { get; set; } 50 | 51 | public int TemperatureC { get; set; } 52 | 53 | public string? Summary { get; set; } 54 | 55 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /MapsuiExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Web; 2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 3 | 4 | namespace MapsuiExercise 5 | { 6 | public class Program 7 | { 8 | public static async Task Main(string[] args) 9 | { 10 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 11 | builder.RootComponents.Add("#app"); 12 | builder.RootComponents.Add("head::after"); 13 | 14 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 15 | 16 | await builder.Build().RunAsync(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MapsuiExercise/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:3030", 8 | "sslPort": 44396 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 17 | "applicationUrl": "http://localhost:5019", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "https": { 23 | "commandName": "Project", 24 | "dotnetRunMessages": true, 25 | "launchBrowser": true, 26 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 27 | "applicationUrl": "https://localhost:7268;http://localhost:5019", 28 | "environmentVariables": { 29 | "ASPNETCORE_ENVIRONMENT": "Development" 30 | } 31 | }, 32 | "IIS Express": { 33 | "commandName": "IISExpress", 34 | "launchBrowser": true, 35 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 36 | "environmentVariables": { 37 | "ASPNETCORE_ENVIRONMENT": "Development" 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /MapsuiExercise/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 8 | @using Microsoft.JSInterop 9 | @using MapsuiExercise 10 | @using MapsuiExercise.Layout 11 | -------------------------------------------------------------------------------- /MapsuiExercise/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 3 | } 4 | 5 | h1:focus { 6 | outline: none; 7 | } 8 | 9 | a, .btn-link { 10 | color: #0071c1; 11 | } 12 | 13 | .btn-primary { 14 | color: #fff; 15 | background-color: #1b6ec2; 16 | border-color: #1861ac; 17 | } 18 | 19 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 20 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 21 | } 22 | 23 | .content { 24 | padding-top: 1.1rem; 25 | } 26 | 27 | .valid.modified:not([type=checkbox]) { 28 | outline: 1px solid #26b050; 29 | } 30 | 31 | .invalid { 32 | outline: 1px solid red; 33 | } 34 | 35 | .validation-message { 36 | color: red; 37 | } 38 | 39 | #blazor-error-ui { 40 | background: lightyellow; 41 | bottom: 0; 42 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 43 | display: none; 44 | left: 0; 45 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 46 | position: fixed; 47 | width: 100%; 48 | z-index: 1000; 49 | } 50 | 51 | #blazor-error-ui .dismiss { 52 | cursor: pointer; 53 | position: absolute; 54 | right: 0.75rem; 55 | top: 0.5rem; 56 | } 57 | 58 | .blazor-error-boundary { 59 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 60 | padding: 1rem 1rem 1rem 3.7rem; 61 | color: white; 62 | } 63 | 64 | .blazor-error-boundary::after { 65 | content: "An error has occurred." 66 | } 67 | 68 | .loading-progress { 69 | position: relative; 70 | display: block; 71 | width: 8rem; 72 | height: 8rem; 73 | margin: 20vh auto 1rem auto; 74 | } 75 | 76 | .loading-progress circle { 77 | fill: none; 78 | stroke: #e0e0e0; 79 | stroke-width: 0.6rem; 80 | transform-origin: 50% 50%; 81 | transform: rotate(-90deg); 82 | } 83 | 84 | .loading-progress circle:last-child { 85 | stroke: #1b6ec2; 86 | stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; 87 | transition: stroke-dasharray 0.05s ease-in-out; 88 | } 89 | 90 | .loading-progress-text { 91 | position: absolute; 92 | text-align: center; 93 | font-weight: bold; 94 | inset: calc(20vh + 3.25rem) 0 auto 0.2rem; 95 | } 96 | 97 | .loading-progress-text:after { 98 | content: var(--blazor-load-percentage-text, "Loading"); 99 | } 100 | 101 | code { 102 | color: #c02d76; 103 | } 104 | -------------------------------------------------------------------------------- /MapsuiExercise/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MapsuiExercise/wwwroot/favicon.png -------------------------------------------------------------------------------- /MapsuiExercise/wwwroot/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/MapsuiExercise/wwwroot/icon-192.png -------------------------------------------------------------------------------- /MapsuiExercise/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | MapsuiExercise 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 |
22 |
23 | 24 |
25 | An unhandled error has occurred. 26 | Reload 27 | 🗙 28 |
29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /MapsuiExercise/wwwroot/sample-data/weather.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "date": "2022-01-06", 4 | "temperatureC": 1, 5 | "summary": "Freezing" 6 | }, 7 | { 8 | "date": "2022-01-07", 9 | "temperatureC": 14, 10 | "summary": "Bracing" 11 | }, 12 | { 13 | "date": "2022-01-08", 14 | "temperatureC": -13, 15 | "summary": "Freezing" 16 | }, 17 | { 18 | "date": "2022-01-09", 19 | "temperatureC": -16, 20 | "summary": "Balmy" 21 | }, 22 | { 23 | "date": "2022-01-10", 24 | "temperatureC": -2, 25 | "summary": "Chilly" 26 | } 27 | ] 28 | -------------------------------------------------------------------------------- /MethodTimerExercise/FodyWeavers.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | -------------------------------------------------------------------------------- /MethodTimerExercise/FodyWeavers.xsd: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed. 12 | 13 | 14 | 15 | 16 | A comma-separated list of error codes that can be safely ignored in assembly verification. 17 | 18 | 19 | 20 | 21 | 'false' to turn off automatic generation of the XML Schema file. 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /MethodTimerExercise/MethodTimerExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /MethodTimerExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using MethodTimer; 2 | using System.Reflection; 3 | 4 | namespace MethodTimerExercise 5 | { 6 | internal class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | TimeMethod(); 11 | } 12 | 13 | [Time] 14 | public static void TimeMethod() 15 | { 16 | for (int i = 0; i < 100; i++) 17 | { 18 | Console.WriteLine($"输出结果{i}"); 19 | } 20 | } 21 | 22 | /// 23 | /// 运行耗时为long(毫秒) 24 | /// 25 | public static class MethodTimeLogger1 26 | { 27 | public static void Log(MethodBase methodBase, long milliseconds, string message) 28 | { 29 | Console.WriteLine($"方法:{methodBase.Name} 耗时:{milliseconds} 毫秒,信息:{message}"); 30 | } 31 | } 32 | 33 | /// 34 | /// 运行耗时为TimeSpan 35 | /// 36 | public static class MethodTimeLogger 37 | { 38 | public static void Log(MethodBase methodBase, TimeSpan elapsed, string message) 39 | { 40 | Console.WriteLine($"方法:{methodBase.Name} 耗时:{elapsed.TotalMilliseconds} 毫秒,信息:{message}"); 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /MoqExercise/IUserInfo.cs: -------------------------------------------------------------------------------- 1 | namespace MoqExercise 2 | { 3 | public interface IUserInfo 4 | { 5 | string UserName { get; set; } 6 | int Age { get; set; } 7 | 8 | string GetUserData(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /MoqExercise/MoqExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /MoqExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Moq; 2 | 3 | namespace MoqExercise 4 | { 5 | public class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | UserInfoTest(); 10 | VerifyTest(); 11 | TestThrowException(); 12 | } 13 | 14 | public static void UserInfoTest() 15 | { 16 | // 创建 IUserInfo 的模拟对象 17 | var mockUserInfo = new Mock(); 18 | 19 | // 设置模拟对象的属性值 20 | mockUserInfo.SetupProperty(u => u.UserName, "大姚"); 21 | mockUserInfo.SetupProperty(u => u.Age, 27); 22 | 23 | // 设置 GetUserData 方法的返回值 24 | mockUserInfo.Setup(u => u.GetUserData()).Returns("UserName: 大姚, Age: 25"); 25 | 26 | // 获取模拟对象的实例 27 | var userInfo = mockUserInfo.Object; 28 | 29 | // 调用方法并输出结果 30 | Console.WriteLine(userInfo.GetUserData()); 31 | Console.WriteLine("UserName: {0}, Age: {1}", userInfo.UserName, userInfo.Age); 32 | } 33 | 34 | public static void VerifyTest() 35 | { 36 | // 创建模拟对象 37 | var serviceMock = new Mock(); 38 | 39 | // 创建被测试对象并注入模拟对象 40 | var serviceClient = new VerifyServiceClient(serviceMock.Object); 41 | 42 | // 执行测试 43 | serviceClient.Execute([1, 2, 3]); 44 | 45 | // 验证方法调用次数和参数 46 | serviceMock.Verify(x => x.Process(1)); 47 | serviceMock.Verify(x => x.Process(3)); 48 | serviceMock.Verify(x => x.Process(2)); 49 | //serviceMock.Verify(x => x.Process(12)); //这里会抛出异常,表示验证失败 50 | 51 | // 如果运行到这里没有抛出异常,表示验证通过 52 | Console.WriteLine("验证通过!"); 53 | } 54 | 55 | public static void TestThrowException() 56 | { 57 | // 创建 IUserInfo 的模拟对象 58 | var mockUserInfo = new Mock(); 59 | 60 | // 设置 GetUserData 方法在调用时抛出异常 61 | mockUserInfo.Setup(x => x.GetUserData()).Throws(new Exception("模拟的异常")); 62 | 63 | // 获取模拟对象的实例 64 | var userInfo = mockUserInfo.Object.GetUserData(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /MoqExercise/VerifyServiceClient.cs: -------------------------------------------------------------------------------- 1 | namespace MoqExercise 2 | { 3 | public interface IVerifyService 4 | { 5 | void Process(int value); 6 | } 7 | 8 | public class VerifyServiceClient 9 | { 10 | private readonly IVerifyService _service; 11 | 12 | public VerifyServiceClient(IVerifyService service) 13 | { 14 | _service = service; 15 | } 16 | 17 | public void Execute(int[] values) 18 | { 19 | foreach (var value in values) 20 | { 21 | _service.Process(value); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /QrCodeGeneratorExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Net.Codecrete.QrCodeGenerator; 2 | using SkiaSharp; 3 | using System.Text; 4 | 5 | namespace QrCodeGeneratorExercise 6 | { 7 | internal class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | //生成二维码并保存为png 12 | var test1 = QrCode.EncodeText("追逐时光者!!!", QrCode.Ecc.Medium); 13 | test1.SaveAsPng("test1-qr-code.png", 10, 3); 14 | 15 | //生成带颜色的二维码并保存为png 16 | var test2 = QrCode.EncodeText("追逐时光者!!!", QrCode.Ecc.High); 17 | test2.SaveAsPng("test2-qr-code.png", 12, 4, 18 | foreground: SKColor.Parse("#628bb5"), 19 | background: SKColor.Parse("#ffffff")); 20 | 21 | //生成二维码并保存为svg 22 | var test3 = QrCode.EncodeText("追逐时光者!!!", QrCode.Ecc.Medium); 23 | var svg = test3.ToSvgString(4); 24 | File.WriteAllText("test3-qr-code.svg", svg, Encoding.UTF8); 25 | 26 | //生成带颜色的二维码并保存为svg 27 | var test4 = QrCode.EncodeText("追逐时光者!!!", QrCode.Ecc.Medium); 28 | var svg1 = test4.ToSvgString(4, "#98b2cd", "#ffffff"); 29 | File.WriteAllText("test4-qr-code.svg", svg1, Encoding.UTF8); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /QrCodeGeneratorExercise/QrCodeBitmapExtensions.cs: -------------------------------------------------------------------------------- 1 | using Net.Codecrete.QrCodeGenerator; 2 | using SkiaSharp; 3 | 4 | namespace QrCodeGeneratorExercise 5 | { 6 | public static class QrCodeBitmapExtensions 7 | { 8 | /// 9 | /// The background color. 10 | /// The foreground color. 11 | public static SKBitmap ToBitmap(this QrCode qrCode, int scale, int border, SKColor foreground, SKColor background) 12 | { 13 | // check arguments 14 | if (scale <= 0) 15 | { 16 | throw new ArgumentOutOfRangeException(nameof(scale), "Value out of range"); 17 | } 18 | if (border < 0) 19 | { 20 | throw new ArgumentOutOfRangeException(nameof(border), "Value out of range"); 21 | } 22 | 23 | int size = qrCode.Size; 24 | int dim = (size + border * 2) * scale; 25 | 26 | if (dim > short.MaxValue) 27 | { 28 | throw new ArgumentOutOfRangeException(nameof(scale), "Scale or border too large"); 29 | } 30 | 31 | // create bitmap 32 | SKBitmap bitmap = new SKBitmap(dim, dim, SKColorType.Rgb888x, SKAlphaType.Opaque); 33 | 34 | using (SKCanvas canvas = new SKCanvas(bitmap)) 35 | { 36 | // draw background 37 | using (SKPaint paint = new SKPaint { Color = background }) 38 | { 39 | canvas.DrawRect(0, 0, dim, dim, paint); 40 | } 41 | 42 | // draw modules 43 | using (SKPaint paint = new SKPaint { Color = foreground }) 44 | { 45 | for (int y = 0; y < size; y++) 46 | { 47 | for (int x = 0; x < size; x++) 48 | { 49 | if (qrCode.GetModule(x, y)) 50 | { 51 | canvas.DrawRect((x + border) * scale, (y + border) * scale, scale, scale, paint); 52 | } 53 | } 54 | } 55 | } 56 | } 57 | 58 | return bitmap; 59 | } 60 | 61 | /// 62 | /// Creates a bitmap (raster image) of this QR code. 63 | /// 64 | /// The parameter specifies the scale of the image, which is 65 | /// equivalent to the width and height of each QR code module. Additionally, the number 66 | /// of modules to add as a border to all four sides can be specified. 67 | /// 68 | /// 69 | /// For example, ToBitmap(scale: 10, border: 4) means to pad the QR code with 4 white 70 | /// border modules on all four sides, and use 10×10 pixels to represent each module. 71 | /// 72 | /// 73 | /// The resulting bitmap uses the pixel format . 74 | /// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF). 75 | /// 76 | /// 77 | /// The width and height, in pixels, of each module. 78 | /// The number of border modules to add to each of the four sides. 79 | /// The created bitmap representing this QR code. 80 | /// is 0 or negative, is negative 81 | /// or the resulting image is wider than 32,768 pixels. 82 | public static SKBitmap ToBitmap(this QrCode qrCode, int scale, int border) 83 | { 84 | return qrCode.ToBitmap(scale, border, SKColors.Black, SKColors.White); 85 | } 86 | 87 | /// 88 | /// The background color. 89 | /// The foreground color. 90 | public static byte[] ToPng(this QrCode qrCode, int scale, int border, SKColor foreground, SKColor background) 91 | { 92 | using SKBitmap bitmap = qrCode.ToBitmap(scale, border, foreground, background); 93 | using SKData data = bitmap.Encode(SKEncodedImageFormat.Png, 90); 94 | return data.ToArray(); 95 | } 96 | 97 | /// 98 | /// Creates a PNG image of this QR code and returns it as a byte array. 99 | /// 100 | /// The parameter specifies the scale of the image, which is 101 | /// equivalent to the width and height of each QR code module. Additionally, the number 102 | /// of modules to add as a border to all four sides can be specified. 103 | /// 104 | /// 105 | /// For example, ToPng(scale: 10, border: 4) means to pad the QR code with 4 white 106 | /// border modules on all four sides, and use 10×10 pixels to represent each module. 107 | /// 108 | /// 109 | /// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF). 110 | /// 111 | /// 112 | /// The width and height, in pixels, of each module. 113 | /// The number of border modules to add to each of the four sides. 114 | /// The created bitmap representing this QR code. 115 | /// is 0 or negative, is negative 116 | /// or the resulting image is wider than 32,768 pixels. 117 | public static byte[] ToPng(this QrCode qrCode, int scale, int border) 118 | { 119 | return qrCode.ToPng(scale, border, SKColors.Black, SKColors.White); 120 | } 121 | 122 | /// 123 | /// The background color. 124 | /// The foreground color. 125 | public static void SaveAsPng(this QrCode qrCode, string filename, int scale, int border, SKColor foreground, SKColor background) 126 | { 127 | using SKBitmap bitmap = qrCode.ToBitmap(scale, border, foreground, background); 128 | using SKData data = bitmap.Encode(SKEncodedImageFormat.Png, 90); 129 | using FileStream stream = File.OpenWrite(filename); 130 | data.SaveTo(stream); 131 | } 132 | 133 | /// 134 | /// Saves this QR code as a PNG file. 135 | /// 136 | /// The parameter specifies the scale of the image, which is 137 | /// equivalent to the width and height of each QR code module. Additionally, the number 138 | /// of modules to add as a border to all four sides can be specified. 139 | /// 140 | /// 141 | /// For example, SaveAsPng("qrcode.png", scale: 10, border: 4) means to pad the QR code with 4 white 142 | /// border modules on all four sides, and use 10×10 pixels to represent each module. 143 | /// 144 | /// 145 | /// If not specified, the foreground color is black (0x000000) und the background color always white (0xFFFFFF). 146 | /// 147 | /// 148 | /// The width and height, in pixels, of each module. 149 | /// The number of border modules to add to each of the four sides. 150 | /// is 0 or negative, is negative 151 | /// or the resulting image is wider than 32,768 pixels. 152 | public static void SaveAsPng(this QrCode qrCode, string filename, int scale, int border) 153 | { 154 | qrCode.SaveAsPng(filename, scale, border, SKColors.Black, SKColors.White); 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /QrCodeGeneratorExercise/QrCodeGeneratorExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /QuestPDFExercise/CreateInvoiceDetails.cs: -------------------------------------------------------------------------------- 1 | namespace QuestPDFExercise 2 | { 3 | public class CreateInvoiceDetails 4 | { 5 | private static readonly Random _random = new Random(); 6 | 7 | public enum InvoiceType 8 | { 9 | 餐饮费, 10 | 交通费, 11 | 住宿费, 12 | 日用品, 13 | 娱乐费, 14 | 医疗费, 15 | 通讯费, 16 | 教育费, 17 | 装修费, 18 | 旅游费 19 | } 20 | 21 | /// 22 | /// 获取发票详情数据 23 | /// 24 | /// 25 | public static InvoiceModel GetInvoiceDetails() 26 | { 27 | return new InvoiceModel 28 | { 29 | InvoiceNumber = _random.Next(1_000, 10_000), 30 | IssueDate = DateTime.Now, 31 | DueDate = DateTime.Now + TimeSpan.FromDays(14), 32 | SellerCompanyName = "追逐时光者", 33 | CustomerCompanyName = "DotNetGuide技术社区", 34 | OrderItems = Enumerable 35 | .Range(1, 20) 36 | .Select(_ => GenerateRandomOrderItemInfo()) 37 | .ToList(), 38 | Comments = "DotNetGuide技术社区是一个面向.NET开发者的开源技术社区,旨在为开发者们提供全面的C#/.NET/.NET Core相关学习资料、技术分享和咨询、项目推荐、招聘资讯和解决问题的平台。在这个社区中,开发者们可以分享自己的技术文章、项目经验、遇到的疑难技术问题以及解决方案,并且还有机会结识志同道合的开发者。我们致力于构建一个积极向上、和谐友善的.NET技术交流平台,为广大.NET开发者带来更多的价值和成长机会。" 39 | }; 40 | } 41 | 42 | /// 43 | /// 订单信息生成 44 | /// 45 | /// 46 | private static OrderItem GenerateRandomOrderItemInfo() 47 | { 48 | var types = (InvoiceType[])Enum.GetValues(typeof(InvoiceType)); 49 | return new OrderItem 50 | { 51 | Name = types[_random.Next(types.Length)].ToString(), 52 | Price = (decimal)Math.Round(_random.NextDouble() * 100, 2), 53 | Quantity = _random.Next(1, 10) 54 | }; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /QuestPDFExercise/CreateInvoiceDocument.cs: -------------------------------------------------------------------------------- 1 | using QuestPDF.Fluent; 2 | using QuestPDF.Helpers; 3 | using QuestPDF.Infrastructure; 4 | 5 | namespace QuestPDFExercise 6 | { 7 | public class CreateInvoiceDocument : IDocument 8 | { 9 | /// 10 | /// 获取Logo的的Image对象 11 | /// 12 | public static Image LogoImage { get; } = Image.FromFile("dotnetguide.png"); 13 | 14 | public InvoiceModel Model { get; } 15 | 16 | public CreateInvoiceDocument(InvoiceModel model) 17 | { 18 | Model = model; 19 | } 20 | 21 | public DocumentMetadata GetMetadata() => DocumentMetadata.Default; 22 | 23 | public void Compose(IDocumentContainer container) 24 | { 25 | container 26 | .Page(page => 27 | { 28 | //设置页面的边距 29 | page.Margin(50); 30 | 31 | //字体默认大小18号字体 32 | page.DefaultTextStyle(x => x.FontSize(18)); 33 | 34 | //页眉部分 35 | page.Header().Element(BuildHeaderInfo); 36 | 37 | //内容部分 38 | page.Content().Element(BuildContentInfo); 39 | 40 | //页脚部分 41 | page.Footer().AlignCenter().Text(text => 42 | { 43 | text.CurrentPageNumber(); 44 | text.Span(" / "); 45 | text.TotalPages(); 46 | }); 47 | }); 48 | } 49 | 50 | #region 构建页眉部分 51 | void BuildHeaderInfo(IContainer container) 52 | { 53 | container.Row(row => 54 | { 55 | row.RelativeItem().Column(column => 56 | { 57 | column.Item().Text($"发票编号 #{Model.InvoiceNumber}").FontFamily("fangsong").FontSize(20).SemiBold().FontColor(Colors.Blue.Medium); 58 | 59 | column.Item().Text(text => 60 | { 61 | text.Span("发行日期: ").FontFamily("fangsong").FontSize(13).SemiBold(); 62 | text.Span($"{Model.IssueDate:d}"); 63 | }); 64 | 65 | column.Item().Text(text => 66 | { 67 | text.Span("终止日期: ").FontFamily("fangsong").FontSize(13).SemiBold(); 68 | text.Span($"{Model.DueDate:d}"); 69 | }); 70 | }); 71 | 72 | //在当前行的常量项中插入一个图像 73 | row.ConstantItem(130).Image(LogoImage); 74 | }); 75 | } 76 | 77 | #endregion 78 | 79 | #region 构建内容部分 80 | 81 | void BuildContentInfo(IContainer container) 82 | { 83 | container.PaddingVertical(40).Column(column => 84 | { 85 | column.Spacing(20); 86 | 87 | column.Item().Row(row => 88 | { 89 | row.RelativeItem().Component(new AddressComponent("卖方公司名称", Model.SellerCompanyName)); 90 | row.ConstantItem(50); 91 | row.RelativeItem().Component(new AddressComponent("客户公司名称", Model.CustomerCompanyName)); 92 | }); 93 | 94 | column.Item().Element(CreateTable); 95 | 96 | var totalPrice = Model.OrderItems.Sum(x => x.Price * x.Quantity); 97 | column.Item().PaddingRight(5).AlignRight().Text($"总计: {totalPrice}").FontFamily("fangsong").SemiBold(); 98 | 99 | if (!string.IsNullOrWhiteSpace(Model.Comments)) 100 | column.Item().PaddingTop(25).Element(BuildComments); 101 | }); 102 | } 103 | 104 | /// 105 | /// 创建表格 106 | /// 107 | /// container 108 | void CreateTable(IContainer container) 109 | { 110 | var headerStyle = TextStyle.Default.SemiBold(); 111 | 112 | container.Table(table => 113 | { 114 | table.ColumnsDefinition(columns => 115 | { 116 | columns.ConstantColumn(25); 117 | columns.RelativeColumn(3); 118 | columns.RelativeColumn(); 119 | columns.RelativeColumn(); 120 | columns.RelativeColumn(); 121 | }); 122 | 123 | table.Header(header => 124 | { 125 | header.Cell().Text("#").FontFamily("fangsong"); 126 | header.Cell().Text("消费类型").Style(headerStyle).FontFamily("fangsong"); 127 | header.Cell().AlignRight().Text("花费金额").Style(headerStyle).FontFamily("fangsong"); 128 | header.Cell().AlignRight().Text("数量").Style(headerStyle).FontFamily("fangsong"); 129 | header.Cell().AlignRight().Text("总金额").Style(headerStyle).FontFamily("fangsong"); 130 | //设置了表头单元格的属性 131 | header.Cell().ColumnSpan(5).PaddingTop(5).BorderBottom(1).BorderColor(Colors.Black); 132 | }); 133 | 134 | foreach (var item in Model.OrderItems) 135 | { 136 | var index = Model.OrderItems.IndexOf(item) + 1; 137 | 138 | table.Cell().Element(CellStyle).Text($"{index}").FontFamily("fangsong"); 139 | table.Cell().Element(CellStyle).Text(item.Name).FontFamily("fangsong"); 140 | table.Cell().Element(CellStyle).AlignRight().Text($"{item.Price}").FontFamily("fangsong"); 141 | table.Cell().Element(CellStyle).AlignRight().Text($"{item.Quantity}").FontFamily("fangsong"); 142 | table.Cell().Element(CellStyle).AlignRight().Text($"{item.Price * item.Quantity}").FontFamily("fangsong"); 143 | static IContainer CellStyle(IContainer container) => container.BorderBottom(1).BorderColor(Colors.Grey.Lighten2).PaddingVertical(5); 144 | } 145 | }); 146 | } 147 | 148 | #endregion 149 | 150 | #region 构建页脚部分 151 | 152 | void BuildComments(IContainer container) 153 | { 154 | container.ShowEntire().Background(Colors.Grey.Lighten3).Padding(10).Column(column => 155 | { 156 | column.Spacing(5); 157 | column.Item().Text("DotNetGuide技术社区介绍").FontSize(14).FontFamily("fangsong").SemiBold(); 158 | column.Item().Text(Model.Comments).FontFamily("fangsong"); 159 | }); 160 | } 161 | 162 | #endregion 163 | } 164 | 165 | public class AddressComponent : IComponent 166 | { 167 | private string Title { get; } 168 | private string CompanyName { get; } 169 | 170 | public AddressComponent(string title, string companyName) 171 | { 172 | Title = title; 173 | CompanyName = companyName; 174 | } 175 | 176 | public void Compose(IContainer container) 177 | { 178 | container.ShowEntire().Column(column => 179 | { 180 | column.Spacing(2); 181 | 182 | column.Item().Text(Title).FontFamily("fangsong").SemiBold(); 183 | column.Item().PaddingBottom(5).LineHorizontal(1); 184 | column.Item().Text(CompanyName).FontFamily("fangsong"); 185 | }); 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /QuestPDFExercise/InvoiceModel.cs: -------------------------------------------------------------------------------- 1 | namespace QuestPDFExercise 2 | { 3 | public class InvoiceModel 4 | { 5 | 6 | /// 7 | /// 发票号码 8 | /// 9 | public int InvoiceNumber { get; set; } 10 | 11 | /// 12 | /// 发票开具日期 13 | /// 14 | public DateTime IssueDate { get; set; } 15 | 16 | /// 17 | /// 发票到期日期 18 | /// 19 | public DateTime DueDate { get; set; } 20 | 21 | /// 22 | /// 卖方公司名称 23 | /// 24 | public string SellerCompanyName { get; set; } 25 | 26 | /// 27 | /// 买方公司名称 28 | /// 29 | public string CustomerCompanyName { get; set; } 30 | 31 | /// 32 | /// 订单消费列表 33 | /// 34 | public List OrderItems { get; set; } 35 | 36 | /// 37 | /// 备注 38 | /// 39 | public string Comments { get; set; } 40 | } 41 | 42 | public class OrderItem 43 | { 44 | /// 45 | /// 消费类型 46 | /// 47 | public string Name { get; set; } 48 | 49 | /// 50 | /// 消费金额 51 | /// 52 | public decimal Price { get; set; } 53 | 54 | /// 55 | /// 消费数量 56 | /// 57 | public int Quantity { get; set; } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /QuestPDFExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using QuestPDF.Infrastructure; 2 | using QuestPDF; 3 | using QuestPDF.Fluent; 4 | 5 | namespace QuestPDFExercise 6 | { 7 | internal class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | //1、请确保您有资格使用社区许可证,不设置的话会报异常。 12 | Settings.License = LicenseType.Community; 13 | 14 | //2、禁用QuestPDF库中文本字符可用性的检查 15 | Settings.CheckIfAllTextGlyphsAreAvailable = false; 16 | 17 | //3、PDF Document 创建 18 | var invoiceSourceData = CreateInvoiceDetails.GetInvoiceDetails(); 19 | var document = new CreateInvoiceDocument(invoiceSourceData); 20 | 21 | //4、生成 PDF 文件并在默认的查看器中显示 22 | document.GeneratePdfAndShow(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /QuestPDFExercise/QuestPDFExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /QuestPDFExercise/dotnetguide.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YSGStudyHards/DotNetExercises/65f09699eb89edc25391147eb037abb26e898025/QuestPDFExercise/dotnetguide.png -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/BarChart.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace ScottPlotWinFormsExercise 2 | { 3 | partial class BarChart 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | formsPlot1 = new ScottPlot.WinForms.FormsPlot(); 32 | SuspendLayout(); 33 | // 34 | // formsPlot1 35 | // 36 | formsPlot1.DisplayScale = 1F; 37 | formsPlot1.Location = new Point(23, 12); 38 | formsPlot1.Name = "formsPlot1"; 39 | formsPlot1.Size = new Size(755, 409); 40 | formsPlot1.TabIndex = 0; 41 | // 42 | // BarChart 43 | // 44 | AutoScaleDimensions = new SizeF(7F, 17F); 45 | AutoScaleMode = AutoScaleMode.Font; 46 | ClientSize = new Size(800, 450); 47 | Controls.Add(formsPlot1); 48 | Name = "BarChart"; 49 | Text = "BarChart"; 50 | ResumeLayout(false); 51 | } 52 | 53 | #endregion 54 | 55 | private ScottPlot.WinForms.FormsPlot formsPlot1; 56 | } 57 | } -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/BarChart.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | 11 | namespace ScottPlotWinFormsExercise 12 | { 13 | /// 14 | /// 柱状图实现 15 | /// 16 | public partial class BarChart : Form 17 | { 18 | public BarChart() 19 | { 20 | InitializeComponent(); 21 | 22 | double[] values = { 5, 10, 7, 13, 22, 18, 33, 16 }; 23 | formsPlot1.Plot.Add.Bars(values); 24 | formsPlot1.Refresh(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/BarChart.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/Home.Designer.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ScottPlotWinFormsExercise 3 | { 4 | partial class Home 5 | { 6 | /// 7 | /// Required designer variable. 8 | /// 9 | private System.ComponentModel.IContainer components = null; 10 | 11 | /// 12 | /// Clean up any resources being used. 13 | /// 14 | /// true if managed resources should be disposed; otherwise, false. 15 | protected override void Dispose(bool disposing) 16 | { 17 | if (disposing && (components != null)) 18 | { 19 | components.Dispose(); 20 | } 21 | base.Dispose(disposing); 22 | } 23 | 24 | #region Windows Form Designer generated code 25 | 26 | /// 27 | /// Required method for Designer support - do not modify 28 | /// the contents of this method with the code editor. 29 | /// 30 | private void InitializeComponent() 31 | { 32 | Btn_LineChart = new Button(); 33 | Btn_BarChart = new Button(); 34 | Btn_PieChart = new Button(); 35 | Btn_ScatterChart = new Button(); 36 | SuspendLayout(); 37 | // 38 | // Btn_LineChart 39 | // 40 | Btn_LineChart.Location = new Point(23, 80); 41 | Btn_LineChart.Name = "Btn_LineChart"; 42 | Btn_LineChart.Size = new Size(120, 65); 43 | Btn_LineChart.TabIndex = 0; 44 | Btn_LineChart.Text = "折线图"; 45 | Btn_LineChart.UseVisualStyleBackColor = true; 46 | Btn_LineChart.Click += Btn_LineChart_Click; 47 | // 48 | // Btn_BarChart 49 | // 50 | Btn_BarChart.Location = new Point(184, 80); 51 | Btn_BarChart.Name = "Btn_BarChart"; 52 | Btn_BarChart.Size = new Size(120, 65); 53 | Btn_BarChart.TabIndex = 1; 54 | Btn_BarChart.Text = "柱状图"; 55 | Btn_BarChart.UseVisualStyleBackColor = true; 56 | Btn_BarChart.Click += Btn_BarChart_Click; 57 | // 58 | // Btn_PieChart 59 | // 60 | Btn_PieChart.Location = new Point(342, 80); 61 | Btn_PieChart.Name = "Btn_PieChart"; 62 | Btn_PieChart.Size = new Size(120, 65); 63 | Btn_PieChart.TabIndex = 2; 64 | Btn_PieChart.Text = "饼图"; 65 | Btn_PieChart.UseVisualStyleBackColor = true; 66 | Btn_PieChart.Click += Btn_PieChart_Click; 67 | // 68 | // Btn_ScatterChart 69 | // 70 | Btn_ScatterChart.Location = new Point(509, 80); 71 | Btn_ScatterChart.Name = "Btn_ScatterChart"; 72 | Btn_ScatterChart.Size = new Size(120, 65); 73 | Btn_ScatterChart.TabIndex = 3; 74 | Btn_ScatterChart.Text = "散点图"; 75 | Btn_ScatterChart.UseVisualStyleBackColor = true; 76 | Btn_ScatterChart.Click += Btn_ScatterChart_Click; 77 | // 78 | // Home 79 | // 80 | AutoScaleDimensions = new SizeF(7F, 17F); 81 | AutoScaleMode = AutoScaleMode.Font; 82 | ClientSize = new Size(666, 232); 83 | Controls.Add(Btn_ScatterChart); 84 | Controls.Add(Btn_PieChart); 85 | Controls.Add(Btn_BarChart); 86 | Controls.Add(Btn_LineChart); 87 | Name = "Home"; 88 | Text = "ScottPlotExercise"; 89 | ResumeLayout(false); 90 | } 91 | 92 | private void Btn_ScatterChart_Click(object sender, EventArgs e) 93 | { 94 | ScatterChart formScatterChart = new ScatterChart(); 95 | // 显示目标窗体 96 | formScatterChart.Show(); 97 | } 98 | 99 | private void Btn_PieChart_Click(object sender, EventArgs e) 100 | { 101 | PieChart formPieChart = new PieChart(); 102 | // 显示目标窗体 103 | formPieChart.Show(); 104 | } 105 | 106 | private void Btn_BarChart_Click(object sender, EventArgs e) 107 | { 108 | BarChart formbarChart = new BarChart(); 109 | // 显示目标窗体 110 | formbarChart.Show(); 111 | } 112 | 113 | private void Btn_LineChart_Click(object sender, EventArgs e) 114 | { 115 | LineChart formLineChart = new LineChart(); 116 | // 显示目标窗体 117 | formLineChart.Show(); 118 | } 119 | 120 | #endregion 121 | 122 | private Button Btn_LineChart; 123 | private Button Btn_BarChart; 124 | private Button Btn_PieChart; 125 | private Button Btn_ScatterChart; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/Home.cs: -------------------------------------------------------------------------------- 1 | using ScottPlot; 2 | using System.Diagnostics; 3 | 4 | namespace ScottPlotWinFormsExercise 5 | { 6 | public partial class Home : Form 7 | { 8 | public Home() 9 | { 10 | InitializeComponent(); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/Home.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/LineChart.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace ScottPlotWinFormsExercise 2 | { 3 | partial class LineChart 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | formsPlot1 = new ScottPlot.WinForms.FormsPlot(); 32 | SuspendLayout(); 33 | // 34 | // formsPlot1 35 | // 36 | formsPlot1.DisplayScale = 1F; 37 | formsPlot1.Location = new Point(12, 1); 38 | formsPlot1.Name = "formsPlot1"; 39 | formsPlot1.Size = new Size(758, 437); 40 | formsPlot1.TabIndex = 0; 41 | // 42 | // LineChart 43 | // 44 | AutoScaleDimensions = new SizeF(7F, 17F); 45 | AutoScaleMode = AutoScaleMode.Font; 46 | ClientSize = new Size(800, 450); 47 | Controls.Add(formsPlot1); 48 | Name = "LineChart"; 49 | Text = "LineChart"; 50 | ResumeLayout(false); 51 | } 52 | 53 | #endregion 54 | 55 | private ScottPlot.WinForms.FormsPlot formsPlot1; 56 | } 57 | } -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/LineChart.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Data; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | 11 | namespace ScottPlotWinFormsExercise 12 | { 13 | /// 14 | /// 折线图实现 15 | /// 16 | public partial class LineChart : Form 17 | { 18 | public LineChart() 19 | { 20 | InitializeComponent(); 21 | 22 | double[] dataX = GetRandomNum(20).Distinct().OrderByDescending(x => x).ToArray(); 23 | double[] dataY = GetRandomNum(19).Distinct().OrderByDescending(x => x).ToArray(); 24 | formsPlot1.Plot.Add.Scatter(dataX, dataY); 25 | formsPlot1.Refresh(); 26 | } 27 | 28 | public double[] GetRandomNum(int length) 29 | { 30 | double[] getDate = new double[length]; 31 | Random random = new Random(); //创建一个Random实例 32 | for (int i = 0; i < length; i++) 33 | { 34 | getDate[i] = random.Next(1, 100); //使用同一个Random实例生成随机数 35 | } 36 | return getDate; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/LineChart.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/PieChart.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace ScottPlotWinFormsExercise 2 | { 3 | partial class PieChart 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | formsPlot1 = new ScottPlot.WinForms.FormsPlot(); 32 | SuspendLayout(); 33 | // 34 | // formsPlot1 35 | // 36 | formsPlot1.DisplayScale = 1F; 37 | formsPlot1.Location = new Point(25, 22); 38 | formsPlot1.Name = "formsPlot1"; 39 | formsPlot1.Size = new Size(736, 397); 40 | formsPlot1.TabIndex = 0; 41 | // 42 | // PieChart 43 | // 44 | AutoScaleDimensions = new SizeF(7F, 17F); 45 | AutoScaleMode = AutoScaleMode.Font; 46 | ClientSize = new Size(800, 450); 47 | Controls.Add(formsPlot1); 48 | Name = "PieChart"; 49 | Text = "PieChart"; 50 | ResumeLayout(false); 51 | } 52 | 53 | #endregion 54 | 55 | private ScottPlot.WinForms.FormsPlot formsPlot1; 56 | } 57 | } -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/PieChart.cs: -------------------------------------------------------------------------------- 1 | using ScottPlot; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Data; 6 | using System.Drawing; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using System.Windows.Forms; 11 | 12 | namespace ScottPlotWinFormsExercise 13 | { 14 | /// 15 | /// 饼图实现 16 | /// 17 | public partial class PieChart : Form 18 | { 19 | public PieChart() 20 | { 21 | InitializeComponent(); 22 | 23 | double[] values = { 3, 2, 8, 4, 8, 10 }; 24 | formsPlot1.Plot.Add.Pie(values); 25 | formsPlot1.Refresh(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/PieChart.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/Program.cs: -------------------------------------------------------------------------------- 1 | namespace ScottPlotWinFormsExercise 2 | { 3 | internal static class Program 4 | { 5 | /// 6 | /// The main entry point for the application. 7 | /// 8 | [STAThread] 9 | static void Main() 10 | { 11 | // To customize application configuration such as set high DPI settings or default font, 12 | // see https://aka.ms/applicationconfiguration. 13 | ApplicationConfiguration.Initialize(); 14 | Application.Run(new Home()); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/ScatterChart.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace ScottPlotWinFormsExercise 2 | { 3 | partial class ScatterChart 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | formsPlot1 = new ScottPlot.WinForms.FormsPlot(); 32 | SuspendLayout(); 33 | // 34 | // formsPlot1 35 | // 36 | formsPlot1.DisplayScale = 1F; 37 | formsPlot1.Location = new Point(24, 12); 38 | formsPlot1.Name = "formsPlot1"; 39 | formsPlot1.Size = new Size(736, 413); 40 | formsPlot1.TabIndex = 0; 41 | // 42 | // ScatterChart 43 | // 44 | AutoScaleDimensions = new SizeF(7F, 17F); 45 | AutoScaleMode = AutoScaleMode.Font; 46 | ClientSize = new Size(800, 450); 47 | Controls.Add(formsPlot1); 48 | Name = "ScatterChart"; 49 | Text = "ScatterChart"; 50 | ResumeLayout(false); 51 | } 52 | 53 | #endregion 54 | 55 | private ScottPlot.WinForms.FormsPlot formsPlot1; 56 | } 57 | } -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/ScatterChart.cs: -------------------------------------------------------------------------------- 1 | using ScottPlot; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.ComponentModel; 5 | using System.Data; 6 | using System.Drawing; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using System.Windows.Forms; 11 | 12 | namespace ScottPlotWinFormsExercise 13 | { 14 | /// 15 | /// 散点图实现 16 | /// 17 | public partial class ScatterChart : Form 18 | { 19 | public ScatterChart() 20 | { 21 | InitializeComponent(); 22 | 23 | //从原始数据开始 24 | double[] xs = Generate.Consecutive(100); 25 | double[] ys = Generate.NoisyExponential(100); 26 | 27 | //对数据进行对数缩放,并处理负值 28 | double[] logYs = ys.Select(Math.Log10).ToArray(); 29 | 30 | //将对数缩放的数据添加到绘图中 31 | var sp = formsPlot1.Plot.Add.Scatter(xs, logYs); 32 | sp.LineWidth = 0; 33 | 34 | //创建一个次要刻度生成器,用于放置对数分布的次要刻度 35 | ScottPlot.TickGenerators.LogMinorTickGenerator minorTickGen = new(); 36 | 37 | //创建一个数值刻度生成器,使用自定义的次要刻度生成器 38 | ScottPlot.TickGenerators.NumericAutomatic tickGen = new(); 39 | tickGen.MinorTickGenerator = minorTickGen; 40 | 41 | //创建一个自定义刻度格式化程序,用于设置每个刻度的标签文本 42 | static string LogTickLabelFormatter(double y) => $"{Math.Pow(10, y):N0}"; 43 | 44 | //告诉我们的主要刻度生成器仅显示整数的主要刻度 45 | tickGen.IntegerTicksOnly = true; 46 | 47 | //告诉我们的自定义刻度生成器使用新的标签格式化程序 48 | tickGen.LabelFormatter = LogTickLabelFormatter; 49 | 50 | //告诉左轴使用我们的自定义刻度生成器 51 | formsPlot1.Plot.Axes.Left.TickGenerator = tickGen; 52 | 53 | //显示次要刻度的网格线 54 | var grid = formsPlot1.Plot.GetDefaultGrid(); 55 | grid.MajorLineStyle.Color = Colors.Black.WithOpacity(.15); 56 | grid.MinorLineStyle.Color = Colors.Black.WithOpacity(.05); 57 | grid.MinorLineStyle.Width = 1; 58 | 59 | formsPlot1.Refresh(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/ScatterChart.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | -------------------------------------------------------------------------------- /ScottPlotWinFormsExercise/ScottPlotWinFormsExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | net8.0-windows 6 | enable 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SpectreExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Spectre.Console; 2 | 3 | namespace SpectreExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | //原生控制台文字输出 10 | Console.WriteLine("你好追逐时光者!!!"); 11 | 12 | //类库设置控制台文字输出 13 | //类库文档颜色选择表:https://spectreconsole.net/appendix/colors 14 | AnsiConsole.Markup("[underline red]你好[/][Blue]追逐时光者[/][DarkMagenta]!!![/]"); 15 | 16 | #region 创建表 17 | // 创建表 18 | var table = new Table(); 19 | 20 | //添加一些列 21 | table.AddColumn("[red]编号[/]"); 22 | table.AddColumn("[green]姓名[/]"); 23 | table.AddColumn("[blue]年龄[/]"); 24 | 25 | //添加一些行 26 | table.AddRow("1", "追逐时光者", "20岁"); 27 | table.AddRow("2", "大姚", "22岁"); 28 | table.AddRow("3", "小袁", "18岁"); 29 | table.AddRow("4", "小明", "23岁"); 30 | 31 | // 将表格渲染到控制台 32 | AnsiConsole.Write(table); 33 | #endregion 34 | 35 | #region 条形图 36 | 37 | AnsiConsole.Write(new BarChart() 38 | .Width(60) 39 | .Label("[green bold underline]水果数量[/]") 40 | .CenterLabel() 41 | .AddItem("苹果", 12, Color.Yellow) 42 | .AddItem("西瓜", 54, Color.Green) 43 | .AddItem("香蕉", 33, Color.Red) 44 | .AddItem("芒果", 55, Color.Blue)); 45 | 46 | #endregion 47 | 48 | 49 | //日历 50 | var calendar = new Calendar(2024, 5); 51 | AnsiConsole.Write(calendar); 52 | 53 | #region 布局 54 | 55 | // Create the layout 56 | var layout = new Layout("Root") 57 | .SplitColumns( 58 | new Layout("Left"), 59 | new Layout("Right") 60 | .SplitRows( 61 | new Layout("Top"), 62 | new Layout("Bottom"))); 63 | 64 | // Update the left column 65 | layout["Left"].Update( 66 | new Panel( 67 | Align.Center( 68 | new Markup("[blue]你好![/]"), 69 | VerticalAlignment.Middle)) 70 | .Expand()); 71 | 72 | // Render the layout 73 | AnsiConsole.Write(layout); 74 | 75 | #endregion 76 | 77 | #region 规则水平线 78 | 79 | var rule = new Rule("[red]Hello[/]"); 80 | AnsiConsole.Write(rule); 81 | 82 | var ruleLeft = new Rule("[blue]Hello[/]"); 83 | ruleLeft.Justification = Justify.Left; 84 | AnsiConsole.Write(ruleLeft); 85 | 86 | var ruleRight = new Rule("[yellow]Hello[/]"); 87 | ruleRight.Justification = Justify.Right; 88 | AnsiConsole.Write(ruleRight); 89 | 90 | #endregion 91 | 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /SpectreExercise/SpectreExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SqidsExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Sqids; 2 | 3 | namespace SqidsExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | // 使用默认选项创建 SqidsEncoder 实例 10 | var sqids = new SqidsEncoder(); 11 | 12 | // 编码单个数字 13 | var id = sqids.Encode(99); 14 | Console.WriteLine($"编码单个数字: {id}"); // 输出:Q8P 15 | 16 | // 解码单个 ID 17 | var number = sqids.Decode(id).Single(); 18 | Console.WriteLine($"解码单个 ID '{id}': {number}"); // 输出:99 19 | 20 | // 编码多个数字 21 | var ids = sqids.Encode(7, 8, 9); 22 | Console.WriteLine($"编码多个数字 7, 8, 9: {ids}"); // 输出:ylrR3H 23 | 24 | // 解码多个 ID 25 | var numbers = sqids.Decode(ids); 26 | Console.WriteLine($"解码多个 ID '{ids}': {string.Join(", ", numbers)}"); // 输出:7, 8, 9 27 | 28 | // 使用自定义选项创建 SqidsEncoder 实例 29 | var customSqids = new SqidsEncoder(new SqidsOptions 30 | { 31 | Alphabet = "mTHivO7hx3RAbr1f586SwjNnK2lgpcUVuG09BCtekZdJ4DYFPaWoMLQEsXIqyz",//自定义字母表(注意:字母表至少需要 3 个字符) 32 | MinLength = 5,//最小长度,默认情况下,Sqids 使用尽可能少的字符来编码给定的数字。但是,如果你想让你的所有 ID 至少达到一定的长度(例如,为了美观),你可以通过 MinLength 选项进行配置: 33 | BlockList = { "whatever", "else", "you", "want" } //自定义黑名单,Sqids 自带一个大的默认黑名单,这将确保常见的诅咒词等永远不会出现在您的 ID 中。您可以像这样向这个默认黑名单添加额外项: 34 | }); 35 | 36 | // 使用自定义 SqidsEncoder 编码和解码 37 | var customId = customSqids.Encode(8899); 38 | Console.WriteLine($"使用自定义 SqidsEncoder 编码: {customId}"); // 输出:i1uYg 39 | 40 | var customNumber = customSqids.Decode(customId).Single(); 41 | Console.WriteLine($"使用自定义 SqidsEncoder 解码: {customNumber}"); // 输出:8899 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /SqidsExercise/SqidsExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /TerminalGuiExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using Terminal.Gui; 2 | 3 | namespace TerminalGuiExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | #region 用户登录示例代码 10 | 11 | Application.Run(); 12 | 13 | #endregion 14 | 15 | #region 消息框代码 16 | 17 | Application.Init(); 18 | 19 | MessageBox.Query(100, 15, 20 | "Question", "Do you like console apps?", "Yes", "No"); 21 | 22 | Application.Shutdown(); 23 | 24 | #endregion 25 | 26 | #region 创建一个简单的带菜单栏的文本用户界面示例代码 27 | 28 | Application.Init(); 29 | var menu = new MenuBar(new MenuBarItem[] { 30 | new MenuBarItem ("_File", new MenuItem [] { 31 | new MenuItem ("_Quit", "", () => { 32 | Application.RequestStop (); 33 | }) 34 | }),}); 35 | 36 | var win = new Window("追逐时光者,你好!!!") 37 | { 38 | X = 0, 39 | Y = 1, 40 | Width = Dim.Fill(), 41 | Height = Dim.Fill() - 1 42 | }; 43 | 44 | Application.Top.Add(menu, win); 45 | Application.Run(); 46 | Application.Shutdown(); 47 | 48 | #endregion 49 | } 50 | } 51 | 52 | public class UserLoginExampleWindow : Window 53 | { 54 | public TextField usernameText; 55 | 56 | public UserLoginExampleWindow() 57 | { 58 | Title = "用户登录示例应用程序(Ctrl+Q退出)"; 59 | 60 | //创建输入组件和标签 61 | var usernameLabel = new Label() 62 | { 63 | Text = "用户名:", 64 | Y = 5 65 | }; 66 | 67 | usernameText = new TextField("") 68 | { 69 | X = Pos.Right(usernameLabel), 70 | Y = Pos.Bottom(usernameLabel) - 1, 71 | Width = Dim.Fill(), 72 | }; 73 | 74 | var passwordLabel = new Label() 75 | { 76 | Text = "密码:", 77 | X = Pos.Left(usernameLabel), 78 | Y = Pos.Bottom(usernameLabel) + 5 79 | }; 80 | 81 | var passwordText = new TextField("") 82 | { 83 | Secret = true, 84 | X = Pos.Left(usernameText), 85 | Y = Pos.Top(passwordLabel), 86 | Width = Dim.Fill(), 87 | }; 88 | 89 | //创建登录按钮 90 | var btnLogin = new Button() 91 | { 92 | Text = "登录", 93 | Y = Pos.Bottom(passwordLabel) + 1, 94 | X = Pos.Center(), 95 | IsDefault = true, 96 | }; 97 | 98 | //单击登录按钮时显示消息弹出 99 | btnLogin.Clicked += () => 100 | { 101 | if (usernameText.Text == "admin" && passwordText.Text == "123456") 102 | { 103 | MessageBox.Query("登录结果", "登录成功", "Ok"); 104 | Application.RequestStop(); 105 | } 106 | else 107 | { 108 | MessageBox.ErrorQuery("登录结果", "用户名或密码不正确", "Ok"); 109 | } 110 | }; 111 | 112 | //将视图添加到窗口 113 | Add(usernameLabel, usernameText, passwordLabel, passwordText, btnLogin); 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /TerminalGuiExercise/TerminalGuiExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /TimeCrontabExercise/Program.cs: -------------------------------------------------------------------------------- 1 | using TimeCrontab; 2 | 3 | namespace TimeCrontabExercise 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | //常规格式:分 时 天 月 周 10 | var crontab = Crontab.Parse("* * * * *"); 11 | var nextOccurrence = crontab.GetNextOccurrence(DateTime.Now); 12 | 13 | //支持年份:分 时 天 月 周 年 14 | var crontab1 = Crontab.Parse("* * * * * *", CronStringFormat.WithYears); 15 | var nextOccurrence1 = crontab1.GetNextOccurrence(DateTime.Now); 16 | 17 | //支持秒数:秒 分 时 天 月 周 18 | var crontab2 = Crontab.Parse("* * * * * *", CronStringFormat.WithSeconds); 19 | var nextOccurrence2 = crontab2.GetNextOccurrence(DateTime.Now); 20 | 21 | //支持秒和年:秒 分 时 天 月 周 年 22 | var crontab3 = Crontab.Parse("* * * * * * *", CronStringFormat.WithSecondsAndYears); 23 | var nextOccurrence3 = crontab3.GetNextOccurrence(DateTime.Now); 24 | 25 | // Macro 字符串 26 | var secondly = Crontab.Parse("@secondly"); //每秒 [* * * * * *] 27 | var minutely = Crontab.Parse("@minutely"); //每分钟 [* * * * *] 28 | var hourly = Crontab.Parse("@hourly"); //每小时 [0 * * * *] 29 | var daily = Crontab.Parse("@daily"); //每天 00:00:00 [0 0 * * *] 30 | var monthly = Crontab.Parse("@monthly"); //每月 1 号 00:00:00 [0 0 1 * *] 31 | var weekly = Crontab.Parse("@weekly"); //每周日 00:00:00 [0 0 * * 0] 32 | var yearly = Crontab.Parse("@yearly"); //每年 1 月 1 号 00:00:00 [0 0 1 1 *] 33 | var workday = Crontab.Parse("@workday"); //每周一至周五 00:00:00 [0 0 * * 1-5] 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /TimeCrontabExercise/TimeCrontabExercise.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | --------------------------------------------------------------------------------