添加api模拟项目;测试登录和下载远程数据接口

Former-commit-id: 48a168a0e45eb696e68757ff1e7853297d44149f
TangShanKaiPing
wanggang 5 years ago
parent 9009f627d1
commit 91e539564c

@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CameraCard", "CameraCard\Ca
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoUpdate", "AutoUpdate\AutoUpdate.csproj", "{0F767D6D-72DE-47FD-BE40-432DADFA1FAE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApi", "WebApi\WebApi.csproj", "{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -31,6 +33,14 @@ Global
{0F767D6D-72DE-47FD-BE40-432DADFA1FAE}.Release|Any CPU.Build.0 = Release|Any CPU
{0F767D6D-72DE-47FD-BE40-432DADFA1FAE}.Release|x86.ActiveCfg = Release|Any CPU
{0F767D6D-72DE-47FD-BE40-432DADFA1FAE}.Release|x86.Build.0 = Release|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Debug|x86.ActiveCfg = Debug|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Debug|x86.Build.0 = Debug|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Release|Any CPU.Build.0 = Release|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Release|x86.ActiveCfg = Release|Any CPU
{630F17A8-49DB-4DCA-BDB6-1F16EEEA2ED3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="login" value="http://www.baidu.com" />
<add key="pull" value="http://www.baidu.com" />
<add key="push" value="http://www.baidu.com" />
<add key="login" value="http://localhost:5000/api/login" />
<add key="pull" value="http://localhost:5000/api/pull" />
<add key="push" value="http://localhost:5000/api/push" />
<add key="version" value="1.0.0" />
</appSettings>
<startup>

@ -82,6 +82,7 @@
<Compile Include="Data\Entity.cs" />
<Compile Include="Data\LoginResponse.cs" />
<Compile Include="Data\MyDbContext.cs" />
<Compile Include="Data\PullResponse.cs" />
<Compile Include="Data\Student.cs" />
<Compile Include="Data\User.cs" />
<Compile Include="CVRSDK.cs" />
@ -155,6 +156,9 @@
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mapster">
<Version>5.0.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.AspNet.WebApi.Client">
<Version>5.2.7</Version>
</PackageReference>

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using System;
namespace CameraCard.Data
{
@ -24,5 +25,6 @@ namespace CameraCard.Data
{
//this.Users.Add(new User { UserName = "admin", Password = "123456" });
}
}
}

@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace CameraCard.Data
{
public class PullResponse
{
public int code { get; set; }
public string message { get; set; }
public List<Student> data { get; set; }
}
}

@ -1,6 +1,4 @@
using System;
namespace CameraCard.Data
namespace CameraCard.Data
{
public class Student : Entity
{

@ -124,10 +124,12 @@
this.Controls.Add(this.userNameInput);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.KeyPreview = true;
this.Name = "LoginForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "登录";
this.Load += new System.EventHandler(this.LoginForm_Load);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LoginForm_KeyDown);
this.ResumeLayout(false);
this.PerformLayout();

@ -1,12 +1,11 @@
using CameraCard.Data;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
@ -57,8 +56,11 @@ namespace CameraCard
{
if (db.Users.Any())
{
if (db.Users.Any(o => o.UserName == userName && o.Password == password))
var user = db.Users.FirstOrDefault(o => o.UserName == userName && o.Password == password);
if (user != null)
{
this._progress?.SetProgress("本地登录成功", 100);
MainForm.User = user;
this.Hide();
new MainForm().Show();
}
@ -71,63 +73,86 @@ namespace CameraCard
{
this.BeginInvoke(new Action(() =>
{
if (this._progress == null)
this.LoginFromServer(userName, password);
}));
}
}
}
}
private void LoginFromServer(string userName, string password)
{
if (this._progress == null)
{
var thread = new Thread(() =>
{
this._progress?.SetProgress("正在登录,请稍候", 30);
var url = ConfigurationManager.AppSettings["login"];
var client = HttpClientFactory.Create();
var content = new StringContent(new JavaScriptSerializer().Serialize(new { userName = userName, password = password }), Encoding.UTF8, "application/json");
var response = client.PostAsync(url, content).Result;
this._progress?.SetProgress("正在登录,请稍候", 60);
if (response.StatusCode == HttpStatusCode.OK)
{
var result = new JavaScriptSerializer().Deserialize<LoginResponse>(response.Content.ReadAsStringAsync().Result);
if (result.code == 0)
{
using (var db = new MyDbContext())
{
var thread = new Thread(() =>
var user = db.Users.FirstOrDefault(o => o.UserName == userName);
if (user == null)
{
this._progress?.SetProgress("正在登录,请稍候", 30);
var url = ConfigurationManager.AppSettings["login"];
var client = HttpClientFactory.Create();
var content = new JavaScriptSerializer().Serialize(new { userName = userName, password = password });
var response = client.PostAsync(url, new StringContent(content)).Result;
this._progress?.SetProgress("正在登录,请稍候", 60);
if (response.StatusCode == HttpStatusCode.OK)
{
var result = new JavaScriptSerializer().Deserialize<LoginResponse>(response.Content.ReadAsStringAsync().Result);
if (result.code == 0)
{
var user = db.Users.FirstOrDefault(o => o.UserName == userName);
if (user == null)
{
user = new User { UserName = userName, Password = password, PasswordHash = result.data };
}
else
{
user.Password = password;
user.PasswordHash = result.data;
}
db.SaveChanges();
//this.Update();
this._progress?.SetProgress("登录成功", 100);
this._progress.Close();
this.Hide();
new MainForm().Show();
}
else
{
MessageBox.Show(result.message);
this._progress?.SetProgress("登录失败", 100);
this._progress.Close();
}
}
else
{
MessageBox.Show(response.Content.ReadAsStringAsync().Result);
this._progress?.SetProgress("登录失败", 100);
this._progress.Close();
}
});
this._progress = new ProgressForm("登录中", "正在登录,请稍候", 0, 100, this.Width, () =>
user = new User { UserName = userName, Password = password, PasswordHash = result.data };
}
else
{
this._progress = null;
thread.Abort();
});
thread.Start();
this._progress.ShowDialog();
user.Password = password;
user.PasswordHash = result.data;
}
db.SaveChanges();
MainForm.User = user;
}
}));
this._progress?.SetProgress("登录成功,正在加载数据", 50);
MainForm.LoadData(this._progress);
this._progress.CloseProgress();
this.Invoke(new Action(() =>
{
this.Hide();
new MainForm().Show();
}));
}
else
{
MessageBox.Show($"错误代码:{result.code},错误消息:{result.message}");
this._progress?.SetProgress("登录失败", 100);
this._progress.CloseProgress();
}
}
}
else
{
MessageBox.Show(response.Content.ReadAsStringAsync().Result);
this._progress?.SetProgress("登录失败", 100);
this._progress.CloseProgress();
}
});
this._progress = new ProgressForm("登录中", "正在登录,请稍候", 0, 100, this.Width, () =>
{
this._progress = null;
if (thread != null && thread.IsAlive)
{
thread.Abort();
}
});
thread.Start();
this._progress.ShowDialog();
}
}
private void LoginForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.login_Click(sender, e);
}
}
}

