public void Salvar(Rede rede, Tipo tipo, string onda) { DatabaseEntities entities = new DatabaseEntities(); REDE fromdb; var query = from r in entities.REDE where r.descricao == rede.Descricao select r; if (entities.REDE.Count(r => r.descricao == rede.Descricao) == 0) { fromdb = new REDE(); entities.AddToREDE(fromdb); } else { fromdb = (REDE)query.First(); } fromdb.onda = onda; fromdb.camadas = rede.NumeroCamadas; fromdb.entradas = rede.NumeroEntradas; fromdb.neuronios = Utils.NeuroniosToString(rede); fromdb.pesos = Utils.PesosParaString((RedeAtivacao)rede); fromdb.threshold = Utils.ThresholdParaString((RedeAtivacao)rede); fromdb.descricao = rede.Descricao; entities.SaveChanges(); }
public static List<CursoView> GetAllCursos() { using (var context = new DatabaseEntities()) { return context.Curso.ToList().toCursos(); } }
public static TurmaView GetTurmaByID(int id) { using (var context = new DatabaseEntities()) { return context.Turma.Find(id).toTurma(); } }
public static CursoView GetCursoByID(int id) { using (var context = new DatabaseEntities()) { return context.Curso.Find(id).toCursos(); } }
protected void Page_Load(object sender, EventArgs e) { db = new DatabaseEntities(); /* //Kreiraj kontekst baze DatabaseEntities db = new DatabaseEntities(); // Daj mi sve životinje iz baze u obliku liste da mogu biti izvor podataka za GV List<zivotinja> lista_zivotinja = db.zivotinja.ToList<zivotinja>(); //postavi listu kao izvor za GV gv_zivotinje.DataSource = lista_zivotinja; //Učitaj podatke u GV gv_zivotinje.DataBind(); */ if (!IsPostBack) { //definiraj polje koje će se prikazati na stranici ddl_zoo.DataTextField = "grad"; //Definiraj polje koje će sadržavati vrijednost izbora ddl_zoo.DataValueField = "id"; List<zoo> lista_zoo = db.zoo.ToList<zoo>(); //lista kao izvor podataka ddl_zoo.DataSource = lista_zoo; //osvleži podatke ddl_zoo.DataBind(); postavi_grid(); } }
public static List<TurmaView> GetAllTurma() { using (var context = new DatabaseEntities()) { return context.Turma.ToList().toTurmas(); } }
public RedeAtivacao Setup(string descricao, Tipo tipo) { DatabaseEntities entities = new DatabaseEntities(); RedeAtivacao ativacao; REDE fromdb; var query = from r in entities.REDE where r.descricao == descricao select r; if (entities.REDE.Count(r => r.descricao == descricao) == 0) return null; fromdb = (REDE)query.First(); int entradas = fromdb.entradas; int[] neuronios = Utils.StringToInt(fromdb.neuronios); ativacao = new RedeAtivacao(new BipolarSigmoideFuncaoAtivacao(), entradas, neuronios); ativacao = Utils.SetupPesos(ativacao, fromdb.pesos); ativacao = Utils.SetupThreshold(ativacao, fromdb.threshold); ativacao.Descricao = descricao; return ativacao; }
//Vid registering lägg en ny User till public static void AddUser(string firstname, string lastname, string phone, int age, int gender, string email, int privat, string city, int preferedeGender) { using (var context = new DatabaseEntities()) { int loginID = context.Logins.Max(x => x.LoginID); User u = new User { LoginID = loginID, FirstName = firstname, LastName = lastname, Phone = phone, Age = age, Gender = gender, Email = email, Private = privat, City = city, PreferedGender = preferedeGender }; context.Users.Add(u); context.SaveChanges(); } }
public static OficinaView GetOficinaByID(int id) { using (var context = new DatabaseEntities()) { return context.Oficina.Find(id).toOficina(); } }
public static List<OficinaView> GetAllOficina() { using (var context = new DatabaseEntities()) { return context.Oficina.ToList().toOficinas(); } }
public static PessoaView GetPessoaById(int id) { using (var context = new DatabaseEntities()) { return context.Pessoa.Find(id).toPessoaView(); } }
public static void Editar(PessoaView pessoa) { using (var context = new DatabaseEntities()) { var item = context.Pessoa.Find(pessoa.Id); item.Nome = pessoa.Nome; item.Email = pessoa.Email; item.DataInclusao = pessoa.DataInclusao; item.DataNascimento = pessoa.DataNascimento; item.CPFCNPJ = pessoa.CPFCNPJ; item.IdPessoaTipo = pessoa.IdPessoaTipo; item.Telefone.NumeroFixo = pessoa.Telefone.NumeroFixo; item.Telefone.NumeroCelular = pessoa.Telefone.NumeroCelular; item.Endereco.Endereco1 = pessoa.Endereco.Endereco; item.Endereco.Complemento = pessoa.Endereco.Complemento; item.Endereco.Numero = pessoa.Endereco.Numero; item.Endereco.Cidade = pessoa.Endereco.Cidade; item.Endereco.Estado = pessoa.Endereco.Estado; item.Endereco.Bairro = pessoa.Endereco.Bairro; item.Endereco.CEP = pessoa.Endereco.CEP; item.Endereco.Pais = pessoa.Endereco.Pais; context.SaveChanges(); } }
public static List<PessoaView> RecuperarListaPessoasCompleta() { using (var context = new DatabaseEntities()) { return context.Pessoa.ToList().toPessoasView(); } }
/// <summary> /// Returnerar en användare baserat på det UserID som skickas in. /// </summary> /// <param name="userID"></param> /// <returns></returns> public static User GetUser(int userID) { using (var context = new DatabaseEntities()) { return context.Users.FirstOrDefault(x => x.UserID.Equals(userID)); } }
public JsonResult GetSiteMenu() { using (DatabaseEntities dc = new DatabaseEntities()) { var menu = dc.Menus.ToList(); return new JsonResult { Data = menu, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
public static List<Models.PessoaTipo> GetAllPessoaTipo() { using (var context = new DatabaseEntities()) { return context.PessoaTipo.ToList().toPessoasTipos(); } }
/// <summary> /// Returnerar en login genom att matcha användarnamnet i tabellen "Login". /// </summary> /// <param name="username"></param> /// <returns></returns> public static Login GetLogin(string username) { using (var context = new DatabaseEntities()) { return context.Logins.FirstOrDefault(x => x.LoginName.Equals(username)); } }
public static List<User> GetAllUsers() { using (var context = new DatabaseEntities()) { return context.Users .OrderBy(x => x.FirstName) .ToList(); } }
//Beroende på ifall användaren accepterar vänförfrågan eller nekar så blir dom vänner eller icke då statusen uppdateras. public static void AnswerFriendRequest(int userID, int friendID, int answer) { using (var context = new DatabaseEntities()) { FriendRequest friendRequest = context.FriendRequests.FirstOrDefault(x => x.UserID == userID && x.FriendID == friendID); friendRequest.Status = answer; context.SaveChanges(); } }
/// <summary> /// Uppdaterar profilbilden till den som användaren valt att ändra till. /// </summary> /// <param name="userID, profilImage"></param> /// <returns></returns> public static void EditProfileImage(int userID, byte[] profilImage) { using (var context = new DatabaseEntities()) { Image image = context.Images.FirstOrDefault(x => x.UserID == userID); image.Picture = profilImage; context.SaveChanges(); } }
public static Login ValidateLogin(string username, string password) { using (var context = new DatabaseEntities()) { return context.Logins.FirstOrDefault(x => x.LoginName.Equals(username) && x.Password.Equals(password)); } }
public static void Deletar(int id) { using (var context = new DatabaseEntities()) { var item = context.Turma.Find(id); context.Turma.Remove(item); context.SaveChanges(); } }
/// <summary> /// Hämtar alla användare som har den första bokstaven /// i sökningen i sitt namn och de personer som har sin /// profil som "Upptäckbar profil". /// </summary> /// <param name="firstLetterInFirstName"></param> /// <returns></returns> public static List<User> GetAllUsers(string firstLetterInFirstName) { using (var context = new DatabaseEntities()) { return context.Users .Where(x => x.FirstName.Contains(firstLetterInFirstName) && x.Private.Equals(1)) .OrderBy(x => x.FirstName) .ToList(); } }
//Kollar så inte personerna redan är vänner eller har en friendrequest som väntar på svar public static FriendRequest ValidateFriendRequest(int userID, int friendID) { using (var context = new DatabaseEntities()) { return context.FriendRequests.FirstOrDefault(x => x.UserID.Equals(userID) && x.FriendID.Equals(friendID) || x.UserID.Equals(friendID) && x.FriendID.Equals(userID)); } }
/// <summary> /// Sends email to notify user they have been nominated /// </summary> /// <param name="user">User to be notified</param> public void sendApproveEligibility(DatabaseEntities.User user) { loadTemplate("officerApproveEligibility"); string message = template; message += footer; string[] receiver = { user.Email }; sendEmail.sendEmailToList(receiver, message, "APSCUF iVote Nomination Approved"); }
public static void Editar(OficinaView oficina) { using (var context = new DatabaseEntities()) { var item = context.Oficina.Find(oficina.Id); item.Nome = oficina.Nome; item.DataCriacao = oficina.DataCriacao; context.SaveChanges(); } }
public static List<PessoaView> RecuperarListaPessoaFiltrada(string nomeFiltro, string CnpjCpfFiltro, string EmailFiltro, int idPessoaTipo) { using (var context = new DatabaseEntities()) { return context.Pessoa.Where (x => ((string.IsNullOrEmpty(nomeFiltro) || x.Nome.Contains(nomeFiltro)) && (string.IsNullOrEmpty(CnpjCpfFiltro) || x.CPFCNPJ.ToString().Contains(CnpjCpfFiltro)) && (string.IsNullOrEmpty(EmailFiltro) || x.Email.Contains(EmailFiltro)) && (idPessoaTipo == 0 || x.IdPessoaTipo.Equals(idPessoaTipo)) )).ToList().toPessoasView(); } }
public static void Editar(CursoView curso) { using (var context = new DatabaseEntities()) { var item = context.Curso.Find(curso.Id); item.Nome = curso.Nome; item.DataCriacao = curso.DataCriacao; context.SaveChanges(); } }
protected void Button1_Click(object sender, EventArgs e) { String desc = TextBox1.Text; String num = TextBox2.Text; Vehicle vh = new Vehicle(); vh.Description =desc; vh.TrackingNumber = num; DatabaseEntities de = new DatabaseEntities(); de.Vehicles.Add(vh); de.SaveChanges(); GridView1.DataBind(); }
//Listar alla vänförfrågningar som är obesvarade som alltså har status 3. public static List<FriendRequest> FriendRequests(int userID) { using (var context = new DatabaseEntities()) { var result = context.FriendRequests .Include(x => x.User1) .Where(x => x.FriendID == userID && x.Status == 3) .ToList(); return result; } }
protected void Page_Load(object sender, EventArgs e) { c = (Cliente)Session["Usuario"]; if (c != null) { using (DatabaseEntities context = new DatabaseEntities()) { c = context.Cliente.Where(cliente => cliente.cpf.Equals(c.cpf)).FirstOrDefault(); Funcionario f = c.Funcionario; if (f == null) { Response.Redirect("home.aspx", false); } else if (f.Oficina == null) { Response.Redirect("home.aspx", false); } else { if (produtosSelecionados == null) { produtosSelecionados = new Dictionary <Produto, int>(); } if (servicosSelecionados == null) { servicosSelecionados = new List <Servico>(); } carregarTabelaServicos(); carregarTabelaProdutos(); lbl_Nome.Text = c.nome; if (f == null) { pnl_Oficina.Visible = false; btn_CadastroOficina.Visible = true; List <RequisicaoFuncionario> requisicoes = context.RequisicaoFuncionario.Where(r => r.cpfCliente.Equals(c.cpf)).ToList(); if (requisicoes.Count > 0) { pnl_Funcionario.Visible = true; badge_Requisicoes.InnerHtml = requisicoes.Count.ToString(); } else { pnl_Funcionario.Visible = false; } } else { pnl_Oficina.Visible = true; pnl_Funcionario.Visible = false; btn_CadastroOficina.Visible = false; lbl_Nome.Text += " | " + f.Oficina.nome; if (f.cargo.ToLower().Equals("gerente")) { btn_Configuracoes.Visible = true; btn_Funcionarios.Visible = true; } else { btn_Configuracoes.Visible = false; btn_Funcionarios.Visible = false; } } } } } else { Response.Redirect("login.aspx", false); } }
/// <summary> /// This method is used to Save the screen permission details /// </summary> /// <param name="ScreenPermissions"></param> /// <param name="RoleID"></param> /// <param name="CreatedBy"></param> /// <returns></returns> public string SaveScreenPermissionDetails(Guid RoleID, Guid CreatedBy, FormCollection fCollection) { try { SiteMapRolePermission SiteMapRolePermissionModel; using (var DatabaseEntities = new DatabaseEntities()) { var sitemapRolePermissions = DatabaseEntities.SiteMapRolePermissions.Where(y => y.RoleId == RoleID); foreach (var item in sitemapRolePermissions) { DatabaseEntities.SiteMapRolePermissions.Remove(item); } DatabaseEntities.SaveChanges(); foreach (var item in fCollection.Keys) { if (item.ToString() != "hdnRoleID") { if (fCollection[item.ToString()] == "on") { string[] sitemapRolePermission = item.ToString().Split('_'); if (sitemapRolePermission != null) { SiteMapRolePermissionModel = new SiteMapRolePermission(); Guid Id = Guid.NewGuid(); SiteMapRolePermissionModel.Id = Id; if (sitemapRolePermission.Count() > 0) { if (!string.IsNullOrWhiteSpace(sitemapRolePermission[0])) { SiteMapRolePermissionModel.SiteMapId = Guid.Parse(sitemapRolePermission[0]); } } if (sitemapRolePermission.Count() > 1) { if (!string.IsNullOrWhiteSpace(sitemapRolePermission[1])) { SiteMapRolePermissionModel.RoleId = Guid.Parse(sitemapRolePermission[1]); } } if (sitemapRolePermission.Count() > 2) { if (!string.IsNullOrWhiteSpace(sitemapRolePermission[2])) { SiteMapRolePermissionModel.PermissionId = Guid.Parse(sitemapRolePermission[2]); } } // SiteMapRolePermissionAPI.PutSiteMapRolePermission(Id, SiteMapRolePermissionModel); DatabaseEntities.SiteMapRolePermissions.Add(SiteMapRolePermissionModel); DatabaseEntities.SaveChanges(); } } } } } return("Permissions assigned successfully"); } catch (Exception ex) { // ExceptionTrans.SaveException(ex.ToString(), 1, ex.Message, "SaveScreenPermissionDetails"); return(ex.Message); } }
public StoreController() { database = new DatabaseEntities(); }
public UnitOfWork() { entities = new DatabaseEntities(); }
/// <summary> /// This Method is used to Get the Main Office Configuration Details /// </summary> /// <returns></returns> public async Task <SubSiteDTO> GetById(Guid userid) { try { DropDownService ddService = new DropDownService(); List <EntityHierarchyDTO> EntityHierarchyDTOs = new List <EntityHierarchyDTO>(); EntityHierarchyDTOs = ddService.GetEntityHierarchies(userid); Guid ParentId = Guid.Empty; int Level = EntityHierarchyDTOs.Count; if (EntityHierarchyDTOs.Count == 1) { var LevelOne = EntityHierarchyDTOs.Where(o => o.Customer_Level == 0).FirstOrDefault(); if (LevelOne != null) { ParentId = LevelOne.CustomerId ?? Guid.Empty; } } else { var LevelOne = EntityHierarchyDTOs.Where(o => o.Customer_Level == 1).FirstOrDefault(); if (LevelOne != null) { ParentId = LevelOne.CustomerId ?? Guid.Empty; } } userid = ParentId; db = new DatabaseEntities(); var data = await db.SubSiteConfigurations.Where(o => (o.StatusCode == EMPConstants.Active || o.StatusCode == EMPConstants.Pending) && o.emp_CustomerInformation_ID == userid).Select(o => new SubSiteDTO { Id = o.ID.ToString(), refId = o.emp_CustomerInformation_ID.ToString(), IsuTaxManageingEnrolling = o.IsuTaxManageingEnrolling, IsuTaxPortalEnrollment = o.IsuTaxPortalEnrollment, IsuTaxManageOnboarding = o.IsuTaxManageOnboarding, EnrollmentEmails = o.EnrollmentEmails ?? false, IsuTaxCustomerSupport = o.IsuTaxCustomerSupport, NoofSupportStaff = o.NoofSupportStaff, NoofDays = o.NoofDays, OpenHours = o.OpenHours.Value.ToString(), // "hh:mm tt"),// "hh:mm tt"), CloseHours = o.CloseHours.Value.ToString(), //"hh:mm tt"),//"hh:mm tt"), TimeZone = o.TimeZone.ToString(), SubSiteTaxReturn = o.SubSiteTaxReturn, IsAutoEnrollAffiliateProgram = o.IsAutoEnrollAffiliateProgram, IsSubSiteEFINAllow = o.IsSubSiteEFINAllow, CanSubSiteLoginToEmp = o.CanSubSiteLoginToEmp, Affiliates = o.SubSiteAffiliateProgramConfigs.Select(s => new SubSiteAffiliateProgramDTO() { AffiliateProgramId = s.AffiliateProgramMaster_ID }).ToList(), SubSiteBankQuestions = o.SubSiteBankConfigs.Select(s => new SubSiteBankQuestionDTO() { BankId = s.BankMaster_ID, QuestionId = s.SubQuestion_ID ?? Guid.Empty }).ToList() }).FirstOrDefaultAsync(); if (data != null) { DateTime dt = new DateTime(); bool res = DateTime.TryParse(data.OpenHours, out dt); string ddt = new DateTime().Add(dt.TimeOfDay).ToString("hh:mm tt"); data.OpenHours = ddt; DateTime dt1 = new DateTime(); bool res1 = DateTime.TryParse(data.CloseHours, out dt1); string ddt1 = new DateTime().Add(dt1.TimeOfDay).ToString("hh:mm tt"); data.CloseHours = ddt1; } else { if (Level > 2) { data = new DTO.SubSiteDTO(); var SubSiteOfficeCon = db.SubSiteOfficeConfigs.Where(o => o.RefId == ParentId).FirstOrDefault(); if (SubSiteOfficeCon != null) { if (SubSiteOfficeCon.SOorSSorEFIN == 2 || SubSiteOfficeCon.SOorSSorEFIN == 3) { data.IsSubSiteEFINAllow = true; } } } // OpenHours = new DateTime().Add(o.OpenHours.Value).ToString("hh:mm tt"),// "hh:mm tt"), // CloseHours = new DateTime().Add(o.CloseHours.Value).ToString("hh:mm tt"),//"hh:mm tt"), } return(data); } catch (Exception ex) { EMPPortal.Core.Utilities.ExceptionLogger.LogException(ex.ToString(), "SubSiteConfigService/GetById", userid); return(null); } }
protected void preencherTabela() { try { if (tbl_Agendamentos.Rows.Count > 0) { tbl_Agendamentos.Rows.Clear(); } using (DatabaseEntities context = new DatabaseEntities()) { TableHeaderRow headerRow; TableHeaderCell headerCell; headerRow = new TableHeaderRow(); headerRow.CssClass = "thead-dark"; headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Cliente"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Telefone"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "E-mail"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Data/Hora"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Veículo"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Status"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Ações"; headerRow.Cells.Add(headerCell); tbl_Agendamentos.Rows.Add(headerRow); TableRow row; TableCell cell; Button btn; DateTime dataHora; List <Agendamento> agendamentos = context.Agendamento.Where(a => a.cnpjOficina.Equals(o.cnpj)).ToList(); agendamentos = agendamentos.OrderBy(a => a.data + a.hora).ToList(); if (agendamentos.Count > 0) { foreach (Agendamento a in agendamentos) { if (mostrarPassados) { row = new TableRow(); cell = new TableCell(); cell.Text = a.Cliente.nome; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Cliente.telefone; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Cliente.email; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); dataHora = a.data + a.hora; cell.Text = dataHora.ToString("dd/MM/yyyy") + " - " + dataHora.Hour.ToString("00") + ":" + dataHora.Minute.ToString("00"); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Veiculo.marca + " " + a.Veiculo.modelo; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.status; if (a.status.Equals("Confirmado")) { cell.CssClass = "text-center text-success align-middle"; } else if (a.status.Equals("Cancelado pelo cliente") || a.status.Equals("Cancelado pela oficina")) { cell.CssClass = "text-center text-danger align-middle"; } else { cell.CssClass = "text-center align-middle"; } row.Cells.Add(cell); cell = new TableCell(); cell.CssClass = "text-center align-middle"; if (dataHora.CompareTo(DateTime.Now) > 0) { if (a.status.Equals("Confirmação pendente")) { btn = new Button(); btn.Click += new EventHandler(btn_Confirmar_Click); btn.ID = "btn_Confirmar" + a.idAgendamento; btn.Text = "Confirmar"; btn.CssClass = "btn btn-success mb-1"; btn.CommandArgument = a.idAgendamento.ToString(); cell.Controls.Add(btn); } if (a.status.Equals("Confirmação pendente") || a.status.Equals("Confirmado")) { btn = new Button(); btn.Click += new EventHandler(btn_Cancelar_Click); btn.ID = "btn_Cancelar" + a.idAgendamento; btn.Text = "Cancelar"; btn.CssClass = "btn btn-danger"; btn.CommandArgument = a.idAgendamento.ToString(); cell.Controls.Add(btn); } } row.Cells.Add(cell); tbl_Agendamentos.Rows.Add(row); } else { if (a.data.CompareTo(DateTime.Now.Date) >= 0) { row = new TableRow(); cell = new TableCell(); cell.Text = a.Cliente.nome; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Cliente.telefone; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Cliente.email; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); dataHora = a.data + a.hora; cell.Text = dataHora.ToString("dd/MM/yyyy") + " - " + dataHora.Hour.ToString("00") + ":" + dataHora.Minute.ToString("00"); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.Veiculo.marca + " " + a.Veiculo.modelo; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = a.status; if (a.status.Equals("Confirmado")) { cell.CssClass = "text-center text-success align-middle"; } else if (a.status.Equals("Cancelado pelo cliente") || a.status.Equals("Cancelado pela oficina")) { cell.CssClass = "text-center text-danger align-middle"; } else { cell.CssClass = "text-center align-middle"; } row.Cells.Add(cell); cell = new TableCell(); cell.CssClass = "text-center align-middle"; if (a.status.Equals("Confirmação pendente")) { btn = new Button(); btn.Click += new EventHandler(btn_Confirmar_Click); btn.ID = "btn_Confirmar" + a.idAgendamento; btn.Text = "Confirmar"; btn.CssClass = "btn btn-success mb-1"; btn.CommandArgument = a.idAgendamento.ToString(); cell.Controls.Add(btn); } if (a.status.Equals("Confirmação pendente") || a.status.Equals("Confirmado")) { btn = new Button(); btn.Click += new EventHandler(btn_Cancelar_Click); btn.ID = "btn_Cancelar" + a.idAgendamento; btn.Text = "Cancelar"; btn.CssClass = "btn btn-danger"; btn.CommandArgument = a.idAgendamento.ToString(); cell.Controls.Add(btn); } row.Cells.Add(cell); tbl_Agendamentos.Rows.Add(row); } } } } else { row = new TableRow(); cell = new TableCell(); cell.Text = "Nenhum agendamento foi encontrado"; cell.ColumnSpan = 7; cell.CssClass = "text-center align-middle font-weight-bold text-primary"; row.Cells.Add(cell); tbl_Agendamentos.Rows.Add(row); } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } }
protected void preencher_Tabela() { try { using (DatabaseEntities context = new DatabaseEntities()) { List <Servico> servicos = context.Servico.Where(s => s.cnpjOficina.Equals(c.Funcionario.cnpjOficina)).ToList(); TableRow row; TableCell cell; Button btn; if (servicos.Count > 0) { foreach (Servico s in servicos) { row = new TableRow(); cell = new TableCell(); cell.Text = s.descricao; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = "R$ " + s.valor.ToString("0.00"); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); //Botao Editar cell = new TableCell(); cell.CssClass = "text-center align-middle"; btn = new Button(); btn.Click += new EventHandler(btn_EditarServico_Click); btn.Text = "Editar"; btn.CssClass = "btn btn-primary"; btn.CommandArgument = s.idServico.ToString(); btn.Attributes.Add("formnovalidate", "true"); cell.Controls.Add(btn); row.Cells.Add(cell); tbl_Servicos.Rows.Add(row); } } else { row = new TableRow(); cell = new TableCell(); cell.Text = "Nenhum serviço encontrado"; cell.ColumnSpan = 6; cell.CssClass = "text-center align-middle font-weight-bold text-primary"; row.Cells.Add(cell); tbl_Servicos.Rows.Add(row); } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } }
protected async Task <XmlDocument> reqPagar(string token) { using (DatabaseEntities context = new DatabaseEntities()) { Oficina oficina = context.Oficina.Where(of => of.cnpj.Equals(o.cnpjOficina)).FirstOrDefault(); CredenciaisPagamento cred = context.CredenciaisPagamento.FirstOrDefault(); var values = new Dictionary <string, string> { { "payment.mode", "default" }, { "payment.method", "creditCard" }, { "currency", "BRL" }, { "item[1].id", o.idOrcamento.ToString() }, { "item[1].description", "Orçamento" }, { "item[1].amount", o.valor.ToString("0.00").Replace(",", ".") }, { "item[1].quantity", "1" }, { "notificationURL", "https://*****:*****@sandbox.pagseguro.com.br" }, { "shipping.address.street", "Av. Brig. Faria Lima" }, { "shipping.address.number", "1384" }, { "shipping.address.complement", "5o andar" }, { "shipping.address.district", "Jardim Paulistano" }, { "shipping.address.postalCode", "01452002" }, { "shipping.address.city", "Sao Paulo" }, { "shipping.address.state", "SP" }, { "shipping.address.country", "BRA" }, { "shipping.type", "3" }, { "shipping.cost", "0.00" }, { "installment.value", o.valor.ToString("0.00").Replace(",", ".") }, { "installment.quantity", "1" }, { "installment.noInterestInstallmentQuantity", "2" }, { "creditCard.token", token }, { "creditCard.holder.name", c.nome }, { "creditCard.holder.CPF", c.cpf }, { "creditCard.holder.birthDate", c.dataNascimento.ToString().Split(' ')[0] }, { "creditCard.holder.areaCode", c.telefone.Substring(0, 2) }, { "creditCard.holder.phone", c.telefone.Substring(2, c.telefone.Length - 2) }, { "billingAddress.street", "Av. Brig. Faria Lima" }, { "billingAddress.number", "1384" }, { "billingAddress.complement", "5o andar" }, { "billingAddress.district", "Jardim Paulistano" }, { "billingAddress.postalCode", "01452002" }, { "billingAddress.city", "Sao Paulo" }, { "billingAddress.state", "SP" }, { "billingAddress.country", "BRA" }, { "primaryReceiver.publicKey", oficina.chavePublica } }; var content = new FormUrlEncodedContent(values); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/vnd.pagseguro.com.br.v3+xml")); var response = await client.PostAsync("https://ws.sandbox.pagseguro.uol.com.br/transactions?appId=" + cred.appId + "&appKey=" + cred.appKey, content); if (response.IsSuccessStatusCode) { var responseString = await response.Content.ReadAsStringAsync(); XmlDocument xml = new XmlDocument(); xml.LoadXml(responseString); return(xml); } else { var responseString = await response.Content.ReadAsStringAsync(); return(null); } } }
protected void Page_Load(object sender, EventArgs e) { c = (Cliente)Session["usuario"]; o = (Orcamento)Session["orcamento"]; if (c == null) { Response.Redirect("login.aspx", false); } else if (o == null) { Response.Redirect("orcamento_ListaCliente.aspx", false); } else if (!o.status.Equals("Pagamento pendente")) { Response.Redirect("orcamento_ListaCliente.aspx", false); } else { using (DatabaseEntities context = new DatabaseEntities()) { Oficina oficina = context.Oficina.Where(of => of.cnpj.Equals(o.cnpjOficina)).FirstOrDefault(); lbl_Oficina.InnerText = oficina.nome; if (oficina.reputacao == null) { lbl_Reputacao.Text = "-/10"; } else { lbl_Reputacao.Text = oficina.reputacao + "/10"; } lbl_Valor.InnerText = "Valor do pagamento: R$ " + o.valor.ToString("0.00"); if (client == null) { client = new HttpClient(); } if (!IsPostBack) { List <Cartao> cartoes = context.Cartao.Where(card => card.cpfCliente.Equals(c.cpf)).ToList(); if (cartoes.Count > 0) { ListItem item; item = new ListItem(); item.Value = "-"; item.Text = "Selecione um cartão"; txt_Cartao.Items.Add(item); string mes; foreach (Cartao card in cartoes) { if (card.mesVencimento < 10) { mes = "0" + card.mesVencimento; } else { mes = card.mesVencimento.ToString(); } item = new ListItem(); item.Value = card.idCartao.ToString(); item.Text = card.bandeira.ToUpper() + " - " + card.numero.Substring(card.numero.Length - 4) + " - Vence em " + mes + "/" + card.anoVencimento; txt_Cartao.Items.Add(item); } } else { div_Quick.Visible = false; } } //Dash Time f = context.Funcionario.Where(func => func.cpf.Equals(c.cpf)).FirstOrDefault(); lbl_Nome.Text = c.nome; if (f == null) { pnl_Oficina.Visible = false; btn_CadastroOficina.Visible = true; List <RequisicaoFuncionario> requisicoes = context.RequisicaoFuncionario.Where(r => r.cpfCliente.Equals(c.cpf)).ToList(); if (requisicoes.Count > 0) { pnl_Funcionario.Visible = true; badge_Requisicoes.InnerHtml = requisicoes.Count.ToString(); } else { pnl_Funcionario.Visible = false; } } else { pnl_Oficina.Visible = true; pnl_Funcionario.Visible = false; btn_CadastroOficina.Visible = false; lbl_Nome.Text += " | " + f.Oficina.nome; if (f.cargo.ToLower().Equals("gerente")) { btn_Configuracoes.Visible = true; btn_Funcionarios.Visible = true; } else { btn_Configuracoes.Visible = false; btn_Funcionarios.Visible = false; } } } } }
protected async void btn_Pagar_Click(object sender, EventArgs e) { try { using (DatabaseEntities context = new DatabaseEntities()) { string idSessao = await reqSessao(); if (idSessao.Length == 0) { showError("Erro no pagamento." + Environment.NewLine + "Por favor entre em contato com o suporte"); } else { string bandeira = await reqBandeira(idSessao); if (bandeira.Length == 0) { showError("Erro no pagamento. Verifique o número do cartão inserido"); } else { int mes = int.Parse(txt_Vencimento.Text.Split('/')[0]); int ano = int.Parse(txt_Vencimento.Text.Split('/')[1]); if (ano < DateTime.Now.Year || (mes < DateTime.Now.Month && ano == DateTime.Now.Year)) { showError("Erro no pagamento. Verifique a data de vencimento inserida"); } else { Cartao card = new Cartao() { numero = txt_NumeroCartao.Text.Replace(" ", ""), bandeira = bandeira, mesVencimento = mes, anoVencimento = ano, titular = txt_Titular.Text, cpfCliente = c.cpf }; string token = await reqToken(idSessao, card); if (token.Length == 0) { showError("Erro no pagamento. Verifique os dados inseridos"); } else { if (chk_Salvar.Checked) { context.Cartao.Add(card); context.SaveChanges(); } XmlDocument transaction = await reqPagar(token); if (transaction == null) { showError("Erro no pagamento. Por favor entre em contato com o suporte e/ou verifique os dados inseridos"); } else { Pagamento p = new Pagamento() { idOrcamento = o.idOrcamento, status = "1", data = DateTime.Parse(transaction.GetElementsByTagName("date")[0].InnerXml), valor = o.valor, code = transaction.GetElementsByTagName("code")[0].InnerXml }; context.Pagamento.Add(p); o = context.Orcamento.Where(orc => orc.idOrcamento == o.idOrcamento).FirstOrDefault(); o.status = "Pagamento em processamento"; context.SaveChanges(); Session["orcamento"] = null; Session["message"] = "Seu pagamento está agora em processamento"; Response.Redirect("orcamento_ListaCliente.aspx", false); } } } } } } } catch (Exception ex) { showError("Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte e/ou verifique os dados inseridos"); } }
public void UpdateModel(ProjectFirmaModels.Models.Project project, DatabaseEntities databaseEntities) { var currentProjectFundingSourceBudgets = project.ProjectFundingSourceBudgets.ToList(); databaseEntities.ProjectFundingSourceBudgets.Load(); var allProjectFundingSourceBudgets = databaseEntities.AllProjectFundingSourceBudgets.Local; var currentProjectNoFundingSourceIdentifieds = project.ProjectNoFundingSourceIdentifieds.ToList(); databaseEntities.ProjectNoFundingSourceIdentifieds.Load(); var allProjectNoFundingSourceIdentifieds = HttpRequestStorage.DatabaseEntities.AllProjectNoFundingSourceIdentifieds.Local; project.FundingTypeID = FundingTypeID; var projectFundingSourceBudgetsUpdated = new List <ProjectFirmaModels.Models.ProjectFundingSourceBudget>(); if (ProjectFundingSourceBudgets != null) { // Completely rebuild the list projectFundingSourceBudgetsUpdated = ProjectFundingSourceBudgets.Where(x => x.IsRelevant ?? false).SelectMany(x => x.ToProjectFundingSourceBudgets()).ToList(); } currentProjectFundingSourceBudgets.Merge(projectFundingSourceBudgetsUpdated, allProjectFundingSourceBudgets, (x, y) => x.ProjectID == y.ProjectID && x.FundingSourceID == y.FundingSourceID && x.CostTypeID == y.CostTypeID && x.CalendarYear == y.CalendarYear, (x, y) => x.SetSecuredAndTargetedAmounts(y.SecuredAmount, y.TargetedAmount), databaseEntities); var projectNoFundingSourceAmountsUpdated = new List <ProjectNoFundingSourceIdentified>(); if (FundingTypeID == FundingType.BudgetSameEachYear.FundingTypeID && NoFundingSourceIdentifiedYet != null) { // Completely rebuild the list projectNoFundingSourceAmountsUpdated.Add(new ProjectNoFundingSourceIdentified(project.ProjectID) { NoFundingSourceIdentifiedYet = NoFundingSourceIdentifiedYet }); } else if (FundingTypeID == FundingType.BudgetVariesByYear.FundingTypeID && NoFundingSourceAmounts != null) { // Completely rebuild the list projectNoFundingSourceAmountsUpdated = NoFundingSourceAmounts.Where(x => x.MonetaryAmount.HasValue) .Select(x => new ProjectNoFundingSourceIdentified(project.ProjectID) { CalendarYear = x.CalendarYear, NoFundingSourceIdentifiedYet = x.MonetaryAmount.Value }) .ToList(); } currentProjectNoFundingSourceIdentifieds.Merge(projectNoFundingSourceAmountsUpdated, allProjectNoFundingSourceIdentifieds, (x, y) => x.ProjectID == y.ProjectID && x.CalendarYear == y.CalendarYear, (x, y) => x.NoFundingSourceIdentifiedYet = y.NoFundingSourceIdentifiedYet, databaseEntities); var currentProjectRelevantCostTypes = project.GetBudgetsRelevantCostTypes(); var allProjectRelevantCostTypes = databaseEntities.AllProjectRelevantCostTypes.Local; var projectRelevantCostTypes = new List <ProjectRelevantCostType>(); if (ProjectRelevantCostTypes != null) { // Completely rebuild the list projectRelevantCostTypes = ProjectRelevantCostTypes.Where(x => x.IsRelevant) .Select(x => new ProjectRelevantCostType(x.ProjectRelevantCostTypeID, x.ProjectID, x.CostTypeID, ProjectRelevantCostTypeGroup.Budgets.ProjectRelevantCostTypeGroupID)) .ToList(); } currentProjectRelevantCostTypes.Merge(projectRelevantCostTypes, allProjectRelevantCostTypes, (x, y) => x.ProjectID == y.ProjectID && x.CostTypeID == y.CostTypeID && x.ProjectRelevantCostTypeGroupID == y.ProjectRelevantCostTypeGroupID, databaseEntities); }
public AmortizationModel() { db = new DatabaseEntities(); }
public MessagesController() { _db = new DatabaseEntities(); }
protected void carregarTabelaServicos() { try { using (DatabaseEntities context = new DatabaseEntities()) { TableRow row; TableHeaderRow headerRow; TableCell cell; TableHeaderCell headerCell; Button btn; if (servicosSelecionados.Count > 0) { headerRow = new TableHeaderRow(); headerRow.CssClass = "thead-light"; headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Descrição"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Valor"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Ações"; headerRow.Cells.Add(headerCell); tbl_Servicos.Rows.Add(headerRow); foreach (Servico s in servicosSelecionados) { row = new TableRow(); cell = new TableCell(); cell.Text = s.descricao; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = "R$ " + s.valor.ToString("0.00"); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.CssClass = "text-center align-middle"; btn = new Button(); btn.Text = "Remover"; btn.Click += new EventHandler(btn_RemoverServico_Click); btn.ID = "btn_Servico" + s.idServico.ToString(); btn.CommandArgument = s.idServico.ToString(); btn.CssClass = "btn btn-danger"; cell.Controls.Add(btn); row.Cells.Add(cell); tbl_Servicos.Rows.Add(row); } tbl_Servicos.Visible = true; } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } }
protected void carregarTabelaProdutos() { try { using (DatabaseEntities context = new DatabaseEntities()) { TableRow row; TableHeaderRow headerRow; TableCell cell; TableHeaderCell headerCell; Button btn; if (produtosSelecionados.Count > 0) { headerRow = new TableHeaderRow(); headerRow.CssClass = "thead-light"; headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Descrição"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Marca"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Preço"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Validade"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Quantidade em<br />estoque"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Quantidade<br />selecionada"; headerRow.Cells.Add(headerCell); headerCell = new TableHeaderCell(); headerCell.CssClass = "text-center"; headerCell.Text = "Ações"; headerRow.Cells.Add(headerCell); tbl_Produtos.Rows.Add(headerRow); Double precoVenda; DateTime validade; foreach (Produto p in produtosSelecionados.Keys) { row = new TableRow(); cell = new TableCell(); cell.Text = p.descricao; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = p.marca; cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); if (p.precoVenda == null) { cell.Text = "-"; } else { precoVenda = (Double)p.precoVenda; cell.Text = "R$ " + precoVenda.ToString("0.00"); } cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); if (p.validade == null) { cell.Text = "-"; } else { validade = (DateTime)p.validade; cell.Text = validade.ToString("dd/MM/yyyy"); } cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = p.quantidade.ToString(); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.Text = produtosSelecionados[p].ToString(); cell.CssClass = "text-center align-middle"; row.Cells.Add(cell); cell = new TableCell(); cell.CssClass = "text-center align-middle"; btn = new Button(); btn.Text = "Remover"; btn.Click += new EventHandler(btn_RemoverProduto_Click); btn.ID = "btn_Produto" + p.idProduto.ToString(); btn.CommandArgument = p.idProduto.ToString(); btn.CssClass = "btn btn-danger"; cell.Controls.Add(btn); row.Cells.Add(cell); tbl_Produtos.Rows.Add(row); } tbl_Produtos.Visible = true; } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } }
public void UpdateAndSaveChanges(string WhatSave) { try { using (db = new DatabaseEntities()) { //Логика обновления ВСЁ ИМУЩЕСТВО if (WhatSave == "GoodsInfo") { if (MainDataGrid.SelectedCells.Count == 9) { //выделеная строка StaffItems rowView = MainDataGrid.SelectedItem as StaffItems; StaffItems updatedStaffItem = new StaffItems(); //поиск обновляемого элемента в контексте по ID (Primary key) updatedStaffItem = db.StaffItems.Where(x => x.Id == rowView.Id).FirstOrDefault(); //Название updatedStaffItem.ItemName = textBoxStaffItemsName.Text.ToString(); //Кол-во bool ammountIsParsed = int.TryParse(textBoxItemsAmmount.Text, out int _ammount); if (!ammountIsParsed) { updatedStaffItem.Ammount = null; } else { updatedStaffItem.Ammount = _ammount; } //Цена bool priceIsParsed = int.TryParse(textBoxItemsPrice.Text, out int _price); if (!priceIsParsed) { updatedStaffItem.Price = null; } else { updatedStaffItem.Price = _price; } //Дата покупки updatedStaffItem.ArrivalData = textBoxItemsArrivalData.Text; //Срок службы (число) bool lifeTimeIsParsed = int.TryParse(textBoxItemsPeriodOfStorage.Text, out int _lifeTime); if (!lifeTimeIsParsed) { updatedStaffItem.PeriodOfStorage = null; } else { updatedStaffItem.PeriodOfStorage = _lifeTime; } //Категория if (comboBoxItemsCategories.Text != "") { Categories category = db.Categories.Where(x => x.Name == comboBoxItemsCategories.Text).FirstOrDefault(); if (category != null) { updatedStaffItem.FK_Category = category.Name; } } else { updatedStaffItem.FK_Category = null; } //Обновление срока службы (дата списания) if (textBoxItemsArrivalData.Text != "") { if (textBoxItemsPeriodOfStorage.Text != "") { DateTime buyDateFromTextBox = Convert.ToDateTime(textBoxItemsArrivalData.Text); updatedStaffItem.OffData = buyDateFromTextBox.AddMonths(_lifeTime).ToString("dd.MM.yyyy"); } } else { updatedStaffItem.OffData = null; } //Ответственный сотрудник if (comboBoxItrmsResponsibleHuman.Text != "") { Employees employee = db.Employees.Where(x => x.Name == comboBoxItrmsResponsibleHuman.Text).FirstOrDefault(); if (employee != null) { updatedStaffItem.FK_ResponsibleEmployee = employee.Name; } } else { updatedStaffItem.FK_ResponsibleEmployee = null; } db.Entry(updatedStaffItem).State = EntityState.Modified; db.SaveChanges(); FillDataGrid(); } } } } catch (Exception exteption) { MessageBox.Show($"Информация об ошибке: {exteption.Message}", "Произошла ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } }
public ValuesController() { db = new DatabaseEntities(); }
public RecipeManager(DatabaseEntities context) { _context = context; }
public HttpResponseMessage Post([FromBody] Bought bought, int id) { try { string username = Thread.CurrentPrincipal.Identity.Name; using (DatabaseEntities entities = new DatabaseEntities()) { var entity = entities.Users.Where(e => e.Email.Equals(username)).FirstOrDefault(); var IP = entities.InProgresses.Where(e => e.IdItem == id).FirstOrDefault(); var item = entities.Items.Where(e => e.Id == id).FirstOrDefault(); var userWhoSold = entities.Users.Where(e => e.Id == item.IdSeller).FirstOrDefault(); string emailBefore = ""; // double pricebefore = 0; try { var priceBefore = entities.InProgresses.Where(e => e.IdItem == id).FirstOrDefault(); var userBefore = entities.Boughts.Where(e => e.IdItem == id && e.Price == priceBefore.ActualPrice).DefaultIfEmpty(); // pricebefore = Convert.ToDouble(priceBefore.ActualPrice); var UB = entities.Users.Where(e => e.Id == userBefore.FirstOrDefault().IdSeller).FirstOrDefault(); emailBefore = UB.Email.ToString(); } catch (Exception edsg) { } DateTime date = DateTime.Now; bought.Date = date; bought.IdItem = IP.IdItem; bought.IdSeller = entity.Id; bought.Type = IP.Type; bought.NumberOfItems = Convert.ToInt32(bought.NumberOfItems); bought.Price = Convert.ToDouble(bought.Price); // if (bought.Type.Equals("Licytacja") && !emailBefore.Equals(entity.Email)) // { // var EB = entities.Users.Where(e => e.Email.Equals(emailBefore)).FirstOrDefault(); // EB.Money = EB.Money + pricebefore; // entity.Money = entity.Money - bought.Price; // } if ((bought.Type.Equals("Licytacja") && (bought.Price != IP.PriceForOne))) { entity.Money = entity.Money - bought.Price; } if (bought.Type.Equals("Kup teraz")) { entity.Money = entity.Money - bought.Price; } if (bought.Type.Equals("Kup teraz") || (bought.Type.Equals("Licytacja") && (bought.Price == IP.PriceForOne))) { userWhoSold.Money = userWhoSold.Money + bought.Price; } entities.Boughts.Add(bought); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, bought); if (bought.Type.Equals("Kup teraz")) { try { System.Net.Mail.SmtpClient client = new SmtpClient(); // client.UseDefaultCredentials = false; // client.Credentials new System.Net.NetworkCredential("yetju000", "uughns56", "yetju000-001-site1.htempurl.com"); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wchujdrogo"); MailMessage mm = new MailMessage("*****@*****.**", entity.Email, "Alledrogo - Zakupione przedmioty", "Kupiłeś przedmiot[y] '" + item.Title + "'. Id aukcji:" + item.Id + "! Sztuk:" + bought.NumberOfItems + " Cena : " + bought.Price); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm); client = new SmtpClient(); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wchujdrogo"); mm = new MailMessage("*****@*****.**", userWhoSold.Email, "Alledrogo - Sprzedane przedmioty", "Sprzedałeś przedmiot[y] '" + item.Title + "'. Id aukcji:" + item.Id + "! Sztuk:" + bought.NumberOfItems + " Cena : " + bought.Price); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm); } catch (Exception exx) { } } else if (bought.Type.Equals("Licytacja")) { try { System.Net.Mail.SmtpClient client = new SmtpClient(); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wchujdrogo"); MailMessage mm = new MailMessage("*****@*****.**", emailBefore, "Alledrogo - Nowa cena aukcji którą licytowałeś", "Została ustalona nowa cena przedmiot[y] '" + item.Title + "'. Id aukcji:" + item.Id + ". Nowa cena : " + bought.Price); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm); client.Port = 587; client.Host = "smtp.gmail.com"; client.EnableSsl = true; client.Timeout = 10000; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "wchujdrogo"); mm = new MailMessage("*****@*****.**", userWhoSold.Email, "Alledrogo - Nowa cena twojej aukcji", "Została ustalona nowa cena twojego przedmiot[y] '" + item.Title + "'. Id aukcji:" + item.Id + ". Nowa cena : " + bought.Price); mm.BodyEncoding = UTF8Encoding.UTF8; mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client.Send(mm); } catch (Exception gdgd) { } } return(message); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public RiskAvailabilityRepository(DatabaseEntities ctx) { _ctx = ctx; }
public LoadGeneratingUnitRefreshScheduledBackgroundJob(DatabaseEntities dbContext) : base(dbContext) { }
public LogRepository(DatabaseEntities context) { _database = context; }
public questStatus SaveTablesetConfiguration(TablesetConfiguration tablesetConfiguration, out TablesetId tablesetId) { // Initialize questStatus status = null; tablesetId = null; DbMgrTransaction trans = null; bool bFiltersRemoved = false; questStatus status2 = null; try { // BEGIN TRANSACTION status = BeginTransaction("SaveTablesetConfiguration" + Guid.NewGuid().ToString(), out trans); if (!questStatusDef.IsSuccess(status)) { return(status); } /* * Update tableset info. */ // Read the tableset TablesetsMgr tablesetsMgr = new TablesetsMgr(this.UserSession); TablesetId _tablesetId = new TablesetId(tablesetConfiguration.Tableset.Id); Tableset _tableset = null; status = tablesetsMgr.Read(trans, _tablesetId, out _tableset); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } /* * Remove all tableset entities. */ status = ClearTablesetEntities(trans, _tablesetId); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } // TESTING ONLY: COMMIT TRANSACTION bool bKlugie = false; if (bKlugie) { status = CommitTransaction(trans); if (!questStatusDef.IsSuccess(status)) { return(status); } } /* * Get database entites. */ DatabaseId databaseId = new DatabaseId(tablesetConfiguration.Database.Id); DatabaseMgr databaseMgr = new DatabaseMgr(this.UserSession); DatabaseEntities databaseEntities = null; status = databaseMgr.ReadDatabaseEntities(databaseId, out databaseEntities); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } #region Save tableset info. /* * Save tableset info. */ DbTablesetColumnsMgr dbTablesetColumnsMgr = new DbTablesetColumnsMgr(this.UserSession); // Save table info. DbTablesetTablesMgr dbTablesetTablesMgr = new DbTablesetTablesMgr(this.UserSession); List <TablesetTable> tablesetTableList = new List <TablesetTable>(); foreach (TablesetTable tablesetTable in tablesetConfiguration.TablesetTables) { Table _table = databaseEntities.TableList.Find(delegate(Table t) { return(t.Schema == tablesetTable.Schema && t.Name == tablesetTable.Name); }); if (_table == null) { RollbackTransaction(trans); return(new questStatus(Severity.Error, String.Format("ERROR: tableset table [{0}].[{1}] not found in database metainfo. Try refreshing database schema info", tablesetTable.Schema, tablesetTable.Name))); } tablesetTable.TablesetId = _tableset.Id; tablesetTable.Table = _table; tablesetTableList.Add(tablesetTable); // Create tableset table. TablesetTableId tablesetTableId = null; status = dbTablesetTablesMgr.Create(trans, tablesetTable, out tablesetTableId); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } foreach (Column column in _table.ColumnList) { Column _column = _table.ColumnList.Find(delegate(Column c) { return(c.Name == column.Name); }); if (_column == null) { RollbackTransaction(trans); return(new questStatus(Severity.Error, String.Format("ERROR: column [{0}] not found in table [{1}].[{2}] in database metainfo. Try refreshing database schema info", column.Name, _table.Schema, _table.Name))); } TablesetColumn tablesetColumn = new TablesetColumn(); tablesetColumn.EntityTypeId = EntityType.Table; tablesetColumn.TableSetEntityId = tablesetTableId.Id; tablesetColumn.Name = column.Name; TablesetColumnId tablesetColumnId = null; status = dbTablesetColumnsMgr.Create(trans, tablesetColumn, out tablesetColumnId); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } } } // Save view info. DbTablesetViewsMgr dbTablesetViewsMgr = new DbTablesetViewsMgr(this.UserSession); List <TablesetView> tablesetViewList = new List <TablesetView>(); foreach (TablesetView tablesetView in tablesetConfiguration.TablesetViews) { View _view = databaseEntities.ViewList.Find(delegate(View v) { return(v.Schema == tablesetView.Schema && v.Name == tablesetView.Name); }); if (_view == null) { RollbackTransaction(trans); return(new questStatus(Severity.Error, String.Format("ERROR: tableset view [{0}].[{1}] not found in database metainfo. Try refreshing database schema info", tablesetView.Schema, tablesetView.Name))); } tablesetView.TablesetId = _tableset.Id; tablesetView.View = _view; tablesetViewList.Add(tablesetView); // Create tableset view. TablesetViewId tablesetViewId = null; status = dbTablesetViewsMgr.Create(trans, tablesetView, out tablesetViewId); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } foreach (Column column in _view.ColumnList) { Column _column = _view.ColumnList.Find(delegate(Column c) { return(c.Name == column.Name); }); if (_column == null) { RollbackTransaction(trans); return(new questStatus(Severity.Error, String.Format("ERROR: column [{0}] not found in view [{1}].[{2}] in database metainfo. Try refreshing database schema info", column.Name, _view.Schema, _view.Name))); } TablesetColumn tablesetColumn = new TablesetColumn(); tablesetColumn.EntityTypeId = EntityType.View; tablesetColumn.TableSetEntityId = tablesetViewId.Id; tablesetColumn.Name = column.Name; TablesetColumnId tablesetColumnId = null; status = dbTablesetColumnsMgr.Create(trans, tablesetColumn, out tablesetColumnId); if (!questStatusDef.IsSuccess(status)) { RollbackTransaction(trans); return(status); } } } #endregion // Update tableset. bFiltersRemoved = false; _tableset.DatabaseId = tablesetConfiguration.Database.Id; status2 = tablesetsMgr.Update(trans, _tableset); if (!questStatusDef.IsSuccess(status2)) { if (questStatusDef.IsWarning(status2)) { bFiltersRemoved = true; } else { RollbackTransaction(trans); return(status); } } // COMMIT TRANSACTION status = CommitTransaction(trans); if (!questStatusDef.IsSuccess(status)) { return(status); } // Return the tableset id tablesetId = new TablesetId(tablesetConfiguration.Tableset.Id); } catch (System.Exception ex) { if (trans != null) { RollbackTransaction(trans); } return(new questStatus(Severity.Fatal, String.Format("EXCEPTION: {0}.{1}: {2}", this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.InnerException != null ? ex.InnerException.Message : ex.Message))); } if (bFiltersRemoved) { return(status2); } return(new questStatus(Severity.Success)); }
protected void carregarSelectProdutos() { try { using (DatabaseEntities context = new DatabaseEntities()) { List <Produto> produtos = context.Produto.Where(produto => produto.cnpjOficina.Equals(c.Funcionario.cnpjOficina)).ToList(); ListItem item; if (produtos.Count > 0) { if (txt_ProdutoSelecionado.Items.Count > 0) { txt_ProdutoSelecionado.Items.Clear(); } double precoVenda; DateTime validade; foreach (Produto p in produtos) { item = new ListItem(); if (p.precoVenda != null) { precoVenda = (Double)p.precoVenda; } else { precoVenda = 0; } if (p.validade == null) { item.Text = p.descricao + " " + p.marca + " - R$ " + precoVenda.ToString("0.00") + " - Estoque: " + p.quantidade; } else { validade = (DateTime)p.validade; item.Text = p.descricao + " " + p.marca + " - R$ " + precoVenda.ToString("0.00") + " - Estoque: " + p.quantidade + " (Vence em " + validade.ToString("dd/MM/yyyy") + ")"; } item.Value = p.idProduto.ToString(); txt_ProdutoSelecionado.Items.Add(item); txt_ProdutoSelecionado.Enabled = true; } foreach (Produto p in produtosSelecionados.Keys) { item = txt_ProdutoSelecionado.Items.FindByValue(p.idProduto.ToString()); if (item != null) { txt_ProdutoSelecionado.Items.Remove(item); } } if (txt_ProdutoSelecionado.Items.Count == 0) { item = new ListItem(); item.Text = "Todos os produtos cadastrados já foram adicionados"; item.Value = "-"; txt_ProdutoSelecionado.Items.Add(item); txt_ProdutoSelecionado.Enabled = false; } } else { item = new ListItem(); item.Text = "Nenhum produto encontrado"; item.Value = "-"; txt_ProdutoSelecionado.Items.Add(item); txt_ProdutoSelecionado.Enabled = false; } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } }
protected void btn_EnviarEmail_Click(object sender, EventArgs e) { Boolean erroEmailCPF = false; Cliente cliente = null; String email = ""; String CPF = ""; pnl_Alert.Visible = false; if (txt_CPF.Text != "") { CPF = txt_CPF.Text.Replace(".", "").Replace("-", ""); } if (txt_Email.Text != "") { email = txt_Email.Text; } if (CPF == "" && email == "") { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Forneça um e-mail ou CPF"; pnl_Alert.Visible = true; } else { using (var context = new DatabaseEntities()) { try { if (CPF != "" && email == "") { cliente = context.Cliente.Where(c => (c.cpf == CPF)).FirstOrDefault <Cliente>(); } else if (email != "" && CPF == "") { cliente = context.Cliente.Where(c => (c.email == email)).FirstOrDefault <Cliente>(); } else { if (context.Cliente.Where(c => (c.email == email)).FirstOrDefault <Cliente>() != context.Cliente.Where(c => (c.cpf == CPF)).FirstOrDefault <Cliente>()) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "O e-mail informado não corresponde ao CPF cadastrado. Forneça apenas um dos campos e tente novamente"; pnl_Alert.Visible = true; erroEmailCPF = true; } else { cliente = context.Cliente.Where(c => (c.cpf == CPF)).FirstOrDefault <Cliente>(); } } } catch (Exception ex) { Response.Write("<script>alert('" + ex.Message + "');</script>"); } } if (cliente != null) { Enviar_Email(cliente); pnl_Alert.CssClass = "alert alert-success"; lbl_Alert.Text = "E-mail enviado."; pnl_Alert.Visible = true; } else if (!erroEmailCPF) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "CPF/E-mail não cadastrado!"; pnl_Alert.Visible = true; } } }
public RiskAvailabilityRepository() { _ctx = new DatabaseEntities(); }
public EDMXComparison() { _context = new DatabaseEntities(); }
protected void btn_Cadastro_Click(object sender, EventArgs e) { if (servicosSelecionados.Count == 0) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Insira no mínimo 1 serviço"; pnl_Alert.Visible = true; } else { if (txt_Veiculo.Enabled == false) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Informe um cliente com no mínimo 1 veículo cadastrado"; pnl_Alert.Visible = true; } else { try { using (DatabaseEntities context = new DatabaseEntities()) { int id = int.Parse(txt_Veiculo.SelectedValue); Veiculo veiculo = context.Veiculo.Where(v => v.idVeiculo == id).FirstOrDefault(); Cliente cliente = veiculo.Cliente; Funcionario funcionario = context.Funcionario.Where(f => f.cpf.Equals(c.cpf)).FirstOrDefault(); Oficina oficina = funcionario.Oficina; DateTime data = DateTime.Now; Double total = atualizarTotal(); String status = "Aprovação da gerencia pendente"; Produto prod; if (total <= 0) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Orçamento com valor inválido"; pnl_Alert.Visible = true; } else { Orcamento orcamento = new Orcamento() { valor = total, data = data, status = status, cpfFuncionario = funcionario.cpf, cnpjOficina = oficina.cnpj, idVeiculo = veiculo.idVeiculo, cpfCliente = cliente.cpf, }; context.Orcamento.Add(orcamento); context.SaveChanges(); ServicosOrcamento so; foreach (Servico s in servicosSelecionados) { so = new ServicosOrcamento() { idOrcamento = orcamento.idOrcamento, idServico = s.idServico, status = "Pendente" }; context.ServicosOrcamento.Add(so); context.SaveChanges(); } if (produtosSelecionados.Count > 0) { ProdutosOrcamento po; foreach (Produto p in produtosSelecionados.Keys) { po = new ProdutosOrcamento() { idOrcamento = orcamento.idOrcamento, idProduto = p.idProduto, quantidade = produtosSelecionados[p] }; context.ProdutosOrcamento.Add(po); context.SaveChanges(); prod = context.Produto.Where(produto => produto.idProduto == p.idProduto).FirstOrDefault(); prod.quantidade -= po.quantidade; context.SaveChanges(); } } clearForm(); pnl_Alert.CssClass = "alert alert-success"; lbl_Alert.Text = "Orçamento criado com sucesso"; pnl_Alert.Visible = true; } } } catch (Exception ex) { pnl_Alert.CssClass = "alert alert-danger"; lbl_Alert.Text = "Erro: " + ex.Message + Environment.NewLine + "Por favor entre em contato com o suporte"; pnl_Alert.Visible = true; } } } }
public AddWorkerModel() { db = new DatabaseEntities(); }
public TransactionRepository(DatabaseEntities entities) { _entities = entities ?? throw new ArgumentNullException(); }