private void Init()
 {
     // Instantiate the partition resolver as if it is not instantiated on initialization,
     // queries and inserts will fail.
     _partitionResolver = DocumentDbUtil.CreateHashPartitionResolver(Client, Database,
                                                                     _partitionKeyExtractor, PartitionCollectionsSelfLinks);
 }
Example #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TransitionHashPartitionResolver" /> class.
 /// </summary>
 /// <param name="current">The current IPartitionResolver.</param>
 /// <param name="next">The next IPartitionResolver.</param>
 /// <param name="readMode">How to handle read requests during transition.</param>
 public TransitionHashPartitionResolver(
     IPartitionResolver current,
     IPartitionResolver next,
     TransitionReadMode readMode = TransitionReadMode.ReadBoth)
 {
     this.CurrentResolver = current;
     this.NextResolver    = next;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TransitionHashPartitionResolver" /> class.
 /// </summary>
 /// <param name="current">The current IPartitionResolver.</param>
 /// <param name="next">The next IPartitionResolver.</param>
 /// <param name="readMode">How to handle read requests during transition.</param>
 public TransitionHashPartitionResolver(
     IPartitionResolver current,
     IPartitionResolver next,
     TransitionReadMode readMode = TransitionReadMode.ReadBoth)
 {
     this.CurrentResolver = current;
     this.NextResolver = next;
     this.ReadMode = readMode;
 }
Example #4
0
        public async Task InitializeAsync()
        {
            var collectionLinks = new List <string>();

            foreach (var collection in Configuration.Collections)
            {
                collectionLinks.Add(await Client.GetOrCreateCollectionAsync(collection, Configuration.CollectionTier));
            }

            partitionResolver = PartitionResolverFactory.Instance.Create(Configuration.PartitionKey, collectionLinks);
        }
Example #5
0
        /// <summary>
        /// Run examples of how to perform create, read, update, delete and query documents against a partitioned database.
        /// </summary>
        /// <param name="database">The database to run the samples on.</param>
        /// <param name="partitionResolver">The PartitionResolver instance to use.</param>
        /// <returns>The Task for asynchronous execution of these samples.</returns>
        private async Task RunCrudAndQuerySample(Database database, IPartitionResolver partitionResolver)
        {
            // Create some documents. Note that creates use the database's self link instead of a specific collection's self link.
            // The hash resolver will compute the hash of UserId in order to route the create to either of the collections.
            Document johnDocument = await this.client.CreateDocumentAsync(database.SelfLink, new UserProfile("J1", "@John", Region.UnitedStatesEast));

            Document ryanDocument = await this.client.CreateDocumentAsync(database.SelfLink, new UserProfile("U4", "@Ryan", Region.AsiaPacific, UserStatus.AppearAway));

            // Delete document using self link (as usual).
            await this.client.DeleteDocumentAsync(ryanDocument.SelfLink);

            // Read, then update status using self link (as usual).
            Document latestJohnDocument = await this.client.ReadDocumentAsync(johnDocument.SelfLink);

            UserProfile johnProfile = (UserProfile)(dynamic)latestJohnDocument;

            johnProfile.Status = UserStatus.Busy;

            await this.client.ReplaceDocumentAsync(latestJohnDocument.SelfLink, johnProfile);

            // Query for John's document by ID. We can use the PartitionResolver to restrict the query to just the partition containing @John
            // Again the query uses the database self link, and relies on the hash resolver to route the appropriate collection.
            var query = this.client.CreateDocumentQuery <UserProfile>(database.SelfLink, null, partitionResolver.GetPartitionKey(johnProfile))
                        .Where(u => u.UserName == "@John");

            johnProfile = query.AsEnumerable().FirstOrDefault();

            // Query for all Busy users. Here since there is no partition key, the query is serially executed across each partition/collection.
            query = this.client.CreateDocumentQuery <UserProfile>(database.SelfLink).Where(u => u.Status == UserStatus.Busy);
            foreach (UserProfile busyUser in query)
            {
                Console.WriteLine(busyUser);
            }

            // Find the collections where a document exists in. It's uncommon to do this, but can be useful if for example to execute a
            // stored procedure against a specific set of partitions.
            IPartitionResolver resolver        = this.client.PartitionResolvers[database.SelfLink];
            List <string>      collectionLinks = resolver.ResolveForRead(resolver.GetPartitionKey(johnProfile)).ToList();

            // Find the collections where a document will be created in.
            string collectionLink = resolver.ResolveForCreate(resolver.GetPartitionKey(johnProfile));

            // Cleanup.
            await this.client.DeleteDatabaseAsync(database.SelfLink);
        }
        public async Task InitializeAsync()
        {
            var initializationTasks = new List <Task>();
            var storedProcName      = BulkImportStoredProcPrefix + Guid.NewGuid().ToString("N");
            var collections         = Configuration.Collections.ToList();

            foreach (var collectionName in collections)
            {
                var adapter = new DocumentDbBulkSinkAdapter(Client, PassThroughTransformation.Instance,
                                                            CreateInstanceConfiguration(collectionName, storedProcName));
                dataAdapters.Add(collectionName, adapter);
                initializationTasks.Add(adapter.InitializeAsync());
            }

            partitionResolver = PartitionResolverFactory.Instance.Create(Configuration.PartitionKey, collections);

            await Task.WhenAll(initializationTasks);
        }
        private void InitModuleFromConfig(HttpApplication app, SessionStateSection config)
        {
            if (config.Mode != SessionStateMode.Off)
            {
                app.AddOnAcquireRequestStateAsync(new BeginEventHandler(this.BeginAcquireState), new EndEventHandler(this.EndAcquireState));
                app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
                app.EndRequest          += new EventHandler(this.OnEndRequest);
                this._partitionResolver  = this.InitPartitionResolver(config);
                switch (config.Mode)
                {
                case SessionStateMode.InProc:
                    if (HttpRuntime.UseIntegratedPipeline)
                    {
                        s_canSkipEndRequestCall = true;
                    }
                    this._store = new InProcSessionStateStore();
                    this._store.Initialize(null, null);
                    break;

                case SessionStateMode.StateServer:
                    if (HttpRuntime.UseIntegratedPipeline)
                    {
                        s_canSkipEndRequestCall = true;
                    }
                    this._store = new OutOfProcSessionStateStore();
                    ((OutOfProcSessionStateStore)this._store).Initialize(null, null, this._partitionResolver);
                    break;

                case SessionStateMode.SQLServer:
                    this._store = new SqlSessionStateStore();
                    ((SqlSessionStateStore)this._store).Initialize(null, null, this._partitionResolver);
                    break;

                case SessionStateMode.Custom:
                    this._store = this.InitCustomStore(config);
                    break;
                }
                this._idManager = this.InitSessionIDManager(config);
                if (((config.Mode == SessionStateMode.InProc) || (config.Mode == SessionStateMode.StateServer)) && this._usingAspnetSessionIdManager)
                {
                    this._ignoreImpersonation = true;
                }
            }
        }
        private IPartitionResolver InitPartitionResolver(SessionStateSection config)
        {
            string partitionResolverType = config.PartitionResolverType;

            if (string.IsNullOrEmpty(partitionResolverType))
            {
                return(null);
            }
            if ((config.Mode != SessionStateMode.StateServer) && (config.Mode != SessionStateMode.SQLServer))
            {
                throw new ConfigurationErrorsException(System.Web.SR.GetString("Cant_use_partition_resolve"), config.ElementInformation.Properties["partitionResolverType"].Source, config.ElementInformation.Properties["partitionResolverType"].LineNumber);
            }
            Type type = ConfigUtil.GetType(partitionResolverType, "partitionResolverType", config);

            ConfigUtil.CheckAssignableType(typeof(IPartitionResolver), type, config, "partitionResolverType");
            IPartitionResolver resolver = (IPartitionResolver)HttpRuntime.CreatePublicInstance(type);

            resolver.Initialize();
            return(resolver);
        }
 internal object GetPartition(IPartitionResolver partitionResolver, string id)
 {
     object obj2;
     if (EtwTrace.IsTraceEnabled(5, 1))
     {
         EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_START, HttpContext.Current.WorkerRequest, partitionResolver.GetType().FullName, id);
     }
     string connectionString = null;
     string message = null;
     IPartitionInfo info = null;
     try
     {
         try
         {
             connectionString = partitionResolver.ResolvePartition(id);
             if (connectionString == null)
             {
                 throw new HttpException(System.Web.SR.GetString("Bad_partition_resolver_connection_string", new object[] { partitionResolver.GetType().FullName }));
             }
         }
         catch (Exception exception)
         {
             message = exception.Message;
             throw;
         }
         try
         {
             this._lock.AcquireReaderLock(-1);
             info = (IPartitionInfo) this._partitions[connectionString];
             if (info != null)
             {
                 return info;
             }
         }
         finally
         {
             if (this._lock.IsReaderLockHeld)
             {
                 this._lock.ReleaseReaderLock();
             }
         }
         try
         {
             this._lock.AcquireWriterLock(-1);
             info = (IPartitionInfo) this._partitions[connectionString];
             if (info == null)
             {
                 info = this._createCallback(connectionString);
                 this._partitions.Add(connectionString, info);
             }
             return info;
         }
         finally
         {
             if (this._lock.IsWriterLockHeld)
             {
                 this._lock.ReleaseWriterLock();
             }
         }
     }
     finally
     {
         if (EtwTrace.IsTraceEnabled(5, 1))
         {
             string tracingPartitionString = message;
             if (tracingPartitionString == null)
             {
                 if (info != null)
                 {
                     tracingPartitionString = info.GetTracingPartitionString();
                 }
                 else
                 {
                     tracingPartitionString = string.Empty;
                 }
             }
             EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_END, HttpContext.Current.WorkerRequest, tracingPartitionString);
         }
     }
     return obj2;
 }
        /// <summary>
        /// Run examples of how to perform create, read, update, delete and query documents against a partitioned database. 
        /// </summary>
        /// <param name="database">The database to run the samples on.</param>
        /// <param name="partitionResolver">The PartitionResolver instance to use.</param>
        /// <returns>The Task for asynchronous execution of these samples.</returns>
        private async Task RunCrudAndQuerySample(Database database, IPartitionResolver partitionResolver)
        {
            // Create some documents. Note that creates use the database's self link instead of a specific collection's self link. 
            // The hash resolver will compute the hash of UserId in order to route the create to either of the collections.
            Document johnDocument = await this.client.CreateDocumentAsync(database.SelfLink, new UserProfile("J1", "@John", Region.UnitedStatesEast));
            Document ryanDocument = await this.client.CreateDocumentAsync(database.SelfLink, new UserProfile("U4", "@Ryan", Region.AsiaPacific, UserStatus.AppearAway));

            // Delete document using self link (as usual).
            await this.client.DeleteDocumentAsync(ryanDocument.SelfLink);

            // Read, then update status using self link (as usual).
            Document latestJohnDocument = await this.client.ReadDocumentAsync(johnDocument.SelfLink);
            UserProfile johnProfile = (UserProfile)(dynamic)latestJohnDocument;
            johnProfile.Status = UserStatus.Busy;

            await this.client.ReplaceDocumentAsync(latestJohnDocument.SelfLink, johnProfile);

            // Query for John's document by ID. We can use the PartitionResolver to restrict the query to just the partition containing @John
            // Again the query uses the database self link, and relies on the hash resolver to route the appropriate collection.
            var query = this.client.CreateDocumentQuery<UserProfile>(database.SelfLink, null, partitionResolver.GetPartitionKey(johnProfile))
                .Where(u => u.UserName == "@John");
            johnProfile = query.AsEnumerable().FirstOrDefault();

            // Query for all Busy users. Here since there is no partition key, the query is serially executed across each partition/collection. 
            query = this.client.CreateDocumentQuery<UserProfile>(database.SelfLink).Where(u => u.Status == UserStatus.Busy);
            foreach (UserProfile busyUser in query)
            {
                Console.WriteLine(busyUser);
            }
             
            // Find the collections where a document exists in. It's uncommon to do this, but can be useful if for example to execute a 
            // stored procedure against a specific set of partitions.
            IPartitionResolver resolver = this.client.PartitionResolvers[database.SelfLink];
            List<string> collectionLinks = resolver.ResolveForRead(resolver.GetPartitionKey(johnProfile)).ToList();

            // Find the collections where a document will be created in.
            string collectionLink = resolver.ResolveForCreate(resolver.GetPartitionKey(johnProfile));

            // Cleanup.
            await this.client.DeleteDatabaseAsync(database.SelfLink);
        }
 internal virtual void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver)
 {
 }
 internal override void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver) {
     _partitionResolver = partitionResolver;
     Initialize(name, config);
 }
        internal object GetPartition(IPartitionResolver partitionResolver, string id) {
            if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure))
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_START, HttpContext.Current.WorkerRequest, partitionResolver.GetType().FullName, id);
            
            string partitionString = null;
            string errorMessage = null;
            IPartitionInfo partitionInfo = null;
            try {
                try {
                    partitionString = partitionResolver.ResolvePartition(id);

                    if (partitionString == null) {
                        throw new HttpException(
                                SR.GetString(SR.Bad_partition_resolver_connection_string, partitionResolver.GetType().FullName));
                    }
                }
                catch (Exception e) {
                    errorMessage = e.Message;
                    throw;
                }

                try {
                    _lock.AcquireReaderLock(-1);
                    partitionInfo = (IPartitionInfo)_partitions[partitionString];
                    if (partitionInfo != null) {
                        Debug.Trace("PartitionManager", "id=" + id + "; partitionString=" + partitionString);
                        return partitionInfo;
                    }

                }
                finally {
                    if (_lock.IsReaderLockHeld) {
                        _lock.ReleaseReaderLock();
                    }
                }

                // Not found.  Has to add it.
                try {
                    _lock.AcquireWriterLock(-1);
                    // One more time
                    partitionInfo = (IPartitionInfo)_partitions[partitionString];
                    if (partitionInfo == null) {
                        partitionInfo = _createCallback(partitionString);

                        Debug.Trace("PartitionManager", "Add a new partition; id=" + id + "; partitionString=" + partitionString);
                        _partitions.Add(partitionString, partitionInfo);
                    }

                    Debug.Trace("PartitionManager", "id=" + id + "; partitionString=" + partitionString);
                    return partitionInfo;
                }
                finally {
                    if (_lock.IsWriterLockHeld) {
                        _lock.ReleaseWriterLock();
                    }
                }
            }
            finally {
                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure)) {
                    string msg = errorMessage;
                    if (msg == null) {
                        if (partitionInfo != null) {
                            msg = partitionInfo.GetTracingPartitionString();
                        }
                        else {
                            msg = String.Empty;
                        }
                    }
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_END, HttpContext.Current.WorkerRequest, msg);
                }
            }
        }
        private void InitModuleFromConfig(HttpApplication app, SessionStateSection config)
        {
            if (config.Mode != SessionStateMode.Off)
            {
                app.AddOnAcquireRequestStateAsync(new BeginEventHandler(this.BeginAcquireState), new EndEventHandler(this.EndAcquireState));
                app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
                app.EndRequest += new EventHandler(this.OnEndRequest);
                this._partitionResolver = this.InitPartitionResolver(config);
                switch (config.Mode)
                {
                    case SessionStateMode.InProc:
                        if (HttpRuntime.UseIntegratedPipeline)
                        {
                            s_canSkipEndRequestCall = true;
                        }
                        this._store = new InProcSessionStateStore();
                        this._store.Initialize(null, null);
                        break;

                    case SessionStateMode.StateServer:
                        if (HttpRuntime.UseIntegratedPipeline)
                        {
                            s_canSkipEndRequestCall = true;
                        }
                        this._store = new OutOfProcSessionStateStore();
                        ((OutOfProcSessionStateStore) this._store).Initialize(null, null, this._partitionResolver);
                        break;

                    case SessionStateMode.SQLServer:
                        this._store = new SqlSessionStateStore();
                        ((SqlSessionStateStore) this._store).Initialize(null, null, this._partitionResolver);
                        break;

                    case SessionStateMode.Custom:
                        this._store = this.InitCustomStore(config);
                        break;
                }
                this._idManager = this.InitSessionIDManager(config);
                if (((config.Mode == SessionStateMode.InProc) || (config.Mode == SessionStateMode.StateServer)) && this._usingAspnetSessionIdManager)
                {
                    this._ignoreImpersonation = true;
                }
            }
        }
