Exemple #1
0
        public GeneralTrigger(BsonDocument doc, TriggerType triggerType) {
            TriggerOn = new List<string>();
            And = new List<string>();
            NotOn = new List<string>();
            MessageOverrideAsString = new List<string>();
            if (doc != null && doc.ElementCount > 0 && doc.Contains("TriggerOn")) {
                foreach (var on in doc["TriggerOn"].AsBsonArray) {
                    TriggerOn.Add(on.AsString);
                }
                foreach (var and in doc["And"].AsBsonArray) {
                    And.Add(and.AsString);
                }
                foreach (var not in doc["NoTriggerOn"].AsBsonArray) {
                    NotOn.Add(not.AsString);
                }
                AutoProcess = doc.Contains("AutoProcess") ? doc["AutoProcess"].AsBoolean : false;
                ChanceToTrigger = doc["ChanceToTrigger"].AsInt32;
                script = ScriptFactory.GetScript(doc["ScriptID"].AsString, triggerType.ToString());
                foreach (var overrides in doc["Overrides"].AsBsonArray) {
                    MessageOverrideAsString.Add(overrides.AsString);
                }
                Type = doc["Type"].AsString;
				TriggerId = doc["Id"].AsString;
            }
        }
Exemple #2
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            decimal price = 0m;
            if (!document.Contains(OrganizationRepository.FieldNames.PlanId))
                return;

            switch (document.GetValue(OrganizationRepository.FieldNames.PlanId).AsString) {
                case "EX_SMALL":
                    price = BillingManager.SmallPlan.Price;
                    break;
                case "EX_MEDIUM":
                    price = BillingManager.MediumPlan.Price;
                    break;
                case "EX_LARGE":
                    price = BillingManager.LargePlan.Price;
                    break;
            }

            if (price == 0m)
                return;

            if (!document.Contains(OrganizationRepository.FieldNames.BillingPrice))
                document.Add(OrganizationRepository.FieldNames.BillingPrice, new BsonString(price.ToString()));
            else
                document.Set(OrganizationRepository.FieldNames.BillingPrice, new BsonString(price.ToString()));

            collection.Save(document);
        }
Exemple #3
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document)
        {
            if (document.Contains("ErrorCount"))
                document.ChangeName("ErrorCount", "EventCount");

            if (document.Contains("TotalErrorCount"))
                document.ChangeName("TotalErrorCount", "TotalEventCount");

            if (document.Contains("LastErrorDate"))
                document.ChangeName("LastErrorDate", "LastEventDate");

            if (document.Contains("MaxErrorsPerMonth"))
                document.ChangeName("MaxErrorsPerMonth", "MaxEventsPerMonth");

            if (document.Contains("SuspensionCode")) {
                var value = document.GetValue("SuspensionCode");
                document.Remove("SuspensionCode");

                SuspensionCode suspensionCode;
                if (value.IsString && Enum.TryParse(value.AsString, true, out suspensionCode))
                    document.Set("SuspensionCode", suspensionCode);
            }

            collection.Save(document);
        }
Exemple #4
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("OverageHours"))
                document.Remove("OverageHours");

            if (document.Contains("Usage"))
                document.Remove("Usage");

            collection.Save(document);
        }
Exemple #5
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("MaxErrors"))
                document.Remove("MaxErrors");

            if (document.Contains("MaxErrorsPerStack"))
                document.Remove("MaxErrorsPerStack");

            collection.Save(document);
        }
 public void InsertOneBsonDocument()
 {
     var bsonDocument = new BsonDocument()
     {
         {"Name","Mehmet Çakır"},
         {"Email","*****@*****.**"}
     };
     bsonDocument.Contains("_id").Should().BeFalse();
     Func<Task> act = () => BlogContext.UserAsBson.InsertOneAsync(bsonDocument);
     act.ShouldNotThrow();
     bsonDocument.Contains("_id").Should().BeTrue();
     bsonDocument["_id"].Should().NotBe(ObjectId.Empty);
 }
