Ejemplo n.º 1
0
        protected InsertRequest CreateInsertRequest(Media media)
        {
            MediaLibContainer context = ContextHelper <MediaLibContainer> .GetCurrentContext();

            InsertRequest insertRequest = new InsertRequest();

            insertRequest.RequestDate = DateTime.Now;
            insertRequest.User        = context.UserSet.First <User>();
            insertRequest.Media       = media;

            context.InsertRequestSet.AddObject(insertRequest);
            context.SaveChanges();

            return(insertRequest);
        }
 internal void ModifyRequest(Table table, InsertRequest request)
 {
     if (Description != null)
     {
         table.Description = Description;
     }
     if (FriendlyName != null)
     {
         table.FriendlyName = FriendlyName;
     }
     if (Expiration != null)
     {
         table.ExpirationTime = (long)(Expiration.Value - UnixEpoch).TotalMilliseconds;
     }
 }
Ejemplo n.º 3
0
        public async Task SendToServer_Dispose_WasNowCatched_ArgumentNullException()
        {
            // arrange
            var request = new InsertRequest();
            var socket  = PrepareSocket(request);

            socket.When(x => x.Dispose()).Do(x => { throw new ArgumentNullException(); });

            var ipEndpoint = new IPEndPoint(IPAddress.Any, 500);

            var service = new Connection(ipEndpoint, 0);

            //  act and assert
            await Assert.ThrowsAsync(typeof(ArgumentNullException), async() => await service.SendAsync(request));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        internal static string GetInsertText(InsertRequest request)
        {
            var commandText = (string)null;

            if (cache.TryGetValue(request, out commandText) == false)
            {
                var fields = GetActualFields(request.Connection,
                                             request.Name,
                                             request.Fields,
                                             request.Transaction);
                commandText = GetInsertTextInternal(request, fields);
                cache.TryAdd(request, commandText);
            }
            return(commandText);
        }
Ejemplo n.º 5
0
        public void Handle_ReturnsTrueWhenElementAdded(bool added)
        {
            // arrange
            var request   = new InsertRequest();
            var processor = new InsertProcessor();
            var storage   = Substitute.For <IStorage>();

            storage.Add(Arg.Any <string>(), Arg.Any <DateTime?>(), Arg.Any <ByteString>()).Returns(added);

            // Act
            InsertResponse response = processor.Reply(request, storage);

            // assert
            Assert.Equal(response.Added, added);
        }
 internal void ModifyRequest(Table table, InsertRequest request)
 {
     if (Description != null)
     {
         table.Description = Description;
     }
     if (FriendlyName != null)
     {
         table.FriendlyName = FriendlyName;
     }
     if (Expiration != null)
     {
         table.ExpirationTime = (long)(Expiration.Value - UnixEpoch).TotalMilliseconds;
     }
     if (TimePartitionType != null)
     {
         if (TimePartitionType.Value == V2.TimePartitionType.None)
         {
             table.TimePartitioning = null;
         }
         else
         {
             table.TimePartitioning = new TimePartitioning {
                 Type = EnumMap.ToApiValue(TimePartitionType.Value)
             };
         }
     }
     if (TimePartitionExpiration != null)
     {
         if (table.TimePartitioning == null)
         {
             throw new ArgumentException($"Cannot specify {nameof(TimePartitionExpiration)} when not using time partitioning.");
         }
         table.TimePartitioning.ExpirationMs = (long)TimePartitionExpiration.Value.TotalMilliseconds;
     }
     if (ExternalDataConfiguration != null && View != null)
     {
         throw new ArgumentException($"Cannot specify both {nameof(ExternalDataConfiguration)} and {nameof(View)}");
     }
     if (ExternalDataConfiguration != null)
     {
         table.ExternalDataConfiguration = ExternalDataConfiguration;
     }
     if (View != null)
     {
         table.View = View;
     }
 }
        public void ModifyRequest()
        {
            var options = new CreateDatasetOptions
            {
                DefaultTableExpiration = TimeSpan.FromSeconds(10),
                Description            = "A description",
                FriendlyName           = "A friendly name"
            };
            Dataset       dataset = new Dataset();
            InsertRequest request = new InsertRequest(new BigqueryService(), dataset, "project");

            options.ModifyRequest(dataset, request);
            Assert.Equal(10 * 1000, dataset.DefaultTableExpirationMs);
            Assert.Equal("A description", dataset.Description);
            Assert.Equal("A friendly name", dataset.FriendlyName);
        }
Ejemplo n.º 8
0
        public void DeclineRequestShouldReturnNotAuthorizedView()
        {
            AdminController adminController = new AdminController(membershipService, insertRequestService, mediaService);

            InsertRequest insertRequest = TestUtil.generateInsertRequest();

            insertRequest.Media = TestUtil.generateTV_Show(true);

            Expect.Call(membershipService.IsAdmin(fakeAdmin.Identity.Name)).Return(false);
            mocks.ReplayAll();

            ViewResult result = adminController.DeclineRequest(7, fakeAdmin) as ViewResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(notAuthorized_ViewName, result.ViewName);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        internal static async Task <string> GetInsertTextAsync(InsertRequest request,
                                                               CancellationToken cancellationToken = default)
        {
            if (cache.TryGetValue(request, out var commandText) == false)
            {
                var fields = await GetActualFieldsAsync(request.Connection,
                                                        request.Name,
                                                        request.Fields,
                                                        request.Transaction,
                                                        cancellationToken);

                commandText = GetInsertTextInternal(request, fields);
                cache.TryAdd(request, commandText);
            }
            return(commandText);
        }
Ejemplo n.º 10
0
        public override async Task <InsertResponse> InsertProductRPC(InsertRequest request, ServerCallContext context)
        {
            ProductRepository productRepository = new ProductRepository();
            var ena = request.Product.EAN.Replace("*", "");

            return(new InsertResponse
            {
                Result = productRepository.InsertProduct(
                    new BarcodeProduct()
                {
                    BarcodeNo = ena,
                    ProductName = request.Product.Name,
                    Description = request.Product.Description
                })
            });
        }
Ejemplo n.º 11
0
        public void PropertiesSetOnRequest()
        {
            var options = new CreateTableOptions
            {
                Expiration   = new DateTimeOffset(1970, 1, 1, 0, 0, 5, 0, TimeSpan.Zero),
                Description  = "A description",
                FriendlyName = "A friendly name"
            };
            Table         table   = new Table();
            InsertRequest request = new InsertRequest(new BigqueryService(), table, "project", "dataset");

            options.ModifyRequest(table, request);
            Assert.Equal(5 * 1000, table.ExpirationTime);
            Assert.Equal("A description", table.Description);
            Assert.Equal("A friendly name", table.FriendlyName);
        }
Ejemplo n.º 12
0
        public ActionResult Post([FromBody] ParticipantMessage message)
        {
            var request = new InsertRequest <ParticipantMessage>()
            {
                Message = message,
                User    = new UserRequest()
                {
                    Principal = this.User,
                    IpAddress = this.HttpContext.Connection.RemoteIpAddress
                }
            };

            var response = _app.Insert(request);

            return(new ApplicationResult <Participant>(response));
        }
        internal void ModifyRequest(Dataset dataset, InsertRequest request)
        {
            if (Description != null)
            {
                dataset.Description = Description;
            }
            if (FriendlyName != null)
            {
                dataset.FriendlyName = FriendlyName;
            }

            if (DefaultTableExpiration != null)
            {
                dataset.DefaultTableExpirationMs = (long)DefaultTableExpiration.Value.TotalMilliseconds;
            }
        }
Ejemplo n.º 14
0
        private string GetInsertStatement(InsertRequest request)
        {
            var type             = request.Items.First().GetType();
            var tableInformation = GetTableName(type);

            List <string> columnNames = new List <string>();
            List <Func <object, string> > columnValues = new List <Func <object, string> >();

            foreach (var property in type.GetProperties())
            {
                var columnNameAttribute = Attribute
                                          .GetCustomAttributes(property, typeof(ColumnNameAttribute))
                                          .Cast <ColumnNameAttribute>()
                                          .FirstOrDefault();

                var columnName = !string.IsNullOrWhiteSpace(columnNameAttribute?.Name)
                    ? columnNameAttribute.Name
                    : property.Name.ToLower();

                columnNames.Add(columnName);

                columnValues.Add(obj =>
                {
                    var value = property.GetValue(obj);
                    if (value == null)
                    {
                        return("null");
                    }

                    return(GetValueText(value));
                });
            }

            var values = request.Items
                         .Select(item => $"({string.Join(",", columnValues.Select(func => func(item)))})");

            var commandString = request.Upsert ? "upsert" : "insert";

            return($@"
{commandString} into
    {tableInformation.Database}.{tableInformation.TableName}
        ({string.Join(", ", columnNames)})
values
    {string.Join(", ", values)};
");
        }
Ejemplo n.º 15
0
        public void ModifyRequest_NoLocation()
        {
            // When the options don't specify a location, we should keep the one in the original Dataset.
            var options = new CreateDatasetOptions
            {
                DefaultTableExpiration = TimeSpan.FromSeconds(10),
                Description            = "A description",
                FriendlyName           = "A friendly name",
            };
            Dataset dataset = new Dataset {
                Location = "US"
            };
            InsertRequest request = new InsertRequest(new BigqueryService(), dataset, "project");

            options.ModifyRequest(dataset, request);
            Assert.Equal("US", dataset.Location);
        }
Ejemplo n.º 16
0
        public override async Task <BaseReply> Insert(InsertRequest request, ServerCallContext context)
        {
            try
            {
                var rows = request.Rows
                           .Select(x => new List <object>(x.Items
                                                          .Select(i =>
                {
                    var res = new object();
                    try
                    {
                        res = JsonSerializer.Deserialize <object>(i);
                    }
                    catch
                    {
                        res = JsonSerializer.Deserialize <object>($"\"{i}\"");
                    }

                    return(res);
                }))).ToList();

                await _tableDal.InsertData(request.TableName, request.DbName, rows);


                var response = new BaseReply()
                {
                    Code = 200
                };

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("***************************************************************************************************************");
                Console.WriteLine("Rows inserted: " + request.TableName + ", " + request.Rows.Count);
                Console.WriteLine("***************************************************************************************************************");

                return(response);
            }
            catch (Exception ex)
            {
                return(new BaseReply()
                {
                    Code = 400, Message = ex.Message, StackTrace = ex.StackTrace
                });
            }
        }
        /// <summary>
        /// Create the firewall rule.
        /// </summary>
        protected override void EndProcessing()
        {
            var firewall = new Firewall
            {
                Name         = Name,
                Allowed      = _allAllowed,
                Description  = Description,
                Network      = Network,
                SourceRanges = SourceRange,
                SourceTags   = SourceTag,
                TargetTags   = TargetTag
            };
            InsertRequest request = Service.Firewalls.Insert(firewall, Project);

            WaitForGlobalOperation(Project, request.Execute());
            WriteObject(Service.Firewalls.Get(Project, Name).Execute());
            base.EndProcessing();
        }
Ejemplo n.º 18
0
        public void SendsDataToTheClient()
        {
            // Arrange
            var request   = new InsertRequest();
            var processor = new FakeProcessor();
            var socket    = Substitute.For <Socket>();

            byte[] expectedBytes = SerializationUtils.SerializeToStreamWithLength(true);

            socket.Send(Arg.Any <byte[]>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <SocketFlags>())
            .Returns(expectedBytes.Length);

            // Act
            processor.Handle(ref request, Substitute.For <IStorage>(), socket);

            // Assert
            socket.Received(1).Send(Arg.Is <byte[]>(x => x.SequenceEqual(expectedBytes)), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <SocketFlags>());
        }
Ejemplo n.º 19
0
        public async Task SendToServer_WorksCorrect()
        {
            // arrange
            var request = new InsertRequest();
            var socket  = PrepareSocket(request);

            var ipEndpoint = new IPEndPoint(IPAddress.Any, 500);

            var service = new Connection(ipEndpoint);

            // act
            await service.SendAsync(request);

            // assert
            socket.Received(1).Connect(ipEndpoint);
            socket.Received(2).Send(Arg.Any <byte[]>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <SocketFlags>());
            socket.Received(1).Dispose();
        }
Ejemplo n.º 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="connection"></param>
        /// <param name="tableName"></param>
        /// <param name="fields"></param>
        /// <param name="hints"></param>
        /// <param name="transaction"></param>
        /// <param name="statementBuilder"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public static async Task <InsertExecutionContext> CreateAsync(Type entityType,
                                                                      IDbConnection connection,
                                                                      string tableName,
                                                                      IEnumerable <Field> fields,
                                                                      string hints = null,
                                                                      IDbTransaction transaction          = null,
                                                                      IStatementBuilder statementBuilder  = null,
                                                                      CancellationToken cancellationToken = default)
        {
            var key = GetKey(entityType, tableName, fields, hints);

            // Get from cache
            var context = InsertExecutionContextCache.Get(key);

            if (context != null)
            {
                return(context);
            }

            // Create
            var dbFields = await DbFieldCache.GetAsync(connection, tableName, transaction, cancellationToken);

            var request = new InsertRequest(tableName,
                                            connection,
                                            transaction,
                                            fields,
                                            hints,
                                            statementBuilder);
            var commandText = await CommandTextCache.GetInsertTextAsync(request, cancellationToken);

            // Call
            context = CreateInternal(entityType,
                                     connection,
                                     dbFields,
                                     tableName,
                                     fields,
                                     commandText);

            // Add to cache
            InsertExecutionContextCache.Add(entityType, key, context);

            // Return
            return(context);
        }
Ejemplo n.º 21
0
        public void DeclineRequestShouldReturnRedirectToAction()
        {
            AdminController adminController = new AdminController(membershipService, insertRequestService, mediaService);

            InsertRequest insertRequest = TestUtil.generateInsertRequest();

            insertRequest.Media = TestUtil.generateTV_Show(true);

            Expect.Call(membershipService.IsAdmin(fakeAdmin.Identity.Name)).Return(true);
            Expect.Call(insertRequestService.GetById(7)).Return(insertRequest);
            Expect.Call(delegate { insertRequestService.Delete(insertRequest); });
            Expect.Call(delegate { insertRequestService.Save(); });
            mocks.ReplayAll();

            RedirectToRouteResult result = adminController.DeclineRequest(7, fakeAdmin) as RedirectToRouteResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(mediaRequests_ViewName, result.RouteValues["action"]);
        }
        private string UpdateSuiteRegistration(CreateRegistrationRequest registerRequest, string logId)
        {
            var suiteWrapper = new SuiteWrapper();

            suitesessionId = suiteWrapper.Login().GetAwaiter().GetResult();
            var request = new InsertRequest();

            request.SessionId  = suitesessionId;
            request.ModuleName = "reg_Registration";
            request.Entity     = registerRequest;
            var resp = suiteWrapper.Update(request).GetAwaiter().GetResult();

            common.InsertSuiteAmIntegrationLogDetail(new CreateTraceLogRequest()
            {
                Description = "Updated Suite Registration successfully Id: " + resp.Id, Name = "UpdateSuiteRegistration", Entity_c = "Registration"
            }, logId);
            SuiteWrapper.WriteTraceLog("UpdateSuiteRegistration", "Updated Suite Registration successfully Id: " + resp.Id);
            return(resp.Id);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets a command text from the cache for the insert operation.
        /// </summary>
        /// <param name="request">The request object.</param>
        /// <returns>The cached command text.</returns>
        internal static string GetInsertText(InsertRequest request)
        {
            var commandText = (string)null;

            if (m_cache.TryGetValue(request, out commandText) == false)
            {
                var statementBuilder = EnsureStatementBuilder(request.Connection, request.StatementBuilder);
                var fields           = GetActualFields(request.Connection, request.Name, request.Fields, request.Transaction);
                var primaryField     = GetPrimaryField(request);
                var identityField    = GetIdentityField(request);
                commandText = statementBuilder.CreateInsert(new QueryBuilder(),
                                                            request.Name,
                                                            fields,
                                                            primaryField,
                                                            identityField);
                m_cache.TryAdd(request, commandText);
            }
            return(commandText);
        }
Ejemplo n.º 24
0
        public ActionResult DeclineRequest(int id, IPrincipal admin)
        {
            if (!membershipService.IsAdmin(admin.Identity.Name))
            {
                return(View("NotAuthorized"));
            }

            InsertRequest insertRequest = insertRequestService.GetById(id);

            if (insertRequest == null)
            {
                return(View("NotFound"));
            }

            insertRequestService.Delete(insertRequest);
            insertRequestService.Save();

            return(RedirectToAction("MediaRequests"));
        }
Ejemplo n.º 25
0
        public ActionResult AddMovieToDb(FormCollection collection, IPrincipal user)
        {
            string title         = collection["ctl00$MainContent$MovieTitle"];
            string originalTitle = collection["ctl00$MainContent$MovieTitleOriginal"];
            string genre         = collection["GenreList"];
            string date          = collection["ctl00$MainContent$Datepicker"];

            DateTime releaseDate = DateTime.MaxValue;

            try
            {
                if (date.Length == 4)
                {
                    DateTime year = new DateTime(Int32.Parse(date), 01, 01);
                    releaseDate = year;
                }
                else
                {
                    releaseDate = DateTime.Parse(date);
                }
            }
            catch (Exception)
            {
            }

            Models.Movie movie = new Movie();
            movie.Title         = title;
            movie.OriginalTitle = originalTitle;
            movie.Genre         = genre;
            movie.ReleaseDate   = releaseDate;
            movie.Pending       = true;
            movie.AddingDate    = DateTime.Now;

            InsertRequest request = new InsertRequest();

            request.RequestDate = DateTime.Now;
            request.Media       = movie;
            request.User        = MembershipService.Instance.GetCurrentUser(user.Identity.Name);

            MediaService.Instance.AddMovie(movie);
            return(View("ConfirmationAddedMedia"));
        }
Ejemplo n.º 26
0
        public void ShowOffDirectBulkWriteToSpecifyOtherArguments()
        {
            var args = new BulkWriteArgs
            {
                CheckElementNames = false
            };
            var insert = new InsertRequest(typeof(BsonDocument), new BsonDocument {
                { "$invalid", 1 }
            });

            try
            {
                _Collection.BulkWrite(args, insert);
            }
            catch (BulkWriteException exception)
            {
                WriteErrors(exception);
                throw;
            }
        }
Ejemplo n.º 27
0
        public async Task ExecuteAsync_CallsService()
        {
            // Arrange
            bool fakeResult = true;

            byte[]      fakeData   = SerializationUtils.Serialize(fakeResult);
            var         request    = new InsertRequest();
            IConnection connection = Substitute.For <IConnection>();

            connection.SendAsync(request).Returns(fakeData);
            var processor = new FakeProcessor();

            // Act
            bool result = await processor.ExecuteAsync(request, connection);

            // Assert
            await connection.Received(1).SendAsync(request);

            Assert.Equal(fakeResult, result);
        }
Ejemplo n.º 28
0
        public void Handle_ReturnsTrueWhenElementAdded(bool added)
        {
            // arrange
            var request   = new InsertRequest();
            var processor = new InsertProcessor();
            var storage   = Substitute.For <IStorage>();

            storage.TryRemove(request.Key).Returns(added);
            byte[] expectedBytes = SerializationUtils.SerializeToStreamWithLength(added);
            var    socket        = Substitute.For <Socket>();

            socket.Send(Arg.Any <byte[]>(), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <SocketFlags>())
            .Returns(expectedBytes.Length);

            // act
            processor.Handle(ref request, storage, socket);

            // assert
            socket.Received(1).Send(Arg.Is <byte[]>(x => x.SequenceEqual(expectedBytes)), Arg.Any <int>(), Arg.Any <int>(), Arg.Any <SocketFlags>());
        }
Ejemplo n.º 29
0
 internal void ModifyRequest(Table table, InsertRequest request)
 {
     if (Description != null)
     {
         table.Description = Description;
     }
     if (FriendlyName != null)
     {
         table.FriendlyName = FriendlyName;
     }
     if (Expiration != null)
     {
         table.ExpirationTime = (long)(Expiration.Value - UnixEpoch).TotalMilliseconds;
     }
     // TODO: There's currently no way of forcing table.TimePartitioning to be set to null. Not a problem at the moment,
     // but we may want a sentinel value at some point.
     if (TimePartitioning != null)
     {
         table.TimePartitioning = TimePartitioning;
     }
     if (ExternalDataConfiguration != null && View != null)
     {
         throw new ArgumentException($"Cannot specify both {nameof(ExternalDataConfiguration)} and {nameof(View)}");
     }
     if (ExternalDataConfiguration != null)
     {
         table.ExternalDataConfiguration = ExternalDataConfiguration;
     }
     if (View != null)
     {
         table.View = View;
     }
     if (EncryptionConfiguration != null)
     {
         table.EncryptionConfiguration = EncryptionConfiguration;
     }
     if (Clustering != null)
     {
         table.Clustering = Clustering;
     }
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Adds the specified bundle of item to the pod.
 /// </summary>
 /// <param name="itemBundle">The item-bundle to add.</param>
 /// <param name="insertRequest">The corresponding insertion request, if available.</param>
 /// <returns><code>true</code> if the item was added successfully, <code>false</code> otherwise.</returns>
 public bool Add(ItemBundle itemBundle, InsertRequest insertRequest = null)
 {
     // Signal change
     _changed = true;
     // Init, if not done yet
     if (_itemDescriptionCountContained == null)
     {
         InitPodContentInfo();
     }
     // Only add the item, if there is enough remaining capacity
     if (CapacityInUse + itemBundle.BundleWeight <= Capacity)
     {
         // Prepare info for the interface
         _contentChanged = true;
         // Keep track of weight
         CapacityInUse += itemBundle.BundleWeight;
         // Keep track of reserved space
         _registeredBundles.Remove(itemBundle);
         CapacityReserved = _registeredBundles.Sum(b => b.BundleWeight);
         // Keep track of items actually contained in this pod
         if (_itemDescriptionCountContained[itemBundle.ItemDescription] <= 0)
         {
             _itemDescriptionsContained.Add(itemBundle.ItemDescription);
         }
         // Keep track of the number of available items on this pod (for picking)
         _itemDescriptionCountAvailable[itemBundle.ItemDescription] += itemBundle.ItemCount;
         // Keep track of the number of contained items on this pod (for picking)
         _itemDescriptionCountContained[itemBundle.ItemDescription] += itemBundle.ItemCount;
         // Mark insert request completed, if there is one
         insertRequest?.Finish();
         // Signal the success
         return(true);
     }
     else
     {
         // Mark insert request aborted, if there is one
         insertRequest?.Abort();
         // Signal the failed add operation
         return(false);
     }
 }
        private void AddRequest(BsonBuffer buffer, InsertRequest request)
        {
            var document = request.Document;
            if (document == null)
            {
                throw new ArgumentException("Batch contains one or more null documents.");
            }

            var serializer = request.Serializer;
            if (serializer == null)
            {
                var actualType = document.GetType();
                if (_cachedSerializerType != actualType)
                {
                    _cachedSerializer = BsonSerializer.LookupSerializer(actualType);
                    _cachedSerializerType = actualType;
                }
                serializer = _cachedSerializer;
            }
            var serializationOptions = request.SerializationOptions ?? DocumentSerializationOptions.SerializeIdFirstInstance;

            _lastDocumentStartPosition = buffer.Position;
            using (var bsonWriter = new BsonBinaryWriter(buffer, false, WriterSettings))
            {
                bsonWriter.PushMaxDocumentSize(_maxDocumentSize);
                bsonWriter.CheckElementNames = _checkElementNames;
                serializer.Serialize(bsonWriter, request.NominalType, document, serializationOptions);
                bsonWriter.PopMaxDocumentSize();
            }

            _batchCount++;
            _batchLength = buffer.Position - _batchStartPosition;
        }
Ejemplo n.º 32
0
        private void AddRequest(BsonStreamWriter streamWriter, InsertRequest request)
        {
            var document = request.Document;
            if (document == null)
            {
                throw new ArgumentException("Batch contains one or more null documents.");
            }

            var serializer = request.Serializer;
            if (serializer == null)
            {
                var nominalType = request.NominalType;
                if (_cachedSerializerType != nominalType)
                {
                    _cachedSerializer = BsonSerializer.LookupSerializer(nominalType);
                    _cachedSerializerType = nominalType;
                }
                serializer = _cachedSerializer;
            }

            _lastDocumentStartPosition = (int)streamWriter.Position;
            using (var bsonWriter = new BsonBinaryWriter(streamWriter.BaseStream, WriterSettings))
            {
                bsonWriter.PushMaxDocumentSize(_maxDocumentSize);
                bsonWriter.CheckElementNames = _checkElementNames;
                var context = BsonSerializationContext.CreateRoot(bsonWriter, request.NominalType, c => c.SerializeIdFirst = true);
                serializer.Serialize(context, document);
                bsonWriter.PopMaxDocumentSize();
            }

            _batchCount++;
            _batchLength = (int)streamWriter.Position - _batchStartPosition;
        }