Example #15
0
 internal override void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver)
 {
     _partitionResolver = partitionResolver;
     Initialize(name, config);
 }
Example #16
0
        internal object GetPartition(IPartitionResolver partitionResolver, string id)
        {
            object obj2;

            if (EtwTrace.IsTraceEnabled(5, 1))
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_START, HttpContext.Current.WorkerRequest, partitionResolver.GetType().FullName, id);
            }
            string         connectionString = null;
            string         message          = null;
            IPartitionInfo info             = null;

            try
            {
                try
                {
                    connectionString = partitionResolver.ResolvePartition(id);
                    if (connectionString == null)
                    {
                        throw new HttpException(System.Web.SR.GetString("Bad_partition_resolver_connection_string", new object[] { partitionResolver.GetType().FullName }));
                    }
                }
                catch (Exception exception)
                {
                    message = exception.Message;
                    throw;
                }
                try
                {
                    this._lock.AcquireReaderLock(-1);
                    info = (IPartitionInfo)this._partitions[connectionString];
                    if (info != null)
                    {
                        return(info);
                    }
                }
                finally
                {
                    if (this._lock.IsReaderLockHeld)
                    {
                        this._lock.ReleaseReaderLock();
                    }
                }
                try
                {
                    this._lock.AcquireWriterLock(-1);
                    info = (IPartitionInfo)this._partitions[connectionString];
                    if (info == null)
                    {
                        info = this._createCallback(connectionString);
                        this._partitions.Add(connectionString, info);
                    }
                    return(info);
                }
                finally
                {
                    if (this._lock.IsWriterLockHeld)
                    {
                        this._lock.ReleaseWriterLock();
                    }
                }
            }
            finally
            {
                if (EtwTrace.IsTraceEnabled(5, 1))
                {
                    string tracingPartitionString = message;
                    if (tracingPartitionString == null)
                    {
                        if (info != null)
                        {
                            tracingPartitionString = info.GetTracingPartitionString();
                        }
                        else
                        {
                            tracingPartitionString = string.Empty;
                        }
                    }
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_END, HttpContext.Current.WorkerRequest, tracingPartitionString);
                }
            }
            return(obj2);
        }
 internal virtual void Initialize(string name, NameValueCollection config, IPartitionResolver partitionResolver) {
 }
