예제 #1
0
            public void WhenTagsHaveSameValue_RegardlessOfStrength_IsEqual(bool isWeak1, bool isWeak2)
            {
                var t1 = new ETag("abc", isWeak: isWeak1);
                var t2 = new ETag("abc", isWeak: isWeak2);

                Assert.True(WeakETagComparer.Instace.Equals(t1, t2));
            }
예제 #2
0
            public void WhenOneTagsIsStrongAndTheOtherWeak_AndHaveTheSameValue_IsNotEqual(bool isWeak1, bool isWeak2)
            {
                var t1 = new ETag("abc", isWeak: isWeak1);
                var t2 = new ETag("abc", isWeak: isWeak2);

                Assert.False(t1.Equals(t2));
            }
예제 #3
0
            public void WhenBothTagsAreWeak_AndHaveTheSameValue_IsEqual()
            {
                var t1 = new ETag("abc", isWeak: true);
                var t2 = new ETag("abc", isWeak: true);

                Assert.True(t1.Equals(t2));
            }
예제 #4
0
            public void WhenTagsHaveDifferentValues_RegardlessOfStrength_IsNotEqual(bool isWeak1, bool isWeak2)
            {
                var t1 = new ETag("abc", isWeak: isWeak1);
                var t2 = new ETag("ABC", isWeak: isWeak2);

                Assert.False(StrongETagComparer.Instace.Equals(t1, t2));
            }
예제 #5
0
            public void WhenAtLeastOneTagsIsWeak_AndHaveTheSameValue_IsNotEqual(bool isWeak1, bool isWeak2)
            {
                var t1 = new ETag("abc", isWeak: isWeak1);
                var t2 = new ETag("abc", isWeak: isWeak2);

                Assert.False(StrongETagComparer.Instace.Equals(t1, t2));
            }
예제 #6
0
            public void WhenBothTagsAreStrong_AndHaveTheSameValue_IsEqual()
            {
                var t1 = new ETag("abc", isWeak: false);
                var t2 = new ETag("abc", isWeak: false);

                Assert.True(StrongETagComparer.Instace.Equals(t1, t2));
            }
예제 #7
0
        /// <summary>
        /// Creates an instance indicating the server currently does have a representation. The <paramref name="lastModified"/>
        /// and <paramref name="eTag"/> parameters are optional, but providing both will result in more accurate responses to 
        /// conditional requests.
        /// </summary>
        /// <param name="lastModified">The time the resource instance was last modified, if known.</param>
        /// <param name="eTag">The ETag of the resource instance, if known.</param>
        public static CurrentRepresentation Existing(DateTimeOffset? lastModified = null, ETag eTag = null)
        {
            if (ETag.Any.Equals(eTag))
                throw new ArgumentException("The ETag.Any instance is not valid in this context", nameof(eTag));

            return new CurrentRepresentation(exists: true)
            {
                LastModified = lastModified,
                ETag = eTag,
            };
        }
예제 #8
0
        public async Task ReadItemAsync_PreconditionsFailed_Returns304()
        {
            var firstResponse = await SendRequestToServer <Movie>(HttpMethod.Get, $"/tables/movies/{Movie4.Id}", null);

            Assert.AreEqual(HttpStatusCode.OK, firstResponse.StatusCode);
            var firstActual = await GetValueFromResponse <Movie>(firstResponse);

            var response = await SendRequestToServer <Movie>(HttpMethod.Get, $"/tables/movies/{Movie4.Id}", null, new Dictionary <string, string>
            {
                { "If-None-Match", ETag.FromByteArray(firstActual.Version) }
            });

            Assert.AreEqual(HttpStatusCode.NotModified, response.StatusCode);
        }
예제 #9
0
        /// <summary>
        /// Wraps eTag with quotes if not already wrapped.
        /// This a workaround for https://github.com/Azure/azure-sdk-for-net/issues/22877
        /// </summary>
        /// <param name="value">Etag to wrap with quotes if needed</param>
        /// <returns>Etag string wrapped with quotes</returns>
        public static string GetHttpSafeETag(this ETag value)
        {
            //TODO Remove when https://github.com/Azure/azure-sdk-for-net/issues/22877 is fixed
            var eTag = value.ToString();

            if (!string.IsNullOrEmpty(eTag))
            {
                if (!(eTag.StartsWith("\"") || eTag.StartsWith("W")))
                {
                    eTag = string.Format("\"{0}\"", eTag);
                }
            }
            return(eTag);
        }
