// public methods
        public BulkWriteResult Execute(MongoConnection connection)
        {
            var batchResults = new List<BulkWriteBatchResult>();
            var remainingRequests = Enumerable.Empty<WriteRequest>();
            var hasWriteErrors = false;

            var runCount = 0;
            foreach (var run in FindRuns())
            {
                runCount++;

                if (hasWriteErrors && _isOrdered)
                {
                    remainingRequests = remainingRequests.Concat(run.Requests);
                    continue;
                }

                var batchResult = ExecuteBatch(connection, run);
                batchResults.Add(batchResult);

                hasWriteErrors |= batchResult.HasWriteErrors;
            }

            if (runCount == 0)
            {
                throw new InvalidOperationException("Bulk write operation is empty.");
            }

            var combiner = new BulkWriteBatchResultCombiner(batchResults, _writeConcern.Enabled);
            return combiner.CreateResultOrThrowIfHasErrors(remainingRequests);
        }
        // public methods
        /// <summary>
        /// Authenticates the connection against the given database.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        public void Authenticate(MongoConnection connection, MongoCredential credential)
        {
            var nonceCommand = new CommandDocument("getnonce", 1);
            var commandResult = connection.RunCommand(credential.Source, QueryFlags.None, nonceCommand, false);
            if (!commandResult.Ok)
            {
                throw new MongoAuthenticationException(
                    "Error getting nonce for authentication.",
                    new MongoCommandException(commandResult));
            }

            var nonce = commandResult.Response["nonce"].AsString;
            var passwordDigest = MongoUtils.Hash(credential.Username + ":mongo:" + ((PasswordEvidence)credential.Evidence).Password);
            var digest = MongoUtils.Hash(nonce + credential.Username + passwordDigest);
            var authenticateCommand = new CommandDocument
                {
                    { "authenticate", 1 },
                    { "user", credential.Username },
                    { "nonce", nonce },
                    { "key", digest }
                };

            commandResult = connection.RunCommand(credential.Source, QueryFlags.None, authenticateCommand, false);
            if (!commandResult.Ok)
            {
                var message = string.Format("Invalid credential for database '{0}'.", credential.Source);
                throw new MongoAuthenticationException(
                    message,
                    new MongoCommandException(commandResult));
            }
        }
        // public methods
        public virtual BulkWriteResult Execute(MongoConnection connection)
        {
            var batchResults = new List<BulkWriteBatchResult>();
            var remainingRequests = Enumerable.Empty<WriteRequest>();
            var hasWriteErrors = false;

            var decoratedRequests = DecorateRequests(_args.Requests);
            using (var enumerator = decoratedRequests.GetEnumerator())
            {
                var originalIndex = 0;
                Batch<WriteRequest> batch = new FirstBatch<WriteRequest>(enumerator);
                while (batch != null)
                {
                    if (hasWriteErrors && _args.IsOrdered)
                    {
                        remainingRequests = remainingRequests.Concat(batch.RemainingItems);
                        break;
                    }

                    var batchResult = ExecuteBatch(connection, batch, originalIndex);
                    batchResults.Add(batchResult);

                    hasWriteErrors |= batchResult.HasWriteErrors;
                    originalIndex += batchResult.BatchCount;
                    batch = batchResult.NextBatch;
                }
            }

            var combiner = new BulkWriteBatchResultCombiner(batchResults, _args.WriteConcern.Enabled);
            return combiner.CreateResultOrThrowIfHasErrors(remainingRequests);
        }
        // public methods
        /// <summary>
        /// Authenticates the connection against the given database.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        public void Authenticate(MongoConnection connection, MongoCredential credential)
        {
            string nonce;
            try
            {
                var nonceCommand = new CommandDocument("getnonce", 1);
                var nonceResult = RunCommand(connection, credential.Source, nonceCommand);
                nonce = nonceResult.Response["nonce"].AsString;
            }
            catch (MongoCommandException ex)
            {
                throw new MongoAuthenticationException("Error getting nonce for authentication.", ex);
            }

            try
            {
                var passwordDigest = ((PasswordEvidence)credential.Evidence).ComputeMongoCRPasswordDigest(credential.Username);
                var digest = MongoUtils.Hash(nonce + credential.Username + passwordDigest);
                var authenticateCommand = new CommandDocument
                {
                    { "authenticate", 1 },
                    { "user", credential.Username },
                    { "nonce", nonce },
                    { "key", digest }
                };

                RunCommand(connection, credential.Source, authenticateCommand);
            }
            catch (MongoCommandException ex)
            {
                var message = string.Format("Invalid credential for database '{0}'.", credential.Source);
                throw new MongoAuthenticationException(message, ex);
            }
        }
 protected MongoMessage(
     MongoConnection connection,
     MessageOpcode opcode
 ) {
     this.connection = connection;
     this.opcode = opcode;
 }
 internal MongoKillCursorsMessage(
     MongoConnection connection,
     params long[] cursorIds
 )
     : base(connection, MessageOpcode.KillCursors) {
     this.cursorIds = cursorIds;
 }
        public static void ImportToSqlAndMongo(BoardgameSimulatorData data, MongoConnection mongoData, string filePath = "../../../DataSources/xml/")
        {
            if (!Directory.Exists(filePath))
            {
                Console.WriteLine("There are no xml files present in " + filePath + " suitable for importing!");
                return;
            }

            var files = Directory.GetFiles(filePath).Select(x => x).Where(x => Path.GetExtension(x) == ".xml");

            Console.WriteLine("Importing from xml into Sql and MongoDb initialized.");

            foreach (var file in files)
            {
                var heroes = GetHeroes(file);
                var items = GetItems(file);

                Console.WriteLine("importing into sql...");
                AddHeroesToSql(heroes, data);
                AddItemsToSql(items, data);

                Console.WriteLine("importing into mongodb...");
                AddHeroesToMongo(heroes, mongoData);
                AddItemsToMongo(items, mongoData);
            }

            Console.WriteLine("Importing from xml into Sql and MongoDb completed!");
        }
        /// <summary>
        /// Initializes migration with the connection object
        /// </summary>
        /// <param name="connection">MongoConnection object</param>
        public void Initialize(MongoConnection connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            Connection = connection;
        }