Example #18
0
        void InitModuleFromConfig(HttpApplication app, SessionStateSection config) {
            if (config.Mode == SessionStateMode.Off) {
                return;
            }

            app.AddOnAcquireRequestStateAsync(
                    new BeginEventHandler(this.BeginAcquireState),
                    new EndEventHandler(this.EndAcquireState));

            app.ReleaseRequestState += new EventHandler(this.OnReleaseState);
            app.EndRequest += new EventHandler(this.OnEndRequest);

            _partitionResolver = InitPartitionResolver(config);

            switch (config.Mode) {
                case SessionStateMode.InProc:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new InProcSessionStateStore();
                    _store.Initialize(null, null);
                    break;

#if !FEATURE_PAL // FEATURE_PAL does not enable out of proc session state
                case SessionStateMode.StateServer:
                    if (HttpRuntime.UseIntegratedPipeline) {
                        s_canSkipEndRequestCall = true;
                    }
                    _store = new OutOfProcSessionStateStore();
                    ((OutOfProcSessionStateStore)_store).Initialize(null, null, _partitionResolver);
                    break;

                case SessionStateMode.SQLServer:
                    _store = new SqlSessionStateStore();
                    ((SqlSessionStateStore)_store).Initialize(null, null, _partitionResolver);
#if DBG
                    ((SqlSessionStateStore)_store).SetModule(this);
#endif
                    break;
#else // !FEATURE_PAL
                case SessionStateMode.StateServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;

                case SessionStateMode.SQLServer:
                    throw new NotImplementedException("ROTORTODO");
                    break;
#endif // !FEATURE_PAL

                case SessionStateMode.Custom:
                    _store = InitCustomStore(config);
                    break;

                default:
                    break;
            }

            // We depend on SessionIDManager to manage session id
            _idManager = InitSessionIDManager(config);

            if ((config.Mode == SessionStateMode.InProc || config.Mode == SessionStateMode.StateServer) &&
                _usingAspnetSessionIdManager) {
                // If we're using InProc mode or StateServer mode, and also using our own session id module,
                // we know we don't care about impersonation in our all session state store read/write
                // and session id read/write.
                _ignoreImpersonation = true;
            }

        }