Exemple #7
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("OverageDays"))
                document.Remove("OverageDays");

            if (document.Contains("MaxErrorsPerDay")) {
                document.ChangeName("MaxErrorsPerDay", "MaxErrorsPerMonth");
                var maxErrorsPerMonth = document.GetValue("MaxErrorsPerMonth").AsInt32;
                if (maxErrorsPerMonth > 0)
                    document.Set("MaxErrorsPerMonth", maxErrorsPerMonth * 30);
            }

            collection.Save(document);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        private UpdateFlags GetUpdateFlags(BsonDocument document) {
            var flags = UpdateFlags.None;

            if (document.Contains("upsert")) {
                flags = flags | ((document["upsert"].ToBoolean()) ? (UpdateFlags.Upsert) : (UpdateFlags.None));
            }

            if (document.Contains("multi")) {
                flags = flags | ((document["multi"].ToBoolean()) ? (UpdateFlags.Upsert) : (UpdateFlags.None));
            }

            return flags;
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="AggregateResult" /> class.
 /// </summary>
 /// <param name="response">The response.</param>
 public AggregateResult(BsonDocument response)
     : base(response)
 {
     if (response.Contains("cursor"))
     {
         var cursorDocument = response["cursor"];
         _cursorId = cursorDocument["id"].ToInt64();
         _resultDocuments = cursorDocument["firstBatch"].AsBsonArray.Select(v => v.AsBsonDocument);
     }
     if (response.Contains("result"))
     {
         _resultDocuments = response["result"].AsBsonArray.Select(v => v.AsBsonDocument);
     }
 }
Exemple #10
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("OrganizationId"))
                document.ChangeName("OrganizationId", "oid");
            
            if (document.Contains("ProjectId"))
                document.ChangeName("ProjectId", "pid");

            if (document.Contains("Version"))
                document.Remove("Version");

            document.Set("Version", "1.0.0.0");

            collection.Save(document);
        }
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (!document.Contains(OrganizationRepository.FieldNames.PlanId))
                return;

            string planId = document.GetValue(OrganizationRepository.FieldNames.PlanId).AsString;
            if (String.IsNullOrEmpty(planId) || !String.Equals(planId, BillingManager.FreePlan.Id))
                return;

            if (!document.Contains(OrganizationRepository.FieldNames.RetentionDays))
                document.Add(OrganizationRepository.FieldNames.RetentionDays, new BsonInt64(BillingManager.FreePlan.RetentionDays));
            else
                document.Set(OrganizationRepository.FieldNames.RetentionDays, new BsonInt64(BillingManager.FreePlan.RetentionDays));

            collection.Save(document);
        }
Exemple #12
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            ObjectId organizationId = document.GetValue(ProjectRepository.FieldNames.OrganizationId).AsObjectId;
            var users = Database.GetCollection(UserRepository.CollectionName)
                .Find(Query.In(UserRepository.FieldNames.OrganizationIds, new List<BsonValue> {
                    organizationId
                }))
                .SetFields(ProjectRepository.FieldNames.Id).ToList();

            if (!document.Contains(ProjectRepository.FieldNames.NotificationSettings))
                document.Add(ProjectRepository.FieldNames.NotificationSettings, new BsonDocument());

            BsonDocument settings = document.GetValue(ProjectRepository.FieldNames.NotificationSettings).AsBsonDocument;
            foreach (var user in users) {
                var userId = user.GetValue(ProjectRepository.FieldNames.Id).AsObjectId.ToString();
                if (!settings.Contains(userId))
                    settings.Add(userId, new BsonDocument());

                var userSettings = settings.GetValue(userId).AsBsonDocument;
                if (!userSettings.Contains("SendDailySummary"))
                    userSettings.Add("SendDailySummary", new BsonBoolean(true));
                else
                    userSettings.Set("SendDailySummary", new BsonBoolean(true));
            }

            collection.Save(document);
        }
Exemple #13
0
 public static long GetInt64(BsonDocument doc, string propertyName)
 {
     long result = 0;
     if (doc.Contains(propertyName))
         result = doc[propertyName].AsInt64;
     return result;
 }
Exemple #14
0
 /// <summary>
 ///     获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     var matchlist = new BsonDocument();
     foreach (CtlMatchItem item in Controls)
     {
         var match = item.GetMatchItem();
         if (match != null)
         {
             var matchName = match.GetElement(0).Name;
             if (matchlist.Contains(matchName))
             {
                 var addMatch = match.GetElement(0).Value.AsBsonDocument;
                 matchlist.GetElement(matchName).Value.AsBsonDocument.AddRange(addMatch);
             }
             else
             {
                 matchlist.AddRange(match);
             }
         }
     }
     if (matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", matchlist);
     }
     return null;
 }
Exemple #15
0
 public static Guid GetGuid(BsonDocument doc, string propertyName)
 {
     Guid result = Guid.Empty;
     if (doc.Contains(propertyName))
         result = new Guid(doc[propertyName].AsByteArray);
     return result;
 }
Exemple #16
0
 public static int GetInt32(BsonDocument doc, string propertyName)
 {
     int result = 0;
     if (doc.Contains(propertyName))
         result = doc[propertyName].AsInt32;
     return result;
 }