Esempio n. 9
0
        /// <summary>
        /// Initializes the mechanism.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        /// <returns>The initial step.</returns>
        public ISaslStep Initialize(MongoConnection connection, MongoCredential credential)
        {
            var serviceName = credential.GetMechanismProperty<string>("SERVICE_NAME", "mongodb");
            var canonicalizeHostname = credential.GetMechanismProperty<bool>("CANONICALIZE_HOST_NAME", false);

            var hostname = connection.ServerInstance.Address.Host;
            if (canonicalizeHostname)
            {
                var entry = Dns.GetHostEntry(hostname);
                if (entry != null)
                {
                    hostname = entry.HostName;
                }
            }

            // TODO: provide an override to force the use of gsasl?
            if (__useGsasl)
            {
                return new GsaslGssapiImplementation(
                    serviceName,
                    hostname,
                    credential.Username,
                    credential.Evidence);
            }

            return new WindowsGssapiImplementation(
                serviceName,
                hostname,
                credential.Username,
                credential.Evidence);
        }
        // public methods
        public WriteConcernResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;
            if (serverInstance.Supports(FeatureId.WriteCommands) && _args.WriteConcern.Enabled)
            {
                var emulator = new UpdateOpcodeOperationEmulator(_args);
                return emulator.Execute(connection);
            }

            SendMessageWithWriteConcernResult sendMessageResult;
            using (var buffer = new BsonBuffer(new MultiChunkBuffer(BsonChunkPool.Default), true))
            {
                var requests = _args.Requests.ToList();
                if (requests.Count != 1)
                {
                    throw new NotSupportedException("Update opcode only supports a single update request.");
                }
                var updateRequest = (UpdateRequest)requests[0];

                var flags = UpdateFlags.None;
                if (updateRequest.IsMultiUpdate ?? false) { flags |= UpdateFlags.Multi; }
                if (updateRequest.IsUpsert ?? false) { flags |= UpdateFlags.Upsert; }

                var maxDocumentSize = connection.ServerInstance.MaxDocumentSize;
                var query = updateRequest.Query ?? new QueryDocument();

                var message = new MongoUpdateMessage(WriterSettings, CollectionFullName, _args.CheckElementNames, flags, maxDocumentSize, query, updateRequest.Update);
                message.WriteTo(buffer);

                sendMessageResult =  SendMessageWithWriteConcern(connection, buffer, message.RequestId, ReaderSettings, WriterSettings, WriteConcern);
            }

            return WriteConcern.Enabled ? ReadWriteConcernResult(connection, sendMessageResult) : null;
        }
 internal MongoInsertMessage(
     MongoConnection connection,
     string collectionFullName
 )
     : base(connection, MessageOpcode.Insert) {
     this.collectionFullName = collectionFullName;
 }
        public MongoDbDataTest()
        {
            var connection = new MongoConnection();

            DataContext = new DataContext(typeof(MongoConnection).Assembly);
            DataContext.SetRepositoryCreator(type => Activator.CreateInstance(type, connection));
        }
        // public methods
        public BulkWriteResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;
            if (!serverInstance.Supports(FeatureId.WriteOpcodes))
            {
                throw new NotSupportedException("Write opcodes are not supported.");
            }

            var batchResults = new List<BulkWriteBatchResult>();
            var remainingRequests = new List<WriteRequest>();
            var hasWriteErrors = false;

            var originalIndex = 0;
            foreach (WriteRequest request in _args.Requests)
            {
                if (hasWriteErrors && _args.IsOrdered)
                {
                    remainingRequests.Add(request);
                    continue;
                }

                var batchResult = EmulateSingleRequest(connection, request, originalIndex);
                batchResults.Add(batchResult);

                hasWriteErrors |= batchResult.HasWriteErrors;
                originalIndex++;
            }

            var combiner = new BulkWriteBatchResultCombiner(batchResults, _args.WriteConcern.Enabled);
            return combiner.CreateResultOrThrowIfHasErrors(remainingRequests);
        }
        private static void AddItemsToMongo(List<DummyItem> items, MongoConnection mongoData)
        {
            mongoData.Database.DropCollection("items");

            var itemsCollection = new GenericData<DummyItem>(mongoData.Database, "items");

            itemsCollection.Collection.InsertBatch(items);
        }
Esempio n. 15
0
        private static MongoConnection[] CreateConnectionPool(Int32 count)
        {
            var connections = new MongoConnection[count];

            for (var i = 0; i < count; i++)
                connections[i] = new MongoConnection(Host, Port, Serializer);

            return connections;
        }
 internal MongoDeleteMessage(
     MongoConnection connection,
     string collectionFullName,
     RemoveFlags flags,
     IMongoQuery query
 ) :
     base(connection, MessageOpcode.Delete) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.query = query;
 }
