A class that wraps your database table in Dynamic Funtime
        private static void Main( string[] args )
        {
            var model = new DynamicModel( args[0] );

            bool whatif = Array.IndexOf( args, "-whatif" ) > 0;

            IEnumerable<dynamic> packages = model.Query(
                    @"  SELECT pr.Id, p.[Key], p.Version, p.NormalizedVersion
                        FROM Packages p
                        INNER JOIN PackageRegistrations pr ON pr.[Key] = p.PackageRegistrationKey
                        WHERE p.NormalizedVersion IS NOT NULL AND p.Version != p.NormalizedVersion" );

            foreach ( dynamic package in packages )
            {
                string old = String.Format( "{0}.{1}.nupkg", package.Id.ToLower(), package.Version );

                string replacement = String.Format( "{0}.{1}.nupkg", package.Id.ToLower(), package.NormalizedVersion );

                Console.WriteLine( "Copy: {0} to {1}", old, replacement );

                if ( !whatif )
                {
                    File.Copy( Path.Combine( args[1], old ), Path.Combine( args[1], replacement ), true );
                }
            }
        }
        public static void CheckSolicitud(string solicitudId)
        {
            var tbl = new DynamicModel("diarco", tableName: "SolicitudEntrega", primaryKeyField: "id");

            var solicitud = new  {id = solicitudId, checks = 1};
            tbl.Save(solicitud);
        }
Example #3
0
 protected void InitializeDatabase()
 {
     _cachedDefinitions = new Dictionary<string, DynamicModel>();
       _tableDefinitions = new Dictionary<String, dynamic>();
       var massive = new DynamicModel(_connectionName);
       var tableDefinitions = massive.Query(SqlTableScript);
       foreach (dynamic definition in tableDefinitions){
     _tableDefinitions[definition.Table.ToUpper()] = definition;
       }
 }
Example #4
0
        public object GetRecord(Entity entity, object key)
        {
            var table = new DynamicModel(
                AdminInitialise.ConnectionStringName,
                tableName: entity.TableName,
                primaryKeyField: entity.Key.ColumnName);

            var result = table.Single(key);

            return result;
        }
 public void Should_connect_to_sql_ce_db()
 {
     var dbPath = Path.Combine(new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.FullName,
                               "TeamReview.Web", "App_Data", "TeamReview.sdf");
     var connectionString = string.Format("Data Source={0};Persist Security Info=False;", dbPath);
     var database = new DynamicModel("DefaultConnection", "UserProfile", "UserId").SetConnectionString(connectionString);
     var results = database.Query("SELECT UserName FROM UserProfile");
     foreach (var result in results) {
         Console.WriteLine(result.UserName);
     }
 }
Example #6
0
        public IDictionary<string, object> GetRecord(Entity entity, params object[] key)
        {
            var table = new DynamicModel(
                Admin.ConnectionStringName,
                tableName: entity.TableName,
                primaryKeyField: entity.JoinedKey);

            var result = table.Single(key);

            return result;
        }
Example #7
0
        public static void InitDatabase()
        {
            DynamicModel dm = new DynamicModel("NietoYostenDb", "Albums", "ID");
            dm.Execute("DELETE FROM Pictures");
            dm.Execute("DELETE FROM Albums");
            dm.Execute("DELETE FROM ApprovalRequests");
            dm.Execute("DELETE FROM Users");

            var users = new Users();
            dynamic testUser = users.Register("[email protected]", TestUtil.DefaultUserPassword, TestUtil.DefaultUserPassword);
            TestUtil.TestUserId = (int)users.Scalar("SELECT ID FROM Users WHERE [email protected]", args:"[email protected]");
        }
        public RecordHierarchy GetRecordHierarchy(Entity entity)
        {
            var index = 0;
            var hierarchy = GetEntityHierarchy(null, entity, ref index);
            var sql = GenerateHierarchySql(hierarchy);
            var model = new DynamicModel(AdminInitialise.ConnectionStringName);
            var records = model.Query(sql, entity.Key.Value.Raw).ToList();

            var recordHierarchy = GetHierarchyRecords(records, hierarchy);

            return recordHierarchy;
        }
        public static void ScrapeChannels(object args)
        {
            if (Interlocked.CompareExchange(ref Running, 1, 0) != 0)
                return;

            try
            {
                if (String.IsNullOrEmpty(downloadDir))
                {
                    string dir = ConfigurationManager.AppSettings["torrentsdir"];
                    if (!String.IsNullOrEmpty(dir))
                    {
                        var context = args as HttpContextBase;
                        if (Path.IsPathRooted(dir) == false && context != null)
                            dir = context.Server.MapPath(dir);

                        if (Directory.Exists(dir))
                            downloadDir = dir;
                        else
                            downloadDir = Environment.CurrentDirectory;
                    }
                }

                var table = new DynamicModel("LDSTorrents", tableName: "Channels", primaryKeyField: "ChannelID");

                var channels = table.All();
                foreach (var channel in channels)
                {
                    try
                    {
                        logger.InfoFormat("Scraping '{0}'...", channel.Title);
                        var videos = ScrapeChannel(channel);
                        Torrents.Save(videos.ToArray());
                        table.Update(new { LastUpdated = DateTime.Now }, channel.ChannelID);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(String.Format("Failed to scrape channel '{0}' with the following exception: ", channel.Title), ex);
                        ErrorLog.GetDefault(null).Log(new Error(ex));
                    }
            #if DEBUG
                    break;
            #endif
                }
            }
            catch (Exception ex)
            {
                logger.Error("ScrapeChannels failed with the following exception: ", ex);
                ErrorLog.GetDefault(null).Log(new Error(ex));
            }

            Interlocked.Exchange(ref Running, 0);
        }
Example #10
0
        public ActionResult Approve(int id)
        {
            dynamic user = this.users.Single(id);
            user.IsApproved = true;
            this.users.Update(user, id);

            var db = new DynamicModel("NietoYostenDb", "ApprovalRequests");
            db.Delete(where: "UserID = @0", args: id);

            NyUtil.SetAlertMessage(this, string.Format("El usuario {0} ha sido approvado.", user.Email));
            return RedirectToAction("ApprovalRequests", "Account");
        }
Example #11
0
		public static void Export(ExportArguments exportArgs)
		{
			var connStrBuilder = new MySqlConnectionStringBuilder
			{
				Server = exportArgs.Server,
				UserID = exportArgs.User,
				Password = exportArgs.Password,
				Database = exportArgs.Database
			};
			var model = new DynamicModel(connStrBuilder.ConnectionString, exportArgs.Table);
			IEnumerable<dynamic> records = exportArgs.UseQuery ? model.Query(exportArgs.Query) : model.All();
			string json = JsonConvert.SerializeObject(records);
			Console.WriteLine(json);
		}
        public RecordHierarchy GetRecordHierarchy(Entity entity)
        {
            _log.InfoFormat("Getting record hierarchy for entity record ({0}#{1})", entity.Name, entity.JoinedKeyWithValue);

            var index = 0;
            var hierarchy = GetEntityHierarchy(null, entity, ref index);
            var sql = GenerateHierarchySql(hierarchy);
            _log.DebugFormat("Sql hierarchy: \r\n {0}", sql);
            var model = new DynamicModel(Admin.ConnectionStringName);
            var records = model.Query(sql, entity.Key.Select(x => x.Value.Raw).ToArray()).ToList();

            var recordHierarchy = GetHierarchyRecords(records, hierarchy);

            return recordHierarchy;
        }
Example #13
0
        private static void BasicQuery()
        {
            /* initialize dynamic model */
            var tbl = new DynamicModel("MyConnection", tableName: "Customers", primaryKeyField: "CustomerID");

            /* retrieve all records */
            var customers = tbl.All();

            /* iterate over result set */
            foreach (var customer in customers)
            {
                Console.WriteLine("{0} {1} {2} {3}", customer.Title, customer.FirstName, customer.LastName, customer.Suffix);
            }

            /* pause output */
            Console.ReadLine();
        }
Example #14
0
 public override sealed bool TryGetMember(GetMemberBinder binder, out object result)
 {
     var keyName = binder.Name.ToUpper();
       if (_cachedDefinitions.ContainsKey(keyName)){
     result = _cachedDefinitions[keyName];
     return true;
       }
       if (keyName == BasicConnection){
     result = _cachedDefinitions[keyName] = new DynamicModel(_connectionName);
     return true;
       }
       if (_tableDefinitions.ContainsKey(keyName)){
     var definition = _tableDefinitions[keyName];
     result = _cachedDefinitions[keyName] = new DynamicModel(_connectionName, definition.Table, definition.Key, "", definition.IsIdentity);
     return true;
       }
       throw new InvalidOperationException("Table, " + binder.Name + ", does not exist.");
 }
        public RecordHierarchy GetRecordHierarchy(
            EntityRecord entityRecord,
            IList<PropertyDeleteOption> deleteOptions = null)
        {
            _log.InfoFormat(
                "Getting record hierarchy for entity record ({0}#{1})",
                entityRecord.Entity.Name,
                entityRecord.JoinedKeyWithValue);

            var hierarchy = GetEntityHierarchy(entityRecord.Entity, deleteOptions);
            var sql = GenerateHierarchySql(hierarchy);
            _log.Debug($"Sql hierarchy: \r\n {sql}");
            var model = new DynamicModel(_admin.ConnectionStringName);
            var records = model.Query(sql, entityRecord.Key.Select(x => x.Raw).ToArray()).ToList();

            var recordHierarchy = GetHierarchyRecords(records, hierarchy);

            return recordHierarchy;
        }
        public static IList<SolicitudEntrega> GetSolicitudesEntregadas()
        {
            var sucursalId = int.Parse(ConfigurationManager.AppSettings["SucursalId"]);
            var tbl = new DynamicModel("diarco", tableName: "SolicitudEntrega", primaryKeyField: "id");

            var result = tbl.Query(@"SELECT SolicitudEntrega.id as Id, SolicitudEntrega.startsAt as StartsAt, SolicitudEntrega.sucursalId as SucursalId,  User.firstName as ProveedorRazonSocial, ordenDeCompraId as OrdenDeCompraId 
                                     FROM SolicitudEntrega 
                                     INNER JOIN User On User.id = SolicitudEntrega.userId 
                                     INNER JOIN SolicitudEntrega_OrdenDeCompra On SolicitudEntrega_OrdenDeCompra.solicitudEntregaId = SolicitudEntrega.id 
                                     WHERE SolicitudEntrega.status = 5 and  SolicitudEntrega.checks is null 
                                     ORDER BY SolicitudEntrega.startsAt").ToList().Where(s => s.SucursalId == sucursalId || sucursalId == 0).ToList();

            return result.GroupBy(s => s.Id)
                .Select(g => new SolicitudEntrega
                {
                    Id = g.Key,
                    StartAt = g.First().StartsAt,
                    ProveedorRazonSocial = g.First().ProveedorRazonSocial,
                    OrdenesDeCompra = string.Join(" | ",g.Select(o => o.OrdenDeCompraId).Distinct())
                }).ToList();


        }
 private static void AddTbl(ScriptScope scriptScope, string connectionString)
 {
     var tbl = new DynamicModel(connectionString);
     scriptScope.SetVariable("tbl", tbl);
 }
        private static void ScrapeChannels()
        {
            var table = new DynamicModel("LDSTorrents", tableName: "Channels", primaryKeyField: "ChannelID");

            var channels = table.All();
            foreach (var channel in channels)
            {
                Console.WriteLine("Scraping '{0}'...", channel.Title);
                var videos = ScrapeChannel(channel);
                Torrents.Save(videos.ToArray());
                table.Update(new { LastUpdated = DateTime.Now }, channel.ChannelID);
                break;
            }
        }
 public void BasicPaging()
 {
     dynamic artists = new DynamicModel("Chinook", "Artist", "ArtistId");
     dynamic artistsPage2 = artists.Paged(currentPage: 2, pageSize: 5);
     foreach( dynamic item in artistsPage2.Items) {};
 }
Example #20
0
 public Finder(DynamicModel model)
 {
     _model = model;
 }
Example #21
0
        public IList<DataRow> GetRecords(
            Entity entity,
            IList<IEntityFilter> filters = null,
            string searchQuery = null,
            string order = null,
            string orderDirection = null,
            bool determineDisplayValue = false)
        {
            var search = new EntitySearch
            {
                Query = searchQuery,
                Properties = entity.SearchProperties
            };
            order = order.IsNullOrEmpty() ? entity.Key.ColumnName : order;
            orderDirection = orderDirection.IsNullOrEmpty() ?
                "ASC" :
                orderDirection.ToUpper();
            var orderBy = order + " " + orderDirection;
            var columns = string.Join(",",
                entity.Properties
                    .Where(x =>
                        !x.IsForeignKey ||
                        (!x.TypeInfo.IsCollection && x.IsForeignKey))
                    .Select(x => x.ColumnName)
                    .Distinct());
            List<object> args;
            var where = ConvertFiltersToSql(filters, search, out args);

            var table = new DynamicModel(
                AdminInitialise.ConnectionStringName,
                entity.TableName,
                entity.Key.ColumnName);

            var result = table.All(
                columns: columns,
                where: where,
                orderBy: orderBy,
                args: args.ToArray());

            var data = result
                .Select(item => new DataRow(item, entity))
                .ToList();

            if (determineDisplayValue)
            {
                foreach (var row in data)
                {
                    row.DisplayName = entity.ToString(row);
                }
            }

            return data;
        }
Example #22
0
 public ContactRepository(IConnectionStringProvider connectionStringProvider)
 {
     table = new DynamicModel("ConnectionString", tableName: "Contacts", primaryKeyField: "Id",
         connectionStringProvider: connectionStringProvider);
 }
Example #23
0
 public jgridDisplayHelper(DynamicModel _tbl, DelegateShapeGridRow convertMethod)
 {
     tbl = _tbl;
     this.ConvertMethod = convertMethod;
 }
Example #24
0
        public PagedRecords GetRecords(
            Entity entity,
            int page,
            int take,
            IList<IEntityFilter> filters,
            string searchQuery,
            string order,
            string orderDirection)
        {
            var search = new EntitySearch
            {
                Query = searchQuery,
                Properties = entity.SearchProperties
            };
            order = order.IsNullOrEmpty() ? entity.Key.ColumnName : order;
            orderDirection = orderDirection.IsNullOrEmpty() ?
                "ASC" :
                orderDirection.ToUpper();
            var orderBy = order + " " + orderDirection;
            var columns = string.Join(",", entity.GetColumns());
            List<object> args;
            var where = ConvertFiltersToSql(filters, search, out args);

            var table = new DynamicModel(
                AdminInitialise.ConnectionStringName,
                entity.TableName,
                entity.Key.ColumnName);

            var result = table.Paged(
                columns: columns,
                where: where,
                orderBy: orderBy,
                currentPage: page,
                pageSize: take,
                args: args.ToArray());

            var data = new List<DataRow>();
            foreach (var item in result.Items)
            {
                data.Add(new DataRow(item, entity));
            }

            return new PagedRecords
            {
                TotalItems = result.TotalRecords,
                TotalPages = result.TotalPages,
                Records = data
            };
        }
Example #25
0
 public void SaveTable(DynamicModel table, List<dynamic> items )
 {
     foreach (dynamic item in items)
     {
         if (item.State == RowState.New)
         {
             table.Insert(item);
         }
         else if(item.State == RowState.Updated)
         {
             table.Update(item, item.ID);
         }
     }
 }
Example #26
0
        public PagedRecords GetRecords(
            Entity entity,
            IList<BaseFilter> filters = null,
            string searchQuery = null,
            string order = null,
            string orderDirection = null,
            bool determineDisplayValue = false,
            int? page = null,
            int? take = null)
        {
            var search = new EntitySearch
            {
                Query = searchQuery,
                Properties = entity.SearchProperties
            };
            order = order.IsNullOrEmpty() ? entity.Key.FirstOrDefault().ColumnName : order;
            orderDirection = orderDirection.IsNullOrEmpty() ?
                "ASC" :
                orderDirection.ToUpper();
            var orderBy = order + " " + orderDirection;
            var columns = string.Join(",",
                entity.Properties
                    .Where(x =>
                        !x.IsForeignKey ||
                        (!x.TypeInfo.IsCollection && x.IsForeignKey))
                    .Select(x => x.ColumnName)
                    .Distinct());
            List<object> args;
            var where = ConvertFiltersToSql(filters, search, out args);

            var table = new DynamicModel(
                Admin.ConnectionStringName,
                entity.TableName,
                entity.JoinedKey);

            if (page.HasValue && take.HasValue)
            {
                var result = table.Paged(
                    columns: columns,
                    where: where,
                    orderBy: orderBy,
                    currentPage: page.Value,
                    pageSize: take.Value,
                    args: args.ToArray());

                var data = new List<DataRow>();
                foreach (var item in result.Items)
                {
                    data.Add(new DataRow(item, entity));
                }

                return new PagedRecords
                {
                    TotalItems = result.TotalRecords,
                    TotalPages = result.TotalPages,
                    Records = data
                };
            }
            else
            {
                var result = table.All(
                    columns: columns,
                    where: where,
                    orderBy: orderBy,
                    args: args.ToArray());

                var data = result
                    .Select(item => new DataRow(item, entity))
                    .ToList();

                if (determineDisplayValue)
                {
                    foreach (var row in data)
                    {
                        row.DisplayName = entity.ToString(row);
                    }
                }

                return new PagedRecords
                {
                    Records = data
                };
            }
        }
Example #27
0
 public ProductionSpecs()
 {
     this.Describes("商品信息 测试!");
     _db = new DynamicModel("DefaultConnection", "Test.Productions", "Id");
     _product = new Product();
 }
Example #28
0
 private AlbumsModel()
 {
     this.dynamicModel = new DynamicModel("NietoYostenDb", "Albums", "ID");
 }
Example #29
0
 public static DynamicModel Open(string connectionStringName)
 {
     dynamic dm = new DynamicModel(connectionStringName);
     return dm;
 }
Example #30
0
        public PagedRecords GetRecords(
            Entity entity,
            IList<BaseFilter> filters = null,
            string searchQuery = null,
            string order = null,
            string orderDirection = null,
            bool determineDisplayValue = false,
            int? page = null,
            int? take = null,
            bool loadForeignKeys = false)
        {
            var search = new EntitySearch
            {
                Query = searchQuery,
                Properties = entity.SearchProperties
            };
            order = order.IsNullOrEmpty() ? entity.Keys.FirstOrDefault().Column : order;
            orderDirection = orderDirection.IsNullOrEmpty() ?
                "ASC" :
                orderDirection.ToUpper();
            var orderBy = order + " " + orderDirection;
            var columns = string.Join(",",
                entity.DisplayProperties
                    .Union(entity.Keys)
                    .Where(x =>
                        !x.IsForeignKey ||
                        (!x.TypeInfo.IsCollection && x.IsForeignKey))
                    .Select(x => $"{entity.Table}.{x.Column} as {x.Column}")
                    .Distinct());
            List<object> args;
            var where = ConvertFiltersToSql(filters, search, out args);

            var table = new DynamicModel(
                _admin.ConnectionStringName,
                entity.Table,
                entity.JoinedKeys);

            if (page.HasValue && take.HasValue)
            {
                var result = table.Paged(
                    columns: columns,
                    where: where,
                    orderBy: orderBy,
                    currentPage: page.Value,
                    pageSize: take.Value,
                    args: args.ToArray());

                var records = new List<EntityRecord>();
                foreach (var item in result.Items)
                {
                    records.Add(entity.CreateRecord((Dictionary<string, object>)item));
                }

                return new PagedRecords
                {
                    TotalItems = result.TotalRecords,
                    TotalPages = result.TotalPages,
                    Records = records
                };
            }
            else
            {
                var joins = "";
                if (loadForeignKeys)
                {
                    foreach (var foreignKey in entity.ForeignKeys.WhereOneToMany())
                    {
                        var joinTable = foreignKey.ForeignEntity.Table;
                        var joinProperty = foreignKey.ForeignEntity.Keys.FirstOrDefault(x => x.ForeignEntity == entity);

                        var keyProperty = foreignKey.TypeInfo.IsCollection ?
                            entity.Keys.FirstOrDefault() :
                            foreignKey;

                        joins += Environment.NewLine +
                            $"left join {joinTable} on {joinTable}.{joinProperty.Column} = {entity.Table}.{keyProperty.Column}";

                        var propertyToGet = foreignKey.ForeignEntity.Keys.FirstOrDefault(x => x.ForeignEntity != entity) ??
                                            joinProperty;

                        columns += $",{joinTable}.{propertyToGet.Column} as {foreignKey.Column}";
                    }
                }
                var result = table.All(
                    columns: columns,
                    joins: joins,
                    where: where,
                    orderBy: orderBy,
                    args: args.ToArray());

                var records = result
                    .Select(item => entity.CreateRecord(item))
                    .ToList();

                return new PagedRecords
                {
                    Records = records
                };
            }
        }