Exemple #17
0
 public static bool GetBoolean(BsonDocument doc, string propertyName)
 {
     bool result = false;
     if (doc.Contains(propertyName))
         result = doc[propertyName].AsBoolean;
     return result;
 }
Exemple #18
0
 public static DateTime GetDateTime(BsonDocument doc, string propertyName)
 {
     DateTime result = DateTime.MinValue;
     if (doc.Contains(propertyName))
         result = doc[propertyName].ToUniversalTime();
     return result;
 }
Exemple #19
0
 /// <summary>
 ///     获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     var matchlist = new BsonDocument();
     foreach (Control item in Controls)
     {
         if (item.GetType().FullName == typeof(Button).FullName) continue;
         var match = ((CtlMatchItem)item).GetMatchItem();
         if (match != null)
         {
             var matchName = match.GetElement(0).Name;
             if (matchlist.Contains(matchName))
             {
                 var addMatch = match.GetElement(0).Value.AsBsonDocument;
                 matchlist.GetElement(matchName).Value.AsBsonDocument.AddRange(addMatch);
             }
             else
             {
                 matchlist.AddRange(match);
             }
         }
     }
     if (matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", matchlist);
     }
     return null;
 }
Exemple #20
0
 public static BsonArray GetArray(BsonDocument doc, string propertyName)
 {
     BsonArray result = null;
     if (doc.Contains(propertyName))
         result = doc[propertyName].AsBsonArray;
     return result;
 }
        /// <summary>
        /// Combines subqueries with an and operator.
        /// </summary>
        /// <param name="queries">The subqueries.</param>
        /// <returns>The builder (so method calls can be chained).</returns>
        public static QueryComplete And(
            params QueryComplete[] queries
        ) {
            var document = new BsonDocument();
            foreach (var query in queries) {
                foreach (var queryElement in query.ToBsonDocument()) {
                    // if result document has existing operations for same field append the new ones
                    if (document.Contains(queryElement.Name)) {
                        var existingOperations = document[queryElement.Name] as BsonDocument;
                        var newOperations = queryElement.Value as BsonDocument;

                        // make sure that no conditions are Query.EQ, because duplicates aren't allowed
                        if (existingOperations == null || newOperations == null) {
                            var message = string.Format("Query.And does not support combining equality comparisons with other operators (field: '{0}')", queryElement.Name);
                            throw new InvalidOperationException(message);
                        }

                        // add each new operation to the existing operations
                        foreach (var operation in newOperations) {
                            // make sure that there are no duplicate $operators
                            if (existingOperations.Contains(operation.Name)) {
                                var message = string.Format("Query.And does not support using the same operator more than once (field: '{0}', operator: '{1}')", queryElement.Name, operation.Name);
                                throw new InvalidOperationException(message);
                            } else {
                                existingOperations.Add(operation);
                            }
                        }
                    } else {
                        document.Add(queryElement);
                    }
                }
            }
            return new QueryComplete(document);
        }
Exemple #22
0
        public static BsonDocument ToBsonDocument(this XElement xElement)
        {
            var bsonDocument = new BsonDocument();

            var type = xElement.Name.ToString();
            bsonDocument.Add(Constants._TYPE, type);
            var mainId = xElement.Attribute(Constants._ID) != null ? xElement.Attribute(Constants._ID).Value : null;

            foreach (XAttribute attribure in xElement.Attributes())
            {
                var key = attribure.Name.ToString();
                var value = attribure.Value;
                if (bsonDocument.Contains(key))
                    bsonDocument.Set(key, value);
                else
                    bsonDocument.Add(key, value);
            }
            foreach (XElement kid in xElement.Descendants())
            {
                var id = kid.Attribute(Constants._ID);
                if (id == null || mainId == null)
                {
                    bsonDocument.Add(kid.Name.ToString(), kid.ToBsonDocument());
                }
                else
                {
                    kid.SetAttributeValue(Constants.PARENT_ID, mainId);
                    DBFactory.GetData().Save(kid);
                }
            }
            return bsonDocument;
        }
 /// <summary>
 /// 获取Match
 /// </summary>
 /// <returns></returns>
 public BsonDocument GetMatchDocument()
 {
     BsonDocument Matchlist = new BsonDocument();
     foreach (ctlMatchItem item in this.Controls)
     {
         BsonDocument match = item.getMatchItem();
         if (match != null)
         {
             string MatchName = match.GetElement(0).Name;
             if (Matchlist.Contains(MatchName))
             {
                 BsonDocument AddMatch = match.GetElement(0).Value.AsBsonDocument;
                 Matchlist.GetElement(MatchName).Value.AsBsonDocument.Add(AddMatch);
             }
             else {
                 Matchlist.Add(match);
             }
         }
     }
     if (Matchlist.ElementCount > 0)
     {
         return new BsonDocument("$match", Matchlist);
     }
     else
     {
         return null;
     }
 }