예제 #10
0
        public void Configure(IEndpointRouteBuilder builder) => builder
        .MapGet(string.Empty, context => {
            var readModel = context.RequestServices.GetRequiredService <InMemoryReadModel>();

            var hasValue = readModel.TryGetValue <ReadModel>(
                nameof(ChartOfAccounts),
                out var entry);

            var statusCode = hasValue
                                        ? HttpStatusCode.OK
                                        : HttpStatusCode.NotFound;
            var response = new HalResponse(context.Request, new ChartOfAccountsRepresentation(),
                                           ETag.Create(entry?.Item.Checkpoint ?? Optional <Position> .Empty),
                                           hasValue ? new Optional <object>(entry?.Item !) : Optional <object> .Empty);
예제 #11
0
 /// <summary>
 /// Creates a new ShareFileUploadInfo instance for mocking.
 /// </summary>
 public static ShareFileUploadInfo ShareFileUploadInfo(
     ETag eTag,
     DateTimeOffset lastModified,
     byte[] contentHash,
     bool isServerEncrypted)
 {
     return(new ShareFileUploadInfo()
     {
         ETag = eTag,
         LastModified = lastModified,
         ContentHash = contentHash,
         IsServerEncrypted = isServerEncrypted,
     });
 }
예제 #12
0
 public IActionResult Get()
 {
     var responseHeaders = Response.GetTypedHeaders();
     responseHeaders.CacheControl = new CacheControlHeaderValue
     {
         SharedMaxAge = TimeSpan.FromSeconds(120)
     };
     responseHeaders.LastModified = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(10));
     var etag = new ETag("backend2", isWeak: false);
     responseHeaders.ETag = etag.ToETagHeaderValue();
     var conditionalDirective = Request.ReadConditionalReqeustDirective();
     var status = conditionalDirective.ShouldPerformRequest(CurrentRepresentation.Existing(responseHeaders.LastModified.Value, etag)) ? StatusCodes.Status200OK : StatusCodes.Status304NotModified;
     return BuildBackendResult(status);
 }
예제 #13
0
        public async Task GivenDirectoryEntry_WhenRoundTripWithETag_Success()
        {
            DirectoryClient client = TestApplication.GetDirectoryClient();

            var documentId = new DocumentId("test/unit-tests/entry1");

            var query = new QueryParameter()
            {
                Filter    = "test",
                Recursive = false,
            };

            await client.Delete(documentId);

            var entry = new DirectoryEntryBuilder()
                        .SetDirectoryId(documentId)
                        .SetClassType("test")
                        .AddProperty(new EntryProperty {
                Name = "property1", Value = "value1"
            })
                        .Build();

            await client.Set(entry);

            DirectoryEntry?readEntry = await client.Get(documentId);

            readEntry.Should().NotBeNull();
            readEntry !.ETag.Should().NotBeNull();
            readEntry.Properties.Count.Should().Be(1);

            var updateEntry = new DirectoryEntryBuilder(readEntry)
                              .SetClassType("test-next")
                              .AddProperty(new EntryProperty {
                Name = "property2", Value = "value2"
            })
                              .Build();

            await client.Set(updateEntry);

            readEntry = await client.Get(documentId);

            readEntry.Should().NotBeNull();
            readEntry !.Properties.Count.Should().Be(2);

            await client.Delete(documentId);

            IReadOnlyList <DatalakePathItem> search = (await client.Search(query).ReadNext()).Records;

            search.Any(x => x.Name == (string)documentId).Should().BeFalse();
        }
        public override void ExecuteResult(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            var request     = httpContext.Request;
            var response    = httpContext.Response;

            // Fix Last Modified Time.  We might need it soon
            // if we encounter a Range: and If-Range header
            // Using UTC time to avoid daylight savings time bug 83230
            var lastModified = new DateTime(LastModifiedUtc.Year,
                                            LastModifiedUtc.Month,
                                            LastModifiedUtc.Day,
                                            LastModifiedUtc.Hour,
                                            LastModifiedUtc.Minute,
                                            LastModifiedUtc.Second,
                                            0,
                                            DateTimeKind.Utc);

            // Because we can't set a "Last-Modified" header to any time
            // in the future, check the last modified time and set it to
            // DateTime.Now if it's in the future.
            // This is to fix VSWhidbey #402323
            var utcNow = DateTime.UtcNow;

            if (lastModified > utcNow)
            {
                // use 1 second resolution
                lastModified = new DateTime(utcNow.Ticks - (utcNow.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
            }

            LastModifiedUtc = lastModified;

            // Generate ETag if empty
            if (ETag.IsEmpty())
            {
                ETag = GenerateETag(httpContext, lastModified, utcNow);
            }

            // Determine applicable file responder
            var responder = ResolveResponder(request);

            // Execute response (send file)
            if (responder.TrySendHeaders(httpContext))
            {
                responder.SendFile(httpContext);
            }

            // Finish: invoke the optional callback
            OnExecuted?.Invoke();
        }
예제 #15
0
 /// <summary>
 /// Creates a new ShareFileCopyInfo instance for mocking.
 /// </summary>
 public static ShareFileCopyInfo ShareFileCopyInfo(
     ETag eTag,
     DateTimeOffset lastModified,
     string copyId,
     CopyStatus copyStatus)
 {
     return(new ShareFileCopyInfo()
     {
         ETag = eTag,
         LastModified = lastModified,
         CopyId = copyId,
         CopyStatus = copyStatus,
     });
 }
예제 #16
0
        private void CalcQETagButton_Click(object sender, RoutedEventArgs e)
        {
            string fileName = this.QETagSourceFileTextBox.Text;

            if (File.Exists(fileName))
            {
                try
                {
                    string qetag = ETag.CalcHash(fileName);
                    this.QETagResultTextBox.Text = qetag;
                }
                catch (Exception) { }
            }
        }
 public override int CalculateVersion()
 {
     return(new
     {
         DocumentationUri,
         Patch = Patch.GetETagHashCode(),
         Bulk = Bulk.GetETagHashCode(),
         Filter = Filter.GetETagHashCode(),
         ChangePassword = ChangePassword.GetETagHashCode(),
         Sort = Sort.GetETagHashCode(),
         ETag = ETag.GetETagHashCode(),
         AuthenticationSchemes = AuthenticationSchemes.GetMultiValuedAttributeCollectionVersion()
     }.GetHashCode());
 }
        public void ApplyToNonGenericThrows_IfPassedAnIQueryableOfTheWrongType()
        {
            // Arrange
            ETag <Customer> etagCustomer = new ETag <Customer> {
                IsIfNoneMatch = true
            };
            IQueryable query = Enumerable.Empty <int>().AsQueryable();

            // Act & Assert
            ExceptionAssert.Throws <ArgumentException>(
                () => etagCustomer.ApplyTo(query),
                "Cannot apply ETag of 'Microsoft.AspNet.OData.Test.Formatter.Serialization.Models.Customer' to IQueryable of " +
                "'System.Int32'.\r\nParameter name: query");
        }
        public void GetETag_Returns_ETagInHeader_ForDouble(double value, bool isEqual)
        {
            // Arrange
            Dictionary <string, object> properties = new Dictionary <string, object> {
                { "Version", value }
            };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);

            var builder = new ODataConventionModelBuilder();

            builder.EntitySet <MyEtagCustomer>("Customers");
            IEdmModel               model       = builder.GetEdmModel();
            IEdmEntityType          customer    = model.SchemaElements.OfType <IEdmEntityType>().FirstOrDefault(e => e.Name == "MyEtagCustomer");
            IEdmEntitySet           customers   = model.FindDeclaredEntitySet("Customers");
            Mock <ODataPathSegment> mockSegment = new Mock <ODataPathSegment> {
                CallBase = true
            };

            mockSegment.Setup(s => s.GetEdmType(null)).Returns(customer);
            mockSegment.Setup(s => s.GetNavigationSource(null)).Returns(customers);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });

            HttpRequestMessage request      = new HttpRequestMessage();
            HttpConfiguration  cofiguration = new HttpConfiguration();

            request.SetConfiguration(cofiguration);
            request.ODataProperties().Path  = odataPath;
            request.ODataProperties().Model = model;

            // Act
            ETag    result        = request.GetETag(etagHeaderValue);
            dynamic dynamicResult = result;

            // Assert
            double actual = Assert.IsType <double>(result["Version"]);

            Assert.Equal(actual, dynamicResult.Version);

            if (isEqual)
            {
                Assert.Equal(value, actual);
            }
            else
            {
                Assert.NotEqual(value, actual);

                Assert.True(actual - value < 0.0000001);
            }
        }