Esempio n. 17
0
        /// <summary>
        /// Specifies a MongoConnection to use
        /// </summary>
        /// <param name="connection">MongoConnection object</param>
        public Migrator(MongoConnection connection)
        {
            _connection = connection;
            _migrations = GetType().Assembly.GetTypes()
                .Where(t => !t.IsAbstract && typeof(MigrationBase).IsAssignableFrom(t))
                .Select(t => (MigrationBase)Activator.CreateInstance(t))
                .OrderBy(m => m.Version).ToList();

            foreach (var migration in _migrations)
                migration.Initialize(connection);
        }
        internal MongoConnectionPool(
            MongoServer server,
            MongoConnection firstConnection
        )
        {
            this.server = server;
            this.address = firstConnection.Address;

            pool.Add(firstConnection);
            firstConnection.JoinConnectionPool(this);
        }
 internal MongoGetMoreMessage(
     MongoConnection connection,
     string collectionFullName,
     int numberToReturn,
     long cursorId
 )
     : base(connection, MessageOpcode.GetMore) {
     this.collectionFullName = collectionFullName;
     this.numberToReturn = numberToReturn;
     this.cursorId = cursorId;
 }
 internal MongoQueryMessage(
     MongoConnection connection,
     string collectionFullName,
     QueryFlags flags,
     int numberToSkip,
     int numberToReturn,
     IMongoQuery query,
     IMongoFields fields
 ) :
     this(connection, collectionFullName, flags, numberToSkip, numberToReturn, query, fields, null) {
 }
        /// <summary>
        /// Initializes the mechanism.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        /// <returns>
        /// The initial step.
        /// </returns>
        public ISaslStep Initialize(MongoConnection connection, MongoCredential credential)
        {
            var securePassword = ((PasswordEvidence)credential.Evidence).SecurePassword;

            var dataString = string.Format("\0{0}\0{1}",
                credential.Username,
                MongoUtils.ToInsecureString(securePassword));

            var bytes = new UTF8Encoding(false, true).GetBytes(dataString);
            return new SaslCompletionStep(bytes);
        }
        // public methods
        public override BulkWriteResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;
            if (!serverInstance.Supports(FeatureId.WriteCommands))
            {
                var emulator = new BulkInsertOperationEmulator(_args);
                return emulator.Execute(connection);
            }

            return base.Execute(connection);
        }
 public WriteConcernResult Execute(MongoConnection connection)
 {
     using (var buffer = new BsonBuffer(new MultiChunkBuffer(BsonChunkPool.Default), true))
     {
         var readerSettings = GetNodeAdjustedReaderSettings(connection.ServerInstance);
         var writerSettings = GetNodeAdjustedWriterSettings(connection.ServerInstance);
         var message = new MongoDeleteMessage(writerSettings, CollectionFullName, _flags, _query);
         message.WriteToBuffer(buffer);
         return SendMessageWithWriteConcern(connection, buffer, message.RequestId, readerSettings, writerSettings, WriteConcern);
     }
 }
        internal MongoConnectionPool(
            MongoServer server,
            MongoConnection firstConnection
        ) {
            this.server = server;
            this.endPoint = firstConnection.EndPoint;

            firstConnection.JoinConnectionPool(this);
            availableConnections.Add(firstConnection);
            poolSize = 1;
            timer = new Timer(TimerCallback, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));
        }
        protected WriteConcernResult SendMessageWithWriteConcern(
            MongoConnection connection,
            BsonBuffer buffer,
            int requestId,
            BsonBinaryReaderSettings readerSettings,
            BsonBinaryWriterSettings writerSettings,
            WriteConcern writeConcern)
        {
            CommandDocument getLastErrorCommand = null;
            if (writeConcern.Enabled)
            {
                var fsync = (writeConcern.FSync == null) ? null : (BsonValue)writeConcern.FSync;
                var journal = (writeConcern.Journal == null) ? null : (BsonValue)writeConcern.Journal;
                var w = (writeConcern.W == null) ? null : writeConcern.W.ToGetLastErrorWValue();
                var wTimeout = (writeConcern.WTimeout == null) ? null : (BsonValue)(int)writeConcern.WTimeout.Value.TotalMilliseconds;

                getLastErrorCommand = new CommandDocument
                {
                    { "getlasterror", 1 }, // use all lowercase for backward compatibility
                    { "fsync", fsync, fsync != null },
                    { "j", journal, journal != null },
                    { "w", w, w != null },
                    { "wtimeout", wTimeout, wTimeout != null }
                };

                // piggy back on network transmission for message
                var getLastErrorMessage = new MongoQueryMessage(writerSettings, DatabaseName + ".$cmd", QueryFlags.None, 0, 1, getLastErrorCommand, null);
                getLastErrorMessage.WriteToBuffer(buffer);
            }

            connection.SendMessage(buffer, requestId);

            WriteConcernResult writeConcernResult = null;
            if (writeConcern.Enabled)
            {
                var writeConcernResultSerializer = BsonSerializer.LookupSerializer(typeof(WriteConcernResult));
                var replyMessage = connection.ReceiveMessage<WriteConcernResult>(readerSettings, writeConcernResultSerializer, null);
                if (replyMessage.NumberReturned == 0)
                {
                    throw new MongoCommandException("Command 'getLastError' failed. No response returned");
                }
                writeConcernResult = replyMessage.Documents[0];
                writeConcernResult.Command = getLastErrorCommand;

                var mappedException = ExceptionMapper.Map(writeConcernResult);
                if (mappedException != null)
                {
                    throw mappedException;
                }
            }

            return writeConcernResult;
        }