Example #19
0
        internal object GetPartition(IPartitionResolver partitionResolver, string id)
        {
            if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure))
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_START, HttpContext.Current.WorkerRequest, partitionResolver.GetType().FullName, id);
            }

            string         partitionString = null;
            string         errorMessage    = null;
            IPartitionInfo partitionInfo   = null;

            try {
                try {
                    partitionString = partitionResolver.ResolvePartition(id);

                    if (partitionString == null)
                    {
                        throw new HttpException(
                                  SR.GetString(SR.Bad_partition_resolver_connection_string, partitionResolver.GetType().FullName));
                    }
                }
                catch (Exception e) {
                    errorMessage = e.Message;
                    throw;
                }

                try {
                    _lock.AcquireReaderLock(-1);
                    partitionInfo = (IPartitionInfo)_partitions[partitionString];
                    if (partitionInfo != null)
                    {
                        Debug.Trace("PartitionManager", "id=" + id + "; partitionString=" + partitionString);
                        return(partitionInfo);
                    }
                }
                finally {
                    if (_lock.IsReaderLockHeld)
                    {
                        _lock.ReleaseReaderLock();
                    }
                }

                // Not found.  Has to add it.
                try {
                    _lock.AcquireWriterLock(-1);
                    // One more time
                    partitionInfo = (IPartitionInfo)_partitions[partitionString];
                    if (partitionInfo == null)
                    {
                        partitionInfo = _createCallback(partitionString);

                        Debug.Trace("PartitionManager", "Add a new partition; id=" + id + "; partitionString=" + partitionString);
                        _partitions.Add(partitionString, partitionInfo);
                    }

                    Debug.Trace("PartitionManager", "id=" + id + "; partitionString=" + partitionString);
                    return(partitionInfo);
                }
                finally {
                    if (_lock.IsWriterLockHeld)
                    {
                        _lock.ReleaseWriterLock();
                    }
                }
            }
            finally {
                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.Infrastructure))
                {
                    string msg = errorMessage;
                    if (msg == null)
                    {
                        if (partitionInfo != null)
                        {
                            msg = partitionInfo.GetTracingPartitionString();
                        }
                        else
                        {
                            msg = String.Empty;
                        }
                    }
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSIONSTATE_PARTITION_END, HttpContext.Current.WorkerRequest, msg);
                }
            }
        }