예제 #20
0
        public async Task GivenAgentAssignment_WhenRoundTrip_ShouldSucceed()
        {
            // Arrange
            IWatcherRepository watcherRepository = new CosmosWatcherRepository(_watcherOption, _loggerFactory);
            await watcherRepository.Database.Delete(_databaseName, CancellationToken.None);

            IRecordContainer <TraceRecord> container = await watcherRepository.Container.Create <TraceRecord>(_databaseName);

            container.Should().NotBeNull();

            // Act - Write
            var record = new TraceRecord
            {
                Id             = Guid.NewGuid().ToString(),
                AgentId        = "agent",
                TargetId       = "target",
                Url            = "http://localhost",
                HttpStatusCode = HttpStatusCode.BadRequest,
                Body           = "this is the body",
                TargetState    = TargetState.Ok.ToString(),
            };

            ETag etag = await container.Set(record);

            etag.Should().NotBeNull();
            etag.Value.Should().NotBeEmpty();

            IReadOnlyList <TraceRecord> activeList = await container.Search("select * from ROOT");

            activeList.Should().NotBeNull();
            activeList.Count.Should().Be(1);

            // Act - Read
            Record <TraceRecord>?read = await container.Get(record.Id);

            read.Should().NotBeNull();
            (read !.Value == record).Should().BeTrue();

            // Act - Delete
            (await container.Delete(record.Id, etag)).Should().BeTrue();

            IReadOnlyList <TraceRecord> deleteList = await container.Search("select * from ROOT");

            deleteList.Should().NotBeNull();
            deleteList.Count.Should().Be(0);

            // Clean up
            (await watcherRepository.Database.Delete(_databaseName, CancellationToken.None)).Should().BeTrue();
        }
