public Site SetupSite(SetupInput input, out ValidationStateDictionary validationState) { Site site = null; using (TransactionScope transaction = new TransactionScope()) { site = this.CreateSite(out validationState); if (!validationState.IsValid) { return(null); } UserInputAdd userInput = new UserInputAdd(input.AdminUserName, input.AdminDisplayName, input.AdminEmail, input.AdminPassword, input.AdminPasswordConfirm); ModelResult <User> results = this.SetupUser(userInput); if (!results.IsValid) { validationState = results.ValidationState; return(null); } transaction.Complete(); } return(site); }
/// <summary> /// Get a list of available domain models /// </summary> /// <returns></returns> private async Task <ModelResult> GetAvailableDomainModels() { // ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- // // Create Project Oxford Vision API Service client // VisionServiceClient VisionServiceClient = new VisionServiceClient(SubscriptionKey, SubscriptionEndpoint); Log("VisionServiceClient is created"); // // Analyze the url against the given domain // Log("Calling VisionServiceClient.ListModelsAsync()..."); ModelResult modelResult = await VisionServiceClient.ListModelsAsync(); return(modelResult); // ----------------------------------------------------------------------- // KEY SAMPLE CODE ENDS HERE // ----------------------------------------------------------------------- }
public static ModelResult <int> ContactUsRead(int id) { int x; var oResult = new ModelResult <int>(); var conn = new SqlConnection(DbConnection.ConnectionString); try { using (conn) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Clear(); cmd.CommandText = "SP_ContactUsRead"; cmd.Parameters.AddWithValue("@Id", id); conn.Open(); x = Convert.ToInt32(cmd.ExecuteNonQuery()); if (x > 0) { oResult.HasResult = true; } } } } finally { conn.Close(); } return(oResult); }
public static ModelResult <int> UpdateStaticData(DTO.News.StaticData oStaticData) { var oResult = new ModelResult <int>(); using (var conn = new SqlConnection(DbConnection.ConnectionString)) { try { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = "SP_UpdateStaticData"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", oStaticData.Id); cmd.Parameters.AddWithValue("@Title", oStaticData.Title); cmd.Parameters.AddWithValue("@Data", oStaticData.Data); cmd.Parameters.AddWithValue("@Status", oStaticData.Status); cmd.Parameters.AddWithValue("@Icon", oStaticData.Icon); conn.Open(); oResult.Results = Convert.ToInt32(cmd.ExecuteScalar()); oResult.HasResult = true; } } catch { conn.Close(); throw; } return(oResult); } }
/// <summary> /// Get a list of available domain models /// </summary> /// <returns></returns> private async Task <ModelResult> GetAvailableDomainModels() { // ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- // // Create Project Oxford Vision API Service client // VisionServiceClient VisionServiceClient = new VisionServiceClient(SubscriptionKey, "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0"); Log("VisionServiceClient is created"); // // Analyze the url against the given domain // Log("Calling VisionServiceClient.ListModelsAsync()..."); ModelResult modelResult = await VisionServiceClient.ListModelsAsync(); return(modelResult); // ----------------------------------------------------------------------- // KEY SAMPLE CODE ENDS HERE // ----------------------------------------------------------------------- }
/// <summary> /// 刪除學生資料 /// </summary> /// <param name="gid"></param> /// <returns></returns> public IModelResult DeleteStudent(string gid) { IModelResult modelResult; try { doEventLog($"刪除資料:input=>{gid}"); doLog($"刪除資料:input=>{gid}"); dao = GetDao(); IModelResult dbResult = dao.StudentDelete(gid); if (dbResult.IsOk) { modelResult = new ModelResult(); } else { modelResult = new ModelResult(dbResult.ErrorCode.Value) { SystemMessage = dbResult.SystemMessage }; } doEventLog($"刪除結果:input=>{gid},result=>{JsonConvert.SerializeObject(modelResult)}"); doLog($"刪除結果:input=>{gid},result=>{JsonConvert.SerializeObject(modelResult)}"); } catch (Exception ex) { modelResult = new ModelResult(SystemCodes.Codes.ApplicationError02) { SystemMessage = ex.Message }; } return(modelResult); }
// </snippet_maintask> // <snippet_train> // Train model using training form data (pdf, jpg, png files) private static async Task <Guid> TrainModelAsync( IFormRecognizerClient formClient, string trainingDataUrl) { if (!Uri.IsWellFormedUriString(trainingDataUrl, UriKind.Absolute)) { Console.WriteLine("\nInvalid trainingDataUrl:\n{0} \n", trainingDataUrl); return(Guid.Empty); } try { TrainResult result = await formClient.TrainCustomModelAsync(new TrainRequest(trainingDataUrl)); ModelResult model = await formClient.GetCustomModelAsync(result.ModelId); DisplayModelStatus(model); return(result.ModelId); } catch (ErrorResponseException e) { Console.WriteLine("Train Model : " + e.Message); return(Guid.Empty); } }
// DELETE api/comment?id={comment id}&token={token} public async Task <IActionResult> Delete( [FromQuery(Name = "id")] int id, [FromQuery(Name = "token")] string token) { ModelResult <CommentInfo> result = TokenUtils.CheckToken <CommentInfo>(token, _context); if (result != null) { return(BadRequest(result)); } Session sessionResult = await _context.Sessions .FirstOrDefaultAsync(s => s.SessionToken == token); Comment commentResult = await _context.Comments .FirstOrDefaultAsync(c => c.CommentId == id); if (commentResult == null) { result = new ModelResult <CommentInfo>(404, null, "Comment Not Exists"); return(BadRequest(result)); } if (commentResult.UserId == sessionResult.SessionUserId) { _context.Remove(commentResult); await _context.SaveChangesAsync(); result = new ModelResult <CommentInfo>(200, new CommentInfo(commentResult), "Comment Deleted"); return(Ok(result)); } result = new ModelResult <CommentInfo>(405, null, "Cannot Delete Others' Comment"); return(BadRequest(result)); }
/// <summary> /// 修改學生資料 /// </summary> /// <param name="model"></param> /// <returns></returns> public IModelResult StudentUpdate(UpdateStudentDaoReqModel model) { IModelResult modelResult; try { IEnumerable <Student> dbModel = entities.Student.Where(x => x.id.Equals(model.id)).ToList(); if (dbModel.Any()) { Student dbResult = dbModel.First(); dbResult.studentId = model.studentId; dbResult.studentName = model.studentName; dbResult.studentSex = model.studentSex; dbResult.studentBirth = model.studentBirth; dbResult.studentAddr = model.studentAddr; entities.SaveChanges(); } modelResult = new ModelResult(); } catch (Exception ex) { modelResult = new ModelResult(SystemCodes.Codes.DBError) { SystemMessage = ex.Message }; } return(modelResult); }
public object ItemEditSave(PluginAddress pluginAddress, PluginEditInput pluginEditInput, bool isEditingCode) { if (isEditingCode && !string.IsNullOrEmpty(pluginEditInput.VirtualPath)) { pluginEditInput.VirtualPath.SaveFileText(pluginEditInput.Code, HttpContext); pluginEngine.ReloadPlugin(p => p.Tag == null && !(p.Tag is Plugin) && string.Compare(p.VirtualPath, pluginEditInput.VirtualPath, true) == 0, p => pluginEditInput.VirtualPath); return(EditNotInstalled(new PluginNotInstalledAddress(pluginEditInput.VirtualPath))); } ModelResult <Plugin> results = null; Plugin plugin = pluginService.GetPlugin(pluginAddress); if (isEditingCode && !string.IsNullOrEmpty(pluginEditInput.Code) && pluginEditInput.Code != plugin.GetFileText()) { results = pluginService.EditPlugin(pluginAddress, pluginEditInput, true); } else if (!isEditingCode) { results = pluginService.EditPlugin(pluginAddress, pluginEditInput, false); } if (results != null && !results.IsValid) { ViewData["ValidationState"] = results.ValidationState; } if (isEditingCode || ViewData.ContainsKey("ValidationState")) { return(ItemEdit(pluginAddress, pluginEditInput)); } return(Redirect(Url.Plugin(plugin))); }
public async Task <IActionResult> Get(int id) { ModelResult <CommentInfo> result; Comment commentResult = await _context.Comments .FirstOrDefaultAsync(c => c.CommentId == id); if (commentResult == null) { result = new ModelResult <CommentInfo>(404, null, "Comment Not Exists"); return(BadRequest(result)); } CommentInfo commentInfo = new CommentInfo(commentResult); CommentReply commentReply = await _context.CommentReplies .FirstOrDefaultAsync(cr => cr.CommentId == commentInfo.CommentId); if (commentReply != null) { commentInfo.IsReply = true; commentInfo.RepliedCommentId = commentReply.RepliedCommentId; } else { commentInfo.IsReply = false; commentInfo.RepliedCommentId = 0; } result = new ModelResult <CommentInfo>(400, commentInfo, null); return(Ok(result)); }
public async Task <IActionResult> Post( [FromBody] Tag tag, [FromQuery(Name = "token")] string token) { ModelResult <Tag> result = TokenUtils.CheckToken <Tag>(token, _context); if (result != null) { return(BadRequest(result)); } if (tag.TagName == null || tag.TagId != 0) { result = new ModelResult <Tag>(400, tag, "Invalid Tag"); return(BadRequest(result)); } Tag tagResult = await _context.Tags .FirstOrDefaultAsync(t => t.TagName == tag.TagName); if (tagResult != null) { result = new ModelResult <Tag>(409, tagResult, "Tag Exists"); return(BadRequest(result)); } await _context.Tags.AddAsync(tag); await _context.SaveChangesAsync(); result = new ModelResult <Tag>(201, tag, "Tag Created"); return(Ok(result)); }
public async Task <IActionResult> Delete( int id, [FromQuery(Name = "token")] string token) { ModelResult <Tag> result = TokenUtils.CheckToken <Tag>(token, _context); if (result != null) { return(BadRequest(result)); } Tag tagResult = await _context.Tags.FirstOrDefaultAsync(t => t.TagId == id); if (tagResult == null) { result = new ModelResult <Tag>(405, null, "Tag Not Found"); return(BadRequest(result)); } _context.Tags.Remove(tagResult); await _context.SaveChangesAsync(); result = new ModelResult <Tag>(200, tagResult, "Tag Eleted"); return(Ok(result)); }
public async Task <IActionResult> Put( int id, [FromBody] Tag tag, [FromQuery(Name = "token")] string token) { ModelResult <Tag> result = TokenUtils.CheckToken <Tag>(token, _context); if (result != null) { return(BadRequest(result)); } Tag tagResult = await _context.Tags.FirstOrDefaultAsync(t => t.TagId == id); if (tagResult == null) { result = new ModelResult <Tag>(405, null, "Tag Not Found"); return(BadRequest(result)); } if (id != tag.TagId) { result = new ModelResult <Tag>(405, null, "Cannot Modify TagId"); return(BadRequest(result)); } _context.Entry(tag).State = EntityState.Modified; await _context.SaveChangesAsync(); result = new ModelResult <Tag>(200, null, "Tag Modified"); return(Ok(result)); }
public ActionResult EditPost(string postId, string username, string password, IDictionary <string, object> post, bool publish) { if (string.IsNullOrEmpty(postId)) { throw new ArgumentException(); } Post existingPost = postService.GetPost(new MetaWeblogPostAddress(new Guid(postId))); //TODO: (erikpo) Move into a model binder? PostInput postInput = new PostInput(existingPost.Blog.Name, post["title"] as string, post["description"] as string, post["mt_excerpt"] as string, (post["categories"] as object[]).OfType <string>() ?? Enumerable.Empty <string>(), string.IsNullOrEmpty(post["mt_basename"] as string) ? expressions.Slugify(post["title"] as string) : post["mt_basename"] as string, publish ? existingPost.Published.HasValue ? existingPost.Published.Value : DateTime.UtcNow : (DateTime?)null, existingPost.CommentingDisabled); ModelResult <Post> results = postService.EditPost(new PostAddress(existingPost.Blog.Name, existingPost.Slug), postInput, EntityState.Normal); if (results.IsValid) { return(new XmlRpcResult(true)); } return(new XmlRpcFaultResult(0, results.GetFirstException().Message)); }
/// <summary> /// 刪除學生資料 /// </summary> /// <param name="gid"></param> /// <returns></returns> public IModelResult StudentDelete(string gid) { IModelResult modelResult; try { IList <Student> dbModel = entities.Student.Where(x => x.id.ToString() == gid).ToList(); if (dbModel.Any()) { Student deleteItem = dbModel.First(); entities.Student.Remove(deleteItem); entities.SaveChanges(); modelResult = new ModelResult(); } else { modelResult = new ModelResult(SystemCodes.Codes.DBError) { SystemMessage = $"無此資料{gid}" }; } } catch (Exception ex) { modelResult = new ModelResult(SystemCodes.Codes.DBError) { SystemMessage = ex.Message }; } return(modelResult); }
public static ModelResult <DTO.Account.UserType> AddEditUserType(DTO.Account.UserType userType) { var oResult = new ModelResult <DTO.Account.UserType>(); using (var conn = new SqlConnection(DbConnection.ConnectionString)) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = "SP_UserTypeAddEdit"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", userType.Name); if (userType.Id > 0) { cmd.Parameters.AddWithValue("@Id", userType.Id); } conn.Open(); userType.Id = Convert.ToInt32(cmd.ExecuteScalar()); oResult.HasResult = true; oResult.Results = userType; } return(oResult); } }
public void 測試StudentRepository查詢_Given_查詢資料_When_執行SelectStudent_Then_驗證查詢結果是否與預設結果一致() { FakeStudentRepository fake = new FakeStudentRepository(); //查詢資料 IndexVM vm = new IndexVM() { studentId = null, studentName = "吳" }; IModelResult <IndexVM> selectResult = fake.SelectStudent(vm); string actualStr = JsonConvert.SerializeObject(selectResult); //預期值 IList <IndexStudentItem> expectedLstStudentInfo = new List <IndexStudentItem>(); expectedLstStudentInfo.Add(new IndexStudentItem() { id = new Guid(), studentId = "G121550397", studentName = "吳小欣", studentSex = "1", studentBirth = new DateTime(1888, 3, 3) }); IModelResult <IndexVM> expectedResult = new ModelResult <IndexVM>() { ResultData = new IndexVM() { lstStudentInfo = expectedLstStudentInfo } }; string expectedStr = JsonConvert.SerializeObject(expectedResult); Assert.AreEqual(expectedStr, actualStr); }
public static ModelResult <int> AddUserShortcuts(string pagesIds, int userId) { var oResult = new ModelResult <int>(); using (SqlConnection conn = new SqlConnection(DbConnection.ConnectionString)) { using (SqlCommand comm = new SqlCommand()) { comm.Connection = conn; comm.CommandType = CommandType.StoredProcedure; comm.CommandText = "SP_UserShortcutsAdd"; if (userId > 0) { comm.Parameters.AddWithValue("@UserId", userId); } //if (!string.IsNullOrEmpty(pagesIds)) comm.Parameters.AddWithValue("@PagesIds", pagesIds); conn.Open(); comm.ExecuteNonQuery(); oResult.HasResult = true; conn.Close(); } return(oResult); } }
/// <summary> /// 模擬預設資料 /// </summary> /// <returns></returns> protected override IdbDao GetDao() { ///預設dao查詢資料 IList <SelectStudentDaoResModel> daoStudentSelectItem = new List <SelectStudentDaoResModel>(); daoStudentSelectItem.Add(new SelectStudentDaoResModel() { id = new Guid(), studentId = "G121550397", studentName = "吳小欣", studentSex = "1", studentBirth = new DateTime(1888, 3, 3), studentAddr = "宜蘭縣" }); IModelResult <IList <SelectStudentDaoResModel> > daoStudentSelectModel = new ModelResult <IList <SelectStudentDaoResModel> >() { ResultData = daoStudentSelectItem }; IdbDao idbDao = Substitute.For <IdbDao>(); idbDao.StudentSelect(this.selectStudentModel).Returns(daoStudentSelectModel); return(idbDao); }
public async Task <IActionResult> Delete( int id, [FromQuery(Name = "token")] string token) { ModelResult <UserFollowInfo> result = TokenUtils.CheckToken <UserFollowInfo>(token, _context); if (result != null) { return(BadRequest(result)); } Session sessionResult = await _context.Sessions .FirstOrDefaultAsync(s => s.SessionToken == token); UserFollow userFollowResult = await _context.UserFollows .FirstOrDefaultAsync(uf => uf.FollowingId == id && uf.FollowerId == sessionResult.SessionUserId); if (userFollowResult == null) { result = new ModelResult <UserFollowInfo>(400, null, "User Not Followed"); return(BadRequest(result)); } _context.Remove(userFollowResult); await _context.SaveChangesAsync(); result = new ModelResult <UserFollowInfo>(201, null, "Remove Follow Success"); return(Ok(result)); }
public static ModelResult <int> UpdatePageHdr(DTO.News.PagesHdr oPageHdr) { var oResult = new ModelResult <int>(); using (var conn = new SqlConnection(DbConnection.ConnectionString)) { try { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = "SP_UpdatePagesHdr"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", oPageHdr.Id); cmd.Parameters.AddWithValue("@Image", oPageHdr.Image); conn.Open(); oResult.Results = Convert.ToInt32(cmd.ExecuteScalar()); oResult.HasResult = true; } } catch { conn.Close(); throw; } return(oResult); } }
private ModelResult GetModelResult(DateTimeParseResult parsedDateTime) { ModelResult ret; var modelResult = new ModelResult { Start = parsedDateTime.Start.Value, End = parsedDateTime.Start.Value + parsedDateTime.Length.Value - 1, TypeName = parsedDateTime.Type, Resolution = parsedDateTime.Value as SortedDictionary <string, object>, Text = parsedDateTime.Text, }; var type = parsedDateTime.Type.Split('.').Last(); if (type is Constants.SYS_DATETIME_DATETIMEALT) { ret = new ExtendedModelResult(modelResult) { ParentText = GetParentText(parsedDateTime), }; } else { ret = modelResult; } return(ret); }
public async Task <IActionResult> Delete([FromQuery(Name = "token")] string token) { ModelResult <Session> result; if (token == null) { result = new ModelResult <Session>(401, null, "Token Required"); return(BadRequest(result)); } Session sessionResult = await _context.Sessions .FirstOrDefaultAsync(s => s.SessionToken == token); if (sessionResult == null) { result = new ModelResult <Session>(404, null, "Invalid Token or Session"); return(BadRequest(result)); } _context.Sessions.Remove(sessionResult); await _context.SaveChangesAsync(); result = new ModelResult <Session>(200, sessionResult, "Logout"); return(Ok(result)); }
public static ModelResult <DTO.News.AppSettings> AppSettingsSave(DTO.News.AppSettings oAppSetting) { var oResult = new ModelResult <DTO.News.AppSettings>(); var conn = new SqlConnection(DbConnection.ConnectionString); try { using (conn) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Clear(); cmd.CommandText = "SP_AppSettingsSave"; cmd.Parameters.AddWithValue("@Value", oAppSetting.ConValue); cmd.Parameters.AddWithValue("@Key", oAppSetting.ConKey); conn.Open(); oAppSetting.ConKey = Convert.ToInt32(cmd.ExecuteNonQuery()); oResult.HasResult = true; oResult.Results = oAppSetting; } } } finally { conn.Close(); } return(oResult); }
/// <summary> /// There are several ways to get the model, depends on what quality and file type you want. See the example response in RemixUserListResponse.cs class for full details. /// /// "manifestUris": [{ /// "usage": "View", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/gltf/...", /// "format": "GLTF" /// }, { /// "usage": "Download", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/gltf/...", /// "format": "GLTF" /// }], /// "assetUris": [{ /// "optimizationType": "Preview", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/assets/preview/gltf/1/...", /// "format": "GLTF", /// "version": 1 /// }, { /// "optimizationType": "Performance", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/assets/performance/gltf/1/...", /// "format": "GLTF", /// "version": 1 /// }, { /// "optimizationType": "Quality", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/assets/quality/gltf/1/...", /// "format": "GLTF", /// "version": 1 /// }, { /// "optimizationType": "HoloLens", /// "uri": "https://api.remix3d.com:443/v3/creations/G009SX0LPN59/assets/hololens/glb/1/...", /// "format": "GLB", /// "version": 1 /// }, { /// "optimizationType": "WindowsMR", /// "uri": "...", /// "format": "GLB", /// "version": 1 /// }] /// </summary> /// <param name="model">Model to get file for</param> /// <param name="levelOfDetail">Level of detail requested in the downloaded model</param> /// <param name="cancellationToken">Cancels operation and returns null</param> /// <returns></returns> public async Task <byte[]> DownloadModelFilesAsync(ModelResult model, AssetOptimizationType levelOfDetail, CancellationToken cancellationToken = new CancellationToken()) { if (cancellationToken.IsCancellationRequested) { return(null); } string downloadUrl = string.Empty; if (levelOfDetail == AssetOptimizationType.OriginalView) { downloadUrl = model.ManifestUris.FirstOrDefault(u => u.Usage == "View")?.Uri; } else if (levelOfDetail == AssetOptimizationType.OriginalDownload) { downloadUrl = model.ManifestUris.FirstOrDefault(u => u.Usage == "Download")?.Uri; } else { downloadUrl = model.AssetUris.FirstOrDefault(u => u.OptimizationType == levelOfDetail.ToString())?.Uri; } if (string.IsNullOrEmpty(downloadUrl)) { return(null); } return(await client.GetByteArrayAsync(downloadUrl)); }
public static ModelResult <DTO.News.ContactUs> ContactUsReply(DTO.News.ContactUs oContactUs) { var oResult = new ModelResult <DTO.News.ContactUs>(); var conn = new SqlConnection(DbConnection.ConnectionString); try { using (conn) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Clear(); cmd.CommandText = "SP_ContactUsReply"; cmd.Parameters.AddWithValue("@Id", oContactUs.Id); cmd.Parameters.AddWithValue("@Reply", oContactUs.Reply); conn.Open(); oContactUs.Id = Convert.ToInt32(cmd.ExecuteScalar()); oResult.HasResult = true; oResult.Results = oContactUs; } } } finally { conn.Close(); } return(oResult); }
public ActionResult NewPost(string blogId, string username, string password, IDictionary <string, object> post, bool publish) { if (string.IsNullOrEmpty(blogId)) { throw new ArgumentException(); } Blog blog = blogService.GetBlog(new BlogAddress(blogId)); //TODO: (erikpo) Move into a model binder? PostInput postInput = new PostInput(blog.Name, post["title"] as string, post["description"] as string, post["mt_excerpt"] as string, (post["categories"] as object[]).OfType <string>() ?? Enumerable.Empty <string>(), string.IsNullOrEmpty(post["mt_basename"] as string) ? expressions.Slugify(post["title"] as string) : post["mt_basename"] as string, publish ? DateTime.UtcNow : (DateTime?)null, blog.CommentingDisabled); ModelResult <Post> results = postService.AddPost(postInput, EntityState.Normal); if (results.IsValid) { return(new XmlRpcResult(results.Item.ID.ToString())); } return(new XmlRpcFaultResult(0, results.GetFirstException().Message)); }
public static ModelResult <int> CategoryDelete(int id) { int x; var oResult = new ModelResult <int>(); using (var conn = new SqlConnection(DbConnection.ConnectionString)) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = "SP_CategoryDelete"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Id", id); conn.Open(); x = Convert.ToInt32(cmd.ExecuteNonQuery()); if (x > 0) { oResult.HasResult = true; } oResult.Results = x; } return(oResult); } }
public async Task <IActionResult> Delete( int id, [FromQuery(Name = "token")] string token) { ModelResult <User> result = TokenUtils.CheckToken <User>(token, _context); if (result != null) { return(BadRequest(result)); } User userResult = await _context.Users .FirstOrDefaultAsync(u => u.UserId == id); Session sessionResult = await _context.Sessions .FirstOrDefaultAsync(s => s.SessionToken == token); if (userResult == null || userResult.UserId != sessionResult.SessionUserId) { result = new ModelResult <User>(405, null, "User Not Exists or Token not suit"); return(BadRequest(result)); } _context.Users.Remove(userResult); await _context.SaveChangesAsync(); result = new ModelResult <User>(200, userResult, "User Deleted"); return(Ok(result)); }