/// <summary> /// 更新指定ID的用户通过题目总数 /// </summary> /// <param name="userName">用户名</param> /// <returns>是否成功更新</returns> public static IMethodResult AdminUpdateSolvedCount(String userName) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsUserName(userName)) { return(MethodResult.InvalidRequest(RequestType.User)); } Boolean success = UserRepository.Instance.UpdateEntitySolvedCount(userName) > 0; if (!success) { return(MethodResult.FailedAndLog("No user's solved count was recalculated!")); } return(MethodResult.SuccessAndLog("Admin update user's solved count, name = {0}", userName)); }
/// <summary> /// 更新指定ID的用户是否锁定 /// </summary> /// <param name="userNames">用户名</param> /// <param name="isLocked">是否锁定</param> /// <returns>是否成功更新</returns> public static IMethodResult AdminUpdateUserIsLocked(String userNames, Boolean isLocked) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(userNames)) { return(MethodResult.InvalidRequest(RequestType.User)); } Boolean success = UserRepository.Instance.UpdateEntityIsLocked(userNames, isLocked) > 0; if (!success) { return(MethodResult.FailedAndLog("No user was {0}!", isLocked ? "locked" : "unlocked")); } return(MethodResult.SuccessAndLog("Admin {1} user, name = {0}", userNames, isLocked ? "lock" : "unlock")); }
/// <summary> /// 获取用户信息 /// </summary> /// <param name="userName">用户名</param> /// <returns>用户实体</returns> public static IMethodResult AdminGetUserInfo(String userName) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsUserName(userName)) { return(MethodResult.InvalidRequest(RequestType.User)); } UserEntity entity = UserRepository.Instance.GetEntityWithAllInfo(userName); if (entity == null) { return(MethodResult.NotExist(RequestType.User)); } return(MethodResult.Success(entity)); }
/// <summary> /// 获取题目数据物理路径 /// </summary> /// <param name="problemID">题目ID</param> /// <returns>题目数据物理路径</returns> public static IMethodResult AdminGetProblemDataDownloadPath(Int32 problemID) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } String dataPath = ProblemDataManager.GetProblemDataRealPath(problemID); if (String.IsNullOrEmpty(dataPath)) { return(MethodResult.FailedAndLog("This problem doesn't have data!")); } return(MethodResult.SuccessAndLog <String>(dataPath, "Admin download problem data, id = {0}", problemID.ToString())); }
/// <summary> /// 根据ID得到一个对象实体 /// </summary> /// <param name="resourceID">实体ID</param> /// <returns>对象实体</returns> public static IMethodResult AdminGetResource(Int32 id) { if (!AdminManager.HasPermission(PermissionType.ResourceManage)) { throw new NoPermissionException(); } if (id <= 0) { return(MethodResult.InvalidRequest(RequestType.Resource)); } ResourceEntity entity = ResourceRepository.Instance.GetEntity(id); if (entity == null) { return(MethodResult.NotExist(RequestType.Resource)); } return(MethodResult.Success(entity)); }
/// <summary> /// 根据ID得到一个主题页面实体 /// </summary> /// <param name="id">主题页面ID</param> /// <returns>主题页面实体</returns> public static IMethodResult AdminGetTopicPage(String name) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsPageName(name)) { return(MethodResult.InvalidRequest(RequestType.TopicPage)); } TopicPageEntity entity = TopicPageRepository.Instance.GetEntity(name); if (entity == null) { return(MethodResult.NotExist(RequestType.TopicPage)); } return(MethodResult.Success(entity)); }
/// <summary> /// 保存题目数据文件到磁盘 /// </summary> /// <param name="problemID">题目ID</param> /// <param name="problemdata">题目数据文件</param> /// <returns>是否保存成功</returns> internal static IMethodResult InternalAdminSaveProblemData(Int32 problemID, Byte[] problemdata) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } String fileNewName = problemID.ToString() + ".zip"; String savePath = Path.Combine(ConfigurationManager.ProblemDataPath, fileNewName); File.WriteAllBytes(savePath, problemdata); ProblemDataCache.RemoveProblemDataVersionCache(problemID); return(MethodResult.Success()); }
/// <summary> /// 删除指定ID的主题页面 /// </summary> /// <param name="ids">逗号分隔的主题页面ID</param> /// <returns>是否成功删除</returns> public static IMethodResult AdminDeleteTopicPages(String names) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } Boolean success = TopicPageRepository.Instance.DeleteEntities(names) > 0; if (!success) { return(MethodResult.FailedAndLog("No page was deleted!")); } names.ForEachInIDs(',', name => { TopicPageCache.RemoveTopicPageCache(name);//删除缓存 }); return(MethodResult.SuccessAndLog("Admin delete page, name = {0}", names)); }
/// <summary> /// 更新指定ID的用户的用户权限 /// </summary> /// <param name="userNames">用户名</param> /// <param name="permission">权限类型</param> /// <returns>是否成功更新</returns> internal static IMethodResult InternalAdminUpdatePermission(String userName, PermissionType permission) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsUserName(userName)) { return(MethodResult.InvalidRequest(RequestType.User)); } Boolean success = UserRepository.Instance.UpdateEntityPermision(userName, permission) > 0; if (!success) { return(MethodResult.FailedAndLog("Failed to update user's permission!")); } return(MethodResult.Success()); }
/// <summary> /// 增加一条主题页面 /// </summary> /// <param name="model">对象实体</param> /// <returns>是否成功增加</returns> public static IMethodResult AdminInsertTopicPage(TopicPageEntity entity) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsPageName(entity.PageName)) { return(MethodResult.InvalidRequest(RequestType.TopicPage)); } if (String.IsNullOrEmpty(entity.Title)) { return(MethodResult.FailedAndLog("Page title can not be NULL!")); } if (String.IsNullOrEmpty(entity.Description)) { return(MethodResult.FailedAndLog("Page description can not be NULL!")); } if (String.IsNullOrEmpty(entity.Content)) { return(MethodResult.FailedAndLog("Page content can not be NULL!")); } entity.CreateUser = UserManager.CurrentUserName; entity.IsHide = true; entity.LastDate = DateTime.Now; Boolean success = TopicPageRepository.Instance.InsertEntity(entity) > 0; if (!success) { return(MethodResult.FailedAndLog("No page was added!")); } return(MethodResult.SuccessAndLog("Admin add page, name = {0}", entity.PageName)); }
/// <summary> /// 删除指定ID的公告 /// </summary> /// <param name="ids">逗号分隔的公告ID</param> /// <returns>是否成功删除</returns> public static IMethodResult AdminDeleteNews(String ids) { if (!AdminManager.HasPermission(PermissionType.NewsManage)) { throw new NoPermissionException(); } if (!RegexVerify.IsNumericIDs(ids)) { return(MethodResult.InvalidRequest(RequestType.News)); } String[] arrids = ids.Split(','); String defaultID = NewsRepository.DEFAULTID.ToString(); for (Int32 i = 0; i < arrids.Length; i++) { if (String.Equals(arrids[i], defaultID)) { return(MethodResult.FailedAndLog("Can not delete the default news!")); } } Boolean success = NewsRepository.Instance.DeleteEntities(ids) > 0; if (!success) { return(MethodResult.FailedAndLog("No news was deleted!")); } ids.ForEachInIDs(',', id => { NewsCache.RemoveNewsCache(id); //删除缓存 }); NewsCache.RemoveLastestNewsListCache(); //删除缓存 NewsCache.RemoveNewsCountCache(); //删除缓存 return(MethodResult.SuccessAndLog("Admin delete news, id = {0}", ids)); }
/// <summary> /// 更新指定ID的用户的用户权限 /// </summary> /// <param name="userNames">用户名</param> /// <param name="permissions">权限类型</param> /// <returns>是否成功更新</returns> public static IMethodResult AdminUpdatePermision(String userName, String permissions) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!RegexVerify.IsUserName(userName)) { return(MethodResult.InvalidRequest(RequestType.User)); } PermissionType permission = AdminManager.GetPermission(permissions); Boolean success = UserRepository.Instance.UpdateEntityPermision(userName, permission) > 0; if (!success) { return(MethodResult.FailedAndLog("No user's permission was updated!")); } return(MethodResult.SuccessAndLog("Admin update permission, name = {0}, permission = {1}", userName, ((Int32)permission).ToString())); }
/// <summary> /// 增加一条题目类型种类 /// </summary> /// <param name="entity">题目类型种类实体</param> /// <returns>是否成功增加</returns> public static IMethodResult AdminInsertProblemCategory(ProblemCategoryEntity entity) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(entity.Title)) { return(MethodResult.FailedAndLog("Problem category title cannot be NULL!")); } Boolean success = ProblemCategoryRepository.Instance.InsertEntity(entity) > 0; if (!success) { return(MethodResult.FailedAndLog("No problem category was added!")); } ProblemCategoryCache.RemoveProblemCategoryListCache();//删除缓存 return(MethodResult.SuccessAndLog("Admin add problem category, title = {0}", entity.Title)); }
/// <summary> /// 删除上传文件 /// </summary> /// <param name="fileName">文件名</param> /// <returns>是否删除成功</returns> public static IMethodResult AdminDeleteUploadFile(String fileName) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(fileName)) { return(MethodResult.FailedAndLog("Filename can not be NULL!")); } String filePath = Path.Combine(ConfigurationManager.UploadDirectoryPath, fileName); if (!File.Exists(filePath)) { return(MethodResult.FailedAndLog("File does not exist!")); } File.Delete(filePath); return(MethodResult.SuccessAndLog("Admin delete upload file, name = {0}", fileName)); }
/// <summary> /// 删除指定ID的竞赛用户 /// </summary> /// <param name="cid">竞赛ID</param> /// <param name="usernames">逗号分隔的用户名</param> /// <returns>是否成功删除</returns> public static IMethodResult AdminDeleteContestUsers(Int32 cid, String usernames) { if (!AdminManager.HasPermission(PermissionType.ContestManage)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(usernames)) { return(MethodResult.FailedAndLog("You must select at least one item!")); } Boolean success = ContestUserRepository.Instance.DeleteEntities(cid, usernames) > 0; if (!success) { return(MethodResult.FailedAndLog("No contest user was deleted!")); } ContestUserCache.RemoveContestUserListCache(cid); return(MethodResult.SuccessAndLog("Admin delete contest user, cid = {0}, username = {1}", cid.ToString(), usernames)); }
/// <summary> /// 删除题目数据 /// </summary> /// <param name="problemID">题目ID</param> /// <returns>是否删除成功</returns> public static IMethodResult AdminDeleteProblemDataRealPath(Int32 problemID) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } String dataPath = ProblemDataManager.GetProblemDataRealPath(problemID); if (String.IsNullOrEmpty(dataPath)) { return(MethodResult.FailedAndLog("This problem does not have data!")); } File.Delete(dataPath); ProblemDataCache.RemoveProblemDataVersionCache(problemID); return(MethodResult.SuccessAndLog("Admin delete problem data, id = {0}", problemID.ToString())); }
/// <summary> /// 备份指定数据库 /// </summary> /// <param name="fileName">数据库文件名</param> /// <returns>是否备份成功</returns> public static IMethodResult AdminBackupDataBase(String fileName) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!DatabaseManager.IsAccessDB) { throw new DatabaseNotSupportException(); } String sourcePath = DatabaseManager.AccessDBFullPath; String destPath = Path.Combine(DatabaseManager.AccessDataDirectory, fileName); if (String.Equals(sourcePath, destPath, StringComparison.OrdinalIgnoreCase)) { return(MethodResult.FailedAndLog("You can not use this filename!")); } File.Copy(sourcePath, destPath, true); return(MethodResult.SuccessAndLog("Admin backup database, name = {0}", fileName)); }
/// <summary> /// 更新题目通过总数 /// </summary> /// <param name="problemID">题目ID</param> /// <returns>是否成功更新</returns> public static IMethodResult AdminUpdateProblemSolvedCount(Int32 problemID) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } Boolean success = ProblemRepository.Instance.UpdateEntitySolvedCount(problemID) > 0; if (!success) { return(MethodResult.FailedAndLog("No problem's solved count was recalculated!")); } ProblemCache.RemoveProblemCache(problemID); //删除缓存 ProblemCache.RemoveProblemSetCache(GetProblemPageIndex(problemID)); //删除缓存 return(MethodResult.SuccessAndLog("Admin update problem's solved count, id = {0}", problemID.ToString())); }
/// <summary> /// 更新题目信息 /// </summary> /// <param name="entity">对象实体</param> /// <returns>是否成功更新</returns> public static IMethodResult AdminUpdateProblem(ProblemEntity entity) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (entity.ProblemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } if (String.IsNullOrEmpty(entity.Title)) { return(MethodResult.FailedAndLog("Problem title cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Description)) { return(MethodResult.FailedAndLog("Problem description cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Input)) { return(MethodResult.FailedAndLog("Problem input cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Output)) { return(MethodResult.FailedAndLog("Problem output cannot be NULL!")); } if (String.IsNullOrEmpty(entity.SampleInput)) { return(MethodResult.FailedAndLog("Problem sample input cannot be NULL!")); } if (String.IsNullOrEmpty(entity.SampleOutput)) { return(MethodResult.FailedAndLog("Problem sample output cannot be NULL!")); } if (entity.TimeLimit <= 0) { return(MethodResult.FailedAndLog("Time limit must not be less or equal than zero!")); } if (entity.MemoryLimit <= 0) { return(MethodResult.FailedAndLog("Memory limit must not be less or equal than zero!")); } entity.LastDate = DateTime.Now; Boolean success = ProblemRepository.Instance.UpdateEntity(entity) > 0; if (!success) { return(MethodResult.FailedAndLog("No problem was updated!")); } ProblemCache.RemoveProblemCache(entity.ProblemID);//删除缓存 ProblemCache.RemoveProblemSetCache(GetProblemPageIndex(entity.ProblemID)); return(MethodResult.SuccessAndLog("Admin update problem, id = {0}", entity.ProblemID.ToString())); }
/// <summary> /// 保存题目数据文件到磁盘 /// </summary> /// <param name="problemID">题目ID</param> /// <param name="forms">Request.Forms</param> /// <param name="httpFiles">Request.Files</param> /// <returns>是否保存成功</returns> public static IMethodResult AdminSaveProblemData(Int32 problemID, NameValueCollection forms, HttpFileCollectionBase httpFiles) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } SortedDictionary <String, String> dictData = new SortedDictionary <String, String>(); if (httpFiles != null) { for (Int32 i = 0; i < httpFiles.Count; i++) { HttpPostedFileBase file = httpFiles[i]; if (String.IsNullOrEmpty(file.FileName)) { return(MethodResult.FailedAndLog("Filename can not be NULL!")); } FileInfo fi = new FileInfo(file.FileName); if (httpFiles.GetKey(i).IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0 && !".in".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase)) { return(MethodResult.FailedAndLog("Filename is INVALID!")); } if (httpFiles.GetKey(i).IndexOf("out", StringComparison.OrdinalIgnoreCase) == 0 && !".out".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && !".ans".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase)) { return(MethodResult.FailedAndLog("Filename is INVALID!")); } if (file.ContentLength <= 0) { return(MethodResult.FailedAndLog("You can not upload empty file!")); } StreamReader sr = new StreamReader(file.InputStream); dictData.Add(httpFiles.GetKey(i), sr.ReadToEnd()); } } if (forms != null) { for (Int32 i = 0; i < forms.Count; i++) { if (forms.GetKey(i).IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0 || forms.GetKey(i).IndexOf("out", StringComparison.OrdinalIgnoreCase) == 0) { dictData.Add(forms.GetKey(i), forms[i]); } } } if (dictData.Count == 0) { return(MethodResult.FailedAndLog("No data was added!")); } if (dictData.Count % 2 != 0) { return(MethodResult.FailedAndLog("The count of uploaded data is INVALID!")); } ProblemDataWriter writer = new ProblemDataWriter(); foreach (KeyValuePair <String, String> pair in dictData) { if (pair.Key.IndexOf("in", StringComparison.OrdinalIgnoreCase) == 0) { String input = pair.Value; String output = String.Empty; if (!dictData.TryGetValue(pair.Key.ToLower().Replace("in", "out"), out output)) { return(MethodResult.FailedAndLog("The count of uploaded data is INVALID!")); } writer.WriteData(input, output); } } String fileNewName = problemID.ToString() + ".zip"; String savePath = Path.Combine(ConfigurationManager.ProblemDataPath, fileNewName); Byte[] data = writer.WriteTo(); File.WriteAllBytes(savePath, data); ProblemDataCache.RemoveProblemDataVersionCache(problemID); return(MethodResult.SuccessAndLog("Admin create problem data, id = {0}", problemID.ToString())); }
/// <summary> /// 增加一条题目 /// </summary> /// <param name="entity">题目实体</param> /// <returns>是否成功增加</returns> public static IMethodResult AdminInsertProblem(ProblemEntity entity) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(entity.Title)) { return(MethodResult.FailedAndLog("Problem title cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Description)) { return(MethodResult.FailedAndLog("Problem description cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Input)) { return(MethodResult.FailedAndLog("Problem input cannot be NULL!")); } if (String.IsNullOrEmpty(entity.Output)) { return(MethodResult.FailedAndLog("Problem output cannot be NULL!")); } if (String.IsNullOrEmpty(entity.SampleInput)) { return(MethodResult.FailedAndLog("Problem sample input cannot be NULL!")); } if (String.IsNullOrEmpty(entity.SampleOutput)) { return(MethodResult.FailedAndLog("Problem sample output cannot be NULL!")); } if (entity.TimeLimit <= 0) { return(MethodResult.FailedAndLog("Time limit must not be less or equal than zero!")); } if (entity.MemoryLimit <= 0) { return(MethodResult.FailedAndLog("Memory limit must not be less or equal than zero!")); } entity.IsHide = true; entity.LastDate = DateTime.Now; Boolean success = ProblemRepository.Instance.InsertEntity(entity) > 0; if (!success) { return(MethodResult.FailedAndLog("No problem was added!")); } ProblemCache.IncreaseProblemSetCountCache(); //更新缓存 ProblemCache.IncreaseProblemIDMaxCache(); //更新缓存 ProblemCache.RemoveProblemSetCache(GetProblemPageIndex(entity.ProblemID)); //删除缓存 return(MethodResult.SuccessAndLog("Admin add problem, title = {0}", entity.Title)); }
/// <summary> /// 申请找回密码 /// </summary> /// <param name="userName">用户名</param> /// <param name="email">电子邮箱</param> /// <param name="userip">用户IP</param> /// <param name="checkCode">验证码</param> /// <param name="link">找回密码链接</param> /// <returns>是否可以申请</returns> public static async Task <IMethodResult> RequestResetUserPassword(String userName, String email, String userip, String checkCode, String link) { if (!CheckCodeStatus.VerifyCheckCode(checkCode)) { return(MethodResult.Failed("The verification code you input didn't match the picture, Please try again!")); } if (!RegexVerify.IsUserName(userName)) { return(MethodResult.InvalidRequest(RequestType.User)); } if (!RegexVerify.IsEmail(email)) { return(MethodResult.Failed("Email address is INVALID!")); } UserEntity user = UserManager.InternalGetUserByNameAndEmail(userName, email); if (user == null) { return(MethodResult.Failed("The username \"{0}\" doesn't exist or the email is wrong!", userName)); } if (user.IsLocked) { return(MethodResult.Failed("The user is locked, please contact the administrator!")); } if (String.IsNullOrEmpty(user.Email) || "NULL".Equals(user.Email, StringComparison.OrdinalIgnoreCase)) { return(MethodResult.Failed("The user has no email, please contact the administrator!")); } Random rand = new Random(DateTime.Now.Millisecond); UserForgetPasswordEntity ufp = new UserForgetPasswordEntity() { UserName = userName, SubmitDate = DateTime.Now, SubmitIP = userip, HashKey = MD5Encrypt.EncryptToHexString(String.Format("{0}-{1}-{2}", userName, DateTime.Now.Ticks.ToString(), rand.Next(DateTime.Now.Millisecond)), true) }; Boolean success = UserForgetPasswordRepository.Instance.InsertEntity(ufp) > 0; if (!success) { return(MethodResult.Failed("Failed to process your request!")); } String url = ConfigurationManager.DomainUrl + ((link[0] == '/') ? link.Substring(1) : link); String mailSubject = ConfigurationManager.OnlineJudgeName + " Password Recovery"; String mailContent = UserForgetPasswordManager.GetMailContent(userName, url + ufp.HashKey.ToLowerInvariant()); try { await MailClient.SendMailAsync(ConfigurationManager.EmailSMTPServer, ConfigurationManager.EmailAddresser, email, mailSubject, mailContent, true, true, ConfigurationManager.EmailUsername, ConfigurationManager.EmailPassword); } catch { return(MethodResult.Failed("Failed to send a password reset link to your email address.")); } return(MethodResult.SuccessAndLog("User forget password, name = {0}", userName)); }
/// <summary> /// 添加指定ID的竞赛用户 /// </summary> /// <param name="cid">竞赛ID</param> /// <param name="usernames">竞赛用户</param> /// <returns>是否成功添加</returns> public static IMethodResult AdminInsertContestUsers(Int32 cid, String usernames) { if (!AdminManager.HasPermission(PermissionType.ContestManage)) { throw new NoPermissionException(); } if (String.IsNullOrEmpty(usernames)) { return(MethodResult.InvalidRequest(RequestType.User)); } Dictionary <String, ContestUserEntity> dict = new Dictionary <String, ContestUserEntity>(); StringBuilder names = new StringBuilder(); String[] namelist = usernames.Split('\n'); for (Int32 i = 0; i < namelist.Length; i++) { String[] name = namelist[i].Replace('\t', ' ').Split(' '); if (name.Length < 1 || String.IsNullOrEmpty(name[0].Trim())) { continue; } ContestUserEntity entity = new ContestUserEntity() { ContestID = cid, UserName = name[0].Replace("\r", "").Trim(), RealName = (name.Length >= 2 ? name[1].Replace("\r", "").Trim() : ""), IsEnable = true, RegisterTime = DateTime.Now }; if (!dict.ContainsKey(entity.UserName)) { names.Append(names.Length > 0 ? "," : "").Append(entity.UserName); } dict[entity.UserName] = entity; } try { Int32 count = ContestUserRepository.Instance.InsertEntities(cid, names.ToString(), dict); if (count <= 0) { return(MethodResult.FailedAndLog("No contest user was added!")); } ContestUserCache.RemoveContestUserListCache(cid); return(MethodResult.SuccessAndLog <Int32>(count, "Admin add contest user, cid = {0}, username = {1}", cid.ToString(), usernames)); } catch (DbException) { return(MethodResult.FailedAndLog("Failed to add these users, please check whether the names are all correct.")); } }
/// <summary> /// 导入题目(不存在时返回null) /// </summary> /// <param name="request">Http请求</param> /// <param name="fileType">文件类型</param> /// <param name="uploadType">上传方式</param> /// <param name="content">文件内容</param> /// <param name="file">上传文件</param> /// <returns>题目数据是否插入成功集合(全部失败时为null)</returns> public static IMethodResult AdminImportProblem(HttpRequestBase request, String fileType, String uploadType, String content, HttpPostedFileBase file) { if (!AdminManager.HasPermission(PermissionType.SuperAdministrator)) { throw new NoPermissionException(); } if (!String.Equals("1", fileType)) { return(MethodResult.FailedAndLog("File type is INVALID!")); } if (String.Equals("1", uploadType))//从文件上传 { if (file == null) { return(MethodResult.FailedAndLog("No file was uploaded!")); } StreamReader sr = new StreamReader(file.InputStream); content = sr.ReadToEnd(); } //转换题库模型 List <ProblemEntity> problems = null; List <Byte[]> datas = null; List <Dictionary <String, Byte[]> > images = null; Dictionary <String, Byte[]> imagefiles = new Dictionary <String, Byte[]>(); if (!ProblemImport.TryImportFreeProblemSet(content, out problems, out datas, out images)) { return(MethodResult.FailedAndLog("File content is INVALID!")); } if (problems == null || problems.Count == 0) { return(MethodResult.FailedAndLog("No problem was imported!")); } //处理题目及图片路径 for (Int32 i = 0; i < problems.Count; i++) { problems[i].IsHide = true; problems[i].LastDate = DateTime.Now; if (images[i] == null) { continue; } String uploadRoot = ConfigurationManager.UploadDirectoryUrl; foreach (KeyValuePair <String, Byte[]> pair in images[i]) { if (pair.Value == null || !pair.Key.Contains(".")) { continue; } String oldUrl = pair.Key; String fileNewName = MD5Encrypt.EncryptToHexString(oldUrl + DateTime.Now.ToString("yyyyMMddHHmmssffff"), true) + pair.Key.Substring(pair.Key.LastIndexOf('.')); String newUrl = uploadRoot + fileNewName; problems[i].Description = problems[i].Description.Replace(oldUrl, newUrl); problems[i].Input = problems[i].Input.Replace(oldUrl, newUrl); problems[i].Output = problems[i].Output.Replace(oldUrl, newUrl); problems[i].Hint = problems[i].Hint.Replace(oldUrl, newUrl); imagefiles[fileNewName] = pair.Value; } } //将题目插入到数据库 List <Int32> pids = ProblemRepository.Instance.InsertEntities(problems); if (pids == null || pids.Count == 0) { return(MethodResult.FailedAndLog("Failed to import problem!")); } //保存题目数据 Dictionary <Int32, Boolean> dataadded = new Dictionary <Int32, Boolean>(); for (Int32 i = 0; i < pids.Count; i++) { if (pids[i] < 0) { continue; } try { if (datas[i] != null) { IMethodResult ret = ProblemDataManager.InternalAdminSaveProblemData(pids[i], datas[i]); if (!ret.IsSuccess) { return(ret); } dataadded[pids[i]] = true; } } catch { dataadded[pids[i]] = false; } ProblemCache.IncreaseProblemSetCountCache(); //更新缓存 ProblemCache.IncreaseProblemIDMaxCache(); //更新缓存 ProblemCache.RemoveProblemSetCache(GetProblemPageIndex(pids[i])); //删除缓存 } //保存题目图片 foreach (KeyValuePair <String, Byte[]> pair in imagefiles) { try { UploadsManager.InternalAdminSaveUploadFile(pair.Value, pair.Key); } catch { } } return(MethodResult.SuccessAndLog <Dictionary <Int32, Boolean> >(dataadded, "Admin import problem, id = {0}", String.Join(",", pids))); }
/// <summary> /// 尝试注册用户 /// </summary> /// <param name="entity">用户实体</param> /// <param name="password">密码</param> /// <param name="password2">重复密码</param> /// <param name="checkCode">验证码</param> /// <param name="userip">用户IP</param> /// <returns>执行结果</returns> public static IMethodResult SignUp(UserEntity entity, String password, String password2, String checkCode, String userip) { if (!CheckCodeStatus.VerifyCheckCode(checkCode)) { return(MethodResult.Failed("The verification code you input didn't match the picture, Please try again!")); } if (String.IsNullOrEmpty(entity.UserName)) { return(MethodResult.Failed("Username can not be NULL!")); } if (!RegexVerify.IsUserName(entity.UserName) || !SQLValidator.IsNonNullANDSafe(entity.UserName)) { return(MethodResult.Failed("Username can not contain illegal characters!")); } if (!KeywordsFilterManager.IsUserNameLegal(entity.UserName)) { return(MethodResult.Failed("Username can not contain illegal keywords!")); } if (entity.UserName.Length > UserRepository.USERNAME_MAXLEN) { return(MethodResult.Failed("Username is too long!")); } if (String.IsNullOrEmpty(password)) { return(MethodResult.Failed("Password can not be NULL!")); } if (!String.Equals(password, password2)) { return(MethodResult.Failed("Two passwords are not match!")); } if (String.IsNullOrEmpty(entity.Email)) { return(MethodResult.Failed("Email address can not be NULL!")); } if (!RegexVerify.IsEmail(entity.Email)) { return(MethodResult.Failed("Email address is INVALID!")); } if (entity.Email.Length > UserRepository.EMAIL_MAXLEN) { return(MethodResult.Failed("Email address is too long!")); } if (!String.IsNullOrEmpty(entity.NickName) && entity.NickName.Length > UserRepository.NICKNAME_MAXLEN) { return(MethodResult.Failed("Nick Name is too long!")); } if (!KeywordsFilterManager.IsUserNameLegal(entity.NickName)) { return(MethodResult.Failed("Nick Name can not contain illegal keywords!")); } if (!String.IsNullOrEmpty(entity.School) && entity.School.Length > UserRepository.SCHOOL_MAXLEN) { return(MethodResult.Failed("School Name is too long!")); } if (UserRepository.Instance.ExistsEntity(entity.UserName)) { return(MethodResult.Failed("The username \"{0}\" has already existed!", entity.UserName)); } if (!UserIPStatus.CheckLastRegisterTime(userip)) { return(MethodResult.Failed("You can only register one user from single ip in {0} seconds!", ConfigurationManager.RegisterInterval.ToString())); } entity.PassWord = PassWordEncrypt.Encrypt(entity.UserName, password); entity.NickName = HtmlEncoder.HtmlEncode(entity.NickName); entity.Permission = PermissionType.None; entity.CreateIP = userip; entity.CreateDate = DateTime.Now; try { if (UserRepository.Instance.InsertEntity(entity) == 0) { return(MethodResult.Failed("User Registration Failed!")); } } catch (System.Exception ex) { return(MethodResult.Failed(ex.Message)); } UserCache.RemoveRanklistUserCountCache();//删除缓存 return(MethodResult.SuccessAndLog("User sign up")); }
/// <summary> /// 尝试更新用户信息 /// </summary> /// <param name="entity">对象实体</param> /// <param name="currentPassword">当前密码</param> /// <param name="newPassword">新密码</param> /// <param name="newPassword2">重复新密码</param> /// <param name="result">执行结果</param> /// <returns>执行结果</returns> public static IMethodResult UpdateUserInfo(UserEntity entity, String currentPassword, String newPassword, String newPassword2) { if (String.IsNullOrEmpty(currentPassword)) { return(MethodResult.Failed("Current password can not be NULL!")); } else { entity.UserName = UserManager.CurrentUserName; entity.NickName = HtmlEncoder.HtmlEncode(entity.NickName); currentPassword = PassWordEncrypt.Encrypt(entity.UserName, currentPassword); } if (!String.Equals(newPassword, newPassword2)) { return(MethodResult.Failed("Two new passwords are not match!")); } if (String.IsNullOrEmpty(entity.Email)) { return(MethodResult.Failed("Email address can not be NULL!")); } if (!RegexVerify.IsEmail(entity.Email)) { return(MethodResult.Failed("Email address is INVALID!")); } if (entity.Email.Length > UserRepository.EMAIL_MAXLEN) { return(MethodResult.Failed("Email address is too long!")); } if (!String.IsNullOrEmpty(entity.NickName) && entity.NickName.Length > UserRepository.NICKNAME_MAXLEN) { return(MethodResult.Failed("Nick Name is too long!")); } if (!KeywordsFilterManager.IsUserNameLegal(entity.NickName)) { return(MethodResult.Failed("Nick Name can not contain illegal keywords!")); } if (!String.IsNullOrEmpty(entity.School) && entity.School.Length > UserRepository.SCHOOL_MAXLEN) { return(MethodResult.Failed("School Name is too long!")); } if (!String.IsNullOrEmpty(newPassword)) { entity.PassWord = PassWordEncrypt.Encrypt(entity.UserName, newPassword); } try { if (UserRepository.Instance.UpdateEntityForUser(entity, currentPassword) <= 0) { return(MethodResult.Failed("Current password is wrong!")); } } catch (System.Exception ex) { return(MethodResult.Failed(ex.Message)); } return(MethodResult.SuccessAndLog("User update info")); }
/// <summary> /// 导出竞赛用户列表 /// </summary> /// <param name="cid">竞赛ID</param> /// <param name="maskcode">导出内容掩码</param> /// <param name="withTitle">包括标题行</param> /// <returns>竞赛用户列表</returns> /// <remarks> /// 第1位-竞赛ID (0x01) /// 第2位-用户名 (0x02) /// 第3位-真实姓名 (0x04) /// 第4位-注册时间 (0x08) /// 第5位-是否启用 (0x10) /// </remarks> public static IMethodResult AdminGetContestUserList(Int32 cid, Int32 maskcode, Boolean withTitle) { if (!AdminManager.HasPermission(PermissionType.ContestManage)) { throw new NoPermissionException(); } if (maskcode <= 0) { return(MethodResult.FailedAndLog("You must select at least one item to export!")); } Dictionary <String, ContestUserEntity> dict = ContestUserRepository.Instance.GetEntities(cid); StringBuilder sb = new StringBuilder(); if (dict != null) { StringBuilder line = new StringBuilder(); if (withTitle) { if ((maskcode & 0x1) == 0x1) { line.Append(line.Length > 0 ? "\t" : "").Append("Contest ID"); } if ((maskcode & 0x2) == 0x2) { line.Append(line.Length > 0 ? "\t" : "").Append("User Name"); } if ((maskcode & 0x4) == 0x4) { line.Append(line.Length > 0 ? "\t" : "").Append("Real Name"); } if ((maskcode & 0x8) == 0x8) { line.Append(line.Length > 0 ? "\t" : "").Append("Register Time"); } if ((maskcode & 0x10) == 0x10) { line.Append(line.Length > 0 ? "\t" : "").Append("Enabled"); } sb.AppendLine(line.ToString()); } foreach (ContestUserEntity user in dict.Values) { line = new StringBuilder(); if ((maskcode & 0x1) == 0x1) { line.Append(line.Length > 0 ? "\t" : "").Append(user.ContestID.ToString()); } if ((maskcode & 0x2) == 0x2) { line.Append(line.Length > 0 ? "\t" : "").Append(user.UserName); } if ((maskcode & 0x4) == 0x4) { line.Append(line.Length > 0 ? "\t" : "").Append(user.RealName); } if ((maskcode & 0x8) == 0x8) { line.Append(line.Length > 0 ? "\t" : "").Append(user.RegisterTime.ToString("yyyy-MM-dd HH:mm:ss")); } if ((maskcode & 0x10) == 0x10) { line.Append(line.Length > 0 ? "\t" : "").Append(user.IsEnable ? "Y" : "N"); } sb.AppendLine(line.ToString()); } } return(MethodResult.Success(sb.ToString())); }
/// <summary> /// 设置指定ID的题目类型对 /// </summary> /// <param name="problemID">题目ID</param> /// <param name="sourceIDs">旧逗号分隔的题目类型ID</param> /// <param name="targetIDs">新逗号分隔的题目类型ID</param> /// <returns>是否成功设置</returns> public static IMethodResult AdminUpdateProblemCategoryItems(Int32 problemID, String sourceIDs, String targetIDs) { if (!AdminManager.HasPermission(PermissionType.ProblemManage)) { throw new NoPermissionException(); } if (problemID < ConfigurationManager.ProblemSetStartID) { return(MethodResult.InvalidRequest(RequestType.Problem)); } if ((!String.IsNullOrEmpty(sourceIDs) && !RegexVerify.IsNumericIDs(sourceIDs)) || (!String.IsNullOrEmpty(targetIDs) && !RegexVerify.IsNumericIDs(targetIDs))) { return(MethodResult.InvalidRequest(RequestType.ProblemCategory)); } StringBuilder deleteIDs = new StringBuilder(); StringBuilder insertIDs = new StringBuilder(); List <String> sourceid = (String.IsNullOrEmpty(sourceIDs) ? new List <String>() : new List <String>(sourceIDs.Split(','))); List <String> targetid = (String.IsNullOrEmpty(targetIDs) ? new List <String>() : new List <String>(targetIDs.Split(','))); for (Int32 i = 0; i < targetid.Count; i++)//删除sourceIDs和targetIDs中相同的数据 { for (Int32 j = 0; j < sourceid.Count; j++) { if (String.Equals(targetid[i], sourceid[j], StringComparison.OrdinalIgnoreCase)) { targetid.RemoveAt(i); sourceid.RemoveAt(j); i--; j--; break; } } } for (Int32 i = 0; i < sourceid.Count; i++)//设置deleteIDs { if (i > 0) { deleteIDs.Append(','); } deleteIDs.Append(sourceid[i]); } for (Int32 i = 0; i < targetid.Count; i++)//设置insertIDs { if (i > 0) { insertIDs.Append(','); } insertIDs.Append(targetid[i]); } Boolean ret = true; if (deleteIDs.Length > 0) { ret &= (ProblemCategoryItemRepository.Instance.DeleteEntities(problemID, deleteIDs.ToString()) > 0); } if (insertIDs.Length > 0) { ret &= (ProblemCategoryItemRepository.Instance.InsertEntity(problemID, insertIDs.ToString()) > 0); } if (!ret) { return(MethodResult.FailedAndLog("No problem's category was updated!")); } return(MethodResult.SuccessAndLog("Admin update problem's category, id = {0}, new category = {1}", problemID.ToString(), targetIDs)); }