Esempio n. 26
0
        public DataManager()
        {
            var mongo = Global.Require<MongoModule>("mongodb");

            var Db = mongo.DB;
            Connection = mongo.Connection;
            var server = Server = mongo.Server;

            client = getMongo();
            client.Open((arg1, arg2) => {
                            //client.Collection("test_insert", "test");
                        });
        }
 internal MongoUpdateMessage(
     MongoConnection connection,
     string collectionFullName,
     UpdateFlags flags,
     IMongoQuery query,
     IMongoUpdate update
 ) :
     base(connection, MessageOpcode.Update) {
     this.collectionFullName = collectionFullName;
     this.flags = flags;
     this.query = query;
     this.update = update;
 }
        // public methods
        /// <summary>
        /// Authenticates the connection against the given database.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        public void Authenticate(MongoConnection connection, MongoCredential credential)
        {
            using (var conversation = new SaslConversation())
            {
                var currentStep = _mechanism.Initialize(connection, credential);

                var command = new CommandDocument
                {
                    { "saslStart", 1 },
                    { "mechanism", _mechanism.Name },
                    { "payload", currentStep.BytesToSendToServer }
                };

                while (true)
                {
                    CommandResult result;
                    try
                    {
                        result = RunCommand(connection, credential.Source, command);
                    }
                    catch (MongoCommandException ex)
                    {
                        var message = "Unknown error occured during authentication.";
                        var code = ex.CommandResult.Code;
                        var errmsg = ex.CommandResult.ErrorMessage;
                        if(code.HasValue && errmsg != null)
                        {
                            message = string.Format("Error: {0} - {1}", code, errmsg);
                        }

                        throw new MongoSecurityException(message, ex);
                    }

                    if (result.Response["done"].AsBoolean)
                    {
                        break;
                    }

                    currentStep = currentStep.Transition(conversation, result.Response["payload"].AsByteArray);

                    command = new CommandDocument
                    {
                        { "saslContinue", 1 },
                        { "conversationId", result.Response["conversationId"].AsInt32 },
                        { "payload", currentStep.BytesToSendToServer }
                    };
                }
            }
        }
 protected MongoRequestMessage(
     MongoConnection connection,
     MessageOpcode opcode,
     BsonBuffer buffer // not null if piggybacking this message onto an existing buffer
 )
     : base(connection, opcode) {
     if (buffer == null) {
         this.buffer = new BsonBuffer();
         this.disposeBuffer = true; // only call Dispose if we allocated the buffer
     } else {
         this.buffer = buffer;
         this.disposeBuffer = false;
     }
     this.requestId = Interlocked.Increment(ref lastRequestId);
 }
        /// <summary>
        /// Initializes the mechanism.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="credential">The credential.</param>
        /// <returns>The initial step.</returns>
        public ISaslStep Initialize(MongoConnection connection, MongoCredential credential)
        {
            // TODO: provide an override to force the use of gsasl?
            if (__useGsasl)
            {
                return new GsaslGssapiImplementation(
                    connection.ServerInstance.Address.Host,
                    credential.Username,
                    credential.Evidence);
            }

            return new WindowsGssapiImplementation(
                connection.ServerInstance.Address.Host,
                credential.Username,
                credential.Evidence);
        }
Esempio n. 31
0
        private BulkDeleteOperationEmulator CreateOperation(MongoConnection connection, MongoCollection collection, IEnumerable <DeleteRequest> deletes)
        {
            var serverInstance = connection.ServerInstance;

            return(new BulkDeleteOperationEmulator(new BulkDeleteOperationArgs(
                                                       collection.Name,
                                                       collection.Database.Name,
                                                       1,                               // maxBatchCount
                                                       serverInstance.MaxMessageLength, // maxBatchLength
                                                       serverInstance.MaxDocumentSize,
                                                       serverInstance.MaxWireDocumentSize,
                                                       true, // isOrdered
                                                       BsonBinaryReaderSettings.Defaults,
                                                       deletes,
                                                       WriteConcern.Acknowledged,
                                                       BsonBinaryWriterSettings.Defaults)));
        }
 // public methods
 /// <summary>
 /// Authenticates the specified connection with the given credential.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <param name="credential">The credential.</param>
 public void Authenticate(MongoConnection connection, MongoCredential credential)
 {
     try
     {
         var command = new CommandDocument
         {
             { "authenticate", 1 },
             { "mechanism", Name },
             { "user", credential.Username }
         };
         RunCommand(connection, credential.Source, command);
     }
     catch (MongoCommandException ex)
     {
         throw new MongoAuthenticationException(string.Format("Unable to authenticate '{0}' using '{1}'.", credential.Username, Name), ex);
     }
 }
Esempio n. 33
0
        public async void InsertUser()
        {
            var newUser = new User
            {
                email    = Email,
                password = Password
            };

            try
            {
                await MongoConnection.InsertOneAsync(newUser);
            }
            catch (Exception)
            {
            }
            await Application.Current.MainPage.Navigation.PopAsync();
        }
Esempio n. 34
0
        private BulkWriteBatchResult ExecuteBatch(MongoConnection connection, Batch <WriteRequest> batch, int originalIndex)
        {
            var batchSerializer       = CreateBatchSerializer();
            var writeCommand          = CreateWriteCommand(batchSerializer, batch);
            var writeCommandOperation = CreateWriteCommandOperation(writeCommand);
            var writeCommandResult    = writeCommandOperation.Execute(connection);
            var batchProgress         = batchSerializer.BatchProgress;

            var indexMap = new IndexMap.RangeBased(0, originalIndex, batchProgress.BatchCount);

            return(BulkWriteBatchResult.Create(
                       _args.IsOrdered,
                       batchProgress.BatchItems,
                       writeCommandResult.Response,
                       indexMap,
                       batchProgress.NextBatch));
        }
