Exemplo n.º 1
0
        public Task <ReplaceOneResult> UpdateAsync <T>(string Name, Type Type, T Document)
        {
            if (MongoMapperTransaction.InTransaction && !MongoMapperTransaction.Commiting)
            {
                MongoMapperTransaction.AddToQueue(OperationType.Update, Type, Document);
                Task.FromResult(true);
            }

            var mongoMapperVersionable = Document as IMongoMapperVersionable;
            var mongoMapperIdeable     = Document as IMongoMapperIdeable;

            if (mongoMapperVersionable != null)
            {
                mongoMapperVersionable.m_dv++;
            }

            Debug.Assert(mongoMapperIdeable != null, "mongoMapperIdeable != null");

            return(CollectionsManager.GetCollection <T>(Name).ReplaceOneAsync(
                       Builders <T> .Filter.Eq("_id", mongoMapperIdeable.m_id),
                       Document,
                       new UpdateOptions {
                IsUpsert = true
            }
                       ));
        }
Exemplo n.º 2
0
        public Task <DeleteResult> DeleteAsync <T>(string Name, Type Type, T Document)
        {
            if (MongoMapperTransaction.InTransaction && !MongoMapperTransaction.Commiting)
            {
                MongoMapperTransaction.AddToQueue(OperationType.Delete, Type, Document);
                Task.FromResult(true);
            }

            var mongoMapperIdeable = Document as IMongoMapperIdeable;

            Debug.Assert(mongoMapperIdeable != null, "mongoMapperIdeable != null");

            if (mongoMapperIdeable.m_id == default(long))
            {
                mongoMapperIdeable.m_id = Finder.Instance.FindIdByKey <T>(Type,
                                                                          MongoMapperHelper.GetPrimaryKey(Type).
                                                                          ToDictionary(
                                                                              KeyField => KeyField,
                                                                              KeyField =>
                                                                              ReflectionUtility.
                                                                              GetPropertyValue(
                                                                                  this, KeyField)));
            }

            var query = Builders <T> .Filter.Eq("_id", mongoMapperIdeable.m_id);

            return(CollectionsManager.GetCollection <T>(Type.Name).DeleteOneAsync(query));
        }
Exemplo n.º 3
0
        public long FindIdByKey <T>(Type Type, Dictionary <string, object> KeyValues)
        {
            //Si la key es la interna y vieb
            if (KeyValues.Count == 1 && KeyValues.First().Key == "m_id" &&
                KeyValues.First().Value is long &&
                (long)KeyValues.First().Value == default(long))
            {
                return(default(long));
            }

            var query = Builders <T> .Filter.And(KeyValues.Select(KeyValue => Builders <T> .Filter.Eq(KeyValue.Key, KeyValue.Value)).ToArray());

            var result = CollectionsManager.GetCollection <T>(Type.Name).Find(Builders <T> .Filter.And(query)).Project(Builders <T> .Projection.Include("_id")).Limit(1).ToListAsync().Result;

            //if (ConfigManager.Out != null)
            //{
            //    ConfigManager.Out.Write(String.Format("{0}: ", T.Name));
            //    ConfigManager.Out.WriteLine(result.Query.ToString());
            //    ConfigManager.Out.WriteLine(result.Explain().ToJson());
            //    ConfigManager.Out.WriteLine();
            //}

            if (!result.Any())
            {
                return(default(long));
            }


            return(result.First()["_id"].AsInt64);
        }
        public void ServerUpdate(UpdateDefinition <T> Update, bool Refill = true)
        {
            if (m_id == default(long))
            {
                m_id = Finder.Instance.FindIdByKey <T>(_classType, GetPrimaryKeyValues());
            }

            var query = Builders <T> .Filter.Eq("_id", m_id);

            var result = CollectionsManager.GetCollection <T>(_classType.Name).FindOneAndUpdateAsync(
                query,
                Update,
                new FindOneAndUpdateOptions <T>()
            {
                IsUpsert       = true,
                ReturnDocument = Refill ? ReturnDocument.After : ReturnDocument.Before
            }
                ).Result;


            if (Refill)
            {
                ReflectionUtility.CopyObject <T>(result, this);
            }
        }
        public static IEnumerable <BsonDocument> Aggregate(params BsonDocument[] Operations)
        {
            var agg = CollectionsManager.GetCollection <BsonDocument>((typeof(T).Name)).Aggregate();

            agg = Operations.Aggregate(agg, (Current, Pipe) => Current.AppendStage <BsonDocument>(Pipe));

            return(agg.ToListAsync().Result);
        }
        internal static List <string> GetExistinIndexNames(Type ClassType)
        {
            var existingIndexNames =
                CollectionsManager.GetCollection <BsonDocument>(ClassType.Name)
                .Indexes.ListAsync().GetAwaiter().GetResult().ToList()
                .Select(Index => Index["name"].ToString())
                .ToList();

            return(existingIndexNames);
        }