Exemple #24
0
 private static IEnumerable<BsonElement> ProcessFields(this BsonDocument a, BsonDocument b)
 {
     return from e in a.Where(e => b.Contains(e.Name))
            let d = Diff(e.Value, b[e.Name])
            where d.ElementCount > 0
            select new BsonElement(e.Name, d);
 }
Exemple #25
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("EmailNotificationsEnabled")) {
                bool emailNotificationsEnabled = document.GetValue("EmailNotificationsEnabled").AsBoolean;
                while (document.Contains("EmailNotificationsEnabled"))
                    document.Remove("EmailNotificationsEnabled");

                document.Set("EmailNotificationsEnabled", emailNotificationsEnabled);
            }

            if (document.Contains("EmailAddress")) {
                string emailAddress = document.GetValue("EmailAddress").AsString;
                if (!String.IsNullOrWhiteSpace(emailAddress))
                    document.Set("EmailAddress", emailAddress.ToLowerInvariant().Trim());
            }

            collection.Save(document);
        }
Exemple #26
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (!document.Contains(UserRepository.FieldNames.IsEmailAddressVerified))
                document.Add(UserRepository.FieldNames.IsEmailAddressVerified, new BsonBoolean(true));
            else
                document.Set(UserRepository.FieldNames.IsEmailAddressVerified, new BsonBoolean(true));

            collection.Save(document);
        }
Exemple #27
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (collection.IndexExistsByName("Username_1"))
                collection.DropIndexByName("Username_1");

            if (document.Contains("Username"))
                document.Remove("Username");

            collection.Save(document);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="document"></param>
 static public MailItem BsonDocumentToMailItem(BsonDocument document)
 {
     var mailitem = new MailItem();
     if (document.Contains("_id"))mailitem.Id = document["_id"].ToString();
     if (document.Contains("text"))mailitem.Text = document["text"].AsString;
     if (document.Contains("time"))mailitem.Time = document["time"].ToLocalTime();
     if (document.Contains("form"))mailitem.FormCode = document["form"].AsString;
     if (document.Contains("year"))mailitem.Year = document["year"].AsInt32;
     if (document.Contains("period"))mailitem.Period = document["period"].AsInt32;
     if (document.Contains("obj"))mailitem.ObjId = document["obj"].AsInt32;
     if (document.Contains("user"))mailitem.User = document["user"].AsString;
     if (document.Contains("type"))mailitem.Type = document["type"].AsString;
     TestItem = mailitem;
     return mailitem;
 }
Exemple #29
0
        private List<string> ParseMembers(BsonDocument document)
        {
            if(document == null || !document.Contains("teamMemberIds"))
            {
                return new List<string>();
            }

            var teamMemberIds = document["teamMemberIds"].AsBsonArray;
            return teamMemberIds.Select(i => GetStringValue(i, "userId")).ToList();
        }
Exemple #30
0
        public static bool GetBoolean(BsonDocument doc, string propertyName)
        {
            bool result = false;

            if (doc.Contains(propertyName))
            {
                result = doc[propertyName].AsBoolean;
            }
            return(result);
        }
Exemple #31
0
        public static BsonArray GetArray(BsonDocument doc, string propertyName)
        {
            BsonArray result = null;

            if (doc.Contains(propertyName))
            {
                result = doc[propertyName].AsBsonArray;
            }
            return(result);
        }
Exemple #32
0
        public static long?GetLong(BsonDocument doc, string propertyName)
        {
            long?result = null;

            if (doc.Contains(propertyName))
            {
                result = doc[propertyName].AsInt64;
            }
            return(result);
        }
Exemple #33
0
        public static DateTime GetDateTime(BsonDocument doc, string propertyName)
        {
            DateTime result = DateTime.MinValue;

            if (doc.Contains(propertyName))
            {
                result = doc[propertyName].ToUniversalTime();
            }
            return(result);
        }
 private void FillCursorStatistics(BsonDocument statusOutput, IDictionary <string, object> status)
 {
     if (statusOutput.Contains("cursors"))
     {
         BsonDocument cursorsOutput           = (BsonDocument)statusOutput["cursors"];
         IDictionary <string, object> cursors = new Dictionary <string, object>();
         status.Add("cursors", cursors);
         cursors.Add("totalOpen", cursorsOutput["totalOpen"]);
     }
 }