예제 #21
0
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // Arrange
            HttpRequestMessage request      = new HttpRequestMessage();
            HttpConfiguration  cofiguration = new HttpConfiguration();

            request.SetConfiguration(cofiguration);
            Dictionary <string, object> properties = new Dictionary <string, object> {
                { "Name", "Foo" }
            };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);

            if (header.Equals("IfMatch"))
            {
                request.Headers.IfMatch.Add(etagHeaderValue);
            }
            else
            {
                request.Headers.IfNoneMatch.Add(etagHeaderValue);
            }

            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.Entity <Customer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            IEdmModel model = builder.GetEdmModel();

            Mock <ODataPathSegment> mockSegment = new Mock <ODataPathSegment> {
                CallBase = true
            };

            mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer)));
            mockSegment.Setup(s => s.GetEntitySet(null)).Returns((IEdmEntitySet)null);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });

            request.ODataProperties().Path = odataPath;
            ODataQueryContext context      = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request);
            ETag    result        = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
예제 #22
0
 public virtual void DeleteEntity(string partitionKey, string rowKey, ETag ifMatch = default)
 {
     _batchOperations.AddDeleteEntityRequest(
         _changeset,
         _table,
         partitionKey,
         rowKey,
         ifMatch.ToString(),
         null,
         null,
         queryOptions: new QueryOptions()
     {
         Format = _format
     });
 }
