public void ForeverFrameTransportEscapesTags(string data, string expected) { var request = new Mock<IRequest>(); var response = new CustomResponse(); var context = new HostContext(request.Object, response); var fft = new ForeverFrameTransport(context, new DefaultDependencyResolver()); AssertEscaped(fft, response, data, expected); }
public void ForeverFrameTransportEscapesTagsWithPersistentResponse(string data, string expected) { var request = MockRequest(); var response = new CustomResponse(); var context = new HostContext(request.Object, response); var fft = new ForeverFrameTransport(context, new DefaultDependencyResolver()); AssertEscaped(fft, response, GetWrappedResponse(data), expected); }
private static void AssertEscaped(ForeverFrameTransport fft, CustomResponse response, object input, string expectedOutput) { fft.Send(input).Wait(); string rawResponse = response.GetData(); response.Reset(); // Doing contains due to all the stuff that gets sent through the buffer Assert.True(rawResponse.Contains(expectedOutput)); }
public void ForeverFrameTransportEscapesTags() { var request = new Mock<IRequest>(); var response = new CustomResponse(); var context = new HostContext(request.Object, response); var fft = new ForeverFrameTransport(context, new DefaultDependencyResolver()); AssertEscaped(fft, response, "</sCRiPT>", "\\u003c/sCRiPT\\u003e"); AssertEscaped(fft, response, "</SCRIPT dosomething='false'>", "\\u003c/SCRIPT dosomething='false'\\u003e"); AssertEscaped(fft, response, "<p>ELLO</p>", "\\u003cp\\u003eELLO\\u003c/p\\u003e"); }
public async Task <IActionResult> GetUserProfile() { try { var s = HttpContext.User.Claims; var k = s.FirstOrDefault(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"); var nik = k.Value; var author = HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization"); var rawtok = author.Value.FirstOrDefault(x => x.ToLower().Contains("bearer")).Split("Bearer "); string Token = rawtok[rawtok.Length - 1]; var server = _httpClientFactory.CreateClient(AppEnum.AuthCentralHttp); server.SetBearerToken(Token); var link = _config.GetSection("CentralAuth").Value + "/api/User/GetDetailUser?Kode=" + nik; var request = new HttpRequestMessage(HttpMethod.Get, link); server.SetBearerToken(Token); var resproj = await server.SendAsync(request); if (resproj.IsSuccessStatusCode) { var res = new CustomResponse() { message = "Berhasil mendapatkan data pengguna", title = "Sukses", ok = true, data = await resproj.Content.ReadAsAsync <User>() }; return(Ok(res)); } else { var res = new CustomResponse() { data = JsonConvert.SerializeObject(resproj.Content), message = "Gagal mendapatkan data pengguna. Error Code: " + resproj.StatusCode, title = "Gagal", ok = false }; return(BadRequest(res)); } } catch (Exception ex) { var res = new CustomResponse() { data = ex.Data, message = ex.Message, title = "Gagal", ok = false }; return(BadRequest(res)); } }
public async Task <CustomResponse <PessoaHistorico> > AdicionarHistoricoAcolhimento(Acolhimento acolhimento, PessoaProfissional pessoaProfissionalCadastro) { var _response = new CustomResponse <PessoaHistorico>(); try { var _AcolhimentoHistorico = new AcolhimentoHistorico { Acolhimento = acolhimento, Nome = acolhimento.PessoaPaciente?.NomeCompleto, CPF = acolhimento.PessoaPaciente?.Cpf, CNS = acolhimento.PessoaPaciente?.Cns, NomeSocial = acolhimento.PessoaPaciente?.NomeSocial, Risco = acolhimento.Risco, Peso = acolhimento.Peso, Altura = acolhimento.Altura, IMC = acolhimento.IMC, Temperatura = acolhimento.Temperatura, PressaoArterialSistolica = acolhimento.PressaoArterialSistolica, PressaoArterialDiastolica = acolhimento.PressaoArterialDiastolica, Pulso = acolhimento.Pulso, FrequenciaRespiratoria = acolhimento.FrequenciaRespiratoria, Saturacao = acolhimento.Saturacao, PessoaAlteracao = pessoaProfissionalCadastro.NomeCompleto, DataAlteracao = DateTime.Now, Ativo = acolhimento.Ativo, }; if (acolhimento.EspecialidadeId != Guid.Empty) { _AcolhimentoHistorico.Especialidade = _contextDominio.Especialidades.FindAsync(acolhimento.EspecialidadeId).Result.Descricao; } if (acolhimento.PreferencialId != Guid.Empty) { _AcolhimentoHistorico.Preferencial = _contextDominio.Preferenciais.FindAsync(acolhimento.PreferencialId).Result.Nome; } await base.Adicionar(_AcolhimentoHistorico, pessoaProfissionalCadastro.PessoaId); return(_response); } catch (Exception ex) { _response.Message = ex.InnerException.Message; Error.LogError(ex); } return(_response); }
public async Task <CustomResponse <PessoaProfissional> > ConsultaCpf(string cpf, Guid userId) { var _response = new CustomResponse <PessoaProfissional>(); try { Expression <Func <PessoaProfissional, bool> > _filtroNome = x => x.Cpf.Equals(cpf) && x.Ativo && !x.Master; await Task.Run(() => { var _pessoaEncontrado = _contextKlinikos.PessoaProfissionais .Where(_filtroNome).ToList().FirstOrDefault(); if (_pessoaEncontrado != null) { var lotacoes = _contextKlinikos.LotacoesProfissional .Include(profissional => profissional.TipoProfissional) .Include(profissional => profissional.OrgaoEmissorProfissional) .Where(pessoa => pessoa.Pessoa.PessoaId == _pessoaEncontrado.PessoaId); var newListaLotacao = new List <LotacaoProfissional>(); foreach (var lotacao in lotacoes) { lotacao.Pessoa = null; newListaLotacao.Add(lotacao); } _pessoaEncontrado.LotacoesProfissional = newListaLotacao; if (_pessoaEncontrado != null) { _response.Message = "Cpf encontrado"; _response.StatusCode = StatusCodes.Status302Found; _response.Result = _pessoaEncontrado; } else { _response.Message = "Cpf não encontrado"; _response.StatusCode = StatusCodes.Status404NotFound; } } }); } catch (Exception ex) { _response.Message = ex.InnerException.Message; Error.LogError(ex); } return(_response); }
public async Task <CustomResponse <AtendimentoMedico> > AdicionarAtendimentoMedico(AtendimentoMedico atendimentoMedico, Guid userId) { var _response = new CustomResponse <AtendimentoMedico>(); try { var _pessoaMaster = (PessoaProfissional)_contextKlinikos.Pessoas.Where(x => x.Master).FirstOrDefault(); atendimentoMedico.Ativo = true; await this.Adicionar(atendimentoMedico, userId); await _serviceAtendimentoMedicoHistorico.AdicionarHistoricoAtendimentoMedico(atendimentoMedico, _pessoaMaster); if (atendimentoMedico.AtendimentoMedicoAlergia.Count > 0) { foreach (var alergia in atendimentoMedico.AtendimentoMedicoAlergia) { await _serviceAtendimentoMedicoAlergiaHistorico.AdicionarHistoricoAtendimentoMedicoAlergia(alergia, _pessoaMaster); } } if (atendimentoMedico.AtendimentoMedicoExame.Count > 0) { foreach (var exame in atendimentoMedico.AtendimentoMedicoExame) { await _serviceAtendimentoMedicoExameHistorico.AdicionarHistoricoAtendimentoMedicoExame(exame, _pessoaMaster); } } if (atendimentoMedico.AtendimentoMedicoPrescricaoReceitaDetalhe.Count > 0) { foreach (var prescricaoReceita in atendimentoMedico.AtendimentoMedicoPrescricaoReceitaDetalhe) { await _serviceAtendimentoMedicoPrescricaoReceitaDetalheHistorico.AdicionarHistoricoAtendimentoMedicoPrescricaoReceitaDetalhe(prescricaoReceita, _pessoaMaster); } } _response.StatusCode = StatusCodes.Status201Created; _response.Message = "Incluído com sucesso"; } catch (Exception ex) { _response.Message = ex.InnerException.Message; Error.LogError(ex); } return(_response); }
public IActionResult GetAll([Required] string group) { try { return(Ok(CustomResponse.ok(_service.GetAll(group)))); } catch (Exception ex) { _logger.LogError(ex.Message); return(BadRequest()); } }
public void ForeverFrameTransportThrowsOnInvalidFrameId(string frameId) { var request = new Mock<IRequest>(); var qs = new NameValueCollection { { "frameId", frameId } }; request.Setup(r => r.QueryString).Returns(new NameValueCollectionWrapper(qs)); var response = new CustomResponse(); var context = new HostContext(request.Object, response); var connection = new Mock<ITransportConnection>(); var fft = new ForeverFrameTransport(context, new DefaultDependencyResolver()); Assert.Throws(typeof(InvalidOperationException), () => fft.InitializeResponse(connection.Object)); }
// Based on userrole we need to generate report data , public static dynamic GetReportData(string userid , int tasktype, int taskstatus, DateTime? fromdate, DateTime? todate) { List<ReportData> objreportdata = new List<ReportData>(); CustomResponse objres = new CustomResponse(); try { using (var objcontext = new Db_Zon_Test_techsupportEntities()) { objreportdata = (from t in objcontext.Mst_Task join tt in objcontext.Mst_TaskType on t.TypeID equals tt.ID join ts in objcontext.Mst_TaskStatus on t.Task_Status equals ts.ID join p in objcontext.Mst_Project on t.ProjectID equals p.ID join u in objcontext.AspNetUsers on t.AssignedTo equals u.Id join u1 in objcontext.AspNetUsers on t.RefereedTo equals u1.Id where ( userid.Length==1 || t.AssignedTo == userid) && (0 == tasktype || t.TypeID == tasktype) && (0 == taskstatus || t.Task_Status == taskstatus) && System.Data.Entity.Core.Objects.EntityFunctions.TruncateTime(t.AssigndedDate) >= EntityFunctions.TruncateTime(fromdate) && EntityFunctions.TruncateTime(t.AssigndedDate) <= EntityFunctions.TruncateTime(todate) select new ReportData { ProjectName = p.Name, TicketDisplayName = t.TaskDisplayName, AssignedDate = t.AssigndedDate, AssignedTo = u.FirstName, RefereerTo = u1.FirstName, TaskStatus = ts.Task_Status, TicketType = tt.Type, TicketID = t.ID }).OrderByDescending(x=>x.TicketID).Take(5000).ToList(); objres.Message = "Success"; objres.Response = objreportdata; objres.Status = CustomResponseStatus.Successful; return objres; } } catch (Exception ex) { objres.Message = ex.Message; objres.Response = null; objres.Status = CustomResponseStatus.UnSuccessful; return objres; } }
public IHttpActionResult GetStoreByIdMobile(short Id, double?latitude = 0, double?longitude = 0) { try { DunkeyContext ctx = new DunkeyContext(); var res = new Store(); var Distance = 0.0; if (latitude != 0 && longitude != 0) { var point = DunkeyDelivery.Utility.CreatePoint(latitude.Value, longitude.Value); res = ctx.Stores.Include(z => z.StoreRatings.Select(y => y.User)).Include(z => z.StoreTags).Where(x => x.Id == Id && x.IsDeleted == false).Include("StoreDeliveryHours").First(); res.Distance = res.Location.Distance(point).Value; } else { res = ctx.Stores.Include(z => z.StoreRatings.Select(y => y.User)).Include(z => z.StoreTags).Where(x => x.Id == Id && x.IsDeleted == false).Include("StoreDeliveryHours").First(); } var businessTypeTax = ctx.BusinessTypeTax.FirstOrDefault(x => x.BusinessType.Equals(res.BusinessType)); if (businessTypeTax != null) { res.BusinessTypeTax = businessTypeTax.Tax; } if (res != null) { res.SetAverageRating(); res.CalculateAllTypesAverageRating(); foreach (var item in res.StoreRatings) { var query = "select User_Id, Count(Store_Id) as Count from storeratings group by User_Id"; var resp = ctx.Database.SqlQuery <UserRatingCount>(query).ToList(); item.User.TotalReviews = resp.FirstOrDefault(x => x.User_Id == item.User.Id).Count; item.User.TotalOrders = ctx.Orders.Count(x => x.User_ID == item.User.Id); } } CustomResponse <Store> response = new CustomResponse <Store> { Message = "Success", StatusCode = (int)HttpStatusCode.OK, Result = res }; return(Ok(response)); } catch (Exception ex) { return(StatusCode(DunkeyDelivery.Utility.LogError(ex))); } }
public async Task<IActionResult> SendDecision([FromBody] Decision Dec) { var author = HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization"); var rawtok = author.Value.FirstOrDefault(x=>x.ToLower().Contains("bearer")).Split("Bearer "); string token = rawtok[rawtok.Length - 1]; var proj = _httpClientFactory.CreateClient("bebas"); proj.SetBearerToken(token); var resproj = await proj.PostAsJsonAsync(Dec.Link, Dec); if(resproj.IsSuccessStatusCode) { //Todo hapus data var data = new RequestList { ApiName = Dec.ApiName, Id = Dec.Id, Nik = Dec.Nik }; this._projectReqservice.Remove(data); int i = this._projectReqservice.save(); if (i > 0) { var res = new CustomResponse { message = "Data berhasil dilakukan approval", title = "Approval Sukses", ok = true }; return Ok(res); } else { var res = new CustomResponse { message = "Data di General Approval gagal dihapus", title = "Approval Sukses dengan Tapi", ok = true }; return Ok(res); } } else { var res = new CustomResponse { data = JsonConvert.SerializeObject(resproj.Content), message = "Gagal dilakukan approval. Error Code: " + resproj.StatusCode, title = "Approval ke Project Gagal", ok = false }; return BadRequest(res); } }
public IActionResult Edit([Bind("Id,Nome,Email,TipoUsuario,CondominioId")] UsuarioViewModel usuarioViewModel) { if (ModelState.IsValid) { CustomResponse retorno = UsuarioService.Update(baseUri, usuarioViewModel); if (retorno.Success == true) { return(RedirectToAction("Index")); } } return(View(usuarioViewModel)); }
public void ShouldGetCustomSettingAsync() { // Arrange ICustomSettingsApi settingsApi = CreateSettingsApi(); // Act CustomResponse setting = settingsApi.GetCustomSettingAsync("Language").Result; // Assert setting.Value.ShouldBe("en-us"); Should.Throw<ArgumentNullException>(() => settingsApi.GetCustomSettingAsync(null)); }
public void ShouldDeleteCustomSettingAsync() { // Arrange ICustomSettingsApi settingsApi = CreateSettingsApi(); // Act CustomResponse settings = settingsApi.DeleteCustomSettingAsync("Language").Result; // Assert settings.Name.ShouldBe("Language"); Should.Throw<ArgumentNullException>(() => settingsApi.DeleteCustomSettingAsync(null)); }
public IActionResult Edit([Bind("Id,Nome,AdminsitradoraId,Administradora,Responsavel,Ativo, Excluido")] CondominioViewModel CondominioViewModel) { if (ModelState.IsValid) { CustomResponse retorno = CondominioService.Update(baseUri, CondominioViewModel); if (retorno.Success == true) { return(RedirectToAction("Index")); } } return(View(CondominioViewModel)); }
public async Task <CustomResponse> AddInstructionsToRecipe(int recipeId, List <Instruction> instructions) { for (int i = 0; i < instructions.Count; i++) { CustomResponse response = await AddInstructionToRecipe(recipeId, instructions[i]); if (response.Value == 0) { return(response); } } return(CustomResponse.SuccessMessage()); }
//<summary>Delete Method </summary><description>method takes apiaddress</description> public static CustomResponse Delete(string apiurl) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseurl); HttpResponseMessage response = client.DeleteAsync(apiurl).Result; if (response.IsSuccessStatusCode) { res = response.Content.ReadAsAsync <CustomResponse>().Result; } return(res); }
private static HttpResponseMessage CreateCustomApiResponse(CustomResponse response) { //ApiResponse apiResponse = new ApiResponse(); HttpResponseMessage mainResponse = new HttpResponseMessage(); switch (response.Status) { case 200: response.Result = "OK"; mainResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new ObjectContent <CustomResponse>(response, new JsonMediaTypeFormatter()) }; break; case 201: response.Result = "Created."; mainResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.Created, Content = new ObjectContent <CustomResponse>(response, new JsonMediaTypeFormatter()) }; break; case 500: response.Result = "Internal Server Error.Please Contact your Administrator."; mainResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new ObjectContent <CustomResponse>(response, new JsonMediaTypeFormatter()) }; break; default: response.Result = "Internal Server Error.Please Contact your Administrator."; mainResponse = new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new ObjectContent <CustomResponse>(response, new JsonMediaTypeFormatter()) }; break; } //return new HttpResponseMessage() //{ // Content = new ObjectContent<ApiResponse>(apiResponse, new JsonMediaTypeFormatter()) //}; return(mainResponse); }
public static dynamic GetAllUsers() { CustomResponse objres = new CustomResponse(); List <UserDTO> ObjFilteredUsers = new List <UserDTO>(); try { using (var objcontext = new Db_Zon_Test_techsupportEntities()) { //return all projects information string comp = "1"; List <UserDTO> objuserdetails = (from user in objcontext.AspNetUsers where user.Status == "1" select new UserDTO { Id = user.Id, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, MobileNumber = user.MobileNumber, CreatedBy = user.CreatedBy, Status = user.Status }).ToList(); for (int i = 0; i < objuserdetails.Count; i++) { string uid = objuserdetails[i].CreatedBy; if (uid != null) { objuserdetails[i].CreatedBy = objcontext.AspNetUsers.Where(x => x.Id == uid).FirstOrDefault().UserName; } } objres.Message = "Success"; objres.Response = objuserdetails; objres.Status = CustomResponseStatus.Successful; return(objres); } objres.Message = "Success"; objres.Response = null; objres.Status = CustomResponseStatus.Successful; return(objres); } catch (Exception ex) { objres.Message = ex.Message; objres.Response = null; objres.Status = CustomResponseStatus.UnSuccessful; return(objres); } }
public async Task <IHttpActionResult> Repost(int Post_Id, string Location) { try { var userId = Convert.ToInt32(User.GetClaimValue("userid")); using (RiscoContext ctx = new RiscoContext()) { Post post = ctx.Posts .Include(x => x.Medias).AsNoTracking() .FirstOrDefault(x => x.Id == Post_Id); post.User_Id = userId; post.Location = Location; post.CreatedDate = DateTime.UtcNow; foreach (Media media in post.Medias) { media.CreatedDate = DateTime.UtcNow; } ctx.Posts.Add(post); ctx.SaveChanges(); SetTrends(Text: post.Text, User_Id: userId, Post_Id: post.Id); Share share = new Share { Post_Id = Post_Id, User_Id = userId, CreatedDate = DateTime.UtcNow, }; ctx.Shares.Add(share); ctx.SaveChanges(); CustomResponse <Post> response = new CustomResponse <Post> { Message = Global.ResponseMessages.Success, StatusCode = (int)HttpStatusCode.OK, Result = post }; return(Ok(response)); } } catch (Exception ex) { return(StatusCode(Utility.LogError(ex))); } }
// GET: Dashboard public ActionResult Dashboard() { string Role = RoleHelper.GetUserRole(); DashboardModel objdashboardModel = new DashboardModel(); JavaScriptSerializer serializer1 = new JavaScriptSerializer(); CustomResponse ObjActivityData = APICalls.Get("DashboardAPI/Get?Type=3&pageno=0"); if (ObjActivityData.Status == CustomResponseStatus.Successful && ObjActivityData.Response != null) { var jsondata = ObjActivityData.Response.ToString(); objdashboardModel.ActivityDTO = serializer1.Deserialize <List <Trans_TicketDTO> >(jsondata); } CustomResponse response = APICalls.Get("DashboardAPI/Get?Type=1&pageno=0"); if (response.Status == CustomResponseStatus.Successful) { serializer1.MaxJsonLength = 1000000000; var projects = response.Response.ToString(); List <DashBoardStatisticsDTO> dbinfo = serializer1.Deserialize <List <DashBoardStatisticsDTO> >(projects); foreach (DashBoardStatisticsDTO ds in dbinfo) { if (ds.Type == "1") { objdashboardModel.ProjectsCount = ds.Count; } else if (ds.Type == "2") { objdashboardModel.ClientsCount = ds.Count; } else if (ds.Type == "3") { objdashboardModel.AdminsCount = ds.Count; } else if (ds.Type == "4") { objdashboardModel.UsersCount = ds.Count; } } CustomResponse objtabledata = APICalls.Get("DashboardAPI/Get?Type=2&pageno=0"); if (objtabledata.Status == CustomResponseStatus.Successful) { var tabledata = objtabledata.Response.ToString(); objdashboardModel.TableData = serializer1.Deserialize <List <ProjectTicketUsersDTO> >(tabledata); } return(View(objdashboardModel)); } return(View()); }
async public Task <CustomResponse> AddRecipe(Recipe recipe) { CustomResponse response = await CheckNewRecipeValid(recipe); if (response.Value == 0) { return(response); } DbConnection db = new DbConnection(); try { var query1 = @$ "INSERT INTO recipe (name, people) VALUES ('{recipe.Name.Trim()}', {recipe.People});";
public async Task <IActionResult> AddFollowing([FromBody] ProjectToProject entity) { var trans = await this._projectService.BeginTransactionAsync(); try { using (trans) { this._projectService.FollowProject(entity.ProjekApiName, entity.KolaborasiApiName); var t = await this._projectService.SaveAsync(); var res = new CustomResponse() { errors = null, message = "Follow Projek Berhasil", title = "Success", ok = true }; if (t > 0) { this._projectService.Commit(trans); return(Ok(res)); } this._projectService.Rollback(trans); res = new CustomResponse() { errors = null, message = "Follow Projek Gagal", title = "Warning", ok = false }; return(BadRequest(res)); } } catch (Exception ex) { var res = new CustomResponse() { errors = new List <string>() { ex.InnerException.Message }, message = ex.Message, title = "Error", ok = false }; this._projectService.Rollback(trans); return(BadRequest(res)); } }
public ActionResult EditUser(string id, [FromForm] User user) { CustomResponse response = UserBL.EditUser(id, user, _userRepository); if (!response.success) { return(PartialView("Error", response)); } ICollection <User> users = UserBL.GetAllUsersSync(_userRepository); return(PartialView("GetAllUsers", new UsersViewModel { Users = users.ToList() })); }
// GET: Projects public ActionResult ListAll() { CustomResponse res = APICalls.Get("projectsapi/Get?projectid=0&userid=" + User.Identity.GetUserId()); if (res.Response != null) { JavaScriptSerializer serializer1 = new JavaScriptSerializer(); serializer1.MaxJsonLength = 1000000000; var uinfo = res.Response.ToString(); List <ProjectDTO> userinfo = serializer1.Deserialize <List <ProjectDTO> >(uinfo); return(View(userinfo)); } return(View()); }
public IHttpActionResult GetChecksum([FromBody] IESOrder value) { CustomResponse err = new CustomResponse(); try { var context = new xPenEntities(); using (var dbContextTransaction = context.Database.BeginTransaction()) { var prev = (from p in context.IESOrders where p.PaperID == value.PaperID && p.UserID == value.UserID select p).ToList(); if (prev.Count > 0) { context.IESOrders.RemoveRange(prev); context.SaveChanges(); } context.IESOrders.Add(value); context.SaveChanges(); if (value.OrderID > 1) { checkSum cs = new checkSum(); String csm = CreateChecksum(value.OrderID, value.UserID, value.Paid); string JSONresult = JsonConvert.SerializeObject(cs); dbContextTransaction.Commit(); Transaction newTransaction = new Transaction(); newTransaction.UserID = value.UserID; newTransaction.PaperID = value.PaperID; newTransaction.Paid = value.Paid; newTransaction.OrderID = value.OrderID; newTransaction.CheckSum = csm; return(Ok(newTransaction)); } else { err.Response = "Error Saving Order"; dbContextTransaction.Rollback(); //return BadRequest(cs); return(Content(HttpStatusCode.BadRequest, err)); } } } catch (Exception ex) { return(InternalServerError()); } }
public async Task <IHttpActionResult> GetPostByPostId(int Post_Id) { try { using (RiscoContext ctx = new RiscoContext()) { var userId = Convert.ToInt32(User.GetClaimValue("userid")); Post post = new Post(); post = ctx.Posts.Include(x => x.User) .FirstOrDefault(x => x.Id == Post_Id && x.IsDeleted == false); post.IsLiked = ctx.Likes.Any(x => x.Post_Id == Post_Id && x.User_Id == userId && x.IsDeleted == false); post.LikesCount = ctx.Posts.Sum(p => p.Likes.Where(x => x.Post_Id == post.Id && x.IsDeleted == false).Count()); post.CommentsCount = ctx.Posts.Sum(p => p.Comments.Where(x => x.Post_Id == post.Id && x.IsDeleted == false).Count()); post.ShareCount = ctx.Posts.Sum(p => p.Shares.Where(x => x.Post_Id == post.Id && x.IsDeleted == false).Count()); // For comments and their child comments including self-like List <Comment> comments = ctx.Comments .Include(x => x.User) .Where(x => x.Post_Id == Post_Id && x.ParentComment_Id == 0 && x.IsDeleted == false).ToList(); foreach (Comment comment in comments) { comment.ChildComments = ctx.Comments .Include(x => x.User) .Where(x => x.ParentComment_Id == comment.Id && x.IsDeleted == false).ToList(); comment.IsLiked = ctx.Likes.Any(x => x.Comment_Id == comment.Id && x.User_Id == userId && x.IsDeleted == false); foreach (Comment childComment in comment.ChildComments) { childComment.IsLiked = ctx.Likes.Any(x => x.Comment_Id == childComment.Id && x.User_Id == userId && x.IsDeleted == false); } } post.Comments = comments; CustomResponse <Post> response = new CustomResponse <Post> { Message = Global.ResponseMessages.Success, StatusCode = (int)HttpStatusCode.OK, Result = post }; return(Ok(response)); } } catch (Exception ex) { return(StatusCode(Utility.LogError(ex))); } }
public void ForeverFrameTransportSetsCorrectContentType() { var request = new Mock<IRequest>(); var qs = new NameValueCollection { { "frameId", "1" } }; request.Setup(r => r.QueryString).Returns(new NameValueCollectionWrapper(qs)); var response = new CustomResponse(); var context = new HostContext(request.Object, response); var connection = new Mock<ITransportConnection>(); var fft = new ForeverFrameTransport(context, new DefaultDependencyResolver()); fft.InitializeResponse(connection.Object).Wait(); Assert.Equal("text/html; charset=UTF-8", response.ContentType); }
public async Task <CustomResponse <User> > Incluir(User user, AccessManager accessManager, Guid UserId) { var _response = new CustomResponse <User>(); try { if (user.UserRoles != null) { if (user.UserRoles.Any(x => x.Role != null)) { var _rolesUser = new List <UserRole>(); foreach (Role role in user.UserRoles.Where(x => x.Role.NameRole != Roles.ROLE_API_MASTER).Select(x => x.Role).ToList <Role>()) { var _roleFound = _context.Roles.Where(x => x.NameRole == role.NameRole).FirstOrDefault(); _rolesUser.Add(new UserRole { Role = _roleFound, User = user }); } var _password = Convert.ToBase64String(accessManager.HashPassword(user.Password, _rng)); var _userHash = new User() { Username = user.Username, Email = user.Email, Password = _password, ConfirmPassword = _password, UserRoles = _rolesUser }; _response = await base.Incluir(_userHash, UserId); } } else { user.UserId = UserId = Guid.NewGuid(); user.Password = user.ConfirmPassword = Convert.ToBase64String(accessManager.HashPassword(user.Password, _rng)); _response = await base.Incluir(user, UserId); } } catch (Exception ex) { _response.Message = ex.Message; } return(_response); }
public async Task<IActionResult> GetAutoCompleteListData([FromQuery]string Link, [FromQuery]bool ProvideFilter, [FromQuery]string Search) { if (Search == null) Search = ""; var author = HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization"); var rawtok = author.Value.FirstOrDefault(x => x.ToLower().Contains("bearer")).Split("Bearer "); string token = rawtok[rawtok.Length - 1]; var proj = _httpClientFactory.CreateClient("bebas"); proj.SetBearerToken(token); string matureLink = Link; if (ProvideFilter) { if (Link.Contains("?")) { matureLink += "&label=" + Search.ToLower(); } else { matureLink += "?label=" + Search.ToLower(); } } var resproj = await proj.GetAsync(matureLink); if (resproj.IsSuccessStatusCode) { var temp = await resproj.Content.ReadAsAsync<IEnumerable<FormAutoCompleteItem>>(); if (!ProvideFilter) { temp = temp.Where(x => x.label.ToLower().Contains(Search.ToLower())).ToList(); } var res = new CustomResponse { data = temp, message = "Data berhasil didapatkan", title = "Mendapatkan Data Sukses", ok = true }; return Ok(res); } else { var res = new CustomResponse { data = JsonConvert.SerializeObject(resproj.Content), message = "Gagal Mendapatkan Data. Error Code: " + resproj.StatusCode, title = "Mendapatkan Data Gagal", ok = false }; return BadRequest(res); } }
public static CustomResponse GetDashboardStatistics() { CustomResponse objres = new CustomResponse(); List <DashBoardStatisticsDTO> StatisticsDTO = new List <DashBoardStatisticsDTO>(); try { using (var objcontext = new Db_Zon_Test_techsupportEntities()) { // projects StatisticsDTO.Add(new DashBoardStatisticsDTO { Type = "1", Count = objcontext.Mst_Project.Count() }); // clients SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["Db_Zon_Test_techsupportEntities"].ToString()); con.Open(); SqlCommand cmd = new SqlCommand("select count (distinct ur.UserId) from AspNetUserRoles ur,AspNetUsers u where ur.RoleId=@roleid and ur.Userid =u.Id and u.Status=1", con); cmd.Parameters.AddWithValue("@roleid", "294e2276-384e-4844-ad8a-7a4c4dd9fcdc"); StatisticsDTO.Add(new DashBoardStatisticsDTO { Type = "2", Count = Convert.ToInt32(cmd.ExecuteScalar()) }); // admins SqlCommand cmd1 = new SqlCommand("select count (distinct ur.UserId) from AspNetUserRoles ur,AspNetUsers u where ur.RoleId=@roleid and ur.Userid =u.Id and u.Status=1", con); cmd1.Parameters.AddWithValue("@roleid", "594875d4-5d30-4d84-bdb3-6a9309799ae2"); StatisticsDTO.Add(new DashBoardStatisticsDTO { Type = "3", Count = Convert.ToInt32(cmd1.ExecuteScalar()) }); // users-developers SqlCommand cmd2 = new SqlCommand("select count (distinct ur.UserId) from AspNetUserRoles ur,AspNetUsers u where ur.RoleId=@roleid and ur.Userid =u.Id and u.Status=1", con); cmd2.Parameters.AddWithValue("@roleid", "15d2fcc9-23c3-4ad8-b93d-d134d3f9349e"); StatisticsDTO.Add(new DashBoardStatisticsDTO { Type = "4", Count = Convert.ToInt32(cmd2.ExecuteScalar()) }); con.Close(); objres.Message = "Success"; objres.Response = StatisticsDTO; objres.Status = CustomResponseStatus.Successful; return(objres); } } catch (Exception ex) { objres.Message = ex.Message; objres.Response = null; objres.Status = CustomResponseStatus.UnSuccessful; return(objres); } }
public async Task <CustomResponse <User> > ValidateCredentials(User user, AccessManager accessManager) { var _result = new CustomResponse <User>(); if (user != null && !String.IsNullOrWhiteSpace(user.Username)) { try { var _userFound = await _context.Users.Include(usuario => usuario.UserRoles) .Where(x => x.Username == user.Username && x.Ativo).FirstOrDefaultAsync(); if (_userFound != null) { // Efetua o login com base no Id do usuário e sua senha byte[] decodedByPassword = System.Convert.FromBase64String(_userFound.Password); if (!accessManager.VerifyHashedPassword(decodedByPassword, user.Password)) { _result.Message = "Senha Incorreta"; _result.StatusCode = StatusCodes.Status401Unauthorized; } else { _result.Token = this.GerarAcesso(_userFound, accessManager).Result.Result; var _userSistema = new User() { UserId = _userFound.UserId, Username = _userFound.Username }; _result.Result = _userSistema; _result.StatusCode = StatusCodes.Status200OK; } } else { _result.Message = "Usuário não encontrado"; _result.StatusCode = StatusCodes.Status404NotFound; } } catch (Exception ex) { _result.Message = ex.Message; Error.LogError(ex); } } return(_result); }
public IHttpActionResult RedeemPrize(int UserID, int RewardID) { try { using (DunkeyContext ctx = new DunkeyContext()) { var Reward = new RewardMilestones(); var CurrentUser = ctx.Users.Where(x => x.Id == UserID).FirstOrDefault(); Reward = ctx.RewardMilestones.Where(x => x.Id == RewardID).FirstOrDefault(); if (CurrentUser.RewardPoints >= Reward.PointsRequired) { var reward = ctx.UserRewards.Add(new UserRewards { Created_Date = DateTime.Now, is_deleted = 0, User_Id = CurrentUser.Id, RewardMilestones_Id = Reward.Id }); ctx.SaveChanges(); CurrentUser.RewardPoints = CurrentUser.RewardPoints - Reward.PointsRequired; ctx.SaveChanges(); CustomResponse <UserRewards> response = new CustomResponse <UserRewards> { Message = "Success", StatusCode = (int)HttpStatusCode.OK, Result = reward }; return(Ok(response)); } return(Content(HttpStatusCode.OK, new CustomResponse <Error> { Message = "Forbidden", StatusCode = (int)HttpStatusCode.Forbidden, Result = new Error { ErrorMessage = "Insufficient Points." } })); } } catch (Exception ex) { return(StatusCode(DunkeyDelivery.Utility.LogError(ex))); } }
public async Task <CustomResponse> RemoveAllInstructionsFromRecipe(int recipeId) { DbConnection db = new DbConnection(); try { var query = @$ "DELETE FROM instruction WHERE recipe = {recipeId};"; await db.ExecuteQuery(query); return(new CustomResponse(1, "")); } catch { return(CustomResponse.ErrorMessage()); } finally { db.CloseConnection(); } }
private static void ExecuteAllBladeCommands() { Tracer.Write(""); Tracer.Write("*********************************************************"); Tracer.Write(string.Format("***** BMC Command Execution: {0} ******", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); Tracer.Write("*********************************************************"); Tracer.Write(""); ResponseBase response = new CustomResponse(failure); BladePowerSwitch powerPacket = new BladePowerSwitch(bladeId); BladePowerStatePacket powerOff = powerPacket.SetBladePowerState(0x00); if (powerOff.CompletionCode == CompletionCode.Success) { Console.WriteLine("Power Blade Off"); } else { Console.WriteLine("ERROR: Could not power Blade Off"); } BladePowerStatePacket powerOn = powerPacket.SetBladePowerState(0x01); Console.WriteLine("Power Blade On"); if(powerOn.CompletionCode == CompletionCode.Success) { Console.WriteLine("Waiting for Decompression Time: {0}", powerOn.DecompressionTime); Tracer.Write("Waiting for Decompression Time: {0}", powerOn.DecompressionTime); Thread.Sleep(TimeSpan.FromSeconds(powerOn.DecompressionTime)); } // Get the Power Status of a given device response = WcsBladeFacade.GetPowerStatus(bladeId); ValidateResponse(response, "Get Power Status"); // Get Sensor Reading response = WcsBladeFacade.GetSensorReading(bladeId, 0x01); ValidateResponse(response, "Get Sensor Reading"); // Get Blade Information BladeStatusInfo bladeInfo = WcsBladeFacade.GetBladeInfo(bladeId); ValidateResponse(response, "Get Blade Info"); // Get Fru Device info for Given Device Id FruDevice fru = WcsBladeFacade.GetFruDeviceInfo(bladeId); ValidateResponse(response, "Get Fru Device"); // Queries BMC for the currently set boot device. response = WcsBladeFacade.GetNextBoot(bladeId); ValidateResponse(response, "Get Next Boot"); // Set next boot device response = WcsBladeFacade.SetNextBoot(bladeId, BootType.ForceDefaultHdd, true, false); ValidateResponse(response, "Set Next Boot"); // Physically identify the computer by using a light or sound. if (WcsBladeFacade.Identify(bladeId, 255)) { ValidateResponse(new CustomResponse(success), "Set Identify: On"); } else { ValidateResponse(new CustomResponse(failure), "Set Identify: On"); } // Physically identify the computer by using a light or sound. if (WcsBladeFacade.Identify(bladeId, 0)) { ValidateResponse(new CustomResponse(success), "Set Identify: Off"); } else { ValidateResponse(new CustomResponse(failure), "Set Identify: Off"); } // Set the Power Cycle interval. if (WcsBladeFacade.SetPowerCycleInterval(bladeId, 0x08)) { ValidateResponse(new CustomResponse(success), "Set Power Cycle Interval: 8"); } else { ValidateResponse(new CustomResponse(failure), "Set Power Cycle Interval: 8"); } // Set the computer power state Off if (WcsBladeFacade.SetPowerState(bladeId, IpmiPowerState.Off) == 0x00) { ValidateResponse(new CustomResponse(success), "SetPowerState: Off"); } else { ValidateResponse(new CustomResponse(failure), "SetPowerState: Off"); } // Set the computer power state On if (WcsBladeFacade.SetPowerState(bladeId, IpmiPowerState.On) == 0x00) { ValidateResponse(new CustomResponse(success), "SetPowerState: On"); } else { ValidateResponse(new CustomResponse(failure), "SetPowerState: On"); } // Gets BMC firmware revision. Returns HEX string. response = WcsBladeFacade.GetFirmware(bladeId); ValidateResponse(response, "Get Firmware"); // Queries BMC for the GUID of the system. response = WcsBladeFacade.GetSystemGuid(bladeId); ValidateResponse(response, "Get System Guid"); // Reset SEL Log WcsBladeFacade.ClearSel(bladeId); ValidateResponse(response, "Clear Sel"); // Recursively retrieves System Event Log entries. response = WcsBladeFacade.GetSel(bladeId); ValidateResponse(response, "Get Sel"); // Get System Event Log Information. Returns SEL Info. response = WcsBladeFacade.GetSelInfo(bladeId); ValidateResponse(response, "Get Sel Info"); // Get Device Id Command response = WcsBladeFacade.GetDeviceId(bladeId); ValidateResponse(response, "Get DeviceId"); // Get/Set Power Policy response = WcsBladeFacade.SetPowerRestorePolicy(bladeId, PowerRestoreOption.StayOff); ValidateResponse(response, "Set Power Restore Policy: Off"); response = WcsBladeFacade.SetPowerRestorePolicy(bladeId, PowerRestoreOption.AlwaysPowerUp); ValidateResponse(response, "Set Power Restore Policy: Always On"); // Switches Serial Port Access from BMC to System for Console Redirection response = WcsBladeFacade.SetSerialMuxSwitch(bladeId); ValidateResponse(response, "Set Serial MuxSwitch"); // Disable Safe Mode. CommunicationDevice.DisableSafeMode(); // Switches Serial port sharing from System to Bmc response = WcsBladeFacade.ResetSerialMux(bladeId); ValidateResponse(response, "Reset Serial Mux"); // Get the current advanced state of the host computer. response = WcsBladeFacade.GetChassisState(bladeId); ValidateResponse(response, "Get Chassis State"); // Get Processor Information response = WcsBladeFacade.GetProcessorInfo(bladeId, 0x01); ValidateResponse(response, "Get Processor Info"); // Get Memory Information response = WcsBladeFacade.GetMemoryInfo(bladeId, 0x01); ValidateResponse(response, "Get Memory Info"); // Get PCIe Info response = WcsBladeFacade.GetPCIeInfo(bladeId, 0x01); ValidateResponse(response, "Get PCIe Info"); // Get Nic Info response = WcsBladeFacade.GetNicInfo(bladeId, 0x01); ValidateResponse(response, "Get Nic Info"); // Get Hardware Info HardwareStatus hwStatus = WcsBladeFacade.GetHardwareInfo(bladeId, true, true, true, true, true, true, true, true, true); if (hwStatus.CompletionCode == 0x00) { ValidateResponse(new CustomResponse(success), "Hardware Status"); } else { ValidateResponse(new CustomResponse(failure), "Hardware Status"); } // DCMI Get Power Limit Command response = WcsBladeFacade.GetPowerLimit(bladeId); ValidateResponse(response, "Get Power Limit"); // DCMI Set Power Limit Command response = WcsBladeFacade.SetPowerLimit(bladeId, 220, 6000, 0x00, 0x00); ValidateResponse(response, "Set Power Limit"); // DCMI Get Power Reading Command List<PowerReading> pwReadings = WcsBladeFacade.GetPowerReading(bladeId); if(pwReadings.Count > 0) { ValidateResponse(pwReadings[0], "Get Power Reading"); } else { ValidateResponse(new CustomResponse(failure), "Get Power Reading"); } // Activate/Deactivate DCMI power limit if (WcsBladeFacade.ActivatePowerLimit(bladeId, true)) { ValidateResponse(new CustomResponse(success), "Activate Power Limit"); } else { ValidateResponse(new CustomResponse(failure), "Activate Power Limit"); } if (WcsBladeFacade.ActivatePowerLimit(bladeId, false)) { ValidateResponse(new CustomResponse(success), "Activate Power Limit"); } else { ValidateResponse(new CustomResponse(failure), "Activate Power Limit"); } StressSession(); }
public static void Update(CustomResponse configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } logger.Log(LogLevel.Debug, "Saving custom response"); PluginStore.Instance.Save(Instance, configuration); }