Esempio n. 35
0
        public static long ClearOldResults(MongoConnection mongoConnection, DateTime maxAllowedEndDate)
        {
            IMongoCollection <OptionResult> datas = mongoConnection.Database.GetCollection <OptionResult>(typeof(OptionResult).Name);

            FilterDefinition <OptionResult> deleteFilter = Builders <OptionResult> .Filter.Lt(optionResult => optionResult.EndTime, maxAllowedEndDate);

            Task <DeleteResult> deleteTask = datas.DeleteManyAsync(deleteFilter);

            DeleteResult deleteResult = MongoDataHelper.GetValueOrThrowTimeout(deleteTask);

            if (deleteResult.IsAcknowledged == false)
            {
                return(0);
            }

            return(deleteResult.DeletedCount);
        }
        private BulkWriteResult ExecuteInserts(MongoConnection connection, IEnumerable <InsertRequest> requests)
        {
            var operation = new BulkInsertOperation(new BulkInsertOperationArgs(
                                                        _assignId,
                                                        _checkElementNames,
                                                        _collectionName,
                                                        _databaseName,
                                                        _maxBatchCount,
                                                        _maxBatchLength,
                                                        _isOrdered,
                                                        _readerSettings,
                                                        requests,
                                                        _writeConcern,
                                                        _writerSettings));

            return(operation.Execute(connection));
        }
        public async void Adding_A_Product_Should_Return_The_Product()
        {
            MongoConnection.Configure("mongodb://localhost", "owinMongoTest");
            TestHelpers.DestroyAllData();

            dynamic formVars = new ExpandoObject();

            formVars.Name = "fish";

            var response = await TestHelpers.TestServerInstance.Value.HttpClient.PostAsync("/products/add", TestHelpers.DynamicToFormData(formVars));

            var result = await response.Content.ReadAsStringAsync();

            dynamic addResult = JsonConvert.DeserializeObject <ExpandoObject>(result);

            Assert.AreEqual(addResult.Name, "fish");
        }
Esempio n. 38
0
        private BulkWriteResult ExecuteDeletes(MongoConnection connection, IEnumerable <DeleteRequest> requests)
        {
            var operation = new BulkDeleteOperation(new BulkDeleteOperationArgs(
                                                        _collectionName,
                                                        _databaseName,
                                                        _maxBatchCount,
                                                        _maxBatchLength,
                                                        connection.ServerInstance.MaxDocumentSize,
                                                        connection.ServerInstance.MaxWireDocumentSize,
                                                        _isOrdered,
                                                        _readerSettings,
                                                        requests,
                                                        _writeConcern,
                                                        _writerSettings));

            return(operation.Execute(connection));
        }
Esempio n. 39
0
        static void Main(string[] args)
        {
            try
            {
                var dateTimeNow = String.Format("{0:g}", DateTime.Now);
                var webContent  = WebSite.GetWebContent();
                var ipAddresses = webContent.GetIpAddressesFromWebContent();
                var myIpAddress = RemoveDuplicateIpAddress(ipAddresses);
                var mongoDb     = new MongoConnection();
                try
                {
                    var ipAddressesFromDatabase = mongoDb.GetListIpAddress();

                    if (ipAddressesFromDatabase.Count == 0)
                    {
                        EmailSender.SendEmail("Your IP address", myIpAddress);
                    }
                    else
                    {
                        if (myIpAddress.TrimEnd() != ipAddressesFromDatabase.Last().IpAddress)
                        {
                            EmailSender.SendEmail("Your IP address", myIpAddress);
                        }
                    }

                    mongoDb.InsertIpAddressInMongoDatabase(new IpDataItem
                    {
                        _id       = ipAddressesFromDatabase.Count == 0 ? "1" : (ipAddressesFromDatabase.Count + 1).ToString(),
                        Date      = dateTimeNow,
                        IpAddress = myIpAddress.TrimEnd(),
                    });
                }
                catch (Exception mongoException)
                {
                    var messageBody = String.Format("Your Ip address {0}\n Mongo error exceptio: {1}", myIpAddress,
                                                    mongoException);
                    EmailSender.SendEmail("Mongo Error", messageBody);
                }
                Console.WriteLine("[log Date] {0}\nYour Ip address: {1}", dateTimeNow, myIpAddress);
            }
            catch (Exception ex)
            {
                EmailSender.SendEmail("ERROR", ex.Message);
            }
        }
Esempio n. 40
0
        // protected methods
        protected override BulkWriteBatchResult EmulateSingleRequest(MongoConnection connection, WriteRequest request, int originalIndex)
        {
            var serverInstance = connection.ServerInstance;
            var insertRequest  = (InsertRequest)request;

            var insertRequests = new[] { insertRequest };
            var operationArgs  = new BulkInsertOperationArgs(
                _args.AssignId,
                _args.CheckElementNames,
                _args.CollectionName,
                _args.DatabaseName,
                1,                               // maxBatchCount
                serverInstance.MaxMessageLength, // maxBatchLength
                true,                            // isOrdered
                _args.ReaderSettings,
                insertRequests,
                _args.WriteConcern,
                _args.WriterSettings);
            var operation = new InsertOpcodeOperation(operationArgs);

            WriteConcernResult    writeConcernResult    = null;
            WriteConcernException writeConcernException = null;

            try
            {
                var operationResult = operation.Execute(connection);
                if (operationResult != null)
                {
                    writeConcernResult = operationResult.First();
                }
            }
            catch (WriteConcernException ex)
            {
                writeConcernResult    = ex.WriteConcernResult;
                writeConcernException = ex;
            }

            var indexMap = new IndexMap.RangeBased(0, originalIndex, 1);

            return(BulkWriteBatchResult.Create(
                       insertRequest,
                       writeConcernResult,
                       writeConcernException,
                       indexMap));
        }