예제 #23
0
        public void ApplyTo_SameQueryReturned_GivenQueryableAndETagAny()
        {
            // Arrange
            var any = new ETag {
                IsAny = true
            };
            var customers = _customers.AsQueryable();

            // Act
            var queryable = any.ApplyTo(customers);

            // Assert
            Assert.NotNull(queryable);
            Assert.Same(queryable, customers);
        }
        /// <summary>
        /// Deletes file or folder in the remote storage.
        /// </summary>
        internal async Task <bool> DeleteAsync()
        {
            if (!FsPath.AvoidSync(userFileSystemPath))
            {
                IUserFileSystemItem userFileSystemItem = await virtualDrive.GetItemAsync <IUserFileSystemItem>(userFileSystemPath);

                await userFileSystemItem.DeleteAsync();

                ETag.DeleteETag(userFileSystemPath);

                return(true);
            }

            return(false);
        }
        public UploadingFileViewModel(string targetPath, string filePath) : base()
        {
            TargetPath    = targetPath;
            LocalFilePath = filePath;
            Name          = Path.GetFileName(filePath);
            string hash = ETag.ComputeEtag(filePath);
            GenericResult <UploadToken> x = fileSystem.UploadFile(Name, parentPath: targetPath, hash: hash, originalFilename: Name).Result;

            if (x.Result.HashCached)
            {
                task = new HashCachedTask();
                return;
            }
            task = EzWcs.EzWcs.NewTask(filePath, x.Result.UploadInfo.Token, x.Result.UploadInfo.UploadUrl);
        }
        public async Task <Response> Get(
            ReadStreamMessageByStreamVersionOperation operation,
            CancellationToken cancellationToken)
        {
            var message = await operation.Invoke(_streamStore, cancellationToken);

            var links = Links
                        .FromPath(operation.Path)
                        .Index()
                        .Find()
                        .Browse()
                        .StreamMessageNavigation(message, operation);

            if (message.MessageId == Guid.Empty)
            {
                return(new HalJsonResponse(
                           new HALResponse(new
                {
                    operation.StreamId,
                    operation.StreamVersion
                })
                           .AddLinks(links),
                           404));
            }

            if (operation.StreamVersion == StreamVersion.End)
            {
                return(new TemporaryRedirectResponse($"{message.StreamVersion}"));
            }

            var payload = await message.GetJsonData(cancellationToken);

            var eTag = ETag.FromStreamVersion(message.StreamVersion);

            return(new HalJsonResponse(
                       new StreamMessageHALResponse(message, payload)
                       .AddEmbeddedResource(
                           Constants.Relations.DeleteMessage,
                           DeleteStreamMessage)
                       .AddLinks(links))
            {
                Headers =
                {
                    eTag,
                    CacheControl.OneYear
                }
            });
        }
        /// <summary>
        /// Gets the OData <see cref="ETag"/> from the given request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="entityTagHeaderValue">The entity tag header value.</param>
        /// <returns>The parsed <see cref="ETag"/>.</returns>
        public static ETag GetETag(this HttpRequestMessage request, EntityTagHeaderValue entityTagHeaderValue)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (entityTagHeaderValue != null)
            {
                HttpConfiguration configuration = request.GetConfiguration();
                if (configuration == null)
                {
                    throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
                }

                // get the etag handler, and parse the etag
                IDictionary <string, object> properties =
                    configuration.GetETagHandler().ParseETag(entityTagHeaderValue) ?? new Dictionary <string, object>();
                IList <object> parsedETagValues = properties.Select(property => property.Value).AsList();

                // get property names from request
                ODataPath      odataPath = request.ODataProperties().Path;
                IEdmEntityType type      = odataPath.EdmType as IEdmEntityType;
                if (type != null)
                {
                    IList <string> concurrencyPropertyNames =
                        type.GetConcurrencyProperties().OrderBy(c => c.Name).Select(c => c.Name).AsList();
                    ETag etag = new ETag();

                    if (parsedETagValues.Count != concurrencyPropertyNames.Count)
                    {
                        etag.IsWellFormed = false;
                    }

                    IEnumerable <KeyValuePair <string, object> > nameValues = concurrencyPropertyNames.Zip(
                        parsedETagValues,
                        (name, value) => new KeyValuePair <string, object>(name, value));
                    foreach (var nameValue in nameValues)
                    {
                        etag[nameValue.Key] = nameValue.Value;
                    }

                    return(etag);
                }
            }

            return(null);
        }
예제 #28
0
        /// <summary>
        /// Check the central repository for configuration changes and update the local cache
        /// </summary>
        private async Task CheckForConfigurationChangesAsync()
        {
            try
            {
                // It is assumed that updates are infrequent.
                // To avoid race conditions in refreshing the cache synchronize access to the in memory cache
                await this.syncCacheSemaphore.WaitAsync();

                var latestVersion = await this.settings.GetVersionAsync();

                // If the versions are the same, nothing has changed in the configuration.
                if (this.currentVersion == latestVersion)
                {
                    return;
                }

                // Get the latest settings from the settings store and publish changes.
                var latestSettings = await this.settings.FindAllAsync();

                // Refresh the settings cache.
                try
                {
                    this.settingsCacheLock.EnterWriteLock();

                    if (this.settingsCache != null)
                    {
                        //Notify settings changed
                        latestSettings.Except(this.settingsCache).ToList().ForEach(kv => this.changed.OnNext(kv));
                    }
                    this.settingsCache = latestSettings;
                }
                finally
                {
                    this.settingsCacheLock.ExitWriteLock();
                }

                // Update the current version.
                this.currentVersion = latestVersion;
            }
            catch (Exception ex)
            {
                this.changed.OnError(ex);
            }
            finally
            {
                this.syncCacheSemaphore.Release();
            }
        }
예제 #29
0
        private IReadOnlyDictionary <string, object> GetOriginalValues()
        {
            Dictionary <string, object> originalValues = new Dictionary <string, object>();

            EntityTagHeaderValue etagHeaderValue = this.Request.Headers.IfMatch.SingleOrDefault();

            if (etagHeaderValue != null)
            {
                ETag etag = this.Request.GetETag(etagHeaderValue);
                etag.ApplyTo(originalValues);

                originalValues.Add(ETagHeaderKey, etagHeaderValue.Tag);
            }

            return(originalValues);
        }
