public void ResetJobsForAgent(string agentId) { var allJobs = context.Jobs.OrderBy(j => (j.JobNumber)); var jobsForAgent = allJobs.Where(j => (j.AgentId.Equals(agentId))); int split = jobsForAgent.Count() / 2; int jobsIndex = 0; foreach (Job job in jobsForAgent) { if (jobsIndex < split) { job.Status = "Completed"; } if (jobsIndex == split) { job.Status = "On Site"; } if (jobsIndex > split) { job.Status = "Not Started"; } jobsIndex++; } context.SaveChanges(); }
public ActionResult Create([Bind(Include = "Id,UserName,Category,SubCategory,Amount,Comment,Receipt,Location,Status,PaymentMethod,Credit,Date,UploadedImage,Version,CreatedAt,UpdatedAt,Deleted")] Expense expense) { if (ModelState.IsValid) { db.Expenses.Add(expense); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(expense)); }
public ActionResult Create([Bind(Include = "Id,Name,Region,Country,URL,UpVote,DownVote,Version,CreatedAt,UpdatedAt,Deleted")] Project project) { if (ModelState.IsValid) { db.Projects.Add(project); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(project)); }
public async Task <IHttpActionResult> PostNotification(Notification notification) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (notification.NotificationType == NotificationType.Custom) { notification.Id = Guid.NewGuid().ToString(); db.Notifications.Add(notification); await db.SaveChangesAsync(); Notification.SendPushNotification(notification, Services); } else { var latestDolar = db.CurrencyRates.OrderByDescending(x => x.LastUpdated).First(x => x.CurrencyId == 1); var automaticNotification = Notification.SendPushNotification(latestDolar, notification.NotificationType, Services); if (automaticNotification != null) { db.AutomaticNotifications.Add(automaticNotification); db.SaveChanges(); } } return(Ok(notification)); }
private void SaveParameter(string name, int value) { using (var contextService = new MobileServiceContext()) { Parameters paramChange = contextService.Parameters.FirstOrDefault(p => p.Name == name); if (paramChange != null) { paramChange.Value = value; contextService.Entry(paramChange).State = EntityState.Modified; } else { contextService.Parameters.Add(new Parameters() { Name = name, Id = Guid.NewGuid().ToString(), Value = value }); } try { contextService.SaveChanges(); } catch (DbUpdateConcurrencyException e) { Debug.WriteLine(String.Format(e.Message + "\n" + e.Entries.Single().ToString())); } } }
async Task DeleteMembershipInternal(string id) { lock (_deleteSync) { var membership = _context.Memberships.SingleOrDefault(m => m.Id == id); //Need to remove all the ongoing challenges (not past challenges since those should be locked and sealed in time for eternity for all to see) var challenges = _context.Challenges.Where(c => c.LeagueId == membership.LeagueId && c.DateCompleted == null && (c.ChallengerAthleteId == membership.AthleteId || c.ChallengeeAthleteId == membership.AthleteId)).ToList(); foreach (var c in challenges) { try { var league = _context.Leagues.SingleOrDefault(l => l.Id == c.LeagueId); var payload = new NotificationPayload { Action = PushActions.ChallengeDeclined, Payload = { { "leagueId", c.LeagueId }, { "challengeId", c.Id } } }; var message = "You challenge with {0} has ben removed because they abandoned the {1} league".Fmt(membership.Athlete.Alias, league.Name); _notificationController.NotifyByTag(message, c.Opponent(membership.AthleteId).Id, payload); } catch (Exception e) { //TODO log to Insights Console.WriteLine(e); } } membership.AbandonDate = DateTime.UtcNow; challenges.ForEach(c => c.Deleted = true); _context.SaveChanges(); } }
private static string CheckAddEmailToDB(string email) { string retVal; var ctx = new MobileServiceContext(); var user = ctx.Users.Where(x => x.Email == email); if (user.Count() == 0) { var u = ctx.Users.Add(new Common.Models.User() { Id = Guid.NewGuid().ToString(), Email = email, IsEnabled = true }); try { ctx.SaveChanges(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); // } retVal = u.Id; } else { var u = user.First(); retVal = u.Id; } return retVal; }
public string MakeReservation(Reservation resItem) { ReservationType rtype = ReservationType.GetType(resItem.Type); if (rtype == ReservationType.LTWeekly || rtype == ReservationType.LTWeeklyWorkHrs) { resItem.EndDate = resItem.StartDate.AddDays(7); } else if (rtype == ReservationType.LTMonthly || rtype == ReservationType.LTMonthlyWorkHrs) { resItem.EndDate = resItem.StartDate.AddDays(30); } else { resItem.EndDate = resItem.StartDate.AddDays(1); } resItem.EndDate = resItem.EndDate.AddSeconds(-1); // 12.59.59 PM Local time on the last day of reservation using (var context = new MobileServiceContext()) { try { ParkingLot parkingLot = context.ParkingLots.Find(resItem.LotId); string sql = "SELECT COUNT(*) FROM Reservation rr WHERE rr.LotId = @lotid and @startDt <= rr.EndDate and @endDt >= rr.StartDate"; SqlParameter[] parms = new SqlParameter[] { new SqlParameter("@lotid", resItem.LotId), new SqlParameter("@startDt", resItem.StartDate), new SqlParameter("@endDt", resItem.EndDate), }; int reserved = context.Database.SqlQuery <int>(sql, parms).FirstOrDefault(); if (reserved >= parkingLot.Capacity) { return("Parking not available for the selected date(s)"); } PriceModel priceModel = context.PriceModels.Find(resItem.PriceModelId); resItem.AdvancePaid = priceModel.GetAdvanceCharge(resItem.Type); Utils.CreateStripeCharge(resItem.AdvancePaid.Value, parkingLot.Name, resItem.ConfNumAdvance); parkingLot.Reserved++; context.Reservations.Add(resItem); context.SaveChanges(); } catch (Exception ex) { throw ServerUtils.BuildException(ex); } } return(null); }
private static void AddUser(string identifier, MobileServiceContext ctx) { var u = ctx.Users.Add( new User { Id = identifier, }); ctx.SaveChanges(); }
public Event RegisterForEvent(int userID, string eventID) { RegisteredEvents re = new RegisteredEvents() { UserID = userID, EventID = eventID }; dbContext.RegisteredEvents.Add(re); dbContext.SaveChanges(); return((from e in dbContext.RegisteredEvents where e.EventID == eventID select e.Event).FirstOrDefault()); }
//This method will change the confirmation status of the E-mail in DB private bool ConfirmEmail(User user) { bool success = false; var toUpdate = db.Users.Find(user.Id); db.Users.Attach(toUpdate); toUpdate.EmailConfirmed = true; db.SaveChanges(); success = true; return(success); }
public async Task <IHttpActionResult> Get() { var creds = await User.GetAppServiceIdentityAsync <AzureActiveDirectoryCredentials>(Request); var sid = ((ClaimsPrincipal)User).FindFirst(ClaimTypes.NameIdentifier).Value; string name, email; try { email = creds.UserId; name = creds.UserClaims.FirstOrDefault(claim => claim.Type.Equals("name")).Value; } catch (Exception) { return(BadRequest("Email or Name is not present")); } try { // Insert the record information into the database User user = new User() { Id = sid, Name = name, EmailAddress = email }; dbContext.Users.AddOrUpdate(user); dbContext.SaveChanges(); } catch (DbUpdateException ex) { return(InternalServerError(ex)); } // Mind a new token based on the old one plus the new information var newClaims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, sid), new Claim(JwtRegisteredClaimNames.Email, email), new Claim("name", name) }; JwtSecurityToken token = AppServiceLoginHandler.CreateToken( newClaims, SigningKey, Audience, Issuer, TimeSpan.FromDays(30)); // Return the token and user ID to the client return(Ok(new LoginResult() { AuthenticationToken = token.RawData, UserId = sid })); }
public MobileServiceContext ctx = new MobileServiceContext(); /*Veritanabı modellenmiş hali*/ // GET api/User //public string Get() //{ // //Services.Log.Info("Hello from custom controller!"); // //return "Hello"; //} public string PostUser(User EklenecekUser) { EklenecekUser.Id = Guid.NewGuid().ToString(); /*Hata aldığında gelen kullanıcın id'sini değiştirmek için'*/ string nRet = string.Empty; //ctx.Users.Contains if (ctx.Users.Where(x => x.Username == EklenecekUser.Username).Count() > 0) { //Kullanıcı eklenmisse. nRet = EklenecekUser.Username + "Veritabanında zaten kayıtlı!"; } else { //Kullanıcı Yoksa ctx.Users.Add(EklenecekUser); /*ctx = Context*/ ctx.SaveChanges(); //ctx.SaveChangesAsync; nRet = EklenecekUser.Username + "Veritabanına Kayıt Edildi!"; } return(nRet); }
public ItermediateObjects.Debt Post(ItermediateObjects.Debt newDebt) { var userId = User.Identity.GetUserId(); var debt = Context.Debts.Create(); debt.Id = Guid.NewGuid().ToString(); debt.Name = newDebt.Name; debt.Balance = newDebt.Balance; debt.UserId = userId; var newMovement = Context.Movements.Create(); newMovement.Id = Guid.NewGuid().ToString(); newMovement.Amount = newDebt.Balance; newMovement.Date = DateTimeOffset.UtcNow; newMovement.Reason = newDebt.Reason; debt.Movements.Add(newMovement); Context.Debts.Add(debt); Context.SaveChanges(); return(AutoMapper.Mapper.Map <ItermediateObjects.Debt>(debt)); }
public override Task ExecuteAsync() { string FieldAgentGroupId = this.Services.Settings["FieldAgentGroupId"].ToString(); string tenant = this.Services.Settings["AadTenantDomain"].ToString(); string clientId = this.Services.Settings["MS_AadClientID"].ToString(); string appKey = this.Services.Settings["AadServiceAppKey"].ToString(); string accessToken = this.aadHelperProvider.GetAccessToken(); List <string> agentIds = this.aadHelperProvider.GetUserIdsInGroup(accessToken, FieldAgentGroupId); try { this.Services.Log.Info("Deleting JobHistories"); var jobHistoriesToDelete = context.JobHistories.Where(jh => jh.ActionBy.ToLower().Contains("field")); if (jobHistoriesToDelete != null && jobHistoriesToDelete.Count() > 0) { this.Services.Log.Info("JobHistories to Delete:" + jobHistoriesToDelete.Count()); foreach (JobHistory jobHistory in jobHistoriesToDelete) { context.JobHistories.Remove(jobHistory); } context.SaveChanges(); this.Services.Log.Info("Done Deleting JobHistories"); } else { this.Services.Log.Info("No JobHistories to delete"); return(Task.FromResult(true)); } } catch (Exception e) { this.Services.Log.Error("Deleting JobHistories" + e.Message); } try { ResetJobsHelper resetJobsHelper = new ResetJobsHelper(); foreach (string agentId in agentIds) { this.Services.Log.Info("Cleaning JobStatus for FieldAgent: " + agentId); resetJobsHelper.ResetJobsForAgent(agentId); } this.Services.Log.Info("Done Updating JobStatus"); } catch (Exception e) { this.Services.Log.Error("Error Updating JobStatus" + e.Message); } return(Task.FromResult(true)); }
internal void AddUpdateAgent(string loginId) { var user = db.Agents.FirstOrDefault(a => a.LoginID == loginId); if (user != null) { user.PNSID = loginId; db.SaveChanges(); } //else //{ // var agent = new Agent // { // Id = Guid.NewGuid().ToString(), // LoginID = loginId, // PNSID = loginId, // isEnabled = false, // }; // db.Agents.Add(agent); // db.SaveChanges(); //} }
private void FinalizeCheckout(MobileServiceContext context, Reservation rItem, DateTimeOffset checkoutTime) { ReservationType rtype = ReservationType.GetType(rItem.Type); if (rtype == ReservationType.ST) { rItem.ActualCheckout = checkoutTime; } else { rItem.ActualCheckin = rItem.ActualCheckout = null; } context.SaveChanges(); }
public ItermediateObjects.Movement Put(ItermediateObjects.Movement modifiedMovement) { var userId = User.Identity.GetUserId(); var debt = Context.Debts.FirstOrDefault(m => m.Id == modifiedMovement.DebtId && m.UserId == userId); if (debt == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var movement = Context.Movements.FirstOrDefault(m => m.DebtId == modifiedMovement.DebtId && m.Id == modifiedMovement.Id); movement.Reason = modifiedMovement.Reason; movement.UpdatedAt = DateTimeOffset.UtcNow; Context.SaveChanges(); return(AutoMapper.Mapper.Map <ItermediateObjects.Movement>(movement)); }
protected void Seed(Athlete athlete) { var leagues = new List <League> { new League { Id = Guid.NewGuid().ToString(), Name = "Table Tennis", Description = "It's like tennis for giants", ImageUrl = "https://c5.staticflickr.com/6/5151/14307225316_24c814660a_k.jpg", MatchGameCount = 3, MaxChallengeRange = 2, IsEnabled = true, HasStarted = true, MinHoursBetweenChallenge = 24, StartDate = DateTime.Now, EndDate = DateTime.Now.AddMonths(3), IsAcceptingMembers = true, Season = 1, RulesUrl = "http://www.ittf.com/ittf_handbook/2014/2014_EN_HBK_CHPT_2.pdf", CreatedByAthlete = athlete, Memberships = new List <Membership>(), Challenges = new List <Challenge>() }, new League { Id = Guid.NewGuid().ToString(), Name = "Billiards", Description = "Otherwise known as Pocketball and Stick", ImageUrl = "https://c8.staticflickr.com/2/1690/24814543375_58e16dbfa3_b.jpg", MatchGameCount = 1, MaxChallengeRange = 2, IsEnabled = true, HasStarted = true, MinHoursBetweenChallenge = 24, StartDate = DateTime.Now, EndDate = DateTime.Now.AddMonths(3), IsAcceptingMembers = true, Season = 1, CreatedByAthlete = athlete, } }; leagues.ForEach(l => _context.Leagues.Add(l)); _context.SaveChanges(); }
// GET api/PushRegistration public async Task Post([FromBody] DeviceInstallationInfo deviceInstallInfo) { bool isChanged = false; var ctx = new MobileServiceContext(); var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId); if (registration.Count() == 0) { NotificationPlatform?plat = await GetNotificationPlatform(deviceInstallInfo.InstallationId); if (null != plat) { ctx.DeviceRegistrations.Add(new Common.Models.DeviceRegistration() { Id = Guid.NewGuid().ToString(), InstallationId = deviceInstallInfo.InstallationId, UserId = deviceInstallInfo.UserId, Platform = plat.Value }); isChanged = true; } } else { var reg = registration.First(); if (reg.UserId != deviceInstallInfo.UserId) { reg.UserId = deviceInstallInfo.UserId; isChanged = true; } } try { if (isChanged) { ctx.SaveChanges(); } } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
// GET api/PushRegistration public async Task Post([FromBody] DeviceInstallationInfo deviceInstallInfo) { bool isChanged = false; var ctx = new MobileServiceContext(); var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId); if (registration.Count() == 0) { NotificationPlatform? plat = await GetNotificationPlatform(deviceInstallInfo.InstallationId); if (null != plat) { var newRegistration = new Common.Models.DeviceRegistration() { Id = Guid.NewGuid().ToString(), InstallationId = deviceInstallInfo.InstallationId, UserId = deviceInstallInfo.UserId, Platform = plat.Value }; ctx.DeviceRegistrations.Add(newRegistration); isChanged = true; } } else { var reg = registration.First(); if (reg.UserId != deviceInstallInfo.UserId) { reg.UserId = deviceInstallInfo.UserId; isChanged = true; } } try { if (isChanged) ctx.SaveChanges(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
// DELETE: api/Contact/5 /// <summary> /// Delete user row from Contact, ContactInfo, and Address Tables /// </summary> /// <param name="id"></param> public Object DeleteContact(string id) { Contact currentCandidate = context.Contacts.Include("Address").FirstOrDefault(c => c.Id == id); try { var info = context.ContactInfo.Where(u => u.ContactId == currentCandidate.Id).FirstOrDefault(); context.Addresses.Remove(currentCandidate.Address); context.Contacts.Remove(currentCandidate); context.ContactInfo.Remove(info); context.SaveChanges(); } catch (Exception e) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.InnerException)); } return(Ok()); }
public DateTime StartLeague(string id) { _authController.EnsureAdmin(Request); var league = _context.Leagues.SingleOrDefault(l => l.Id == id); league.HasStarted = true; league.StartDate = DateTime.Now.ToUniversalTime(); _context.SaveChanges(); var message = "The {0} league has officially started!".Fmt(league.Name); var payload = new NotificationPayload { Action = PushActions.LeagueStarted, Payload = { { "leagueId", id } } }; _notificationController.NotifyByTag(message, league.Id, payload); return(league.StartDate.Value.UtcDateTime); }
private static string AddUser(string email, MobileServiceContext ctx) { var u = ctx.Users.Add( new Common.Models.User { Id = Guid.NewGuid().ToString(), Email = email, IsEnabled = true }); try { ctx.SaveChanges(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } return(u.Id); }
public Image AddImageToDB(string AlbumId, string UserId, string containerName, string fileName, string UploadFormat) { ContosoStorage cs = new ContosoStorage(); var ctx = new MobileServiceContext(); var img = new Image { Album = ctx.Albums.Where(x => x.Id == AlbumId).FirstOrDefault(), User = ctx.Users.Where(x => x.Id == UserId).FirstOrDefault(), Id = Guid.NewGuid().ToString(), UploadFormat = UploadFormat, ContainerName = AppSettings.StorageWebUri + containerName, FileName = fileName, }; ctx.Images.Add(img); try { ctx.SaveChanges(); return(img); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } }
public Image AddImageToDB(string AlbumId, string UserId, string containerName, string fileName, string UploadFormat) { ContosoStorage cs = new ContosoStorage(); var ctx = new MobileServiceContext(); var img = new Image { Album = ctx.Albums.Where(x => x.Id == AlbumId).FirstOrDefault(), User = ctx.Users.Where(x => x.Id == UserId).FirstOrDefault(), Id = Guid.NewGuid().ToString(), UploadFormat = UploadFormat, ContainerName = AppSettings.StorageWebUri + containerName, FileName = fileName, }; ctx.Images.Add(img); try { ctx.SaveChanges(); return img; } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } }
public async Task Delete([FromBody] DeviceInstallationInfo deviceInstallInfo) { var ctx = new MobileServiceContext(); var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId); if (registration.Count() > 0) { var reg = registration.First(); await Notifier.Instance.RemoveRegistration(deviceInstallInfo.InstallationId); ctx.DeviceRegistrations.Remove(reg); try { ctx.SaveChanges(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
public async Task Delete([FromBody] DeviceInstallationInfo deviceInstallInfo) { var ctx = new MobileServiceContext(); var registration = ctx.DeviceRegistrations.Where(x => x.InstallationId == deviceInstallInfo.InstallationId); if (registration.Count() > 0) { var reg = registration.First(); await Notifier.Instance.RemoveRegistration(deviceInstallInfo.InstallationId); ctx.DeviceRegistrations.Remove(reg); try { ctx.SaveChanges(); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
// POST tables/Order public async Task <IHttpActionResult> PostOrder(OrderDTO item) { try { MobileServiceContext context = new MobileServiceContext(); List <OrderItems> OI = new List <OrderItems>(); //User InsertedUser = await InsertAsync<User>() for (int i = 0; i < item.OrderItems.Count; i++) { OI.Add(new OrderItems()); OI[i].ItemID = item.OrderItems[i].ItemID; OI[i].ItemCount = (int)item.OrderItems[i].ItemCount; OI[i].Id = Guid.NewGuid().ToString(); } Order order = new Order() { User = context.Users.FirstOrDefault(u => u.Name == item.User.Name), OrderItems = OI, Id = Guid.NewGuid().ToString(), SubmittedOnline = true }; context.Orders.Add(order); context.SaveChanges(); return(Ok()); //Order current = await InsertAsync(order); //return CreatedAtRoute("Tables", new { id = current.Id }, current); } catch (System.Exception ex) { return(BadRequest(ex.Message)); } }
public static void PopulateForLocalUser(MobileServiceContext context) { PopulateCustomerTable(context); context.SaveChanges(); PopulateEquipmentTable(context); context.SaveChanges(); PopulateEquipmentSpecificationTable(context); context.SaveChanges(); PopulateJobTable(context); context.SaveChanges(); PopulateJobHistoryTable(context); context.SaveChanges(); PopulateJobEquipmentMergeTable(context); context.SaveChanges(); }
public ChallengeDto PostMatchResults(List <GameResultDto> results) { if (results.Count < 1) { throw "No game scores were submitted.".ToException(Request); } var challengeId = results.First().ChallengeId; var challenge = _context.Challenges.SingleOrDefault(c => c.Id == challengeId); if (challenge == null) { throw "This challenge no longer exists".ToException(Request); } if (challenge.DateCompleted != null) { throw "Scores for this challenge have already been submitted.".ToException(Request); } var league = _context.Leagues.SingleOrDefault(l => l.Id == challenge.LeagueId); if (league == null) { throw "This league no longer exists".ToException(Request); } if (challenge.ChallengerAthlete == null || challenge.ChallengeeAthlete == null) { throw "The opponent in this challenge no longer belongs to this league".ToException(Request); } var challengerMembership = _context.Memberships.SingleOrDefault(m => m.AthleteId == challenge.ChallengerAthlete.Id && m.AbandonDate == null && m.LeagueId == challenge.LeagueId); var challengeeMembership = _context.Memberships.SingleOrDefault(m => m.AthleteId == challenge.ChallengeeAthlete.Id && m.AbandonDate == null && m.LeagueId == challenge.LeagueId); if (challengerMembership == null || challengeeMembership == null) { throw "The opponent in this challenge no longer belongs to this league".ToException(Request); } _authController.EnsureHasPermission(new[] { challenge.ChallengerAthlete, challenge.ChallengeeAthlete }, Request); var tempChallenge = new Challenge(); tempChallenge.League = league; tempChallenge.MatchResult = results.Select(g => g.ToGameResult()).ToList(); var errorMessage = tempChallenge.ValidateMatchResults(); if (errorMessage != null) { throw errorMessage.ToException(Request); } tempChallenge = null; challenge.DateCompleted = DateTime.UtcNow; var dto = challenge.ToChallengeDto(); foreach (var result in results) { result.Id = Guid.NewGuid().ToString(); _context.GameResults.Add(result.ToGameResult()); } try { var prevChallengeeRating = challengeeMembership.CurrentRating; var prevChallengerRating = challengerMembership.CurrentRating; var wasChallengeeRatedHigher = prevChallengeeRating > prevChallengerRating; var challengeeIsWinner = DetermineWinnerAndUpdateRating(challenge); _context.SaveChanges(); var winner = challengeeIsWinner ? challenge.ChallengeeAthlete : challenge.ChallengerAthlete; var loser = challengeeIsWinner ? challenge.ChallengerAthlete : challenge.ChallengeeAthlete; var mems = challenge.League.Memberships.OrderByDescending(m => m.CurrentRating).ToList(); var newRank = mems.IndexOf(mems.Single(m => m.AthleteId == winner.Id)) + 1; var message = $"{winner.Alias} victors over {loser.Alias} and is now in {newRank.ToOrdinal()} place in {league.Name}."; var payload = new NotificationPayload { Action = PushActions.ChallengeCompleted, Payload = { { "challengeId", challengeId }, { "leagueId", league.Id }, { "winningAthleteId", winner.Id }, { "losingAthleteId", loser.Id } } }; if (!Startup.IsDemoMode) { _notificationController.NotifyByTag(message, challenge.LeagueId, payload); } } catch (DbEntityValidationException e) { #region Error Print foreach (var eve in e.EntityValidationErrors) { Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; #endregion } catch (Exception e) { Console.WriteLine(e); } return(dto); }
// POST api/CustomRegistration public HttpResponseMessage Post(RegistrationRequest registrationRequest) { if (!Regex.IsMatch(registrationRequest.username, "^[a-zA-Z0-9]{4,}$")) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid username (at least 4 chars, alphanumeric only)")); } else if (registrationRequest.password.Length < 8) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password (at least 8 chars required)")); } else if (!registrationRequest.email.Contains("@")) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Please supply a valid email address")); } // TODO: Comment out for Azure Table storage. // SQL Database version using Entity Framework for data access. MobileServiceContext context = new MobileServiceContext(); Account account = context.Accounts.Where(a => a.Username == registrationRequest.username).SingleOrDefault(); //// TODO: Azure Table storage version. //// Create a query for a specific username. //TableQuery<Account> query = new TableQuery<Account>().Where( // TableQuery.GenerateFilterCondition("Username", QueryComparisons.Equal, // registrationRequest.username)); //// Execute the query to retrieve the account. //Account account = accountTable.ExecuteQuery(query).FirstOrDefault(); // If there's already a confirmed account, return an error response. if (account != null) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "That username already exists.")); } else { byte[] salt = CustomLoginProviderUtils.generateSalt(); Account newAccount = new Account { //// TODO: Uncomment the below for Azure Table storage. //PartitionKey = "partition", //RowKey = Guid.NewGuid().ToString(), //// TODO: Comment-out for Azure Table storage. Id = Guid.NewGuid().ToString(), Username = registrationRequest.username, Salt = salt, SaltedAndHashedPassword = CustomLoginProviderUtils.hash(registrationRequest.password, salt), IsConfirmed = true, // this should be false until confirmed. Email = registrationRequest.email, FriendlyName = registrationRequest.friendlyName }; // TODO: Comment out for Azure Table storage. context.Accounts.Add(newAccount); context.SaveChanges(); //// TODO: Azure Table storage version. //// Insert the new account into the table. //accountTable.Execute(TableOperation.Insert(newAccount)); // This is where you would kick-off the independent verification process, // such as sending an email using SendGrid integration (http://aka.ms/busjrt). // https://github.com/sendgrid/sendgrid-csharp // Return the success response. return(this.Request.CreateResponse(HttpStatusCode.Created)); } }
public override async Task ExecuteAsync() { try { var now = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Argentina Standard Time")); var isWeekDay = now.DayOfWeek != DayOfWeek.Saturday && now.DayOfWeek != DayOfWeek.Sunday; var todayAutomaticNotifications = db.AutomaticNotifications.Where(x => x.DateSent >= now.Date).ToList(); AutomaticNotification automaticNotification = null; //Verifica que solo busque actualizaciones de Lunes a Viernes de 10hs a 17hs if (isWeekDay && now.Hour >= 10 && now.Hour <= 17) { var addedList = new List <CurrencyRate>(); var latestUpdatedList = await CurrencyRate.GetLatestRatesAsync(); var latestUpdate = latestUpdatedList.OrderByDescending(x => x.UltimaActualizacion).FirstOrDefault(); //Si la ultima fecha de actualizacion devuelta es anterior a la fecha actual, se interrumpe el proceso if (latestUpdate == null || latestUpdate.UltimaActualizacion.Date < now.Date) { return; } var todayList = db.CurrencyRates.Where(x => x.LastUpdated >= now.Date); foreach (var item in latestUpdatedList) { var newRate = new CurrencyRate(item); var existingRate = todayList.FirstOrDefault(x => x.CurrencyId == newRate.CurrencyId); //Si en la fecha actual ya hay una cotización, la actualiza. Si no la hay, la agrega como nueva if (existingRate != null && existingRate.LastUpdated.Date == now.Date) { existingRate.UpdateRate(newRate); } else { addedList.Add(newRate); } } db.CurrencyRates.AddRange(addedList); db.SaveChanges(); //Verifica que hayan cotizaciones para el ultimo mes en todas las monedas, en caso negativo busca el historial y lo guarda en la DB para mayor respuesta cuando los usuarios lo pidan foreach (var addedRate in addedList) { var rate = addedRate; var lastMonth = now.AddMonths(-1).Date; if (!db.CurrencyRates.Any(x => x.CurrencyId == rate.CurrencyId && x.LastUpdated >= lastMonth)) { continue; } var historyList = await CurrencyRate.GetHistoryRatesAsync(rate.CurrencyId, lastMonth); var lastMonthList = db.CurrencyRates.Where( x => x.CurrencyId == rate.CurrencyId && x.LastUpdated >= lastMonth).ToList(); var historyRatesToAdd = historyList.Where( history => lastMonthList.All(x => x.LastUpdated.Date != history.Fecha.Date)).ToList(); foreach (var history in historyRatesToAdd) { var newRate = new CurrencyRate { Id = Guid.NewGuid().ToString(), CurrencyId = rate.CurrencyId, Name = rate.Name, Buy = history.Compra, Sell = history.Venta, LastUpdated = history.Fecha, Sort = rate.Sort }; db.CurrencyRates.Add(newRate); } } db.SaveChanges(); var latestDolar = db.CurrencyRates.OrderByDescending(x => x.LastUpdated).First(x => x.CurrencyId == 1); //Se envia notificacion de apertura si no hay nunguna notificacion de apertura enviada en el dia if (todayAutomaticNotifications.All(x => x.NotificationType != NotificationType.OpenMarket)) { automaticNotification = Notification.SendPushNotification(latestDolar, NotificationType.OpenMarket, Services); } //Si ya se envio la notificacion de apertura, verifica que para enviar una nueva notificacion, haya pasado 1hs else if (todayAutomaticNotifications.All(x => x.DateSent <= now.AddHours(-1))) { automaticNotification = Notification.SendPushNotification(latestDolar, NotificationType.Hourly, Services); } } else if (isWeekDay && now.Hour >= 18 && todayAutomaticNotifications.Any() && todayAutomaticNotifications.All(x => x.NotificationType != NotificationType.CloseMarket)) { var latestDolar = db.CurrencyRates.OrderByDescending(x => x.LastUpdated).First(x => x.CurrencyId == 1); automaticNotification = Notification.SendPushNotification(latestDolar, NotificationType.CloseMarket, Services); } if (automaticNotification != null) { db.AutomaticNotifications.Add(automaticNotification); db.SaveChanges(); } } catch (Exception ex) { throw ex; } }
public string Checkin(string resCode) { using (var context = new MobileServiceContext()) { Reservation rItem = context.Reservations .Include(rr => rr.ParkingLot) .Where(rr => rr.Id == resCode) .FirstOrDefault(); if (rItem == null) { return($"Invalid Reservation code"); } ParkingLot lot = rItem.ParkingLot; if (rItem.ActualCheckin != null) { return(String.Format("This code was already used to check in at {0:t} on {0:d}", lot.ConvertToLocalTime(rItem.ActualCheckin.Value))); } ReservationType rtype = ReservationType.GetType(rItem.Type); DateTime timeNow = DateTime.UtcNow; if (rtype == ReservationType.ST && timeNow > rItem.ExpectedCheckin.Value.AddMinutes(15)) { return(String.Format("This code is only valid until {0:t} on {0:d}", lot.ConvertToLocalTime(rItem.ExpectedCheckin.Value))); } if (rtype != ReservationType.ST && (timeNow < rItem.StartDate || timeNow > rItem.EndDate)) { if (rtype == ReservationType.LTDaily || rtype == ReservationType.LTDailyWorkHrs) { return($"This code is only valid on {lot.ConvertToLocalTime(rItem.StartDate):d}"); } else { return($"This code is only valid from {lot.ConvertToLocalTime(rItem.StartDate):d} to {lot.ConvertToLocalTime(rItem.EndDate):d}"); } } if (rtype == ReservationType.LTDailyWorkHrs || rtype == ReservationType.LTWeeklyWorkHrs || rtype == ReservationType.LTMonthlyWorkHrs) { DateTime timeNowLocal = lot.ConvertToLocalTime(timeNow, TimeZoneInfo.Utc); if (timeNowLocal.Hour >= rItem.ParkingLot.WorkHrsEnd) { return($"This code is not valid after {lot.WorkHrsEndText}"); } if (timeNowLocal.DayOfWeek == DayOfWeek.Saturday || timeNowLocal.DayOfWeek == DayOfWeek.Sunday) { return($"This code is not valid on Weekends"); } } rItem.ActualCheckin = timeNow; context.SaveChanges(); } return(null); }