Esempio n. 41
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            _IMongoDB = MongoConnection.mongoConnect();
            //if (_IMongoDB == null)
            //{
            //    Debug.WriteLine(Environment.NewLine + "No database donnection, shutting down." + Environment.NewLine);
            //    Application.Current.Exit();
            //}
            //usage:
            //var collection = App.IMongoDB.GetCollection<BsonDocument>("balls");
            //then use collection to query or insert

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }
        }
Esempio n. 42
0
        protected static TDataType ReadNextById <TDataType>(MongoConnection connection, ObjectId id)
            where TDataType : AbstractMongoData
        {
            Expression <Func <TDataType, bool> > filter = data => data._id > id;

            IMongoCollection <TDataType>       datas = connection.Database.GetCollection <TDataType>(typeof(TDataType).Name);
            IFindFluent <TDataType, TDataType> find  = datas.Find(filter);

            find.Limit(1);

            SortDefinitionBuilder <TDataType> sortBuilder    = new SortDefinitionBuilder <TDataType>();
            SortDefinition <TDataType>        sortDefinition = sortBuilder.Descending(document => document._id);

            find.Sort(sortDefinition);
            Task <TDataType> dataTask = find.SingleOrDefaultAsync();

            return(dataTask.Result);
        }
        public ActionResult Index(Answers obj)
        {
            MongoConnection connection = new MongoConnection("surveyAnswers", "szoftver");

            connection.insertMongo(obj);
            var           data          = connection.dataFromMongo().ToList <BsonDocument>();
            QueryBuilding queryBuilding = new QueryBuilding();

            queryBuilding.createTable();
            foreach (var mongoData in data)
            {
                queryBuilding.insertAnswersTable(mongoData);
            }
            //ViewBag.SucessMessage = "1: " + obj.grade + " 2: " + obj.profil
            //    + " 3: " + obj.live + " 4: " + obj.gender + " 5: " + obj.learn
            //    + " 6: " + obj.speciality + " 7: " + obj.where + " 8: " + obj.university;
            return(View());
        }
Esempio n. 44
0
        private static void ComplexCalculation(Delay delay)
        {
            MongoConnection mongoConnection = new MongoConnection(mongoConnectionString, mongoDatabaseName);

            foreach (DeviceTypes type in Enum.GetValues(typeof(CalculatedDeviceType)))
            {
                RawDataResponse response = comm.GetDataForCalculation(new RawDataRequest(delay, type, DateTime.Now.AddHours(-1).ToString(), DateTime.Now.ToString())).Result;

                var max = response.RawData.Max();
                var min = response.RawData.Min();
                var moy = response.RawData.Sum() / response.RawData.Count;

                mongoConnection.InsertData(response.ToCollectionName(CalculType.Max), max, DateTime.Parse(response.From), delay);
                mongoConnection.InsertData(response.ToCollectionName(CalculType.Min), min, DateTime.Parse(response.From), delay);
                mongoConnection.InsertData(response.ToCollectionName(CalculType.Moy), moy, DateTime.Parse(response.From), delay);
            }
            ;
        }
Esempio n. 45
0
        public async void InsertUser()
        {
            var newUser = new User
            {
                name     = Name,
                password = Password,
                email    = Email,
                city     = City,
                district = District,
                image    = Image
            };



            await MongoConnection.InsertOneAsync(newUser);

            await Application.Current.MainPage.Navigation.PopAsync();
        }
Esempio n. 46
0
        public static Progress ReadNext(MongoConnection connection, string targetName)
        {
            IMongoCollection <Progress> progressCollection = connection.Database.GetCollection <Progress>(typeof(Progress).Name);

            IFindFluent <Progress, Progress> progressFind = progressCollection.Find(progress => progress.TargetName == targetName);

            SortDefinition <Progress> sortDefinition = Builders <Progress> .Sort.Ascending(progress => progress.LastProgressDate);

            progressFind = progressFind.Sort(sortDefinition).Limit(1);

            Task <List <Progress> > progressTask = progressFind.ToListAsync();

            progressTask.Wait();

            List <Progress> progressFound = progressTask.Result;

            return(progressFound.FirstOrDefault());
        }
Esempio n. 47
0
        public async Task Save(ITransaction transaction, PersonPerCityCounter personPerCityCounter)
        {
            var session    = ((MongoSession)transaction).Session;
            var collection = MongoConnection.GetPersonPerCityCounterCollection();
            var filter     = Builders <PersonPerCityCounter> .Filter.Eq(x => x.City, personPerCityCounter.City);

            var currentDocument = await GetByCity(personPerCityCounter.City);

            personPerCityCounter.Id = currentDocument?.Id ?? GuidGenerator.GenerateGuid();

            await collection.ReplaceOneAsync(
                filter : filter,
                options : new ReplaceOptions {
                IsUpsert = true
            },
                replacement : personPerCityCounter,
                session : session);
        }
        // private methods
        private CommandResult RunCommand(MongoConnection connection, string databaseName, IMongoCommand command)
        {
            var readerSettings   = new BsonBinaryReaderSettings();
            var writerSettings   = new BsonBinaryWriterSettings();
            var resultSerializer = BsonSerializer.LookupSerializer <CommandResult>();

            var commandOperation = new CommandOperation <CommandResult>(
                databaseName,
                readerSettings,
                writerSettings,
                command,
                QueryFlags.None,
                null, // options
                null, // readPreference
                resultSerializer);

            return(commandOperation.Execute(connection));
        }