예제 #30
0
 public virtual void UpdateEntity <T>(T entity, ETag ifMatch, TableUpdateMode mode = TableUpdateMode.Merge) where T : class, ITableEntity, new()
 {
     _batchOperations.AddUpdateEntityRequest(
         _changeset,
         _table,
         entity.PartitionKey,
         entity.RowKey,
         null,
         null,
         ifMatch.ToString(),
         tableEntityProperties: entity.ToOdataAnnotatedDictionary(),
         queryOptions: new QueryOptions()
     {
         Format = _format
     });
 }
예제 #31
0
 public static BlobContentInfo BlobContentInfo(
     ETag eTag,
     DateTimeOffset lastModified,
     byte[] contentHash,
     string encryptionKeySha256,
     string encryptionScope,
     long blobSequenceNumber)
 => new BlobContentInfo()
 {
     ETag                = eTag,
     LastModified        = lastModified,
     ContentHash         = contentHash,
     EncryptionKeySha256 = encryptionKeySha256,
     EncryptionScope     = encryptionScope,
     BlobSequenceNumber  = blobSequenceNumber,
 };
예제 #32
0
        public async Task SaveAsync(Type aggregateType, IAggregateIdentity aggregateId, ICollection <IEvent> events, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (events.Count == 0)
            {
                return;
            }

            var partition = GetPartition(aggregateType, aggregateId);

            lock (eventStore)
            {
                Tuple <ETag, List <EventEntity> > eTaggedEvents;
                if (eventStore.TryGetValue(partition, out eTaggedEvents))
                {
                    // Check my last ETag against the current ETag
                    var  dbETag = eTaggedEvents.Item1;
                    ETag myETag;
                    if (idToETag.TryGetValue(aggregateId, out myETag) && myETag != dbETag)
                    {
                        throw new Ddd.Domain.Exceptions.ConcurrencyException(aggregateType, aggregateId);
                    }

                    var eventsEntities = eTaggedEvents.Item2;
                    var lastVer        = eventsEntities.Count;

                    eventsEntities.AddRange(events.Select(e => ToEventEntity(e, ++lastVer)));

                    var eTag = ETag.NewGuid();
                    eventStore[partition] = new Tuple <ETag, List <EventEntity> >(
                        eTag,
                        eventsEntities);
                    idToETag[aggregateId] = eTag; // Remeber current ETag
                }
                else
                {
                    var eTag           = ETag.NewGuid();
                    var lastVer        = 0;
                    var eventsEntities = events.Select(e => ToEventEntity(e, ++lastVer)).ToList();
                    eventStore.Add(partition, new Tuple <ETag, List <EventEntity> >(
                                       eTag,
                                       eventsEntities));
                    idToETag.Add(aggregateId, eTag); // Remeber current ETag
                }
            }

            await bus.PublishAsync(events);
        }
 /// <summary>
 /// Creates a new FileDownloadDetails instance for mocking.
 /// </summary>
 public static FileDownloadDetails FileDownloadDetails(
     DateTimeOffset lastModified,
     IDictionary <string, string> metadata,
     string contentRange,
     ETag eTag,
     string contentEncoding,
     string cacheControl,
     string contentDisposition,
     string contentLanguage,
     DateTimeOffset copyCompletionTime,
     string copyStatusDescription,
     string copyId,
     string copyProgress,
     Uri copySource,
     CopyStatus copyStatus,
     LeaseDurationType leaseDuration,
     LeaseState leaseState,
     LeaseStatus leaseStatus,
     string acceptRanges,
     bool isServerEncrypted,
     string encryptionKeySha256,
     byte[] contentHash)
 => new FileDownloadDetails()
 {
     LastModified          = lastModified,
     Metadata              = metadata,
     ContentRange          = contentRange,
     ETag                  = eTag,
     ContentEncoding       = contentEncoding,
     CacheControl          = cacheControl,
     ContentDisposition    = contentDisposition,
     ContentLanguage       = contentLanguage,
     CopyCompletedOn       = copyCompletionTime,
     CopyStatusDescription = copyStatusDescription,
     CopyId                = copyId,
     CopyProgress          = copyProgress,
     CopySource            = copySource,
     CopyStatus            = copyStatus,
     LeaseDuration         = leaseDuration,
     LeaseState            = leaseState,
     LeaseStatus           = leaseStatus,
     AcceptRanges          = acceptRanges,
     IsServerEncrypted     = isServerEncrypted,
     EncryptionKeySha256   = encryptionKeySha256,
     ContentHash           = contentHash
 };
 public static ConfigurationSetting ConfigurationSetting(
     string key,
     string value,
     string label                = null,
     string contentType          = null,
     ETag eTag                   = default,
     DateTimeOffset?lastModified = null,
     bool?locked                 = null)
 {
     return(new ConfigurationSetting(key, value, label)
     {
         ContentType = contentType,
         ETag = eTag,
         LastModified = lastModified,
         Locked = locked
     });
 }
 /// <summary>
 /// Creates a new BlobChangeFeedEventData instance for mocking.
 /// </summary>
 public static BlobChangeFeedEventData BlobChangeFeedEventData(
     string blobOperationName,
     string clientRequestId,
     Guid requestId,
     ETag eTag,
     string contentType,
     long contentLength,
     BlobType blobType,
     string blobVersion,
     string containerVersion,
     AccessTier?blobAccessTier,
     long contentOffset,
     Uri destinationUri,
     Uri sourceUri,
     Uri uri,
     bool recursive,
     string sequencer,
     ChangeFeedEventPreviousInfo previousInfo,
     string snapshot,
     Dictionary <string, BlobChangeFeedEventUpdatedBlobProperty> updatedBlobProperties,
     BlobChangeFeedEventAsyncOperationInfo asyncOperationInfo,
     BlobChangeFeedEventUpdatedBlobTags updatedBlobTags)
 => new BlobChangeFeedEventData
 {
     BlobOperationName = blobOperationName,
     ClientRequestId   = clientRequestId,
     RequestId         = requestId,
     ETag             = eTag,
     ContentType      = contentType,
     ContentLength    = contentLength,
     BlobType         = blobType,
     BlobVersion      = blobVersion,
     ContainerVersion = containerVersion,
     BlobAccessTier   = blobAccessTier,
     ContentOffset    = contentOffset,
     DestinationUri   = destinationUri,
     SourceUri        = sourceUri,
     Uri                   = uri,
     Recursive             = recursive,
     Sequencer             = sequencer,
     PreviousInfo          = previousInfo,
     Snapshot              = snapshot,
     UpdatedBlobProperties = updatedBlobProperties,
     AsyncOperationInfo    = asyncOperationInfo,
     UpdatedBlobTags       = updatedBlobTags
 };
