Example #1
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);
        }
Example #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));
        }
        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);
            }
        }
Example #4
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
            }
                       ));
        }
        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);
        }
Example #7
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));
            }
        }
Example #8
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());
        }
Example #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));
        }
        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);
        }
        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);
        }
Example #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);
            }
        }
 public static void ServerDelete(FilterDefinition <T> Query)
 {
     var result = CollectionsManager.GetCollection <T>(typeof(T).Name).FindOneAndDeleteAsync(Query).GetAwaiter().GetResult();
 }
 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));
 }
        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();
                }
            }
        }