Esempio n. 49
0
        private void button3_Click(object sender, EventArgs e)
        {
            bool control = true;

            if ((textBox1.Text.Length == 0) || (textBox2.Text.Length == 0))
            {
                control = false;
            }
            else
            {
                novo.nome       = textBox1.Text;
                novo.descricao  = textBox2.Text;
                novo.setor      = comboBox1.Text;
                novo.quantidade = 0;
                novo.preco      = textBox5.Text;
                novo.codHVEX    = gerarcodhvex(sender, e);

                control = true;
            }



            novo.ProductCollection = lista;

            var teste = MongoConnection.QueryCollection("produtohvex", Builders <produtoHVEX> .Filter.Where(c => c.nome.Contains(textBox1.Text)), null);

            if (teste.Count != 0)
            {
                control = false;
                MessageBox.Show("Já existe um produto com o mesmo nome no estoque");
                DialogResult = DialogResult.Yes;
            }



            if (control)
            {
                MongoConnection.InsertOne("produtohvex", novo);
                MessageBox.Show("Deu bão!");
                DialogResult = DialogResult.Yes;
                soma         = 0;
            }
        }
 /// <summary>
 /// 保存
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnSave_Click(object sender, RoutedEventArgs e)
 {
     if (ValidateConnectionInfo())
     {
         MongoConnection connection = ModelConverter.ToMongoConnection(ConnectionInfo);
         if (_manager.Save(connection))
         {
             IsSave         = true;
             ConnectionInfo = ModelConverter.ToConnectionViewModel(connection);
             //MessageBox.Show("保存成功!");
             this.Close();
         }
         else
         {
             IsSave = false;
             MessageBox.Show("保存失败!");
         }
     }
 }
Esempio n. 51
0
        // public methods
        public WriteConcernResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;

            if (serverInstance.Supports(FeatureId.WriteCommands) && _args.WriteConcern.Enabled)
            {
                var emulator = new DeleteOpcodeOperationEmulator(_args);
                return(emulator.Execute(connection));
            }

            var requests = _args.Requests.ToArray();

            if (requests.Length != 1)
            {
                throw new NotSupportedException("Delete Opcode only supports a single delete request.");
            }
            var deleteRequest = (DeleteRequest)requests[0];

            RemoveFlags flags;

            switch (deleteRequest.Limit)
            {
            case 0: flags = RemoveFlags.None; break;

            case 1: flags = RemoveFlags.Single; break;

            default: throw new NotSupportedException("Delete Opcode only supports limit values of 0 and 1.");
            }

            SendMessageWithWriteConcernResult sendMessageResult;

            using (var stream = new MemoryStream())
            {
                var maxDocumentSize = connection.ServerInstance.MaxDocumentSize;

                var message = new MongoDeleteMessage(WriterSettings, CollectionFullName, flags, maxDocumentSize, deleteRequest.Query);
                message.WriteTo(stream);

                sendMessageResult = SendMessageWithWriteConcern(connection, stream, message.RequestId, ReaderSettings, WriterSettings, WriteConcern);
            }

            return(WriteConcern.Enabled ? ReadWriteConcernResult(connection, sendMessageResult) : null);
        }
        internal void ReleaseConnection(MongoConnection connection)
        {
            lock (_serverLock)
            {
                // if the thread has called RequestStart just verify that the connection it is releasing is the right one
                int     threadId = Thread.CurrentThread.ManagedThreadId;
                Request request;
                if (_requests.TryGetValue(threadId, out request))
                {
                    if (connection != request.Connection)
                    {
                        throw new ArgumentException("Connection being released is not the one assigned to the thread by RequestStart.", "connection");
                    }
                    return; // hold on to the connection until RequestDone is called
                }
            }

            connection.ServerInstance.ReleaseConnection(connection);
        }
Esempio n. 53
0
        public List <Product> GetAllProducts()
        {
            var collection     = MongoConnection.GetCollection <ProductDto>("Products");
            var storedProducts = collection.AsQueryable().ToList();

            List <Product> products = new List <Product>();

            foreach (var storedProduct in storedProducts)
            {
                products.Add(new Product()
                {
                    Id         = storedProduct.Id,
                    Name       = storedProduct.Name,
                    HashedName = HashName(storedProduct.Name)
                });
            }

            return(products);
        }
Esempio n. 54
0
        public static void Write(MongoConnection connection, string message, Type location, string stackTrace, Config.LogLevelEnum logLevel)
        {
            if (WriteLogLevel.HasFlag(logLevel))
            {
                Log log = new Log()
                {
                    CreatedTime = DateTime.Now,
                    Message     = message,
                    Location    = location.Name,
                    StackTrace  = stackTrace,
                    LogLevel    = logLevel,
                };

                if (IsRepeatedMessage(log) == false)
                {
                    log.Insert(connection);
                }
            }
        }
        public async void Getting_All_Products_Should_Return_All_Products()
        {
            MongoConnection.Configure("mongodb://localhost", "owinMongoTest");
            TestHelpers.DestroyAllData();

            dynamic formVars = new ExpandoObject();

            formVars.Name = "alpha";
            await TestHelpers.TestServerInstance.Value.HttpClient.PostAsync("/products/add", TestHelpers.DynamicToFormData(formVars));

            formVars.Name = "omega";
            await TestHelpers.TestServerInstance.Value.HttpClient.PostAsync("/products/add", TestHelpers.DynamicToFormData(formVars));

            var response = await TestHelpers.TestServerInstance.Value.HttpClient.GetAsync("/products/");

            var result = await response.Content.ReadAsAsync <List <object> >();

            Assert.AreEqual(result.Count, 2);
        }