Exemple #35
0
        public override void UpdateDocument(MongoCollection<BsonDocument> collection, BsonDocument document) {
            if (document.Contains("oid")) {
                var organizationId = document.GetValue("oid").AsNullableObjectId;
                if (!organizationId.HasValue || organizationId.Value == ObjectId.Empty) {
                    document.Remove("oid");
                } else {
                    var organizationCollection = Database.GetCollection("organization");
                    var organization = organizationCollection.FindOneById(organizationId);

                    // The organization with this id could not be found.. Remove the webhook.
                    if (organization == null) {
                        collection.Remove(Query.EQ("_id", document.GetDocumentId()));
                        return;
                    }
                }
            }

            var projectCollection = Database.GetCollection("project");
            if (document.Contains("pid")) {
                var projectId = document.GetValue("pid").AsNullableObjectId;
                if (!projectId.HasValue || projectId.Value == ObjectId.Empty) {
                    document.Remove("pid");
                } else {
                    var project = projectCollection.FindOneById(projectId);

                    // The project with this id could not be found.. Remove the webhook.
                    if (project == null) {
                        collection.Remove(Query.EQ("_id", document.GetDocumentId()));
                        return;
                    }

                    if (!document.Contains("oid"))
                        document.Set("oid", project.GetValue("oid").AsObjectId);
                }
            }

            if (!document.Contains("oid") && !document.Contains("pid")) {
                collection.Remove(Query.EQ("_id", document.GetDocumentId()));
                return;
            }

            collection.Save(document);
        }
Exemple #36
0
        public static string GetString(BsonDocument doc, string propertyName)
        {
            string result = null;

            if (doc.Contains(propertyName))
            {
                result = doc[propertyName].AsString;
            }
            return(result);
        }
        protected override void DropCollection(MongoClient client, string databaseName, string collectionName, BsonDocument test, BsonDocument shared)
        {
            base.DropCollection(client, databaseName, collectionName, test, shared);

            if (shared.Contains("key_vault_data"))
            {
                var keyVaultDatabase = client.GetDatabase(__keyVaultCollectionNamespace.DatabaseNamespace.DatabaseName).WithWriteConcern(WriteConcern.WMajority);
                keyVaultDatabase.DropCollection(__keyVaultCollectionNamespace.CollectionName);
            }
        }
Exemple #38
0
        /// <summary>
        /// Get timesheet fragment for asset. Fragment can be returned directly because we always have just one fragment
        /// and no extra details (overtime etc...).
        /// </summary>
        /// <param name="timesheetEntry"></param>
        /// <returns></returns>
        private TimesheetEntryFragment GetTimesheetFragmentForAsset(BsonDocument timesheetEntry)
        {
            if (!timesheetEntry.Contains("starttimestamp") || !timesheetEntry.Contains("endtimestamp"))
            {
                throw new HandlerException("Start or end time missing in asset timesheet entry.");
            }

            MongoCollection <BsonDocument> assetsCollection = database.GetCollection("asset");
            BsonDocument asset = assetsCollection.FindOne(Query.EQ(DBQuery.Id, timesheetEntry["asset"][0]));

            MongoCollection <BsonDocument> projectsCollection = database.GetCollection("project");
            IMongoQuery  query   = Query.EQ(DBQuery.Id, timesheetEntry["project"]);
            BsonDocument project = projectsCollection.FindOne(Query.EQ(DBQuery.Id, (ObjectId)timesheetEntry["project"][0]));

            if (project == null)
            {
                throw new HandlerException("Project not found for asset timesheet entry.");
            }

            if (asset == null)
            {
                throw new HandlerException("Asset not found for timesheet entry.");
            }

            if (!project.Contains("identifier"))
            {
                throw new HandlerException("Project is missing an identifier.");
            }

            if (!asset.Contains("identifier"))
            {
                throw new HandlerException("Asset is missing an identifier.");
            }

            if (!asset.Contains("projectcategory"))
            {
                throw new HandlerException("Asset is missing category.");
            }

            MongoCollection <BsonDocument> projectCategories = database.GetCollection("projectcategory");
            BsonDocument projectCategory = projectCategories.FindOne(Query.EQ(DBQuery.Id, asset["projectcategory"][0]));

            var timesheetEntryWithDetails = new TimesheetEntryWithDetails();
            var fragment = new TimesheetEntryFragment();

            fragment.Detail              = timesheetEntry;
            fragment.IsRootEntry         = true;
            fragment.ProjectCategoryBase = (string)projectCategory["identifier"];
            fragment.ProjectId           = (string)project["identifier"];
            fragment.Start    = ((DateTime)timesheetEntry["starttimestamp"]).ToLocalTime();
            fragment.End      = ((DateTime)timesheetEntry["endtimestamp"]).ToLocalTime();
            fragment.WorkerId = (string)asset["identifier"];

            return(fragment);
        }
        public async Task <BsonDocument> FindDuplicate(CollectionEnum collectionEnum, BsonDocument doc)
        {
            var col = mongoDB.GetCollection <BsonDocument>(collectionEnum.ToString());

            var builder = Builders <BsonDocument> .Filter;
            FilterDefinition <BsonDocument> filter = null;

            if (doc.Contains(Const.ID))
            {
                string id = doc.GetValue(Const.ID).AsString;

                filter = AddFilter(filter, builder.Eq(Const.ID, new ObjectId(id)));
            }

            if (collectionEnum == CollectionEnum.entries && doc.Contains(Const.DATE_ELEMENT))
            {
                double date = doc.GetValue(Const.DATE_ELEMENT).AsInt64;

                filter = AddFilter(filter, builder.Gt(Const.DATE_ELEMENT, date - 1000));
                filter = AddFilter(filter, builder.Lt(Const.DATE_ELEMENT, date + 1000));
            }

            if (filter == null)
            {
                return(null);
            }

            var list = await col.Find(filter)
                       .Limit(1)
                       .ToListAsync();

            if (list.Count > 0)
            {
                var existingDoc = list[0];
                UnpackId(existingDoc);
                return(existingDoc);
            }
            else
            {
                return(null);
            }
        }
