public AutoRenewLease(CloudBlob blob) { this.blob = blob; blob.Container.CreateIfNotExist(); try { blob.UploadByteArray(new byte[0], new BlobRequestOptions { AccessCondition = AccessCondition.IfNoneMatch("*") }); } catch (StorageClientException e) { if (e.ErrorCode != StorageErrorCode.BlobAlreadyExists && e.StatusCode != HttpStatusCode.PreconditionFailed) // 412 from trying to modify a blob that's leased { throw; } } leaseId = blob.TryAcquireLease(); if (HasLease) { renewalThread = new Thread(() => { Thread.Sleep(TimeSpan.FromSeconds(40)); blob.RenewLease(leaseId); }); renewalThread.Start(); } }
// The mutex must already exists public Mutex(CloudBlobContainer container, string mutexName, Exception e) { blob = container.GetBlobReference(mutexName); byte[] b1 = { 1 }; BlobRequestOptions requestOpt = new BlobRequestOptions(); bool keepGoing = true; string oldEtag = ""; int lastChange = 0; do { byte[] b; string eTag; try { blob.FetchAttributes(); eTag = blob.Attributes.Properties.ETag; if (eTag != oldEtag) { lastChange = Environment.TickCount; oldEtag = eTag; } b = blob.DownloadByteArray(); } catch (Exception) { throw e; } requestOpt.AccessCondition = AccessCondition.IfMatch(eTag); if (b[0] == 0 || Environment.TickCount - lastChange > 3000) // on ne peut garder un lock plus de 3 s { try { blob.UploadByteArray(b1, requestOpt); keepGoing = false; } catch (StorageClientException ex) { if (ex.ErrorCode != StorageErrorCode.ConditionFailed) throw; } } else Thread.Sleep(50); // constante arbitraire } while (keepGoing); }
public void SetUp() { blobSettings = new LeaseBlockBlobSettings { ConnectionString = "UseDevelopmentStorage=true", ContainerName = "test" + Guid.NewGuid().ToString("N"), BlobPath = "lease.blob", ReAquirePreviousTestLease = false, RetryCount = 2, RetryInterval = TimeSpan.FromMilliseconds(250) }; maximumStopDurationEstimateSeconds = 10; var storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true"); var client = storageAccount.CreateCloudBlobClient(); container = client.GetContainerReference(blobSettings.ContainerName); container.CreateIfNotExist(); leaseBlob = container.GetBlobReference(blobSettings.BlobPath); leaseBlob.UploadByteArray(new byte[0]); }
public AutoRenewLease(ILoggerFactory loggerFactory, LoggerLevel logLevel, CloudBlob blob, int renewLeaseSeconds = 40, int leaseLengthSeconds = 90) { _logger = loggerFactory.Create(GetType(), logLevel); var autoRenewLease = this; _blob = blob; blob.Container.CreateIfNotExist(); try { blob.UploadByteArray(new byte[0], new BlobRequestOptions { AccessCondition = AccessCondition.IfNoneMatch("*")}); } catch (StorageClientException ex) { if (ex.ErrorCode != StorageErrorCode.BlobAlreadyExists) { if (ex.StatusCode != HttpStatusCode.PreconditionFailed) throw; } } LeaseId = blob.TryAcquireLease(leaseLengthSeconds); if (!HasLease) return; _cancellationTokenSource = new CancellationTokenSource(); _resetEvent = new ManualResetEvent(false); Task.Factory.StartNew(() => { try { while (true) { _resetEvent.WaitOne(TimeSpan.FromSeconds(renewLeaseSeconds)); if (_cancellationTokenSource.IsCancellationRequested) break; blob.RenewLease(autoRenewLease.LeaseId); } } catch (Exception e) { LeaseId = null; // Release the lease _logger.Error("Error renewing blob lease", e); } }, _cancellationTokenSource.Token); }
public static AutoRenewLease GetOrThrow(CloudBlob blob) { blob.Container.CreateIfNotExist(); // Create lock blob try { var requestOptions = new BlobRequestOptions { AccessCondition = AccessCondition.IfNoneMatch("*") }; blob.UploadByteArray(new byte[0], requestOptions); } catch (StorageClientException e) { if (e.ErrorCode != StorageErrorCode.BlobAlreadyExists && e.StatusCode != HttpStatusCode.PreconditionFailed) // 412 from trying to modify a blob that's leased { throw; } } string leaseId = null; var ex = DoUntilTrue(Try4Times, CancellationToken.None, () => { leaseId = AcquireLease(blob); return !String.IsNullOrEmpty(leaseId); }); if (ex != null) throw new InvalidOperationException("Failed to get lease", ex); // Either we get lease or throw timeout exception if (String.IsNullOrEmpty(leaseId)) throw new InvalidOperationException(); return new AutoRenewLease(blob, leaseId); }
public override void Run() { // This is a sample worker implementation. Replace with your logic. Trace.WriteLine("$projectname$ entry point called", "Information"); while (true) { if (q.Exists()) { q.RetrieveApproximateMessageCount(); if (q.ApproximateMessageCount > 0) { Trace.WriteLine("Working", "Information"); var message = q.GetMessage(); q.DeleteMessage(message); var request = message.AsString; var parts = request.Split('|'); string ICD9Code = parts[0]; DateTime starttime = new DateTime(long.Parse(parts[1])); DateTime endtime = new DateTime(long.Parse(parts[2])); string OperationID = parts[3]; try { IQueryable<AilmentDetails> data = (from i in tableContext.CreateQuery<AilmentDetails>("PatientDetails") where i.PartitionKey == "AilmentDetails" && i.DiagnosisID == ICD9Code select i).AsQueryable<AilmentDetails>(); if (data.AsEnumerable<AilmentDetails>().Any<AilmentDetails>()) { foreach (AilmentDetails x in data) { if (DateTime.Compare(x.TimeIn, starttime) >= 0 && DateTime.Compare(x.TimeIn, endtime) <= 0) { string searchHospital = x.Hospital; IQueryable<HospitalBasicDetails> data2 = (from i in tableContext.CreateQuery<HospitalBasicDetails>("DoctorDetails") where i.PartitionKey == "HospitalBasicDetails" select i).AsQueryable<HospitalBasicDetails>(); if (data2.AsEnumerable<HospitalBasicDetails>().Any<HospitalBasicDetails>()) { HospitalBasicDetails z = new HospitalBasicDetails(); var y = (from HospitalBasicDetails i in data2 where i.HospitalID == searchHospital select i).FirstOrDefault<HospitalBasicDetails>() as HospitalBasicDetails; if (y != null) { ICD9MapPlotResultEntry temp = new ICD9MapPlotResultEntry(); temp.Latitude = y.Latitude; temp.Longitude = y.Longitude; temp.Time = x.TimeIn; rows.Add(temp); } } } } } var serializer = new XmlSerializer(typeof(List<ICD9MapPlotResultEntry>)); var stringBuilder = new StringBuilder(); XmlWriter writer = XmlWriter.Create(stringBuilder); serializer.Serialize(writer, rows); Encoding encoding = Encoding.Default; blob = container.GetBlobReference(OperationID + ".xml"); blob.UploadByteArray(encoding.GetBytes(stringBuilder.ToString())); var resultrecord = new ICD9MapPlotResult(ICD9Code, OperationID); resultrecord.SearchTimeStart = starttime; resultrecord.SearchTimeEnd = endtime; resultrecord.ResultURL = blob.Uri.ToString(); tableContext.AddObject("ICD9MapPlotResult", resultrecord); tableContext.SaveChanges(); } catch (Exception e) { Trace.WriteLine(e.Message, "Error"); } } } Thread.Sleep(10000); } }