// PUT odata/Custodies(5) public IHttpActionResult Put([FromODataUri] long key, Custody custody) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (key != custody.Id) { return(BadRequest()); } db.Entry(custody).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CustodyExists(key)) { return(NotFound()); } else { throw; } } return(Updated(custody)); }
public IHttpActionResult Patch([FromODataUri] long key, Delta <Custody> patch) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Custody custody = db.Custodies.Find(key); if (custody == null) { return(NotFound()); } patch.Patch(custody); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CustodyExists(key)) { return(NotFound()); } else { throw; } } return(Updated(custody)); }
public IHttpActionResult PostCustody(CustodyEntry cust) { if (!ModelState.IsValid) { return(BadRequest()); } var student = (from s in db.Student where s.ticketNumber == cust.TicketNum select s) .SingleOrDefault(); if (student == null) { return(NotFound()); } //check for open custody if (db.Custody.Any(c => c.studentId == student.studentId && c.custodyEndTime == null)) { var vCustody = (from c in db.Custody where c.studentId == student.studentId && // Same thing here c.custodyEndTime == null select c) .Single(); //end cust via private method which performs sql statement SQLEndCust(vCustody); } var custody = new Custody { custodyStartTime = DateTime.Now, custodyType = cust.CustType, staffId = cust.StaffNum, studentId = student.studentId, }; var returnValue = new { student.studentId, student.studentFirstName, student.studentLastName, student.ticketNumber, student.studentDOB }; db.Custody.Add(custody); try { db.SaveChanges(); } catch (DbUpdateException e) { return(BadRequest(e.Message)); } return(Ok(returnValue)); }
public static Child Create(Name name, BirthDate birthDate, Custody currentCustody) { Child parent = new Child(); parent.name = name; parent.birthDate = birthDate; parent.currentCustody = currentCustody; return(parent); }
/// <summary> /// This method configures the database model with EF Core's fluent API /// </summary> protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); string tenantId = "TenantId"; // Measurement Units AddTenantId <MeasurementUnit>(builder); MeasurementUnit.OnModelCreating(builder); // Custodies AddTenantId <Custody>(builder); Custody.OnModelCreating(builder); // Agents : Custodies Agent.OnModelCreating_Agent(builder); // Roles AddTenantId <Role>(builder); Role.OnModelCreating(builder); // Views AddTenantId <View>(builder); View.OnModelCreating(builder); // Local Users AddTenantId <LocalUser>(builder); LocalUser.OnModelCreating(builder); // Role Memberships AddTenantId <RoleMembership>(builder); RoleMembership.OnModelCreating(builder); // Permissions AddTenantId <Permission>(builder); Permission.OnModelCreating(builder); // Settings AddTenantId <Settings>(builder, tenantId); Data.Model.Settings.OnModelCreating(builder); // Blobs AddTenantId <Blob>(builder, nameof(Blob.Id), tenantId); Blob.OnModelCreating(builder); // EF migratios was confused about these for some reason, had to set them manually builder.Entity <Dto.AgentForQuery>().HasOne(e => e.CreatedBy).WithMany().HasForeignKey(e => e.CreatedById); builder.Entity <Dto.AgentForQuery>().HasOne(e => e.ModifiedBy).WithMany().HasForeignKey(e => e.ModifiedById); builder.Entity <Dto.LocalUserForQuery>().HasOne(e => e.Agent).WithMany().HasForeignKey(e => e.AgentId); builder.Entity <Dto.RoleMembershipForQuery>().HasOne(e => e.User).WithMany(e => e.Roles).HasForeignKey(e => e.UserId); builder.Entity <Dto.RoleMembershipForQuery>().HasOne(e => e.CreatedBy).WithMany().HasForeignKey(e => e.CreatedById); builder.Entity <Dto.RoleMembershipForQuery>().HasOne(e => e.ModifiedBy).WithMany().HasForeignKey(e => e.ModifiedById); }
// POST odata/Custodies public IHttpActionResult Post(Custody custody) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.Custodies.Add(custody); db.SaveChanges(); return(Created(custody)); }
/// <summary> /// /// </summary> /// <param name="code"></param> /// <param name="idProduct"></param> /// <param name="idCustody"></param> /// <param name="alias"></param> /// <returns></returns> public ActionResponse GetCustodyInfoAction(string code, int idProduct, int restrictive, int?idCustody = null, string alias = null) { ActionResponse output = new ActionResponse(); try { // Check for product Product oProduct = productData.GetProductById(idProduct); if (oProduct == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "El producto no existe en el sistema", null)); } // Validate code exists Custody oCustody = this.FindCustodyByCode(idProduct, code, "long"); // will find custody by code (long version) if (oCustody == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "No hay ninguna custodia vinculada al código proporcionado", null)); } // If attr 'restrictive' is on, will check for custody integrity if (restrictive == 1) { ActionResponse isCustodyValid = IsCustodyValid(oCustody); if (isCustodyValid.code != (int)CodeStatusEnum.OK) { return(functions.Response(isCustodyValid.code, isCustodyValid.message, null)); } } // OK GetCustodyInfoResponse res = new GetCustodyInfoResponse(); res.idCustody = oCustody.idCustody.Value; res.idProduct = oCustody.idProduct.Value; res.idClient = (int)oCustody.id_cliente; res.value = oCustody.value; res.alias = oCustody.alias; res.code = oCustody.code; res.active = oCustody.active.Value; res.expirationDate = oCustody.expirationDate.Value; res.creationDate = oCustody.creationDate.Value; return(functions.Response((int)CodeStatusEnum.OK, "OK", res)); } catch (Exception e) { logger.Fatal(e.Message); return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, e.Message, null)); } }
// DELETE odata/Custodies(5) public IHttpActionResult Delete([FromODataUri] long key) { Custody custody = db.Custodies.Find(key); if (custody == null) { return(NotFound()); } db.Custodies.Remove(custody); db.SaveChanges(); return(StatusCode(HttpStatusCode.NoContent)); }
public Custody GetCustodyByCode(string code) { Custody o = new Custody(); string sql = String.Format("SELECT * FROM {0} WHERE code = '{1}'", "", code); List <Custody> res = Select <Custody>(sql); if (res.Count > 0) { o = res.First(); } return(o); }
public IHttpActionResult SQLEndCust(Custody pCustody) { if (!ModelState.IsValid) { return(BadRequest()); } var custody = db.Custody.SingleOrDefault(c => c.studentId == pCustody.studentId && c.custodyEndTime == null); if (custody == null) { return(NotFound()); } if (custody.TimeAlertRaised != null) { CancelAlert(custody.studentId, custody.staffId); } var currentTime = CurrentTime(DateTime.Now); string queryString = @"UPDATE dbo.Custody SET custodyEndTime = '" + currentTime + "' WHERE studentId = " + pCustody.studentId + " and custodyEndTime IS null;"; string connectionString = "Server=skiassistdb.database.windows.net;Database=SkiAssistDB;User Id=skiadmin;Password=Ski12345;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) { // Console.WriteLine(String.Format("{0}, {1}", // reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc } } finally { // Always call Close when done reading. reader.Close(); } } return(Ok()); }
public async Task <Child> Handle(AddChildCommand command) { School school = await schoolRepository.GetSchool(command.SchoolId); Parent parent = await schoolRepository.GetParent(command.SchoolId, command.ParentId); Child child = Child.Create( Name.Create(command.Name), BirthDate.Create(command.BirthDate), Custody.Create(CustodyEnum.ChildConfirmedWithFamily)); school.AddChild(parent, child); await bus.Publish(school.GetEvents(), command.Header); return(child); }
/// <summary> /// This method configures the database model with EF Core's fluent API /// </summary> protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); string tenantId = "TenantId"; // Measurement Units AddTenantId <MeasurementUnit>(builder); MeasurementUnit.OnModelCreating(builder); // Custodies AddTenantId <Custody>(builder); Custody.OnModelCreating(builder); // Agents : Custodies Agent.OnModelCreating_Agent(builder); // Roles AddTenantId <Role>(builder); Role.OnModelCreating(builder); // Views AddTenantId <View>(builder); View.OnModelCreating(builder); // Local Users AddTenantId <LocalUser>(builder); LocalUser.OnModelCreating(builder); // Role Memberships AddTenantId <RoleMembership>(builder); RoleMembership.OnModelCreating(builder); // Permissions AddTenantId <Permission>(builder); Permission.OnModelCreating(builder); // Settings AddTenantId <Settings>(builder, tenantId); Data.Model.Settings.OnModelCreating(builder); // Blobs AddTenantId <Blob>(builder, nameof(Blob.Id), tenantId); Blob.OnModelCreating(builder); }
public IHttpActionResult GetCustodyByCode([FromBody] RegisterRequest obj) { try { CustodyController oCustody = new CustodyController(); // Check for data if (obj == null) { throw new NotEnoughAttributesException("No se ha recibido ningún parámetro"); } // Find Custody object linked to code received Custody custody = oCustody.FindCustodyByCode(obj.idProduct.Value, obj.code, obj.codeType); if (custody == null) { throw new NotValidDataException("No hay ninguna custodia vinculada al código proporcionado"); } // OK /*output.code = 0; * output.message = "OK"; * output.result = custody.value;*/ ActionResponse output = new ActionResponse(); return(Ok(output)); } catch (NotValidDataException e) { logger.Error(e.Message); return(ResponseError((int)CodeStatusEnum.BAD_REQUEST, e.Message)); } catch (NotEnoughAttributesException e) { logger.Error(e.Message); return(ResponseError((int)CodeStatusEnum.BAD_REQUEST, e.Message)); } catch (Exception ex) { logger.Fatal(ex.Message); return(ResponseError((int)CodeStatusEnum.INTERNAL_ERROR, "Error desconocido en el sistema")); } }
private void When(ChildAddedDomainEvent domainEvent) { children = children ?? new List <Child>(); Child child = Child.Create( domainEvent.ChildId, domainEvent.Name, domainEvent.BirthDate, Custody.Create(CustodyEnum.ChildConfirmedWithFamily)); children.Add(child); foreach (Parent parent in parents) { if (parent.Id == domainEvent.ParentId) { parent.AddChild(child); } } }
/// <summary> /// Will close Custody object /// </summary> /// <param name="idCustody">ID Custody</param> /// <returns></returns> public ActionResponse CloseCustodyByIdAction(int idCustody) { ActionResponse output = new ActionResponse(); try { CustodyData custodyData = new CustodyData(); // Check if custody exists or not Custody oCustody = custodyData.GetCustodyById(idCustody); if (oCustody == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "No existe ninguna custodia asociada al identificador", null)); } // If custody exists, verify if custody is valid or not ActionResponse isCustodyValid = IsCustodyValid(oCustody); if (isCustodyValid.code != (int)CodeStatusEnum.OK) { return(functions.Response(isCustodyValid.code, isCustodyValid.message, null)); } // If everything is ok, try to close it int res = custodyData.CloseCustody(idCustody); if (res <= 0) { return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, "No se pudo actualizar el estado de la custodia", null)); } CloseCustodyResponse response = new CloseCustodyResponse(); response.updated = DateTime.Now; return(functions.Response((int)CodeStatusEnum.OK, "OK", response)); } catch (Exception e) { logger.Fatal(e.Message); return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, e.Message, null)); } }
/// <summary> /// Verify if Custody object is valid or not /// </summary> /// <param name="oCustody">Custody object</param> /// <returns></returns> public ActionResponse IsCustodyValid(Custody oCustody) { ActionResponse output = new ActionResponse(); try { CustodyData custodyData = new CustodyData(); // If custody exists, verify if custody is valid or not if (oCustody.expirationDate != null) { DateTime today = DateTime.Now; int compare = DateTime.Compare(today, oCustody.expirationDate.Value); if (compare > 0) { return(functions.Response((int)CodeStatusEnum.CONFLICT, "El código proporcionado corresponde a una custodia expirada", null)); } } if (!oCustody.active.Value) { return(functions.Response((int)CodeStatusEnum.CONFLICT, "La custodia ya fue utilizada o se encuentra inactiva", null)); } return(functions.Response((int)CodeStatusEnum.OK, "OK", true)); } catch (Exception e) { logger.Fatal(e.Message); return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, e.Message, null)); } }
public int NewCustody(Custody o) { return(1); }
public void CheckOut() { currentCustody = Custody.Create(CustodyEnum.TeacherCheckOutChildAtSchool); }
public void CheckIn() { currentCustody = Custody.Create(CustodyEnum.ChildConfirmedAtSchool); }
public void Pickup() { currentCustody = Custody.Create(CustodyEnum.FamilyPickeupChildAtSchool); }
public void Left() { currentCustody = Custody.Create(CustodyEnum.FamilyLeftChildAtSchool); }
/// <summary> /// Registration over any channel defined in module. Credential concept is implicated too. /// </summary> /// <param name="obj">Request object</param> /// <returns>ID user if it's ok or null when it's error</returns> public ActionResponse RegisterAction(RegisterRequest obj) { ActionResponse output = new ActionResponse(); try { // OPERATOR registration bool asOperatorRegistration = false; if (obj.code != null) { asOperatorRegistration = true; } // Code doesn't exist, will enter by normal registration flow int idProduct = obj.idProduct.Value; int idChannel = obj.idChannel.Value; string passReq = null; if (!String.IsNullOrEmpty(obj.password)) { passReq = obj.password.Trim(); } // STEP 0: Need to verify if product and channel exist or not ProductData prodData = new ProductData(); Product oProduct = prodData.GetProductById(idProduct); if (oProduct == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "El producto no existe en el sistema", null)); } ChannelData channelData = new ChannelData(); Channel oChannel = channelData.GetChannelById(idChannel); if (oChannel == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "El canal no existe en el sistema", null)); } // We need to check if code is setted // If code exists, will check for this first (custody) CustodyController custodyController = new CustodyController(); Custody oCustody = new Custody(); if (asOperatorRegistration) { // Find Custody object linked to code received oCustody = custodyController.FindCustodyByCode(idProduct, obj.code, obj.codeType.ToLower()); if (oCustody == null) { return(functions.Response((int)CodeStatusEnum.NO_CONTENT, "No hay ninguna custodia vinculada al código proporcionado", null)); } } // Normal flow for registration. Distinct to get code or not, it will do same actions // Firstly, will check consistency value in function of channel switch (obj.idChannel.Value) { case (int)ChannelEnum.EMAIL: try { MailAddress m = new MailAddress(obj.value); break; } catch (FormatException) { return(functions.Response((int)CodeStatusEnum.BAD_REQUEST, "El formato del email es incorrecto", null)); } case (int)ChannelEnum.ANI: int l = 11; string prefix = "569"; bool error = true; string val = obj.value; // Check for prefix (569) considerating solution for Chile (need to be dynamic as soon as possible) if (val.Contains(prefix)) { // Check for length (11) adding prefix if (val.Length == l) { error = false; } } if (error) { return(functions.Response((int)CodeStatusEnum.BAD_REQUEST, "El formato del ani es incorrecto", null)); } break; case (int)ChannelEnum.FACEBOOK: // Will check if ID is a numeric number break; } // STEP 1: Check if user identify already exists // If UserIdentify doesn't exist, it won't check credential because of it doesn't exist too obviously // If UserIdentify exists, we need to check for credentials vinculated. UserIdentifyData uiData = new UserIdentifyData(); UserIdentify ui = uiData.FindByIdChannelAndValue(idChannel, obj.value); string passMD5 = null; if (ui.id_cliente != null) { // STEP 2: Check if credential already exists CredentialData cdData = new CredentialData(); List <Credential> lstCredential = cdData.FindByProductAndUserIdentify(idProduct, ui.idUserIdentify.Value); if (lstCredential.Count > 0) { return(functions.Response((int)CodeStatusEnum.CONFLICT, "La credencial del usuario ya existe en el sistema", null)); } } // If entire data is ok, try to create user // Will return ID user or null (transaction) ClienteData u = new ClienteData(); // string ani, string email, string usuario, decimal id_operador int?res = 0; // Create a random value for ani, it must to be fixed to correct logic with registration operator (custody) int max = Int32.Parse(functions.ConfigItem("MAX_RANDOM_ANI_USER")); string rndString = "user_" + functions.GetUniqueKey(max); // If password is setted, it becomes as MD5 if (!String.IsNullOrEmpty(passReq)) { // Will check password integrity int minLengthPass = Int32.Parse(functions.ConfigItem("MIN_PASS_LENGTH")); if (passReq.Length < minLengthPass) { return(functions.Response((int)CodeStatusEnum.BAD_REQUEST, "La contraseña debe tener un mínimo de " + minLengthPass + " caracteres", null)); } using (MD5 md5Hash = MD5.Create()) { passMD5 = functions.GetMd5Hash(md5Hash, passReq); } } else { // Without password passMD5 = passReq; } // Will create user, receiving UserIdentify or making it within other actions if (ui.idUserIdentify == null) { // Operator registration always won´t have UserIdentify associated (will be created later) // UserIdentify unknown res = u.CreateUser(idChannel, idProduct, obj.value, passMD5, 0, rndString, "", "", 0, false, 0, obj.idGuide.Value); } else { // UserIdentify already known res = u.CreateUser(idChannel, idProduct, obj.value, passMD5, 0, rndString, "", "", 0, true, ui.idUserIdentify.Value, obj.idGuide.Value); } // Sp's response if (res == null) { return(functions.Response((int)CodeStatusEnum.CONFLICT, "No se pudo registrar al usuario en la plataforma", res)); } // OK (will return ID cliente generated -last insert-) RegisterResponse response = new RegisterResponse(); response.idClient = (decimal)res; // Normal or custody registration if (asOperatorRegistration) { // Reserved value into response response.reservedValue = oCustody.value; // Try to close custody int idCustody = oCustody.idCustody.Value; int idClient = (int)oCustody.id_cliente.Value; // Need to close Custody, it will be the end of this process // Will check custody is valid or not ActionResponse resX = custodyController.CloseCustodyByIdAction(idCustody); if (resX.code != (int)CodeStatusEnum.OK) { logger.Error(resX.message); } } return(functions.Response((int)CodeStatusEnum.OK, "OK", response)); } catch (Exception e) { logger.Fatal(e.Message); return(functions.Response((int)CodeStatusEnum.INTERNAL_ERROR, e.Message, null)); } }