Exemple #40
0
        private Type0CommandMessageSection <BsonDocument> CreateType0Section(ConnectionDescription connectionDescription)
        {
            var extraElements = new List <BsonElement>();

            addIfNotAlreadyAdded("$db", _databaseNamespace.DatabaseName);

            if (connectionDescription.IsMasterResult.ServerType != ServerType.Standalone &&
                _readPreference != null &&
                _readPreference != ReadPreference.Primary)
            {
                var readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(_readPreference);
                addIfNotAlreadyAdded("$readPreference", readPreferenceDocument);
            }

            if (_session.Id != null)
            {
                addIfNotAlreadyAdded("lsid", _session.Id);
            }

            if (_session.ClusterTime != null)
            {
                addIfNotAlreadyAdded("$clusterTime", _session.ClusterTime);
            }
            Action <BsonWriterSettings> writerSettingsConfigurator = s => s.GuidRepresentation = GuidRepresentation.Unspecified;

            _session.AboutToSendCommand();
            if (_session.IsInTransaction)
            {
                var transaction = _session.CurrentTransaction;
                addIfNotAlreadyAdded("txnNumber", transaction.TransactionNumber);
                if (transaction.State == CoreTransactionState.Starting)
                {
                    addIfNotAlreadyAdded("startTransaction", true);
                    var readConcern = ReadConcernHelper.GetReadConcernForFirstCommandInTransaction(_session, connectionDescription);
                    if (readConcern != null)
                    {
                        addIfNotAlreadyAdded("readConcern", readConcern);
                    }
                }
                addIfNotAlreadyAdded("autocommit", false);
            }

            var elementAppendingSerializer = new ElementAppendingSerializer <BsonDocument>(BsonDocumentSerializer.Instance, extraElements, writerSettingsConfigurator);

            return(new Type0CommandMessageSection <BsonDocument>(_command, elementAppendingSerializer));

            void addIfNotAlreadyAdded(string key, BsonValue value)
            {
                if (!_command.Contains(key))
                {
                    extraElements.Add(new BsonElement(key, value));
                }
            }
        }