Exemplo n.º 7
0
        public T FindObjectByKey <T>(Dictionary <string, object> KeyValues)
        {
            var query = Builders <T> .Filter.And(KeyValues.Select(KeyValue => Builders <T> .Filter.Eq(KeyValue.Key, KeyValue.Value)).ToArray());

            var result = CollectionsManager.GetCollection <T>(typeof(T).Name).Find(query).Limit(1).ToListAsync().Result;

            if (result == null || !result.Any())
            {
                throw new FindByKeyNotFoundException();
            }

            return(result.First());
        }
Exemplo n.º 8
0
        public T FindById <T>(long Id)
        {
            var result = CollectionsManager.GetCollection <T>(typeof(T).Name).Find(Builders <T> .Filter.Eq("_id", Id)).Limit(1).ToListAsync().Result;

            if (result.Any())
            {
                return(result.First());
            }
            else
            {
                return(default(T));
            }
        }
Exemplo n.º 9
0
        public Task InsertAsync <T>(string Name, Type Type, T Document)
        {
            if (MongoMapperTransaction.InTransaction && !MongoMapperTransaction.Commiting)
            {
                MongoMapperTransaction.AddToQueue(OperationType.Insert, Type, Document);
                Task.FromResult(true);
            }

            var mongoMapperVersionable = Document as IMongoMapperVersionable;

            if (mongoMapperVersionable != null)
            {
                mongoMapperVersionable.m_dv++;
            }

            return(CollectionsManager.GetCollection <T>(Name).InsertOneAsync(Document));
        }
Exemplo n.º 10
0
        public void FillFromLastVersion(bool Force)
        {
            if (!Force && String.IsNullOrEmpty(ConfigManager.GetClientSettings(_classType.Name).ReplicaSetName))
            {
                return;
            }

            if (m_id == default(long))
            {
                m_id = Finder.Instance.FindIdByKey <T>(_classType, GetPrimaryKeyValues());
            }

            var query = Builders <BsonDocument> .Filter.Eq("_id", m_id);

            var result = CollectionsManager.GetCollection <BsonDocument>(_classType.Name).Find(Builders <BsonDocument> .Filter.And(query)).Limit(1).ToListAsync().Result;

            ReflectionUtility.CopyObject(BsonSerializer.Deserialize <T>(result.First()), this);
        }
Exemplo n.º 11
0
        public bool IsLastVersion(bool Force)
        {
            if (!Force && String.IsNullOrEmpty(ConfigManager.GetClientSettings(_classType.Name).ReplicaSetName))
            {
                return(true);
            }

            if (m_id == default(long))
            {
                m_id = Finder.Instance.FindIdByKey <T>(_classType, GetPrimaryKeyValues());
            }

            var query = Builders <BsonDocument> .Filter.Eq("_id", m_id);

            var result = CollectionsManager.GetCollection <BsonDocument>(_classType.Name).Find(Builders <BsonDocument> .Filter.And(query)).Project(Builders <BsonDocument> .Projection.Include("m_dv")).Limit(1).ToListAsync().Result;

            return(result.First()["m_dv"].AsInt64 == m_dv);
        }