Esempio n. 56
0
        public static void Main(string[] args)
        {
            Stopwatch hourlyTimer = new Stopwatch();
            Stopwatch daylyTimer  = new Stopwatch();

            //TEST
            MongoConnection mongoConnection = new MongoConnection(mongoConnectionString, mongoDatabaseName);

            for (var i = 0; i <= 5; i++)
            {
                mongoConnection.InsertData("TempMaxHour", 23.50F - i, DateTime.Now.AddHours(-i), Delay.Hour);
            }

            //IN APP TIMER
            //while (true)
            //{
            //    if(hourlyTimer.Elapsed > TimeSpan.FromHours(1))
            //    {
            //        hourlyTimer.Restart();
            //        ComplexCalculation(Delay.Hour);
            //    }
            //    if(daylyTimer.Elapsed < TimeSpan.FromDays(1))
            //    {
            //        daylyTimer.Restart();
            //        ComplexCalculation(Delay.Day);
            //    }
            //}

            //TASK SCHEDULER
            //foreach (var arg in args)
            //{
            //    if (arg == "Hour")
            //    {
            //        ComplexCalculation(Delay.Hour);
            //    }
            //    if (arg == "Day")
            //    {
            //        ComplexCalculation(Delay.Day);
            //    }
            //}
            //Console.ReadLine();
        }
Esempio n. 57
0
        public async Task <ActionResult> CreateRequestAsync(string accesstoken, string contents, string tag, string deletepolicy)
        {
            //var permissions= await NightscoutPermissions.CheckUploadPermissions(accesstoken);
            //var permissions = await NightscoutPermissions.CheckProcessPermissions(accesstoken);
            if (!await this.checkUploadPermissions(accesstoken))
            {
                return(this.Error("CreateRequestAsync Denied"));
            }



            if (string.IsNullOrWhiteSpace(contents))
            {
                return(this.Error("CreateRequestAsync Denied: invalid parameter contents"));
            }



            var g       = Guid.NewGuid().ToString();
            var reading = new RBS_Blob
            {
                CreatedOn    = DateTime.Now,
                ModifiedOn   = DateTime.Now,
                contents     = contents,
                uuid         = g,
                purpose      = "RBS",
                tag          = string.IsNullOrWhiteSpace(tag) ? null : tag.Substring(0, Math.Min(tag.Length, 10)),
                deletePolicy = deletepolicy == "autodelete" ? "auto" : null
            };

            //return this.Error("synthax ok");
            try{
                await MongoConnection.AsyncInsertReading(reading);
            } catch (System.TimeoutException) {
                return(Error("Timeout, database down?"));
            }

            return(Success <RBS_Blob>(reading, "CreateRequestAsync"));

            //var content = $"accesstoken: {accesstoken}, b64contents: {b64contents}, guid: {g}";
            //return Content("CreateRequestAsync IS NOT IMPLEMENTED YET:" + content);
        }
        // public methods
        public WriteConcernResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;

            if (serverInstance.Supports(FeatureId.WriteCommands) && _args.WriteConcern.Enabled)
            {
                var emulator = new UpdateOpcodeOperationEmulator(_args);
                return(emulator.Execute(connection));
            }

            SendMessageWithWriteConcernResult sendMessageResult;

            using (var stream = new MemoryStream())
            {
                var requests = _args.Requests.ToList();
                if (requests.Count != 1)
                {
                    throw new NotSupportedException("Update opcode only supports a single update request.");
                }
                var updateRequest = (UpdateRequest)requests[0];

                var flags = UpdateFlags.None;
                if (updateRequest.IsMultiUpdate ?? false)
                {
                    flags |= UpdateFlags.Multi;
                }
                if (updateRequest.IsUpsert ?? false)
                {
                    flags |= UpdateFlags.Upsert;
                }

                var maxDocumentSize = connection.ServerInstance.MaxDocumentSize;
                var query           = updateRequest.Query ?? new QueryDocument();

                var message = new MongoUpdateMessage(WriterSettings, CollectionFullName, _args.CheckElementNames, flags, maxDocumentSize, query, updateRequest.Update);
                message.WriteTo(stream);

                sendMessageResult = SendMessageWithWriteConcern(connection, stream, message.RequestId, ReaderSettings, WriterSettings, WriteConcern);
            }

            return(WriteConcern.Enabled ? ReadWriteConcernResult(connection, sendMessageResult) : null);
        }
        // public methods
        public WriteConcernResult Execute(MongoConnection connection)
        {
            var serverInstance = connection.ServerInstance;

            if (!serverInstance.Supports(FeatureId.WriteCommands))
            {
                throw new NotSupportedException("Write commands are not supported.");
            }

            var operation = new BulkUpdateOperation(_args);

            BulkWriteResult    bulkWriteResult;
            BulkWriteException bulkWriteException = null;

            try
            {
                bulkWriteResult = operation.Execute(connection);
            }
            catch (BulkWriteException ex)
            {
                bulkWriteResult    = ex.Result;
                bulkWriteException = ex;
            }

            var converter = new BulkWriteResultConverter();

            if (bulkWriteException != null)
            {
                throw converter.ToWriteConcernException(bulkWriteException);
            }
            else
            {
                if (_args.WriteConcern.Enabled)
                {
                    return(converter.ToWriteConcernResult(bulkWriteResult));
                }
                else
                {
                    return(null);
                }
            }
        }
Esempio n. 60
0
        private void CreateDatabase()
        {
            if (_database != null)
            {
                return;
            }

            // thread safe database creation
            lock (_databaseLock)
            {
                if (_database != null)
                {
                    return;
                }

                _database = string.IsNullOrEmpty(ConnectionName)
                    ? MongoConnection.GetConnection("mongodb://localhost/Messaging")
                    : MongoConnection.GetDatabase(ConnectionName);
            }
        }