Exemple #41
0
        private static string get(string name, BsonDocument b)
        {
            string item = "";

            if (b.Contains(name))
            {
                item = b.GetValue(name).AsString.Trim();
            }

            return(item);
        }
        // public methods
        public override void Arrange(BsonDocument document)
        {
            JsonDrivenHelper.EnsureFieldEquals(document, "object", "collection");

            if (document.Contains("collectionOptions"))
            {
                ParseCollectionOptions(document["collectionOptions"].AsBsonDocument);
            }

            base.Arrange(document);
        }
        /// <summary>
        /// 序列化Bson為Redis格式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static List <HashEntry> Serialize(Type type, BsonDocument entity)
        {
            List <HashEntry> updatedList = new List <HashEntry>();

            string[] propertyNames = GetCachePropertyNames(type);

            for (int j = 0; j < propertyNames.Length; j++)
            {
                string       attName  = propertyNames[j];
                PropertyInfo property = GetCachePropertyInfo(type, attName);

                // 必須允許更新Null的值
                if (!entity.Contains(attName))
                {
                    continue;
                }
                // 非基本型別轉Json處理
                if (!property.PropertyType.IsValueType && property.PropertyType != typeof(string))
                {
                    updatedList.Add(new HashEntry(attName, entity[attName].ToJson()));
                }
                else
                {
                    HashEntry entry = new HashEntry(attName, RedisValue.Null);
                    if (property.PropertyType == typeof(long))
                    {
                        entry = new HashEntry(attName, entity[attName].AsInt64);
                    }
                    else if (property.PropertyType == typeof(int))
                    {
                        entry = new HashEntry(attName, entity[attName].AsInt32);
                    }
                    else if (property.PropertyType == typeof(string))
                    {
                        entry = new HashEntry(attName, entity[attName].AsString);
                    }
                    else if (property.PropertyType == typeof(bool))
                    {
                        entry = new HashEntry(attName, entity[attName].AsBoolean);
                    }
                    else if (property.PropertyType == typeof(float))
                    {
                        entry = new HashEntry(attName, (float)entity[attName].AsDouble);
                    }
                    else if (property.PropertyType == typeof(double))
                    {
                        entry = new HashEntry(attName, entity[attName].AsDouble);
                    }
                    updatedList.Add(entry);
                }
            }

            return(updatedList);
        }