Exemplo n.º 12
0
        public static void DeteleExistingIndexesAndBuildNewOnes(Assembly Assembly, string ClassName)
        {
            List <Type> types = String.IsNullOrEmpty(ClassName) ? Assembly.GetTypes().Where(T => T.BaseType != null && T.BaseType.Name == "MongoMapper`1").ToList() :
                                Assembly.GetTypes().Where(T => T.BaseType != null && T.BaseType.Name == "MongoMapper`1" && T.Name == ClassName).ToList();

            foreach (Type type in types)
            {
                Console.WriteLine("BEGIN " + type.Name);
                var indexes = MongoMapperHelper.GetExistinIndexNames(type);

                foreach (var index in indexes.Where(I => I != "_id_"))
                {
                    Console.WriteLine("DELETING INDEX IN" + type.Name + " => " + index);
                    CollectionsManager.GetCollection <BsonDocument>(type.Name).Indexes.DropOne(index);
                }

                MongoMapperHelper.CreateIndexes(type);

                Console.WriteLine("END " + type.Name);
            }
        }
Exemplo n.º 13
0
        private static void CheckRelation(object Sender, MongoRelation Relation, bool FromUp)
        {
            Dictionary <string, object> fieldValues = new Dictionary <string, object>();

            for (int index = 0; index < Relation.CurrentFieldNames.Length; index++)
            {
                string currentFieldName  = Relation.CurrentFieldNames[index];
                string relationFieldName = Relation.RelationFieldNames[index];
                object v = ReflectionUtility.GetPropertyValue(Sender, currentFieldName);
                fieldValues.Add(relationFieldName, v);
            }

            if (fieldValues.All(V => V.Value == null))
            {
                return;
            }


            var filters = fieldValues.Select(CurrentFieldvalue => MongoQuery <BsonDocument> .Eq(Relation.RelationObjectName, CurrentFieldvalue.Key, CurrentFieldvalue.Value)).ToList();

            var relationCollection = CollectionsManager.GetPrimaryCollection <BsonDocument>(Relation.RelationObjectName);

            var documentCount = relationCollection.CountAsync(Builders <BsonDocument> .Filter.And(filters)).Result;

            bool okRelation = FromUp ? documentCount != 0 : documentCount == 0;

            if (!okRelation)
            {
                if (FromUp)
                {
                    throw new ValidateUpRelationException(string.Join(",", filters.FilterToJson()));
                }

                throw new ValidateDownRelationException(string.Join(",", filters.FilterToJson()));
            }
        }
        internal static void CreateIndexes(Type ClassType)
        {
            var existingIndexNames = GetExistinIndexNames(ClassType);

            foreach (string index in GetIndexes(ClassType))
            {
                if (index.StartsWith("2D|"))
                {
                    var mongoIndex = Builders <BsonDocument> .IndexKeys.Geo2D(MongoMapperHelper.ConvertFieldName(ClassType.Name, index.Split('|')[1]).Trim());

                    var indexName = "2D" + "_" + index.Split('|')[1];

                    if (!existingIndexNames.Contains(indexName))
                    {
                        Console.WriteLine("CREATING INDEX IN" + ClassType.Name + " => " + indexName);
                        CollectionsManager.GetCollection <BsonDocument>(ClassType.Name)
                        .Indexes.CreateOneAsync(mongoIndex, new CreateIndexOptions()
                        {
                            Name = indexName
                        })
                        .GetAwaiter()
                        .GetResult();
                    }
                }
                else if (index.StartsWith("2DSphere|"))
                {
                    var indexName = "2DSphere" + "_" + index.Split('|')[1];

                    if (!existingIndexNames.Contains(indexName))
                    {
                        Console.WriteLine("CREATING INDEX IN" + ClassType.Name + " => " + indexName);
                        var mongoIndex =
                            Builders <BsonDocument> .IndexKeys.Geo2DSphere(
                                MongoMapperHelper.ConvertFieldName(ClassType.Name, index.Split('|')[1]).Trim());

                        CollectionsManager.GetCollection <BsonDocument>(ClassType.Name)
                        .Indexes.CreateOneAsync(mongoIndex, new CreateIndexOptions()
                        {
                            Name = indexName
                        })
                        .GetAwaiter()
                        .GetResult();
                    }
                }
                else
                {
                    var indexFieldnames = MongoMapperHelper.ConvertFieldName(ClassType.Name, index.Split(',').ToList()).Select(IndexField => IndexField.Trim());

                    var fieldnames = indexFieldnames as IList <string> ?? indexFieldnames.ToList();

                    if (fieldnames.Any())
                    {
                        var indexName = "IX" + "_" + string.Join("_", fieldnames);

                        if (!existingIndexNames.Contains(indexName))
                        {
                            Console.WriteLine("CREATING INDEX IN" + ClassType.Name + " => " + indexName);

                            var indexFields = Builders <BsonDocument> .IndexKeys.Ascending(fieldnames.First());

                            indexFields = fieldnames.Skip(1)
                                          .Aggregate(indexFields, (Current, FieldName) => Current.Ascending(FieldName));

                            CollectionsManager.GetCollection <BsonDocument>(ClassType.Name)
                            .Indexes.CreateOneAsync(indexFields, new CreateIndexOptions()
                            {
                                Name = indexName
                            })
                            .GetAwaiter()
                            .GetResult();
                        }
                    }
                }
            }

            string[] pk = GetPrimaryKey(ClassType).ToArray();
            if (pk.Count(K => K == "m_id") == 0)
            {
                var indexFieldnames = MongoMapperHelper.ConvertFieldName(ClassType.Name, pk.ToList()).Select(PkField => PkField.Trim());

                var fieldnames = indexFieldnames as IList <string> ?? indexFieldnames.ToList();
                if (fieldnames.Any())
                {
                    var indexName = "PK_" + string.Join("_", fieldnames);

                    if (!existingIndexNames.Contains(indexName))
                    {
                        Console.WriteLine("CREATING INDEX IN" + ClassType.Name + " => " + indexName);

                        var indexFields = Builders <BsonDocument> .IndexKeys.Ascending(fieldnames.First());

                        indexFields = fieldnames.Skip(1)
                                      .Aggregate(indexFields, (Current, FieldName) => Current.Ascending(FieldName));

                        CollectionsManager.GetCollection <BsonDocument>(ClassType.Name)
                        .Indexes.CreateOneAsync(indexFields,
                                                new CreateIndexOptions()
                        {
                            Unique = true, Name = indexName
                        })
                        .GetAwaiter()
                        .GetResult();
                    }
                }
            }

            string ttlIndex = GetTTLIndex(ClassType);

            if (ttlIndex != string.Empty)
            {
                var tmpIndex  = ttlIndex.Split(',');
                var indexName = "TTL_" + tmpIndex[0].Trim();

                if (!existingIndexNames.Contains(indexName))
                {
                    Console.WriteLine("CREATING INDEX IN" + ClassType.Name + " => " + indexName);

                    var keys = Builders <BsonDocument> .IndexKeys.Ascending(tmpIndex[0].Trim());

                    CollectionsManager.GetCollection <BsonDocument>(ClassType.Name).Indexes.CreateOneAsync(
                        keys,
                        new CreateIndexOptions()
                    {
                        Name        = indexName,
                        ExpireAfter = TimeSpan.FromSeconds(int.Parse(tmpIndex[1].Trim()))
                    })
                    .GetAwaiter()
                    .GetResult();
                }
            }
        }