예제 #36
0
        /// <summary>
        /// Deletes an existing <see cref="ConfigurationSetting"/> in the configuration store.
        /// </summary>
        /// <param name="key">The primary identifier of a configuration setting.</param>
        /// <param name="label">The value used to group configuration settings.</param>
        /// <param name="etag">The value of an etag indicates the state of a configuration setting within a configuration store.
        /// If it is specified, the configuration setting is only deleted if etag value matches etag value in the configuration store.
        /// If no etag value is passed in, then the setting is always deleted.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        public virtual Response Delete(string key, string label = default, ETag etag = default, CancellationToken cancellationToken = default)
        {
            using (Request request = CreateDeleteRequest(key, label, etag))
            {
                Response response = _pipeline.SendRequest(request, cancellationToken);

                switch (response.Status)
                {
                case 200:
                case 204:
                    return(response);

                default:
                    throw response.CreateRequestFailedException();
                }
            }
        }
예제 #37
0
        public TableEntityWrapper(TableEntity entity)
        {
            PartitionKey = entity.PartitionKey;
            RowKey       = entity.RowKey;
            Timestamp    = entity.Timestamp;
            ETag         = entity.ETag;

            foreach (string key in entity.Keys)
            {
                if (KEYWORDS.Contains(key))
                {
                    continue;
                }

                this[key] = entity[key].ToString();
            }
        }
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            builder.EntitySet <Customer>("Customers");
            IEdmModel model = builder.GetEdmModel();

            var customers = model.FindDeclaredEntitySet("Customers");

            var request = RequestFactory.CreateFromModel(model);

            EntitySetSegment entitySetSegment = new EntitySetSegment(customers);
            ODataPath        odataPath        = new ODataPath(new[] { entitySetSegment });

            request.ODataContext().Path = odataPath;

            Dictionary <string, object> properties = new Dictionary <string, object> {
                { "Name", "Foo" }
            };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);

            if (header.Equals("IfMatch"))
            {
                request.Headers.AddIfMatch(etagHeaderValue);
            }
            else
            {
                request.Headers.AddIfNoneMatch(etagHeaderValue);
            }

            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request);
            ETag    result        = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