Exemple #44
0
 /// <summary>
 /// 检查请求是否执行成功
 /// </summary>
 /// <param name="response"></param>
 /// <returns></returns>
 public static bool CheckResponseOk(BsonDocument response)
 {
     if (response.Contains("errcode") && response["errcode"].ToInt64() == 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemple #45
0
        /// <summary>
        /// 获取主键字段名
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public static string  TableName(this BsonDocument bsonDoc)
        {
            var tbName = string.Empty;

            if (bsonDoc.Contains("underTable"))
            {
                tbName = bsonDoc.GetValue("underTable").ToString();      //当前记录所属表
            }

            return(tbName);
        }
Exemple #46
0
            private static string GetTestName(string description, BsonDocument definition)
            {
                var name = description;

                if (definition.Contains("description"))
                {
                    name += " - " + (string)definition["description"];
                }

                return(name);
            }
Exemple #47
0
        private string GetCreatedById(BsonDocument document)
        {
            if (document == null || !document.Contains("createBy"))
            {
                return(string.Empty);
            }

            var createdBy = document["createBy"].AsBsonDocument;

            return(GetStringValue(createdBy, "id"));
        }
        protected object DeserializeState(BsonDocument doc, out string version, out string id)
        {
            string t = doc["_t"].AsString;

            if (string.IsNullOrEmpty(t))
            {
                throw new Exception("No type discriminator in document");
            }
            Type tt = TypeNameDiscriminator.GetActualType(t);

            if (tt == null)
            {
                throw new Exception("Type not found: " + t);
            }
            var ret = BsonSerializer.Deserialize(doc, tt);

            version = doc.Contains("version") ? doc["version"].AsString : null;
            id      = doc.Contains("_id") ? doc["_id"].AsString : null;
            return(ret);
        }
        private string GetValue(BsonDocument document, string key)
        {
            string value = string.Empty;

            if (document.Contains(key))
            {
                value = document[key].ToString();
            }

            return(value);
        }
Exemple #50
0
 protected virtual BsonValue GetId(BsonDocument document)
 {
     if (document.Contains("_id"))
     {
         return(document["_id"]);
     }
     else
     {
         return(null);
     }
 }
 protected DateTime getLastRun(BsonDocument dirDoc)
 {
     if (dirDoc.Contains("lastRun"))
     {
         return(dirDoc.GetValue("lastRun").ToLocalTime());
     }
     else
     {
         return(DateTime.Now.AddYears(-100));
     };
 }
Exemple #52
0
 private void FillConnectionStatistics(BsonDocument statusOutput, IDictionary <string, object> status)
 {
     if (statusOutput.Contains("connections"))
     {
         BsonDocument connectionsOutput           = (BsonDocument)statusOutput["connections"];
         IDictionary <string, object> connections = new Dictionary <string, object>();
         status.Add("connections", connections);
         connections.Add("current", connectionsOutput["current"]);
         connections.Add("available", connectionsOutput["available"]);
     }
 }
Exemple #53
0
 /// <summary>
 /// 通用设置接口
 /// </summary>
 /// <param name="bsonDoc"></param>
 /// <param name="fieldName"></param>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static void SetValue(BsonDocument bsonDoc, string fieldName, string obj)
 {
     if (bsonDoc.Contains(fieldName))
     {
         bsonDoc[fieldName] = obj;
     }
     else
     {
         bsonDoc.Add(fieldName, obj);
     }
 }
Exemple #54
0
        private List <string> ParseMembers(BsonDocument document)
        {
            if (document == null || !document.Contains("teamMemberIds"))
            {
                return(new List <string>());
            }

            var teamMemberIds = document["teamMemberIds"].AsBsonArray;

            return(teamMemberIds.Select(i => GetStringValue(i, "userId")).ToList());
        }
Exemple #55
0
 /// <summary>
 /// 向对象新增key,如果key已经存在,则修改原先key对应的值
 /// </summary>
 /// <param name="bsonDoc"></param>
 /// <param name="key">key值</param>
 /// <param name="val">要新增的对象</param>
 public static void TryAdd(this BsonDocument bsonDoc, string key, string val)
 {
     if (bsonDoc.Contains(key))
     {
         bsonDoc[key] = val;
     }
     else
     {
         bsonDoc.Add(key, val);
     }
 }
Exemple #56
0
        /***************************************************/
        /**** Public Methods                            ****/
        /***************************************************/

        public static string Version(this BsonDocument document)
        {
            if (document != null && document.Contains("_bhomVersion"))
            {
                return(document["_bhomVersion"].ToString());
            }
            else
            {
                return("");
            }
        }
Exemple #57
0
        private static BsonDocument GetTimesheetEntryDetailPayType(BsonDocument timesheetEntryDetail, MongoDatabase database)
        {
            if (!timesheetEntryDetail.Contains("timesheetentrydetailpaytype"))
            {
                throw new HandlerException("Timesheet entry detail pay type missing in timesheet entry detail.");
            }

            MongoCollection <BsonDocument> payTypesCollection = database.GetCollection("timesheetentrydetailpaytype");

            return(payTypesCollection.FindOne(Query.EQ(DBQuery.Id, timesheetEntryDetail["timesheetentrydetailpaytype"][0])));
        }
Exemple #58
0
        /*******************************************/

        public static object FromBson(BsonDocument bson)
        {
            RegisterTypes();

            // Patch for handling the case where a string is a top object - will need proper review in next quarter
            if (bson.Contains("_t") && bson["_t"] == "System.String" && bson.Contains("_v"))
            {
                return(bson["_v"].AsString);
            }

            bson.Remove("_id");

            object obj = BsonSerializer.Deserialize(bson, typeof(object));

            if (obj is ExpandoObject)
            {
                Dictionary <string, object> dic = new Dictionary <string, object>(obj as ExpandoObject);
                CustomObject co = new CustomObject();
                if (dic.ContainsKey("Name"))
                {
                    co.Name = dic["Name"] as string;
                    dic.Remove("Name");
                }
                if (dic.ContainsKey("Tags"))
                {
                    co.Tags = new HashSet <string>(((List <object>)dic["Tags"]).Cast <string>());
                    dic.Remove("Tags");
                }
                if (dic.ContainsKey("BHoM_Guid"))
                {
                    co.BHoM_Guid = (Guid)dic["BHoM_Guid"];
                    dic.Remove("BHoM_Guid");
                }
                co.CustomData = dic;
                return(co);
            }
            else
            {
                return(obj);
            }
        }
Exemple #59
0
 protected virtual void AssertOutcome(BsonDocument outcome, IMongoDatabase database, IMongoCollection <BsonDocument> collection)
 {
     if (outcome != null && outcome.Contains("collection"))
     {
         var collectionToVerify = collection;
         if (outcome["collection"].AsBsonDocument.Contains("name"))
         {
             collectionToVerify = database.GetCollection <BsonDocument>(outcome["collection"]["name"].ToString());
         }
         VerifyCollection(collectionToVerify, (BsonArray)outcome["collection"]["data"]);
     }
 }
 private void AssertEvents(EventCapturer actualEvents, BsonDocument test, Dictionary <string, BsonValue> sessionIdMap)
 {
     if (test.Contains("expectations"))
     {
         foreach (var expectedEvent in test["expectations"].AsBsonArray.Cast <BsonDocument>())
         {
             RecursiveFieldSetter.SetAll(expectedEvent, "lsid", value => sessionIdMap[value.AsString]);
             var actualEvent = actualEvents.Next();
             AssertEvent(actualEvent, expectedEvent);
         }
     }
 }