Exemplo n.º 15
0
 public static IMongoCollection <T> GetCollection()
 {
     return(CollectionsManager.GetCollection <T>(typeof(T).Name));
 }
 private IMongoCollection <T> GetCollection()
 {
     return(FromPrimary
         ? CollectionsManager.GetPrimaryCollection <T>(typeof(T).Name)
         : CollectionsManager.GetCollection <T>(typeof(T).Name));
 }
Exemplo n.º 17
0
 public static void ServerDelete(FilterDefinition <T> Query)
 {
     var result = CollectionsManager.GetCollection <T>(typeof(T).Name).FindOneAndDeleteAsync(Query).GetAwaiter().GetResult();
 }
        internal static void RebuildClass(Type ClassType, bool RepairCollection)
        {
            //MongoCollectionName
            if (!CollectionsManager.CustomCollectionsName.ContainsKey(ClassType.Name))
            {
                lock (LockObjectCustomCollectionNames)
                {
                    if (!CollectionsManager.CustomCollectionsName.ContainsKey(ClassType.Name))
                    {
                        var colNameAtt = (MongoCollectionName)ClassType.GetCustomAttributes(typeof(MongoCollectionName), false).FirstOrDefault();
                        if (colNameAtt != null)
                        {
                            CollectionsManager.CustomCollectionsName.Add(ClassType.Name, colNameAtt);
                        }
                    }
                }
            }


            if ((RepairCollection || !ConfigManager.Config.Context.Generated) &&
                !CollectionsManager.CollectionExists(CollectionsManager.GetCollectioName(ClassType.Name)))
            {
                Db(ClassType.Name).CreateCollectionAsync((CollectionsManager.GetCollectioName(ClassType.Name))).GetAwaiter().GetResult();
            }

            lock (LockObjectCustomDiscritminatorTypes)
            {
                if (!CustomDiscriminatorTypes.Contains(ClassType.Name))
                {
                    lock (LockObjectCustomDiscritminatorTypes)
                    {
                        if (!CustomDiscriminatorTypes.Contains(ClassType.Name))
                        {
                            RegisterCustomDiscriminatorTypes(ClassType);
                            CustomDiscriminatorTypes.Add(ClassType.Name);
                        }
                    }
                }
            }

            lock (LockObjectIdIncrementables)
            {
                if (!BufferIdIncrementables.ContainsKey(ClassType.Name))
                {
                    lock (LockObjectIdIncrementables)
                    {
                        if (!BufferIdIncrementables.ContainsKey(ClassType.Name))
                        {
                            object m =
                                ClassType.GetCustomAttributes(typeof(MongoMapperIdIncrementable), false).FirstOrDefault();
                            if (m == null)
                            {
                                BufferIdIncrementables.Add(ClassType.Name, null);
                            }
                            else
                            {
                                BufferIdIncrementables.Add(ClassType.Name, (MongoMapperIdIncrementable)m);
                            }
                        }
                    }
                }
            }

            if (!BufferDefaultValues.ContainsKey(ClassType.Name))
            {
                lock (LockObjectDefaults)
                {
                    if (!BufferDefaultValues.ContainsKey(ClassType.Name))
                    {
                        BufferDefaultValues.Add(ClassType.Name, new Dictionary <string, object>());
                        var properties = ClassType.GetProperties().Where(P => P.GetCustomAttributes(typeof(BsonDefaultValueAttribute), true).Count() != 0);
                        foreach (PropertyInfo propertyInfo in properties)
                        {
                            var att = (BsonDefaultValueAttribute)propertyInfo.GetCustomAttributes(typeof(BsonDefaultValueAttribute), true).FirstOrDefault();
                            if (att != null)
                            {
                                BufferDefaultValues[ClassType.Name].Add(propertyInfo.Name, att.DefaultValue);
                            }
                        }
                    }
                }
            }


            if (!BufferCustomFieldNames.ContainsKey(ClassType.Name))
            {
                lock (LockObjectCustomFieldNames)
                {
                    if (!BufferCustomFieldNames.ContainsKey(ClassType.Name))
                    {
                        BufferCustomFieldNames.Add(ClassType.Name, new Dictionary <string, string>());
                        var properties = ClassType.GetProperties().Where(p => p.GetCustomAttributes(typeof(BsonElementAttribute), true).Count() != 0);
                        foreach (PropertyInfo propertyInfo in properties)
                        {
                            var att = (BsonElementAttribute)propertyInfo.GetCustomAttributes(typeof(BsonElementAttribute), true).FirstOrDefault();
                            if (att != null)
                            {
                                BufferCustomFieldNames[ClassType.Name].Add(propertyInfo.Name, att.ElementName);
                            }
                        }
                    }
                }
            }


            if (!ConfigManager.Config.Context.Generated || RepairCollection)
            {
                CreateIndexes(ClassType);
            }
        }