public async Task <IActionResult> OnPostAsync(RegistViewModel registViewModel) { if (registViewModel is null) { throw new ArgumentNullException(nameof(registViewModel)); } if (!TryValidateModel(registViewModel)) { return(BadRequest(ModelState)); } //await userManager.DeleteAsync(await userManager.FindByNameAsync(registViewModel.Email).ConfigureAwait(false)).ConfigureAwait(false); var user = await userManager.FindByEmailAsync(registViewModel.Email).ConfigureAwait(false); if (user == null) { user = new ApplicationUser { Id = GuidEx.NewGuid().ToString(CultureInfo.CurrentCulture), UserName = registViewModel.Email, Email = registViewModel.Email, Password = registViewModel.Password, EmailConfirmed = false }; var result = await userManager.CreateAsync(user, registViewModel.Password).ConfigureAwait(false); if (!result.Succeeded) { ModelState.AddModelError(string.Empty, $"账号创建失败[{result.Errors.FirstOrDefault()?.Description}]"); return(BadRequest(ModelState)); } } if (user.EmailConfirmed) { ModelState.AddModelError(string.Empty, $"账号创建失败,邮件已被注册,并且被确认,如果是忘记了密码可以重新找回哦"); return(BadRequest(ModelState)); } var token = await userManager.GenerateEmailConfirmationTokenAsync(user).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { ModelState.AddModelError(string.Empty, "token生成错误"); return(BadRequest(ModelState)); } token = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token)); var callbackUrl = Url.Page( "/Account/Regist", pageHandler: null, values: new { userId = user.Id, token = token }, protocol: Request.Scheme); string body = $"请点击此地址完成学习坊的账号注册: {callbackUrl} <a href=\"{callbackUrl}\" target=\"_blank\">点击验证</a>"; await emailSender.SendEmailAsync(new string[] { user.Email }, "学习坊账号注册", body).ConfigureAwait(false); return(Content($"已经发送注册验证邮件到【{user.Email}】,请查收验证")); }
//public static string ClearPassword; /* * -generate (in order) * 1) gen refs in SignedInfo * 2) construct SignedInfo and create sig element * 1) obtain raw data * add wsu:Id to everything * apply transforms / canonical * calculate digest * create ref elem * 2) create signed info * apply canonical * create actual signature value * sig element * w/SignedInfo, SigVlaue, KeyInfo, ... */ public static XmlDocument SignXml(XmlDocument plainDoc) { if (SigObj == null) { return(plainDoc); //nothing to sign } XmlElement envelope = plainDoc.DocumentElement; XmlElement headerOrBody = (XmlElement)envelope.ChildNodes[0]; XmlElement header; XmlElement body; if (headerOrBody.LocalName == Elem.Body) { header = plainDoc.CreateElement(headerOrBody.Prefix, Elem.Header, headerOrBody.NamespaceURI); envelope.InsertBefore(header, headerOrBody); } header = (XmlElement)envelope.ChildNodes[0]; body = (XmlElement)envelope.ChildNodes[1]; XmlNodeList headers = header.ChildNodes; XmlElement security = null; foreach (XmlNode xn in headers) { if (xn.LocalName == Elem.Security) { security = (XmlElement)xn; } } if (security == null) { security = plainDoc.CreateElement(Pre.wsse, Elem.Security, Ns.wsseLatest); XmlAttribute mustUnderstand = plainDoc.CreateAttribute(Pre.soap, Attrib.mustUnderstand, Ns.soap); mustUnderstand.Value = "1"; security.Attributes.Append(mustUnderstand); header.AppendChild(security); } XmlElement tokenElem = null; string secTokId = null; string sigAlgVal = null; //add BinarySecurityToken or UsernameToken under Security if (SigObj.BinSecTok != null) { XmlElement binSecTok = SigObj.BinSecTok.WriteXml(plainDoc, security); secTokId = SigObj.BinSecTok.Id; sigAlgVal = Alg.rsaSha1; if (SigObj.AsymmAlg is DSACryptoServiceProvider) { sigAlgVal = Alg.dsaSha1; } tokenElem = binSecTok; } /* * <wsse:UsernameToken xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility" wsu:Id="SecurityToken-344570f1-e3b7-42fc-9b78-f0dcd1f90bd8"> * <wsse:Username>Admin</wsse:Username> * <wsse:Password Type="wsse:PasswordDigest">W5xVfXpb+NoV9KaPIQXUIslGGak=</wsse:Password> * <wsse:Nonce>+7L+k37JW8qQCK1SPopXeQ==</wsse:Nonce> * <wsu:Created>2003-10-23T04:40:04Z</wsu:Created> * </wsse:UsernameToken> */ if (SigObj.UserTok != null) { XmlElement userTokElem = SigObj.UserTok.WriteXml(plainDoc, security); tokenElem = userTokElem; /* * //xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" * XmlElement userTokElem = plainDoc.CreateElement(Pre.wsse, Elem.UsernameToken, Ns.wsseLatest); * security.AppendChild(userTokElem); * XmlAttribute uid = plainDoc.CreateAttribute(Pre.wsu, Attrib.Id, Ns.wsuLatest); * uid.Value = SigObj.UserTok.Id; * userTokElem.Attributes.Append(uid); * XmlElement userElem = plainDoc.CreateElement(Pre.wsse, Elem.Username, Ns.wsseLatest); * userElem.InnerText = SigObj.UserTok.Username.Text; * userTokElem.AppendChild(userElem); * if(SigObj.UserTok.Password != null) * { * XmlElement passElem = plainDoc.CreateElement(Pre.wsse, Elem.Password, Ns.wsseLatest); * XmlAttribute type = plainDoc.CreateAttribute(Attrib.Type); * type.Value = SigObj.UserTok.Password.Type; * passElem.Attributes.Append(type); * passElem.InnerText = SigObj.UserTok.Password.Text; * userTokElem.AppendChild(passElem); * } * XmlElement nonceElem = plainDoc.CreateElement(Pre.wsse, Elem.Nonce, Ns.wsseLatest); * nonceElem.InnerText = SigObj.UserTok.Nonce.Text; * userTokElem.AppendChild(nonceElem); * XmlElement creElem = plainDoc.CreateElement(Pre.wsu, Elem.Created, Ns.wsuLatest); * creElem.InnerText = SigObj.UserTok.Created; * userTokElem.AppendChild(creElem); * userTokElem.Attributes.Append(uid); */ secTokId = SigObj.UserTok.Id; sigAlgVal = Alg.hmacSha1; } if (SigObj.securityContextToken != null) { XmlNode sctNode = LameXpath.SelectSingleNode(header, Elem.SecurityContextToken); if (sctNode == null) { //i need to import this node 1st sctNode = plainDoc.ImportNode(SigObj.securityContextToken, true); string dupeId = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value; XmlElement dupeElem = LameXpath.SelectSingleNode(dupeId, security); if (dupeElem == null) { security.AppendChild(sctNode); } else { sctNode = LameXpath.SelectSingleNode(dupeId, security); } } //<wsse:SecurityContextToken wsu:Id=\"SecurityToken-feb27552-6eb5-4a27-a831-e1bdfca326e2\"> secTokId = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value; sigAlgVal = Alg.hmacSha1; tokenElem = (XmlElement)sctNode; if (SigObj.derKeyTok != null) { XmlNode idElem = LameXpath.SelectSingleNode(sctNode, Elem.Identifier); if (idElem != null) { SigObj.derKeyTok.secTokRef.Reference.URI = idElem.InnerText; } XmlElement derKeyTokElem = SigObj.derKeyTok.WriteXml(plainDoc, security, (XmlElement)sctNode); secTokId = SigObj.derKeyTok.id; } } //add Signature element, SignedInfo, CanonicalizationMethod and SignatureMethod XmlElement sigElem = plainDoc.CreateElement(Pre.ds, Elem.Signature, Ns.ds); security.AppendChild(sigElem); //just append //add SignedInfo XmlElement sigInfoElem = plainDoc.CreateElement(Pre.ds, Elem.SignedInfo, Ns.ds); sigElem.AppendChild(sigInfoElem); XmlElement canMethElem = plainDoc.CreateElement(Pre.ds, Elem.CanonicalizationMethod, Ns.ds); XmlAttribute canAlg = plainDoc.CreateAttribute(Attrib.Algorithm); canAlg.Value = Alg.xmlExcC14n; canMethElem.Attributes.Append(canAlg); sigInfoElem.AppendChild(canMethElem); XmlElement sigMethElem = plainDoc.CreateElement(Pre.ds, Elem.SignatureMethod, Ns.ds); XmlAttribute sigAlg = plainDoc.CreateAttribute(Attrib.Algorithm); sigAlg.Value = sigAlgVal; sigMethElem.Attributes.Append(sigAlg); sigInfoElem.AppendChild(sigMethElem); //get each Refs element, add Id if missing //canonical, Digest, add ReferenceElement bool comments = false; bool exclusive = true; SHA1CryptoServiceProvider shaCsp = new SHA1CryptoServiceProvider(); foreach (object oRef in SigObj.Refs) { XmlElement refdElem = LameXpath.SelectSingleNode(plainDoc, oRef.ToString()); if (refdElem == null) { continue; //cant sign it because it doesnt exist } //get or add Id XmlAttribute xaId = null; foreach (XmlAttribute xa in refdElem.Attributes) { if (xa.LocalName == Attrib.Id) { xaId = xa; break; } } if (xaId == null) { xaId = plainDoc.CreateAttribute(Pre.wsu, Attrib.Id, Ns.wsuLatest); string preId = "Id-"; if (oRef.ToString() == Elem.Timestamp) { preId = "Timestamp-"; } xaId.Value = preId + GuidEx.NewGuid().ToString("D"); refdElem.Attributes.Append(xaId); } XmlDocument xdRefd = new XmlDocument(); xdRefd.LoadXml(refdElem.OuterXml); XmlCanonicalizer xc = new XmlCanonicalizer(comments, exclusive); MemoryStream msRefd = (MemoryStream)xc.Canonicalize(xdRefd); byte [] baRefd = new byte[msRefd.Length]; msRefd.Read(baRefd, 0, baRefd.Length); string debugName = oRef.ToString(); byte [] baDigest = shaCsp.ComputeHash(baRefd); XmlElement refElem = plainDoc.CreateElement(Pre.ds, Elem.Reference, Ns.ds); XmlAttribute refUri = plainDoc.CreateAttribute(Attrib.URI); refUri.Value = "#" + xaId.Value; refElem.Attributes.Append(refUri); sigInfoElem.AppendChild(refElem); XmlElement transsElem = plainDoc.CreateElement(Pre.ds, Elem.Transforms, Ns.ds); refElem.AppendChild(transsElem); XmlElement transElem = plainDoc.CreateElement(Pre.ds, Elem.Transform, Ns.ds); XmlAttribute transAlg = plainDoc.CreateAttribute(Attrib.Algorithm); transAlg.Value = Alg.xmlExcC14n; transElem.Attributes.Append(transAlg); transsElem.AppendChild(transElem); XmlElement digMethElem = plainDoc.CreateElement(Pre.ds, Elem.DigestMethod, Ns.ds); XmlAttribute digMethAlg = plainDoc.CreateAttribute("Algorithm"); digMethAlg.Value = Alg.sha1; digMethElem.Attributes.Append(digMethAlg); refElem.AppendChild(digMethElem); XmlElement digValElem = plainDoc.CreateElement(Pre.ds, Elem.DigestValue, Ns.ds); digValElem.InnerText = OpenNETCF.Security.Cryptography.NativeMethods.Format.GetB64(baDigest); refElem.AppendChild(digValElem); } //canonical SignedInfo, get key, get signature XmlDocument xdSigInfo = new XmlDocument(); xdSigInfo.LoadXml(sigInfoElem.OuterXml); XmlCanonicalizer xcSi = new XmlCanonicalizer(comments, exclusive); MemoryStream msSigInfo = (MemoryStream)xcSi.Canonicalize(xdSigInfo); byte [] baSigInfo = new byte[msSigInfo.Length]; msSigInfo.Read(baSigInfo, 0, baSigInfo.Length); byte [] baSig = null; if (SigObj.BinSecTok != null) { byte [] baUnsigHash = shaCsp.ComputeHash(baSigInfo); baSig = SigObj.AsymmAlg.SignHash(baUnsigHash, "SHA"); } if (SigObj.UserTok != null) { byte [] derKey = P_SHA1.DeriveKey(SigObj.ClearPassword, StrKeyLabel, SigObj.UserTok.Nonce.Text, SigObj.UserTok.Created, NumKeyBytes); HMACSHA1 hs = new HMACSHA1(derKey); baSig = hs.ComputeHash(baSigInfo); } if (SigObj.securityContextToken != null) { //XmlElement createdElem = LameXpath.SelectSingleNode(SigObj.securityContextToken, "Created"); //string strCreated = createdElem.InnerText; //2004-03-05T01:59:49Z //string label = "WS-Security"; ////byte [] baKey = P_SHA1.DeriveKey(password, label, nonce, created, 24); //byte [] baKey = P_SHA1.DeriveKey(String.Empty, label, String.Empty, strCreated, 24); //HMACSHA1 hs = new HMACSHA1(baKey); //baSig = hs.ComputeHash(baSigInfo); byte [] hashKey; if (SigObj.derKeyTok != null) { hashKey = SigObj.derKeyTok.derKey; } else { hashKey = SigObj.securityContextKey; } HMACSHA1 hs = new HMACSHA1(hashKey); baSig = hs.ComputeHash(baSigInfo); } //add SignatureValue XmlElement sigValElem = plainDoc.CreateElement(Pre.ds, Elem.SignatureValue, Ns.ds); sigValElem.InnerText = OpenNETCF.Security.Cryptography.NativeMethods.Format.GetB64(baSig); sigElem.AppendChild(sigValElem); //add KeyInfo XmlElement keyInfoElem = plainDoc.CreateElement(Pre.ds, Elem.KeyInfo, Ns.ds); XmlElement secTokRefElem = plainDoc.CreateElement(Pre.wsse, Elem.SecurityTokenReference, Ns.wsseLatest); XmlElement sigRefElem = plainDoc.CreateElement(Pre.wsse, Elem.Reference, Ns.wsseLatest); XmlAttribute uri = plainDoc.CreateAttribute(Attrib.URI); uri.Value = "#" + secTokId; sigRefElem.Attributes.Append(uri); XmlAttribute valueType = plainDoc.CreateAttribute(Attrib.ValueType); valueType.Value = "#" + secTokId; sigRefElem.Attributes.Append(valueType); if (SigObj.UserTok != null) { XmlAttribute valType = plainDoc.CreateAttribute(Attrib.ValueType); valType.Value = Misc.tokenProfUsername + "#UsernameToken"; sigRefElem.Attributes.Append(valType); } if (SigObj.BinSecTok != null) { XmlAttribute valType = plainDoc.CreateAttribute(Attrib.ValueType); valType.Value = Misc.tokenProfX509 + "#X509v3"; sigRefElem.Attributes.Append(valType); } secTokRefElem.AppendChild(sigRefElem); keyInfoElem.AppendChild(secTokRefElem); sigElem.AppendChild(keyInfoElem); //SigObj = null; return(plainDoc); }
public void NewGuidParameter() { var g = GuidEx.NewGuid(); Assert.AreEqual(g.Version, 4); }
public static XmlDocument AddHeaders(XmlDocument xmlDoc, string action, string url, string strReplyTo) { XmlElement envelope = xmlDoc.DocumentElement; //add namespaces if (EndPoint == EndPointType.Addressing) { XmlAttribute wsa = xmlDoc.CreateAttribute(Pre.xmlns, Pre.wsa, Ns.xmlns); wsa.Value = Ns.wsaLatest; envelope.Attributes.Append(wsa); } else //routing { XmlAttribute wsrp = xmlDoc.CreateAttribute(Pre.xmlns, Pre.wsrp, Ns.xmlns); wsrp.Value = Ns.wsrp; envelope.Attributes.Append(wsrp); } XmlAttribute wsu = xmlDoc.CreateAttribute(Pre.xmlns, Pre.wsu, Ns.xmlns); wsu.Value = Ns.wsuLatest; envelope.Attributes.Append(wsu); XmlAttribute wsse = xmlDoc.CreateAttribute(Pre.xmlns, Pre.wsse, Ns.xmlns); wsse.Value = Ns.wsseLatest; envelope.Attributes.Append(wsse); XmlElement headerOrBody = (XmlElement)envelope.ChildNodes[0]; XmlElement header; XmlElement body; if (headerOrBody.LocalName == Elem.Body) { header = xmlDoc.CreateElement(headerOrBody.Prefix, Elem.Header, headerOrBody.NamespaceURI); envelope.InsertBefore(header, headerOrBody); } header = (XmlElement)envelope.ChildNodes[0]; body = (XmlElement)envelope.ChildNodes[1]; XmlNodeList headers = header.ChildNodes; bool hasTimestamp = false; bool hasReplyTo = false; bool hasAction = false; //bool hasFrom = false; bool hasMessageId = false; bool hasTo = false; bool hasPath = false; foreach (XmlNode xn in headers) { XmlElement headerElement = (XmlElement)xn; switch (headerElement.LocalName) { case Elem.Timestamp: hasTimestamp = true; break; case Elem.ReplyTo: hasReplyTo = true; break; case Elem.Action: hasAction = true; break; //case Elem.From: // hasFrom = true; // break; case Elem.MessageID: hasMessageId = true; break; case Elem.To: hasTo = true; break; case Elem.path: hasPath = true; break; } } if (EndPoint == EndPointType.Addressing) { if (hasAction == false) { //<wsa:Action>http://stockservice.contoso.com/wse/samples/2003/06/StockQuoteRequest</wsa:Action> XmlElement actionElem = xmlDoc.CreateElement(Pre.wsa, Elem.Action, Ns.wsaLatest); actionElem.InnerText = action; header.AppendChild(actionElem); } if (hasMessageId == false) { //<wsa:MessageID>uuid:e5b8263b-43f1-4799-aa11-0d53a1ea7ace</wsa:MessageID> XmlElement messageId = xmlDoc.CreateElement(Pre.wsa, Elem.MessageID, Ns.wsaLatest); messageId.InnerText = "uuid:" + GuidEx.NewGuid().ToString("D"); header.AppendChild(messageId); } /* * if(hasFrom == false) * { * //<wsa:From><wsa:Address>http://schemas.xmlsoap.org/ws/2003/03/addressing/role/anonymous</wsa:Address></wsa:From> * XmlElement from = xmlDoc.CreateElement(Pre.wsa, Elem.From, Ns.wsaLatest); * XmlElement address = xmlDoc.CreateElement(Pre.wsa, Elem.Address, Ns.wsaLatest); * address.InnerText = Misc.wsaAddress; * from.AppendChild(address); * header.AppendChild(from); * } */ //<ReplyTo xmlns="http://schemas.xmlsoap.org/ws/2003/03/addressing"><Address>http://tempuri.org/RespondToClientCall/</Address></ReplyTo> if (hasReplyTo == false) { XmlElement replyTo = xmlDoc.CreateElement(Pre.wsa, Elem.ReplyTo, Ns.wsaLatest); XmlElement address = xmlDoc.CreateElement(Pre.wsa, Elem.Address, Ns.wsaLatest); address.InnerText = strReplyTo; replyTo.AppendChild(address); header.AppendChild(replyTo); } if (hasTo == false) { //<wsa:To>http://localhost/RouterService/StockService.asmx</wsa:To> XmlElement to = xmlDoc.CreateElement(Pre.wsa, Elem.To, Ns.wsaLatest); if (SoapActorUrl == null || SoapActorUrl == String.Empty) { to.InnerText = url; } else { to.InnerText = SoapActorUrl; } header.AppendChild(to); } } else //routing { if (hasPath == false) { XmlElement path = xmlDoc.CreateElement(Pre.wsrp, Elem.path, Ns.wsrp); XmlAttribute actor = xmlDoc.CreateAttribute(Pre.soap, Attrib.actor, Ns.soap); actor.Value = Misc.pathActorNext; path.Attributes.Append(actor); XmlAttribute mustUnderstand = xmlDoc.CreateAttribute(Pre.soap, Attrib.mustUnderstand, Ns.soap); mustUnderstand.Value = "1"; path.Attributes.Append(mustUnderstand); XmlElement actionElem = xmlDoc.CreateElement(Pre.wsrp, Elem.action, Ns.wsrp); actionElem.InnerText = action; path.AppendChild(actionElem); XmlElement to = xmlDoc.CreateElement(Pre.wsrp, Elem.to, Ns.wsrp); to.InnerText = url; path.AppendChild(to); XmlElement id = xmlDoc.CreateElement(Pre.wsrp, Elem.id, Ns.wsrp); id.InnerText = "uuid:" + GuidEx.NewGuid().ToString("D"); path.AppendChild(id); header.AppendChild(path); } } if (hasTimestamp == false) { XmlElement security = null; foreach (XmlNode xn in headers) { if (xn.LocalName == Elem.Security) { security = (XmlElement)xn; } } if (security == null) { security = xmlDoc.CreateElement(Pre.wsse, Elem.Security, Ns.wsseLatest); XmlAttribute mustUnderstand = xmlDoc.CreateAttribute(Pre.soap, Attrib.mustUnderstand, Ns.soap); mustUnderstand.Value = "1"; security.Attributes.Append(mustUnderstand); header.AppendChild(security); } XmlElement timestamp = xmlDoc.CreateElement(Pre.wsu, Elem.Timestamp, Ns.wsuLatest); XmlElement created = xmlDoc.CreateElement(Pre.wsu, Elem.Created, Ns.wsuLatest); created.InnerText = TimestampHeader.ConvertDateTime(DateTime.UtcNow); XmlElement expires = xmlDoc.CreateElement(Pre.wsu, Elem.Expires, Ns.wsuLatest); expires.InnerText = TimestampHeader.ConvertDateTime(DateTime.UtcNow.AddSeconds(secondsToTimeout)); timestamp.AppendChild(created); timestamp.AppendChild(expires); //header.AppendChild(timestamp); security.AppendChild(timestamp); } return(xmlDoc); }
public void VersionTestFour() { var g = GuidEx.NewGuid(); Assert.AreEqual(g.Version, 4); }
public UsernameTokenV1(string username, string password, PasswordOption passType, EncodingType encType) { this.Username = new Username(); this.Username.Text = username; System.Guid g = GuidEx.NewGuid(); this.Id = "SecurityToken-" + g.ToString("D"); if (passType == PasswordOption.SendNone) { this.Password = null; } this.Password = new PasswordV1(); if (passType == PasswordOption.SendPlainText) { this.Password.Type = "wsse:PasswordText"; this.Password.Text = password; } if (passType == PasswordOption.SendHashed) { this.Password.Type = "wsse:PasswordDigest"; DateTime dtCreated = DateTime.UtcNow; this.Created = XmlConvert.ToString(dtCreated, "yyyy-MM-ddTHH:mm:ssZ"); byte [] baCreated = Encoding.UTF8.GetBytes(this.Created); this.Nonce = new Nonce(); //this random number gen is not as strong //Random r = new Random(Environment.TickCount); //byte [] baNonce = new byte[20]; //r.NextBytes(baNonce); byte [] baNonce = OpenNETCF.Security.Cryptography.NativeMethods.Rand.GetRandomBytes(20); this.Nonce.Text = Convert.ToBase64String(baNonce, 0, baNonce.Length); byte [] baPassword = Encoding.UTF8.GetBytes(password); int baDigestLength = baNonce.Length + baCreated.Length + baPassword.Length; byte [] baDigest = new byte[baDigestLength]; Array.Copy(baNonce, 0, baDigest, 0, baNonce.Length); Array.Copy(baCreated, 0, baDigest, baNonce.Length, baCreated.Length); Array.Copy(baPassword, 0, baDigest, baNonce.Length + baCreated.Length, baPassword.Length); //byte [] hash = Hash.ComputeHash(CalgHash.SHA1, baDigest); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte [] hash = sha1.ComputeHash(baDigest); if (encType == EncodingType.Base64Binary) { //default is Base64Binary so dont have to set //this.Password.Type = "wsse:Base64Binary"; this.Password.Text = Convert.ToBase64String(hash, 0, hash.Length); } if (encType == EncodingType.HexBinary) { this.Password.Type = "wsse:HexBinary"; this.Password.Text = OpenNETCF.Security.Cryptography.NativeMethods.Format.GetHexBin(hash); } } }
/// <summary> /// 添加学生 /// </summary> /// <param name="upload"></param> /// <returns></returns> public async Task <IActionResult> OnPostAsync(IFormFile upload) { if (upload != null /* && upload.Length <= (5 * 1024 * 1024)*/) { var extend = System.IO.Path.GetExtension(upload.FileName); string[] enableExtend = new string[] { ".xls", ".xlsx" }; if (!enableExtend.Contains(extend.ToLower())) { ModelState.AddModelError(string.Empty, "只能上传.xls 和 .xlsx 文件"); return(Page()); } //name id // Dictionary<string, string> tempClasses = new Dictionary<string, string>(); using MemoryStream memoryStream = new MemoryStream(); await upload.CopyToAsync(memoryStream).ConfigureAwait(false); //name id Dictionary <string, string> tempClasses = new Dictionary <string, string>(); var studentRole = await applicationDbContext.Roles.FirstOrDefaultAsync(e => e.Name == "学生").ConfigureAwait(false); if (studentRole == null) { var role = new ApplicationRole("学生"); await applicationDbContext.Roles.AddAsync(role).ConfigureAwait(false); await applicationDbContext.SaveChangesAsync().ConfigureAwait(false); studentRole = await applicationDbContext.Roles.FirstOrDefaultAsync(e => e.Name == "学生").ConfigureAwait(false); } if (studentRole == null) { ModelState.AddModelError("", "没有学生角色"); return(BadRequest(ModelState)); } using (ExcelPackage package = new ExcelPackage(memoryStream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; //坑 第一行居然不是从第0行开始 for (int row = 1; row <= rowCount; row++) { string className = worksheet.Cells[row, 1]?.Value?.ToString().Trim(); string userName = worksheet.Cells[row, 2]?.Value?.ToString().Trim(); string name = worksheet.Cells[row, 3]?.Value?.ToString().Trim(); string password = "******"; if (className.IsNullOrEmpty() || userName.IsNullOrEmpty() || name.IsNullOrEmpty()) { continue; } if (IsNumber(userName)) { string classId = null; var classInfo = await applicationDbContext.SchoolClasses. FirstOrDefaultAsync(e => e.Name == className).ConfigureAwait(false); if (classInfo == null) { if (!tempClasses.ContainsKey(className)) { tempClasses.Add(className, Guid.NewGuid().ToString("N")); } classId = tempClasses[className]; } else { classId = classInfo.Id; } if (!await applicationDbContext.Users.AnyAsync(e => e.UserName == userName).ConfigureAwait(false)) { var userId = GuidEx.NewGuid().ToString(); await applicationDbContext.Users.AddAsync(new IdentityServerCenter.Models.ApplicationUser { Id = userId, UserName = userName, Name = name, NormalizedUserName = userName.ToUpper(CultureInfo.CurrentCulture), Password = password, ClassId = classId }).ConfigureAwait(false); //分配角色 await applicationDbContext.UserRoles.AddAsync(new IdentityUserRole <string> { UserId = userId, RoleId = studentRole.Id }).ConfigureAwait(false); } } } //添加班级 foreach (var c in tempClasses) { applicationDbContext.SchoolClasses.Add(new IdentityServerCenter.Models.SchoolClass { Id = c.Value, Name = c.Key }); } var rows = await applicationDbContext.SaveChangesAsync().ConfigureAwait(false); } return(RedirectToPage()); } ModelState.AddModelError(string.Empty, "空文件"); return(Page()); }
/// <summary> /// Writes an entry to the log file /// </summary> /// <param name="source"></param> /// <param name="message"></param> /// <param name="type"></param> /// <param name="eventID"></param> /// <param name="category"></param> /// <param name="rawData"></param> private void WriteEntryToLog(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { if (this.nodeLog != null) { //Create the event node XmlNode nodeEventLog = this.xmlLog.CreateNode(XmlNodeType.Element, "eventLogEntry", ""); //Now create all the attributes DateTime timeGenerated = DateTime.Now; string machineName = "."; string userName = ""; //Machine Name XmlAttribute att = this.xmlLog.CreateAttribute("machineName"); att.Value = machineName; nodeEventLog.Attributes.Append(att); //user name att = this.xmlLog.CreateAttribute("userName"); att.Value = userName; nodeEventLog.Attributes.Append(att); //DateTime generate att = this.xmlLog.CreateAttribute("timeGenerated"); att.Value = DateTime.Now.ToString(); nodeEventLog.Attributes.Append(att); //source att = this.xmlLog.CreateAttribute("source"); att.Value = source; nodeEventLog.Attributes.Append(att); //message att = this.xmlLog.CreateAttribute("message"); att.Value = message; nodeEventLog.Attributes.Append(att); //EventLogEntryType att = this.xmlLog.CreateAttribute("eventLogEntryType"); att.Value = ((int)type).ToString(); nodeEventLog.Attributes.Append(att); //EventID att = this.xmlLog.CreateAttribute("eventID"); att.Value = eventID.ToString(); nodeEventLog.Attributes.Append(att); //categor att = this.xmlLog.CreateAttribute("category"); att.Value = category.ToString(); nodeEventLog.Attributes.Append(att); //rawData att = this.xmlLog.CreateAttribute("rawData"); if (rawData == null) { rawData = new byte[0]; } att.Value = Convert.ToBase64String(rawData, 0, rawData.Length); nodeEventLog.Attributes.Append(att); //Add a GUID Guid id = GuidEx.NewGuid(); att = this.xmlLog.CreateAttribute("id"); att.Value = id.ToString(); nodeEventLog.Attributes.Append(att); //add index int index = this.eventLogEntryCollection.Count + 1; att = this.xmlLog.CreateAttribute("index"); att.Value = index.ToString(); nodeEventLog.Attributes.Append(att); //Time written DateTime timeWritten = DateTime.Now; att = this.xmlLog.CreateAttribute("timeWritten"); att.Value = timeWritten.ToString(); nodeEventLog.Attributes.Append(att); //Add the eventLog to the xml this.nodeLog.AppendChild(nodeEventLog); //Add the eventlog to the collection int lastEntry = this.eventLogEntryCollection.Add(new EventLogEntry(category, rawData, type, eventID, index, machineName, message, source, timeGenerated, timeWritten, userName, id.ToString())); //Save the log file this.SaveLogFile(); //Raise the event to listers this.OnEntryWritten(this.eventLogEntryCollection[lastEntry]); } }
public EntityBase() { Id = GuidEx.NewGuid(); }