public async Task CheckpointAsync(Lease lease, string offset, long sequenceNumber) { StateManagerLease stateManagerLease = lease as StateManagerLease; stateManagerLease.Offset = offset; stateManagerLease.SequenceNumber = sequenceNumber; await stateManagerLease.SaveAsync(); }
public async Task CheckpointAsync(Lease lease, string offset, long sequenceNumber) { var reliableStateLease = lease as ReliableStateLease; if (reliableStateLease == null) return; reliableStateLease.Offset = offset; reliableStateLease.SequenceNumber = sequenceNumber; await _leaseRepository.SaveAsync(reliableStateLease); }
private async Task ExtendLease(Lease lease, TimeSpan by) { using (var connection = new SqlConnection(settings.ConnectionString)) { await connection.OpenAsync(); var cmd = connection.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = @"Alluvial.ExtendLease"; cmd.Parameters.AddWithValue(@"@resourceName", lease.LeasableResource.Name); cmd.Parameters.AddWithValue(@"@byMilliseconds", by.TotalMilliseconds); cmd.Parameters.AddWithValue(@"@token", (int) lease.OwnerToken); await cmd.ExecuteNonQueryAsync(); } }
protected override async Task<Lease> AcquireLease() { using (var connection = new SqlConnection(settings.ConnectionString)) { await connection.OpenAsync(); var cmd = connection.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = @"Alluvial.AcquireLease"; cmd.Parameters.AddWithValue(@"@waitIntervalMilliseconds", waitInterval.TotalMilliseconds); cmd.Parameters.AddWithValue(@"@leaseDurationMilliseconds", defaultLeaseDuration.TotalMilliseconds); cmd.Parameters.AddWithValue(@"@scope", scope); using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var resourceName = await reader.GetFieldValueAsync<string>(0); var leaseLastGranted = await reader.GetFieldValueAsync<dynamic>(2); var leaseLastReleased = await reader.GetFieldValueAsync<dynamic>(3); var token = await reader.GetFieldValueAsync<dynamic>(5); var resource = new LeasableResource( resourceName, defaultLeaseDuration) { LeaseLastGranted = leaseLastGranted is DBNull ? DateTimeOffset.MinValue : (DateTimeOffset) leaseLastGranted, LeaseLastReleased = leaseLastReleased is DBNull ? DateTimeOffset.MinValue : (DateTimeOffset) leaseLastReleased }; Lease lease = null; lease = new Lease(resource, resource.DefaultLeaseDuration, (int) token, extend: by => ExtendLease(lease, @by)); return lease; } } return null; } }
public async Task <RentleResponse> Delete(IEnumerable <string> ids) { foreach (string id in ids) { Property property = await _property.FindOneAndDeleteAsync(p => p.ID == id); Lease leaseDeleted = await _lease.FindOneAndDeleteAsync(l => l.PropertyID == property.ID); await _occupant.DeleteOneAsync(o => o.ID == leaseDeleted.OccupantID); } if (ids.Count() == 1) { return(new RentleResponse("le bien a été supprimer avec succés", true)); } return(new RentleResponse("les biens ont été supprimer avec succés", true)); }
protected override async Task ReleaseLease(Lease <T> lease) { if (!workInProgress.Values.Any(l => l.GetHashCode().Equals(lease.GetHashCode()))) { Debug.WriteLine("[Distribute] ReleaseLease (failed): " + lease); return; } Lease <T> _; if (workInProgress.TryRemove(lease.Leasable, out _)) { lease.NotifyReleased(); Debug.WriteLine("[Distribute] ReleaseLease: " + lease); } lease.NotifyCompleted(); }
public IHttpActionResult PostLease(LeaseModel lease) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var dbLease = new Lease(lease); dbLease.Property.User = db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name); db.Leases.Add(dbLease); db.SaveChanges(); lease.LeaseId = dbLease.LeaseId; return(CreatedAtRoute("DefaultApi", new { id = dbLease.LeaseId }, lease)); }
//update lease public Lease UpdateLease(Lease lease) { //check for overlaps var overlapPropertyExists = _db.Lease.Any(l => l.PropertyId == lease.PropertyId && l.Overlaps(lease) && l.Id != lease.Id); // if no overlap exists then if (!overlapPropertyExists) { _db.Entry(lease).State = EntityState.Modified; _db.SaveChanges(); return(lease); } else { throw new HttpRequestException("New Lease Overlaps With Another for this Property, Please Amend Dates"); } }
//Add Lease public Lease AddLease(Lease lease) { //check for overlaps var overlapPropertyExists = _db.Lease.Any(l => l.PropertyId == lease.PropertyId && l.Overlaps(lease) && l.Id != lease.Id); if (!overlapPropertyExists) { //if no overlap add lease _db.Leases.Add(lease); _db.SaveChanges(); return(lease); } else { throw new HttpRequestException("Lease Overlaps With Another for this Property, Please Amend Dates"); } }
public ActionResult DeleteLease(int?id) { try { Lease lease = Db.Leases.Find(id); if (lease != null) { Db.Leases.Remove(lease); Db.SaveChanges(); } return(RedirectToAction("Index", Exo())); } catch { new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return(View()); }
public void SetDeletedOnAndREturnSameValue() { //Arrange var fixture = new Fixture(); var item = fixture.Create <Guid>(); var user = fixture.Create <Guid>(); var startDate = new DateTime(2017, 03, 11); var endDate = new DateTime(2017, 04, 11); var lease = new Lease(item, user, startDate, endDate); var deletedOn = new DateTime(); //Act lease.DeletedOn = deletedOn; //Assert Assert.AreEqual(deletedOn, lease.DeletedOn); }
public async Task <IActionResult> Edit(int id, Lease lease) { ViewBag.CarId = new SelectList(contex.Cars.OrderBy(x => x.Id), "Id", "Id"); ViewBag.UserId = new SelectList(contex.Users.OrderBy(x => x.Id), "UserName", "UserName"); if (ModelState.IsValid) { var user = await contex.Users.FirstOrDefaultAsync(x => x.UserName == lease.UserUserName); var car = await contex.Cars.FirstOrDefaultAsync(x => x.Id == lease.CarId); if (lease.StartDate > lease.EndDate) { ModelState.AddModelError("", "The lease End Date has to be larger than Start date"); return(View(lease)); } if (lease.StartDate == lease.EndDate) { ModelState.AddModelError("", "Minimum lease time is 1 day"); return(View(lease)); } if (lease.Payment == null) { ModelState.AddModelError("", "Select payment option"); return(View(lease)); } lease.CarBrand = car.Brand; lease.CarColor = car.Color; lease.CarRentPrice = car.RentPrice; lease.UserId = user.Id; lease.UserUserName = user.UserName; lease.UserName = user.Name; contex.Update(lease); await contex.SaveChangesAsync(); TempData["Success"] = "The lease has been updated!"; return(RedirectToAction("Index")); } return(View(lease)); }
/// <summary> /// Updates the provided lease, persisting its data to the lease store. /// </summary> /// <remarks> /// This call is not used by the API and is only useful for internal calls like UpdateCheckpointAsync. /// </remarks> /// <param name="lease">The lease to update.</param> /// <returns>True if the lease was updated, false if not.</returns> public async Task<bool> UpdateLeaseAsync(Lease lease) { // BUG: Not safe when used across multiple processes or machines. await Task.Delay(1).ConfigureAwait(false); DiskLease staleLease = lease is DiskLease x ? x : new DiskLease(lease) { LeaseDuration = LeaseDuration, }; DiskLease freshLease = (DiskLease)await GetLeaseAsync(lease.PartitionId).ConfigureAwait(false); string key = GetLockKey(staleLease); bool hasLock = false; try { Monitor.Enter(key, ref hasLock); // We can't modify the lease, it's no longer ours to use. Expiration doesn't matter. If the lease has been // stolen by someone else, but it has already expired, it's still not ours to modify without first acquiring. if (freshLease.Token != staleLease.Token) { return false; } // NOTE: Disabled because there's temporarily only 1 running. //// We can't modify a lease that has already expired. It must first be acquired again. //// Synchronous Task execution because we need to remain in the same thread for the lock we're holding. //if (freshLease.IsExpired().Result) //{ // return false; //} // Synchronous Task execution because we need to remain in the same thread for the lock we're holding. UpdateLeaseInternalAsync(staleLease).Wait(); return true; } finally { if (hasLock) { Monitor.Exit(key); } } }
public ActionResult DeleteMyLease(int id) { var user = Session[CDictionary.welcome] as CMember; if (user == null) { return(RedirectToAction("Login", "Member")); } var memberId = user.fMemberId; Lease l = dbSA.Lease.FirstOrDefault(t => t.ID == id); string roomID = null; if (l != null) { roomID = l.RoomID.ToString(); dbSA.Lease.Remove(l); dbSA.SaveChanges(); //退租成功通知訊息 CInformationFactory x = new CInformationFactory(); x.Add(memberId, 400, id, 40030); var rf = from r in dbSA.RoomFavorite where r.RoomID.ToString() == roomID select r.MemberID; if (rf != null) { foreach (var item in rf) { int reID = item.Value; //通知空房訊息 CInformationFactory y = new CInformationFactory(); y.Add(reID, 400, 0, 40040); } } return(RedirectToAction("SearchPage")); } return(View(l)); }
public List <Lease> Find(bool withouLease) { List <LeaseJoined> query = Join().ToList(); List <Lease> leases = new List <Lease>(); for (int i = 0; i < query.Count; i++) { Lease lease = query[i].Lease; lease.Property = query[i].Property; lease.Occupant = query[i].Occupant; lease.warranty = query[i].Property.Price * 2; lease.IsFirstMonthPaid = query[i].Lease.Deposit == 0 ? false : true; leases.Add(lease); } return(leases); }
private async Task ExecuteLeaseRenewals(CancellationToken token, BlockingCollection <ClientEvent> clientEvents, Lease lease) { var coordinatorToken = new CoordinatorToken(); PostLeaderEvent(lease.FencingToken, lease.ExpiryPeriod, coordinatorToken, clientEvents); await WaitFor(GetInterval(lease.HeartbeatPeriod), token, coordinatorToken); // lease renewal loop while (!token.IsCancellationRequested && !coordinatorToken.FencingTokenViolation) { var response = await TryRenewLeaseAsync(new RenewLeaseRequest() { ClientId = this.clientId, ResourceGroup = this.resourceGroup, FencingToken = lease.FencingToken }, token); if (response.Result == LeaseResult.Granted) { PostLeaderEvent(lease.FencingToken, lease.ExpiryPeriod, coordinatorToken, clientEvents); await WaitFor(GetInterval(lease.HeartbeatPeriod), token, coordinatorToken); } else if (response.Result == LeaseResult.Denied) { PostFollowerEvent(lease.ExpiryPeriod, clientEvents); await WaitFor(GetInterval(lease.HeartbeatPeriod), token); break; } else if (response.Result == LeaseResult.NoLease) { throw new RebalanserException($"The resource group {this.resourceGroup} does not exist."); } else if (response.IsErrorResponse()) { throw new RebalanserException("An non-recoverable error occurred.", response.Exception); } else { throw new RebalanserException("A non-supported lease result was received"); // should never happen, just in case I screw up in the future } } }
public async void InsertLease_Expect_RetrieveByPhysicalAddress() { var repo = new LeaseRepo(DbConfig); var ipAddress = "10.10.10.10"; var lease = new Lease { HostName = "myserver.local", IpAddress = ipAddress, PhysicalAddress = "00:00:00:00:00:00", Expiration = DateTime.Now.AddSeconds(86400) }; var id = await repo.Insert(lease).ConfigureAwait(false); var entity = await repo.GetByPhysicalAddress(lease.PhysicalAddress).ConfigureAwait(false); Assert.Equal(lease.PhysicalAddress, entity.PhysicalAddress); }
/// <summary> /// Creates a new lease if it doesn't exist in the store yet. /// </summary> /// <param name="partitionId">The partition id.</param> /// <returns>The new lease or the existing one.</returns> public async Task <Lease> CreateLeaseIfNotExistsAsync(string partitionId) { Lease lease = await GetLeaseAsync(partitionId).ConfigureAwait(false); if (lease == null) { T typedLease; lease = typedLease = _createLease(partitionId); using (SqlQuery query = new SqlQuery(_connectionString)) { query.InsertAll(new List <T> { typedLease }); } } return(lease); }
private void btnSavePaymentInfo_Click(object sender, EventArgs e) { if (currentLease == null) { currentLease = new Lease(); MessageBox.Show("This Lease Payment Information won't be saved until you save the Lease itself."); DealForm df; if (this.dealForm == null) { df = new DealForm(); } else { df = this.dealForm; } if (rdbAnnually.Checked) { df.rdbLeaseCalculateAnnually.Checked = true; } else if (rdbMonthly.Checked) { df.rdbCalculateMonthly.Checked = true; } df.txtFinanceInterestAmount.Text = txtTotalInterest.Text; df.txtFinanceInterestRate.Text = txtInterestRate.Text; df.txtFinanceNumberofPayments.Text = txtNumberOfMonths.Text; df.txtFinancePaymentAmount.Text = txtMonthlyPayment.Text; df.txtFinanceSubtotal.Text = txtCapitalizedCost.Text; df.txtFinanceTotalBalanceDue.Text = df.CalculateTotal("Finance").ToString("C"); df.txtLeaseInterestRate.Text = txtInterestRate.Text; df.txtLeaseNumberofPayments.Text = txtNumberOfMonths.Text; df.txtLeasePaymentAmount.Text = txtMonthlyPayment.Text; df.txtLeaseSubtotal.Text = txtCapitalizedCost.Text; df.MdiParent = this.MdiParent; df.Show(); } }
public void Start() { s_logger.Information("Starting pending notifications chaser..."); m_pollingJob.Start(async cancellationToken => { var lease = Lease.NotAcquired; var result = false; try { lease = await Lease.AcquireAsync( m_chaserExclusiveAccessBlobLock, TimeSpan.FromMinutes(Constants.Settings.PENDING_NOTIFICATIONS_CHASER_EXCLUSIVE_ACCESS_LOCK_TIMEOUT_IN_MINUTES)); if (Lease.IsAcquired(lease)) { s_logger.Verbose("Chaser lock was successfully acquired. Start pending notification processing..."); var processNotificationCount = await ProcessPendingNotificationsAsync(); s_logger.Information("Chaser republished {NotificationCount} unpublished notifications.", processNotificationCount); result = processNotificationCount != 0; } else { s_logger.Verbose("Chaser lock wasn't acquired."); } } catch (Exception exception) { s_logger.Error(exception, "Notification processing failed."); } await ReleaseLeaseAsync(lease); return(result); }); s_logger.Information("Pending notifications chaser started."); }
public async Task <Lease> CheckpointAsync(Lease lease, string continuationToken, long sequenceNumber) { DocumentServiceLease documentLease = lease as DocumentServiceLease; Debug.Assert(documentLease != null, "documentLease"); documentLease.ContinuationToken = continuationToken; documentLease.SequenceNumber = sequenceNumber; DocumentServiceLease result = await this.UpdateInternalAsync( documentLease, (DocumentServiceLease serverLease) => { serverLease.ContinuationToken = documentLease.ContinuationToken; serverLease.SequenceNumber = documentLease.SequenceNumber; return(serverLease); }); return(result); }
/// <summary> /// Updates the provided checkpoint for the provided lease, persisting it to the checkpoint store. /// </summary> /// <remarks> /// Checkpoints are protected against out of sync and old data by the PartitionContext, so there is no need to /// perform checks on whether or not it's going backwards. /// </remarks> /// <param name="lease">The lease to associate the checkpoint with.</param> /// <param name="checkpoint">The checkpoint to persist.</param> public async Task UpdateCheckpointAsync(Lease lease, Checkpoint checkpoint) { await Task.Delay(1).ConfigureAwait(false); DiskLease realLease = lease is DiskLease x ? x : new DiskLease(lease) { LeaseDuration = LeaseDuration, }; // TODO: Also renew the lease to ensure it doesn't expire right after checkpointing. Basically anything touching the lease should renew it, creating a sliding expiration. realLease.Offset = checkpoint.Offset; realLease.SequenceNumber = checkpoint.SequenceNumber; bool result = await UpdateLeaseAsync(realLease).ConfigureAwait(false); // Because we don't have a return value, we have no other choice than to throw an exception if the lease failed // to update. If we don't, we would have a checkpoint that was never persisted. if (!result) { throw new InvalidOperationException($"The checkpoint for partition '{checkpoint.PartitionId}' could not be updated, because the lease is not owned."); } }
public async Task Distributor_Trace_default_behavior_can_be_overridden() { Lease <int> leaseAcquired = null; Lease <int> leaseReleased = null; var distributor1 = new InMemoryDistributor <int>(new[] { new Leasable <int>(1, "1") }, "").Trace( onLeaseAcquired: l => { leaseAcquired = l; }, onLeaseReleasing: l => { leaseReleased = l; }); distributor1.OnReceive((async _ => { })); var distributor = distributor1; await distributor.Distribute(1); leaseAcquired.Should().NotBeNull(); leaseReleased.Should().NotBeNull(); }
public void StartTrackingLifetime(ILease lease) { // Adds this identity to the LeaseManager. // _serverObject must be set. if (lease != null && lease.CurrentState == LeaseState.Null) { lease = null; } if (lease != null) { if (!(lease is Lease)) { lease = new Lease(); // This seems to be MS behavior } _lease = (Lease)lease; LifetimeServices.TrackLifetime(this); } }
private void btInschrijven_Click(object sender, EventArgs e) { DatabaseManager.InsertItem(new Lease()); Lease lease = new Lease() { ID = int.Parse(DatabaseManager.QueryFirst("SELECT MAX(ID) FROM Lease")["Column1"].ToString()) }; Reserveer_Systeem.frmMain.Lease = lease.ID; Reserveer_Systeem.frmMain.SelectedEvenement = new Reserveer_Systeem.Evenement() { ID = evenement.ID, BeginDate = evenement.BeginDate, EndDate = evenement.EndDate}; frmDatum frmDatum = new frmDatum() { Location = Location, StartPosition = FormStartPosition.CenterParent }; if (frmDatum.ShowDialog(this) != DialogResult.OK) { MessageBox.Show("Geen geldige datum ingevoerd. Probeer het opnieuw"); return; } frmKaart frmKaart = new frmKaart() { Location = Location, StartPosition = FormStartPosition.CenterParent }; if (frmKaart.ShowDialog(this) != DialogResult.OK) { MessageBox.Show("Geen plek gekozen! Probeer het opnieuw."); return; } }
public async Task <IActionResult> Lease(DateTime duedate, string email, string isbn) { Lease newLease; Book leasedBook = dbc.Book.First(b => b.ISBN == isbn); ApplicationUser leasingUser = await _userManager.FindByEmailAsync(email); if (dbc.Lease.Where(l => l.Book == leasedBook && l.LeaseStartDate < DateTime.Today && l.LeaseEndDate > DateTime.Now).Count() < 1) { newLease = new Lease { LeaseStartDate = DateTime.Today, LeaseEndDate = duedate, Book = leasedBook, Email = leasingUser.Email }; dbc.Lease.Add(newLease); dbc.SaveChanges(); } return(RedirectToAction("Index", "Home")); }
/// <summary> /// Delete the given file from all known locations /// </summary> public async Task DeleteFileAsync(string filePath, string blobSasUri, Lease lease = null) { if (!string.IsNullOrWhiteSpace(blobSasUri)) { var fileBlob = BlobController.GetBlobForFile(filePath, blobSasUri); await fileBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, GetAccessCondition(lease), null, null); } foreach (var baseDir in new string[] { Infrastructure.Settings.TempDir, Settings.UserSiteStorageDirectory }) { string fullPath = Path.Combine(baseDir, filePath); if (System.IO.File.Exists(fullPath)) { RetryHelper.RetryOnException("Deleting file asynchronously...", () => { System.IO.File.Delete(fullPath); }, TimeSpan.FromSeconds(1)); } } }
public Lease SaveLease(Property property, Tenant tenant, decimal price, DateTime startDate, DateTime endDate) { var lease = new Lease(_maxId + 1, property, tenant, price, startDate, endDate); if (!IsUnique(lease)) { throw new EntityExistsException("Такая запись уже существует в базе."); } if (!IsAvailable(property, lease)) { throw new InvalidOperationException("Выбранное помещение занято в указанный период времени."); } _dataManager.AddLease(lease); Leases.Add(lease); _maxId = lease.Id; return(lease); }
public JsonResult Extend(string SerialNumber, string EndDate) { AuleaseEntities db = new AuleaseEntities(); Component comp = db.Components.Where(n => n.SerialNumber == SerialNumber).Single(); Lease lastLease = comp.Leases.OrderByDescending(n => n.EndDate).First(); DateTime d = lastLease.EndDate.Value; DateTime begDate = new DateTime(d.AddMonths(1).Year, d.AddMonths(1).Month, 1); DateTime endDate = UnixTimeStampToDateTime(Convert.ToDouble(EndDate)); Lease newLease = new Lease(); newLease.Charges = lastLease.Charges; newLease.Component = lastLease.Component; newLease.ComponentId = lastLease.ComponentId; newLease.ContractNumber = lastLease.ContractNumber; newLease.Department = lastLease.Department; newLease.DepartmentId = lastLease.DepartmentId; newLease.MonthlyCharge = lastLease.MonthlyCharge; newLease.Overhead = lastLease.Overhead; newLease.OverheadId = lastLease.OverheadId; newLease.StatementName = lastLease.StatementName; newLease.SystemGroup = lastLease.SystemGroup; newLease.SystemGroupId = lastLease.SystemGroupId; newLease.Timestamp = DateTime.Now; newLease.BeginDate = begDate; newLease.EndDate = endDate; comp.Leases.Add(newLease); comp.ReturnDate = endDate.AddMonths(1); db.SaveChanges(); var output = new { success = true }; return(Json(output)); }
public override Task <AcquireLeaseResponse> AcquireLease(AcquireLeaseRequest request, ServerCallContext context) { AcquireLeaseResponse.Types.Status status; Lease lease = null; SpotRobot.SpotInstance.Leases.TryGetValue(request.Resource, out var leaseTuple); if (leaseTuple == null) { lease = new Lease { Resource = request.Resource, Sequence = { 1 } }; SpotRobot.SpotInstance.Leases.Add(request.Resource, new Tuple <string, Lease>(request.Header.ClientName, lease)); Console.WriteLine($"AcquireLease - registering new lease for resource \"{request.Resource}\" and client \"{request.Header.ClientName}\""); status = AcquireLeaseResponse.Types.Status.Ok; } else if (leaseTuple.Item1 == request.Header.ClientName) { Console.WriteLine($"AcquireLease - lease already exists for resource \"{request.Resource}\" and client \"{request.Header.ClientName}\""); status = AcquireLeaseResponse.Types.Status.Ok; } else { Console.WriteLine($"AcquireLease - lease already exists for resource \"{request.Resource}\" and but no for client \"{request.Header.ClientName}\""); status = AcquireLeaseResponse.Types.Status.ResourceAlreadyClaimed; } return(Task.FromResult(new AcquireLeaseResponse { Header = HeaderBuilder.Build(request.Header, new CommonError { Code = CommonError.Types.Code.Ok }), Status = status, Lease = lease, LeaseOwner = new LeaseOwner { ClientName = request.Header.ClientName, } })); }
private void OnWriteReceived(IMessage message) { var payload = message.GetPayload<LeaseWriteMessage>(); var ballot = new Ballot(new DateTime(payload.Ballot.Timestamp, DateTimeKind.Utc), payload.Ballot.MessageNumber, payload.Ballot.Identity); IMessage response; if (writeBallot > ballot || readBallot > ballot) { LogNackWrite(ballot); response = Message.Create(new LeaseNackWriteMessage { Ballot = payload.Ballot, SenderUri = synodConfig.LocalNode.Uri.ToSocketAddress() }, LeaseNackWriteMessage.MessageIdentity); } else { LogAckWrite(ballot); writeBallot = ballot; var ownerEndpoint = new OwnerEndpoint { UnicastUri = new Uri(payload.Lease.OwnerEndpoint.UnicastUri), MulticastUri = new Uri(payload.Lease.OwnerEndpoint.MulticastUri) }; lease = new Lease(payload.Lease.Identity, ownerEndpoint, new DateTime(payload.Lease.ExpiresAt, DateTimeKind.Utc)); response = Message.Create(new LeaseAckWriteMessage { Ballot = payload.Ballot, SenderUri = synodConfig.LocalNode.Uri.ToSocketAddress() }, LeaseAckWriteMessage.MessageIdentity); } intercomMessageHub.Send(response, payload.SenderIdentity); }
public IHttpActionResult PutLease(int id, LeaseModel modelLease) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != modelLease.LeaseId) { return(BadRequest()); } Lease dbLease = db.Leases.FirstOrDefault(l => l.User.UserName == User.Identity.Name && l.LeaseId == id); if (dbLease == null) { return(BadRequest()); } dbLease.Update(modelLease); db.Entry(dbLease).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!LeaseExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void SetLeaseDataSource(Lease currentLease) { rptviewer.LocalReport.DataSources.Clear(); this.CustomerTableAdapter.Fill(this.DealershipManagerDataSet.Customer); this.vehicleTableAdapter.Fill(this.DealershipManagerDataSet.Vehicle); this.leaseTableAdapter.Fill(this.DealershipManagerDataSet.Lease); this.leasePaymentsTableAdapter.Fill(this.DealershipManagerDataSet.LeasePayments); var dataTable = this.DealershipManagerDataSet.Lease; DataTable leaseTable = this.DealershipManagerDataSet.Lease.CopyToDataTable(); leaseTable.Clear(); dataTable.Where(x => x.Id == currentLease.Id).CopyToDataTable(leaseTable, LoadOption.OverwriteChanges); rptviewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("LeaseDataSet", leaseTable)); DataTable customerTable = this.DealershipManagerDataSet.Customer.CopyToDataTable(); customerTable.Clear(); var dataTable3 = this.DealershipManagerDataSet.Customer; dataTable3.Where(x => x.Id == currentLease.CustomerId).CopyToDataTable(customerTable, LoadOption.OverwriteChanges); rptviewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("CustomerDataSet", customerTable)); DataTable leasePaymentsTable = this.DealershipManagerDataSet.LeasePayments.CopyToDataTable(); leasePaymentsTable.Clear(); var dataTable2 = this.DealershipManagerDataSet.LeasePayments; dataTable2.Where(x => x.LeaseId == currentLease.Id).CopyToDataTable(leasePaymentsTable, LoadOption.OverwriteChanges); rptviewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("LeasePaymentsDataSet", leasePaymentsTable)); DataTable vehicleTable = this.DealershipManagerDataSet.Vehicle.CopyToDataTable(); vehicleTable.Clear(); var dataTable4 = this.DealershipManagerDataSet.Vehicle; dataTable4.Where(x => x.Id == currentLease.VehicleId).CopyToDataTable(vehicleTable, LoadOption.OverwriteChanges); rptviewer.LocalReport.DataSources.Add(new Microsoft.Reporting.WinForms.ReportDataSource("VehicleDataSet", vehicleTable)); }
/// <summary> /// Releases the provided lease, resetting ownership information so that another owner may acquire the lease. /// </summary> /// <remarks> /// Leases are only ever released if a PartitionPump closes gracefully by shutdown. Stealing of leases or crashes /// of a consumer result in 'dirty' leases of which must be stolen before they can be used by another owner. The /// return value is not used, so failure to release a lease in any way will cause the application to continue anyway. /// However, exceptions during releasing will be propagated to the unhandled exception handler in EventProcessorOptions. /// </remarks> /// <param name="lease">The lease to release.</param> /// <returns>True if the lease was released, false if not.</returns> public async Task<bool> ReleaseLeaseAsync(Lease lease) { // BUG: Not safe when used across multiple processes or machines. await Task.Delay(1).ConfigureAwait(false); DiskLease staleLease = lease is DiskLease x ? x : new DiskLease(lease) { LeaseDuration = LeaseDuration, }; DiskLease freshLease = (DiskLease)await GetLeaseAsync(lease.PartitionId).ConfigureAwait(false); string key = GetLockKey(staleLease); bool hasLock = false; try { Monitor.Enter(key, ref hasLock); // We can't release the lease, it's no longer ours to use. Expiration doesn't matter. If the lease has been // stolen by someone else, but it has already expired, it's still not ours to release without first acquiring. if (freshLease.Token != staleLease.Token) { return false; } // Normally we shouldn't release a lease that has expired, but since we already confirmed we were the last owners, // and the caller doesn't use the return value, we have no choice but to release it anyway. // Synchronous Task execution because we need to remain in the same thread for the lock we're holding. staleLease.Release(); UpdateLeaseInternalAsync(staleLease).Wait(); return true; } finally { if (hasLock) { Monitor.Exit(key); } } }
public ActionResult ChangeStatus(int?id) { try { Lease lease = Db.Leases.Find(id); if (lease != null) { if (lease.Status == LeaseStatus.Delivered) { lease.Status = LeaseStatus.Verified; } Db.Entry(lease).State = EntityState.Modified; Db.SaveChanges(); } return(View("Details", GenerateLeaseDto(lease))); } catch { new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return(View()); }
private Lease GetLeaseWithLeastConnections() { //now get the service with the least connections? Lease leaseWithLeastConnections = null; for (var i = 0; i < _leases.Count; i++) { if (i == 0) { leaseWithLeastConnections = _leases[i]; } else { if (_leases[i].Connections < leaseWithLeastConnections.Connections) { leaseWithLeastConnections = _leases[i]; } } } return(leaseWithLeastConnections); }
protected override async Task ReleaseLease(Lease lease) { using (var connection = new SqlConnection(settings.ConnectionString)) { await connection.OpenAsync(); var cmd = connection.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = @"Alluvial.ReleaseLease"; cmd.Parameters.AddWithValue(@"@resourceName", lease.LeasableResource.Name); cmd.Parameters.AddWithValue(@"@token", (int) lease.OwnerToken); try { var leaseLastReleased = (DateTimeOffset) await cmd.ExecuteScalarAsync(); lease.LeasableResource.LeaseLastReleased = leaseLastReleased; Debug.WriteLine("[Distribute] ReleaseLease: " + lease); } catch (Exception ex) { Debug.WriteLine("[Distribute] ReleaseLease (failed): " + lease + "\n" + ex); } } }
public HttpResponseMessage GetLease() { UserCredentials u = Request.Content.ReadAsAsync<UserCredentials>().Result; string userId = ValidateCredentials(u); HttpResponseMessage response = null; if (!string.IsNullOrEmpty(userId)) { string leaseId = CycliManager.Instance.GetLease(userId); if (!string.IsNullOrEmpty(leaseId)) { Lease l = new Lease(); l.UserId = userId; l.LeaseId = leaseId; response = Request.CreateResponse<Lease>(HttpStatusCode.OK, (l), new System.Net.Http.Formatting.JsonMediaTypeFormatter()); } } if (response == null) { response = Request.CreateResponse(HttpStatusCode.Unauthorized); } return response; }
/// <summary> /// Sets the Lease for an event hub partition in the current namespace. If the lease is null, /// the function removes the lease from the internal structure. /// </summary> /// <param name="ns">Namespace name.</param> /// <param name="eventHub">Event hub name.</param> /// <param name="consumerGroup"></param> /// <param name="partitionId">Partition Id.</param> /// <param name="lease">The lease for the event hub partition.</param> public static void SetLease(string ns, string eventHub, string consumerGroup, string partitionId, Lease lease) { if (string.IsNullOrWhiteSpace(ns) || string.IsNullOrWhiteSpace(eventHub) || string.IsNullOrWhiteSpace(consumerGroup) || string.IsNullOrWhiteSpace(partitionId)) { return; } var key = string.Format(KeyFormat, ns, eventHub, consumerGroup); if (mapDictionary.ContainsKey(key)) { if (lease != null) { if (mapDictionary[key].Leases == null) { mapDictionary[key].Leases = new Dictionary<string, Lease>(); } mapDictionary[key].Leases[partitionId] = lease; } else { if (mapDictionary[key].Leases == null || !mapDictionary[key].Leases.ContainsKey(partitionId)) { return; } mapDictionary[key].Leases.Remove(partitionId); } } else { if (lease == null) { return; } var item = new EventProcessorCheckpointInfo { Namespace = ns, EventHub = eventHub, ConsumerGroup = consumerGroup, Leases = new Dictionary<string, Lease> { { partitionId, lease } } }; lock (mapDictionary) { itemList.Add(item); if (mapDictionary.ContainsKey(key)) { mapDictionary[key].Leases[partitionId] = lease; } else { mapDictionary.Add(key, item); } } } if (lease != null) { mapDictionary[key].Leases[partitionId] = lease; } else { mapDictionary[key].Leases.Remove(partitionId); } }
protected override void OnInit( EventArgs e ) { int leaseId = int.Parse( this.Request.QueryString["id"] ); this.db = new Database(); this.lease = (from l in db.Leases where l.LeaseId == leaseId select l).Single(); }
public Task CheckpointAsync(Lease lease, string offset, long sequenceNumber) { return EventProcessorCheckpointHelper.CheckpointAsync(Namespace, EventHub, lease, offset, sequenceNumber); }
public LeaseTxResult Write(Ballot ballot, Lease lease) { var ackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseAckWriteMessage>(), synodConfig); var nackFilter = new LeaderElectionMessageFilter(ballot, m => m.GetPayload<LeaseNackWriteMessage>(), synodConfig); var awaitableAckFilter = new AwaitableMessageStreamFilter(ackFilter.Match, m => m.GetPayload<LeaseAckWriteMessage>(), GetQuorum()); var awaitableNackFilter = new AwaitableMessageStreamFilter(nackFilter.Match, m => m.GetPayload<LeaseNackWriteMessage>(), GetQuorum()); using (ackWriteStream.Subscribe(awaitableAckFilter)) { using (nackWriteStream.Subscribe(awaitableNackFilter)) { intercomMessageHub.Broadcast(CreateWriteMessage(ballot, lease)); var index = WaitHandle.WaitAny(new[] {awaitableAckFilter.Filtered, awaitableNackFilter.Filtered}, leaseConfig.NodeResponseTimeout); if (ReadNotAcknowledged(index)) { return new LeaseTxResult {TxOutcome = TxOutcome.Abort}; } return new LeaseTxResult { TxOutcome = TxOutcome.Commit, // NOTE: needed??? Lease = lease }; } } }
public Task CheckpointAsync(Lease lease, string offset, long sequenceNumber) { throw new NotImplementedException(); }
public Task CheckpointAsync(Lease lease, string offset, long sequenceNumber) { return _checkpointAsync(); }
private IMessage CreateWriteMessage(Ballot ballot, Lease lease) { return Message.Create(new LeaseWriteMessage { Ballot = new Messages.Ballot { Identity = ballot.Identity, Timestamp = ballot.Timestamp.Ticks, MessageNumber = ballot.MessageNumber }, Lease = new Messages.Lease { Identity = lease.OwnerIdentity, ExpiresAt = lease.ExpiresAt.Ticks, OwnerEndpoint = new Messages.OwnerEndpoint { UnicastUri = lease.OwnerEndpoint.UnicastUri.ToSocketAddress(), MulticastUri = lease.OwnerEndpoint.MulticastUri.ToSocketAddress() } } }, LeaseWriteMessage.MessageIdentity); }
public static Task CheckpointAsync(string ns, string eventHub, string consumerGroup, Lease lease, string offset, long sequenceNumber) { if (string.IsNullOrWhiteSpace(ns) || string.IsNullOrWhiteSpace(eventHub) || string.IsNullOrWhiteSpace(consumerGroup) || lease == null || string.IsNullOrWhiteSpace(offset)) { Task.FromResult<object>(null); } if (lease != null && !string.IsNullOrWhiteSpace(offset)) { lease.Offset = offset; SetLease(ns, eventHub, consumerGroup, lease.PartitionId, lease); } return Task.FromResult<object>(null); }
protected abstract IStreamQueryDistributor CreateDistributor( Func<DistributorUnitOfWork, Task> onReceive = null, Lease[] leases = null, int maxDegreesOfParallelism = 5, [CallerMemberName] string name = null, TimeSpan? waitInterval = null);