예제 #39
0
        public IActionResult Get()
        {
            var conditionalDirective = Request.ReadConditionalReqeustDirective();

            var responseHeaders = Response.GetTypedHeaders();
            var maxAge = TimeSpan.FromMinutes(10);
            responseHeaders.CacheControl = new CacheControlHeaderValue
            {
                NoCache = true,
                MaxAge = maxAge,
                SharedMaxAge = TimeSpan.FromMinutes(3),
            };
            var lastModified = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(30));
            var etag = new ETag("backend1", isWeak: false);
            responseHeaders.ETag = etag.ToETagHeaderValue();
            responseHeaders.LastModified = lastModified;
            responseHeaders.Expires = DateTimeOffset.UtcNow + maxAge;
            Response.Headers[HeaderNames.Age] = 30.ToString();

            var status = conditionalDirective.ShouldPerformRequest(CurrentRepresentation.Existing(lastModified, etag)) ? StatusCodes.Status200OK : StatusCodes.Status304NotModified;
            return BuildBackendResult(status);
        }
 public bool Equals(ETag other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return Equals(other.value, value);
 }
예제 #41
0
            public void WhenOtherTagIsNull_ReturnsFalse()
            {
                var t1 = new ETag("abc", isWeak: false);

                Assert.False(t1.Equals((ETag)null));
            }
 static List<ETag[]> SplitTagsInCollection(int count, Func<ETag, ETag[]> etagSplitter, ICollection<ETag> tags)
 {
     var result = new List<ETag[]>();
     if (tags.Contains(ETag.Any))
     {
         var split = new ETag[count];
         for (int i = 0; i < split.Length; i++)
         {
             split[i] = ETag.Any;
         }
         result.Add(split);
     }
     else
     {
         foreach (var t in tags)
         {
             var split = etagSplitter(t);
             if (split == null)
                 throw new InvalidOperationException("The result of a tag split cannot be null.");
             if (split.Length != count)
                 throw new InvalidOperationException($"The tag {t} was split into an unexpected number of components. Expected {count} and received {split.Length}.");
             result.Add(split);
         }
     }
     return result;
 }
예제 #43
0
            public void WhenBothTagsAreStrong_AndHaveTheSameValue_IsEqual()
            {
                var t1 = new ETag("abc", isWeak: false);
                var t2 = new ETag("abc", isWeak: false);

                Assert.True(t1.Equals((object)t2));
            }
예제 #44
0
            public void WhenOtherTagIsNull_ReturnsFalse()
            {
                var t1 = new ETag("abc", isWeak: false);

                Assert.False(StrongETagComparer.Instace.Equals(t1, (ETag)null));
            }
예제 #45
0
            public void WhenOtherObjectIsDifferentType_ReturnsFalse(object other)
            {
                var t1 = new ETag("abc", isWeak: false);

                Assert.False(t1.Equals(other));
            }
예제 #46
0
            public void WhenTagsHaveDifferentValues_RegardlessOfStrength_IsNotEqual(bool isWeak1, bool isWeak2)
            {
                var t1 = new ETag("abc", isWeak: isWeak1);
                var t2 = new ETag("ABC", isWeak: isWeak2);

                Assert.False(t1.Equals((object)t2));
            }
            public void WhenIfNoneMatchAnyTagPresent_AndRepresentationExists_ReturnsFalse(ETag eTag)
            {
                safeRequestDirective.IfNoneMatch.Add(ETag.Any);

                Assert.False(safeRequestDirective.ShouldPerformRequest(CurrentRepresentation.Existing(eTag: eTag)));
            }
 static bool AnyMatchInCollection(ICollection<ETag> tags, ETag tag, IEqualityComparer<ETag> comparer)
 {
     return tags.Contains(tag, comparer);
 }
            public void ConvertsEtag(EntityTagHeaderValue input, ETag expectedOutput)
            {
                var result = SystemNetHttpExtensions.ToETag(input);

                Assert.Equal(expectedOutput.IsWeak, result.IsWeak);
                Assert.Equal(expectedOutput.Value, result.Value);
            }
예제 #50
0
 // 인덱스로부터 Tag 값을 얻는다.
 public static string GetTagFromIndex(ETag eTag_)
 {
     return m_strTagText[(int)eTag_];
 }
예제 #51
0
            public void ConvertsEtag(ETag input, EntityTagHeaderValue expectedOutput)
            {
                var result = DnxExtensions.ToETagHeaderValue(input);

                Assert.Equal(expectedOutput.IsWeak, result.IsWeak);
                Assert.Equal(expectedOutput.Tag, result.Tag);
            }
            public void WhenIfMatchAnyTagPresent_AndHasRepresentation_ReturnsTrue(ETag eTag)
            {
                safeRequestDirective.IfMatch.Add(ETag.Any);

                Assert.True(safeRequestDirective.ShouldPerformRequest(CurrentRepresentation.Existing(eTag: eTag)));
            }