@ -1,9 +1,16 @@
using System;
using CameraCard.Data;
using Mapster;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace CameraCard
@ -125,6 +132,8 @@ namespace CameraCard
private Rectangle _rect;
private Pen _pen;
public static User User { get; set; }
private void CreateRect()
{
this._photoWidth = 351;
@ -139,6 +148,41 @@ namespace CameraCard
this._pen.DashStyle = DashStyle.Dash;
}
public static void LoadData(ProgressForm progress)
{
var url = ConfigurationManager.AppSettings["pull"];
var client = HttpClientFactory.Create();
var content = new StringContent(new JavaScriptSerializer().Serialize(new { userName = MainForm.User.UserName }), Encoding.UTF8, "application/json");
var response = client.PostAsync(url, content).Result;
var result = new JavaScriptSerializer().Deserialize<PullResponse>(response.Content.ReadAsStringAsync().Result);
if (result.code == 0)
{
using (var db = new MyDbContext())
{
foreach (var item in result.data)
{
var entity = db.Students.FirstOrDefault(o => o.Id == item.Id);
if (entity == null)
{
entity = item;
progress?.SetProgress($"正在加载{entity.Name}", 50);
}
else
{
progress?.SetProgress($"正在更新{entity.Name}", 50);
entity.Adapt(item);
}
db.SaveChanges();
}
}
}
else
{
MessageBox.Show($"错误代码:{result.code},错误消息:{result.message}");
}
}
private void cameraRender_Paint(object sender, PaintEventArgs e)
{
try

@ -27,16 +27,22 @@ namespace CameraCard
public void SetProgress(string label, int progress)
{
this.Invoke(new Action(() =>
if (this.IsHandleCreated)
{
this.status.Text = label;
this.progressBar.Value = progress;
}));
this.Invoke(new Action(() =>
{
this.status.Text = label;
this.progressBar.Value = progress;
}));
}
}
public void CloseProgress()
{
this.CloseProgress();
this.Invoke(new Action(() =>
{
this.Close();
}));
}
}
}

@ -0,0 +1,18 @@
*.bak
*.suo
*.db
*.db-shm
*.db-wal
*.user
.vs
obj
Obj
bin
Bin
debug
Debug
release
Release
Logs
logs
node_modules

@ -0,0 +1,51 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using WebApi.Models;
namespace WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
public TestController()
{
}
[ApiExplorerSettings(IgnoreApi = true)]
[Route("/")]
public string Home()
{
return "";
}
[HttpPost]
[Route("/api/[action]")]
public ApiResponse Login([FromBody]LoginRequest model)
{
if (ModelState.IsValid)
{
return new ApiResponse { Code = 0, Data = model.UserName };
}
return new ApiResponse { Code = 1, Message = "用户名或密码错误" };
}
[HttpPost]
[Route("/api/[action]")]
public ApiResponse Pull([FromBody]PullRequest model)
{
if (ModelState.IsValid)
{
return new ApiResponse
{
Code = 0,
Data = new List<Student> {
new Student{ Id=Guid.NewGuid().ToString(),Name="小明"}
}
};
}
return new ApiResponse { Code = 1, Message = "用户名不能为空" };
}
}
}

@ -0,0 +1,9 @@
namespace WebApi.Models
{
public class ApiResponse
{
public int Code { get; set; }
public string Message { get; set; }
public object Data { get; set; }
}
}

@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace WebApi.Models
{
public class LoginRequest
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
}

@ -0,0 +1,10 @@
using System.ComponentModel.DataAnnotations;
namespace WebApi.Models
{
public class PullRequest
{
[Required]
public string UserName { get; set; }
}
}

@ -0,0 +1,12 @@
namespace WebApi.Models
{
public class Student
{
public string Id { get; set; }
public string Name { get; set; }
public string IdCardNo { get; set; }
public string Image { get; set; }
public bool HasUploaded { get; set; }
public bool IsChecked { get; set; }
}
}

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

@ -0,0 +1,29 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5000",
"sslPort": 0
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebApi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5000"
}
}
}

@ -0,0 +1,53 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
namespace WebApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
</ItemGroup>
</Project>

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

@ -0,0 +1,10 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Loading…
Cancel
Save