Esempio n. 1
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ViewModel = new SelectedItemsPropertiesViewModel();

            if (e.Parameter is ListedItem)
            {
                var listedItem = e.Parameter as ListedItem;
                if (listedItem.PrimaryItemAttribute == StorageItemTypes.File)
                {
                    BaseProperties = new FileProperties(ViewModel, tokenSource, ItemMD5HashProgress, listedItem);
                }
                else if (listedItem.PrimaryItemAttribute == StorageItemTypes.Folder)
                {
                    BaseProperties = new FolderProperties(ViewModel, tokenSource, Dispatcher, listedItem);
                }
            }
            else if (e.Parameter is List <ListedItem> )
            {
                BaseProperties = new CombinedProperties(ViewModel, tokenSource, Dispatcher, e.Parameter as List <ListedItem>);
            }
            else if (e.Parameter is DriveItem)
            {
                BaseProperties = new DriveProperties(ViewModel, e.Parameter as DriveItem);
            }

            AppSettings.ThemeModeChanged += AppSettings_ThemeModeChanged;
            base.OnNavigatedTo(e);
        }
Esempio n. 2
0
        public string GetCreateTable()
        {
            IEnumerable <PropertyMetadata> properties = BaseProperties.ToList();

            //			CREATE TABLE `video` (
            //  `id` int(11) NOT NULL AUTO_INCREMENT,
            //  `name` varchar(200) DEFAULT NULL,
            //  `url` text,
            //  `count` varchar(45) DEFAULT NULL,
            //  `cdate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
            //  PRIMARY KEY (`id`)
            //) ENGINE=InnoDB AUTO_INCREMENT=127 DEFAULT CHARSET=utf8;

            StringBuilder builder = new StringBuilder($"CREATE TABLE IF NOT EXISTS `{Scheme}`.`{TableName}` (");

            string columNames = string.Join(", ", properties.Select(p =>
                                                                    $"`{p.ColumnName}` {p.ValueType} {(p.PrimaryKey ? "AUTO_INCREMENT" : "")}"));

            builder.Append(columNames.Substring(0, columNames.Length));
            if (KeyProperties != null && KeyProperties.Any())
            {
                builder.Append(", PRIMARY KEY(");
                foreach (var p in KeyProperties)
                {
                    builder.Append("`").Append(p.ColumnName).Append("`");
                }
                builder.Append(")");
            }
            builder.Append(") ENGINE=InnoDB  DEFAULT CHARSET=utf8");
            return(builder.ToString());
        }
Esempio n. 3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetInsert(bool bulkInsert)
        {
            //Enumerate the entity properties
            //Identity property (if exists) has to be ignored
            IEnumerable <PropertyMetadata> properties = (IsIdentity ?
                                                         BaseProperties.Where(p => !p.Name.Equals(IdentityProperty.Name, StringComparison.InvariantCultureIgnoreCase)) :
                                                         BaseProperties).ToList();

            string columNames = string.Join(", ", properties.Select(p => $"`{p.ColumnName}`"));
            string values     = string.Join(", ", properties.Select(p => $"@{p.Name}"));

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("INSERT IGNORE INTO `{0}`.`{1}` {2} {3};",
                                    Scheme,
                                    TableName,
                                    string.IsNullOrEmpty(columNames) ? string.Empty : $"({columNames})",
                                    string.IsNullOrEmpty(values) ? string.Empty : $" VALUES ({values})");

            if (IsIdentity && !bulkInsert)
            {
                string query = $"SELECT max(`{IdentityProperty.ColumnName}`) as Id FROM `{Scheme}`.`{TableName}`;";
                sqlBuilder.Append(query);
            }

            return(sqlBuilder.ToString());
        }
Esempio n. 4
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public virtual string GetInsert()
        {
            // Enumerate the entity properties. Identity property (if exists) has to be ignored
            IEnumerable <PropertyMetadata> properties = (IsIdentity ?
                                                         BaseProperties.Where(p => !p.Name.Equals(IdentityProperty.Name, StringComparison.InvariantCultureIgnoreCase)) :
                                                         BaseProperties).ToList();

            var columNames = string.Join(", ", properties.Select(p => $"[{TableName}].[{p.ColumnName}]"));
            var values     = string.Join(", ", properties.Select(p => $"@{p.Name}"));

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("INSERT INTO [{0}].[{1}] {2} {3} ",
                                    Scheme,
                                    TableName,
                                    string.IsNullOrEmpty(columNames) ? string.Empty : $"({columNames})",
                                    string.IsNullOrEmpty(values) ? string.Empty : $" VALUES ({values})");

            // If the entity has an identity key, we create a new variable into the query in order to retrieve the generated id
            if (IsIdentity)
            {
                sqlBuilder.AppendLine("DECLARE @NEWID NUMERIC(38, 0)");
                sqlBuilder.AppendLine("SET	@NEWID = SCOPE_IDENTITY()");
                sqlBuilder.AppendLine("SELECT @NEWID");
            }

            return(sqlBuilder.ToString());
        }
Esempio n. 5
0
        public void BulkInsertAll(IEnumerable <T> entities, IDbTransaction trans = null)
        {
            using (var bulkCopy = new SqlBulkCopy((SqlConnection)Connection, SqlBulkCopyOptions.Default, (SqlTransaction)trans))
            {
                var t = typeof(T);
                var tableAttribute = (TableAttribute)t.GetCustomAttributes(
                    typeof(TableAttribute), false).Single();
                bulkCopy.DestinationTableName = tableAttribute.Name;
                var properties = BaseProperties.ToArray();
                var table      = new DataTable();
                foreach (var property in properties)
                {
                    var propertyType = property.PropertyInfo.PropertyType;
                    if (propertyType.IsGenericType &&
                        propertyType.GetGenericTypeDefinition() == typeof(Nullable <>))
                    {
                        propertyType = Nullable.GetUnderlyingType(propertyType);
                    }

                    table.Columns.Add(new DataColumn(property.ColumnName, propertyType));
                }
                foreach (var entity in entities)
                {
                    table.Rows.Add(
                        properties.Select(
                            property => property.PropertyInfo.GetValue(entity, null) ?? DBNull.Value
                            ).ToArray());
                }
                bulkCopy.WriteToServer(table);
            }
        }
 private void Properties_Loaded(object sender, RoutedEventArgs e)
 {
     if (BaseProperties != null)
     {
         BaseProperties.GetSpecialProperties();
     }
 }
Esempio n. 7
0
        /// <summary>
        /// ToWhere
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="filters"></param>
        /// <returns></returns>
        public virtual string ToWhere(IEnumerable <string> properties, object filters)
        {
            return(string.Join(" AND ", properties.Select(p =>
            {
                var propertyMetadata = BaseProperties.FirstOrDefault(pm => pm.Name.Equals(p, StringComparison.InvariantCultureIgnoreCase));
                var columnName = p;
                var propertyName = p;

                if (propertyMetadata != null)
                {
                    columnName = propertyMetadata.ColumnName;
                    propertyName = propertyMetadata.Name;
                }

                var prop = filters.GetType().GetProperty(propertyMetadata?.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                var values = prop.GetValue(filters, null);

                if (values == null)
                {
                    return $"[{TableName}].[{columnName}] IS NULL";
                }

                if ((values as IEnumerable) != null && !(values is string))
                {
                    return $"[{TableName}].[{columnName}] IN @{propertyName}";
                }

                return $"[{TableName}].[{columnName}] = @{propertyName}";
            })));
        }
Esempio n. 8
0
        public virtual SqlQuery GetUpdate <T>(TEntity entity, Expression <Func <T, dynamic> > fields)
        {
            var targetProperties    = GetPropertyInfos(fields);
            var targetPropertyNames = new List <string>();

            if (targetProperties != null && targetProperties.Any())
            {
                targetPropertyNames = targetProperties.Select(p => p.Name).ToList();
            }

            var properties =
                BaseProperties.Where(
                    p => !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.OrdinalIgnoreCase)));

            if (targetPropertyNames.Any())
            {
                properties = properties.Where(p => targetPropertyNames.Contains(p.Name));
            }

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("UPDATE {0} SET {1} WHERE {2}", TableName,
                                    string.Join(", ",
                                                properties.Select(
                                                    p => string.Format("{0}={1}", p.ColumnName, GetPropertyValue(entity, p.PropertyInfo) ?? "NULL"))),
                                    string.Join(" AND ",
                                                KeyProperties.Select(
                                                    p => string.Format("{0}={1}", p.ColumnName, GetPropertyValue(entity, p.PropertyInfo) ?? "NULL"))));

            return(new SqlQuery(sqlBuilder.ToString().TrimEnd(), entity));
        }
Esempio n. 9
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public virtual string GetInsert()
        {
            //Enumerate the entity properties
            //Identity property (if exists) has to be ignored
            var properties = (IsIdentity
                ? BaseProperties.Where(p =>
                                       !p.Name.Equals(IdentityProperty.Name, StringComparison.InvariantCultureIgnoreCase))
                : BaseProperties).ToList();

            var columNames = string.Join(", ", properties.Select(p => $"[{TableName}].[{p.ColumnName}]"));
            var values     = string.Join(", ", properties.Select(p => $"@{p.Name}"));

            if (!columNames.Any() || !values.Any())
            {
                throw new ArgumentNullException(nameof(columNames));
            }

            var builder = new SqlBuilder();
            var insert  =
                builder.AddTemplate(
                    $"INSERT INTO [{Scheme}].[{TableName}] /**columns**/ /**values**/ /**scopeidentity**/");

            builder.Columns(columNames);
            builder.Values(values);

            //If the entity has an identity key, we create a new variable into the query in order to retrieve the generated id
            if (IsIdentity)
            {
                builder.ScopeIdentity(
                    "\nDECLARE @NEWID NUMERIC(38, 0) \nSET @NEWID = SCOPE_IDENTITY() \nSELECT @NEWID");
            }

            return(insert.RawSql);
        }
Esempio n. 10
0
        public void ShowSettings <T>(T settings) where T : BaseSettings
        {
            m_CurrentObject = WrapSettingsToProperties(settings, ref m_CurrentObjectType);
            this.Text       = m_CurrentObject.Title;

            // Putting null as sender so we don't call properties modified callback. But we want to update dt
            propertyGrid_PropertyValueChanged(null, null);
        }
Esempio n. 11
0
        private void ShowScript <T>(T script) where T : Script
        {
            var scriptProperties = Container.Resolve <ScriptProperties>();

            scriptProperties.Script = script;

            m_CurrentObject = scriptProperties;
        }
Esempio n. 12
0
 public NUnitDiscoveryTestCase(BaseProperties theBase, INUnitDiscoveryCanHaveTestCases parent,
                               string className,
                               string methodname, long seed) : base(theBase, parent)
 {
     ClassName  = className;
     MethodName = methodname;
     Seed       = seed;
 }
Esempio n. 13
0
 protected NUnitDiscoverySuiteBase(BaseProperties other)
     : this(other.Id, other.Name, other.Fullname, other.TestCaseCount)
 {
     RunState = other.RunState;
     foreach (var prop in other.Properties)
     {
         NUnitDiscoveryProperties.Add(prop);
     }
 }
Esempio n. 14
0
 static TableElement()
 {
     BaseProperties.Add(__keyProperty.Value);
     BaseProperties.Add(__nameProperty.Value);
     BaseProperties.Add(__queryProperty.Value);
     BaseProperties.Add(__fixedProperty.Value);
     BaseProperties.Add(__filterProperty.Value);
     BaseProperties.Add(__primaryKeysProperty.Value);
 }
Esempio n. 15
0
 private void Properties_Loaded(object sender, RoutedEventArgs e)
 {
     if (BaseProperties != null)
     {
         BaseProperties.GetSpecialProperties();
         Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
         BaseProperties.GetSystemFileProperties();
         stopwatch.Stop();
         Debug.WriteLine(string.Format("System file properties were obtained in {0} milliseconds", stopwatch.ElapsedMilliseconds));
     }
 }
Esempio n. 16
0
        private void ShowCommand <T>(T command, BaseScriptManager BaseScriptManager) where T : Command
        {
            var designerType = GetDesignerTypeForCommand(command.GetType());

            var commandProperties = (CommandProperties)Container.Resolve(designerType);

            m_OldCommand = command;

            commandProperties.Command         = command;
            m_CurrentObject                   = commandProperties;
            m_CurrentObject.BaseScriptManager = BaseScriptManager;
        }
Esempio n. 17
0
        public string GetSelect(object filters)
        {
            //Projection function
            Func <PropertyMetadata, string> projectionFunction = p =>
            {
                if (!string.IsNullOrEmpty(p.Alias))
                {
                    return($"`{p.ColumnName}` AS `{p.Name}`");
                }

                return($" `{p.ColumnName}`");
            };

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("SELECT {0} FROM `{1}`.`{2}` ",
                                    string.Join(", ", BaseProperties.Select(projectionFunction)),
                                    Scheme,
                                    TableName);
            bool containsFilter = false;
            var  s = filters as string;

            if (s != null)
            {
                string realFilters = s;
                if (!string.IsNullOrEmpty(realFilters))
                {
                    sqlBuilder.AppendFormat(" WHERE {0} ", realFilters);
                    containsFilter = true;
                }
            }
            else
            {
                //Properties of the dynamic filters object
                var filterProperties = filters.GetType().GetProperties().Select(p => p.Name);
                var properties       = filterProperties as IList <string> ?? filterProperties.ToList();
                containsFilter = (properties.Any());

                if (containsFilter)
                {
                    sqlBuilder.AppendFormat(" WHERE {0} ", ToWhere(properties));
                }
            }

            //Evaluates if this repository implements logical delete
            if (LogicalDelete)
            {
                sqlBuilder.AppendFormat(containsFilter ? " AND `{0}` != {1}" : " WHERE `{0}` != {1}", StatusProperty.Name, LogicalDeleteValue);
            }

            return(sqlBuilder.ToString());
        }
Esempio n. 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        private string ToWhere(IEnumerable <string> properties)
        {
            return(string.Join(" AND ", properties.Select(p =>
            {
                var propertyMetadata = BaseProperties.FirstOrDefault(pm => pm.Name.Equals(p, StringComparison.InvariantCultureIgnoreCase));

                if (propertyMetadata != null)
                {
                    return $"`{propertyMetadata.ColumnName}` = @{propertyMetadata.Name}";
                }

                return $"`{p}` = @{p}";
            })));
        }
Esempio n. 19
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetUpdate()
        {
            var properties = BaseProperties.Where(p => !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase)));

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("UPDATE `{0}`.`{1}` SET {2} WHERE {3}",
                                    Scheme,
                                    TableName,
                                    string.Join(", ", properties.Select(p => $"`{p.ColumnName}` = @{p.Name}")),
                                    string.Join(" AND ", KeyProperties.Select(p => $"`{p.ColumnName}` = @{p.Name}")));

            return(sqlBuilder.ToString());
        }
Esempio n. 20
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="filters"></param>
        /// <param name="rowCount">Maximum number of rows to return</param>
        /// <returns></returns>
        public virtual string GetSelect(object filters, int?rowCount = null)
        {
            //Projection function
            string ProjectionFunction(PropertyMetadata p) =>
            !string.IsNullOrEmpty(p.Alias)
                    ? $"[{TableName}].[{p.ColumnName}] AS [{p.Name}]"
                    : $"[{TableName}].[{p.ColumnName}]";

            var rowLimitSql = string.Empty;

            var builder  = new SqlBuilder();
            var selector =
                builder.AddTemplate(
                    $"SELECT /**select**/ FROM [{Scheme}].[{TableName}] WITH (NOLOCK) /**where**/ /**orderby**/");

            if (rowCount.HasValue)
            {
                rowLimitSql = string.Format("TOP {0} ", rowCount);
            }

            var properties = string.Join(", ", BaseProperties.Select(ProjectionFunction));

            builder.Select($"{rowLimitSql} {properties}");

            //Properties of the dynamic filters object
            var filterProperties = filters?.GetType().GetProperties().Select(p => p.Name);

            if (filterProperties != null)
            {
                var enumerable     = filterProperties as IList <string> ?? filterProperties.ToList();
                var containsFilter = enumerable.Any();

                if (containsFilter)
                {
                    ToWhere(ref builder, enumerable, filters);
                }
            }

            //Evaluates if this repository implements logical delete
            if (!LogicalDelete)
            {
                return(selector.RawSql);
            }

            builder.Where($"[{TableName}].[{StatusProperty.Name}] != {LogicalDeleteValue}");
            return(selector.RawSql);
        }
Esempio n. 21
0
        public static void BuildBase()
        {
            var            baseDescription = new BaseDescription();
            BaseProperties baseProperties  = FromProperties(baseDescription);

            //TODO populate layout and upgrades
            WriteDefensesLayout(baseDescription);

            //TODO automatically assing asset bundle names to corresponding assets

            var manifest   = BuildPipeline.BuildAssetBundles(Constants.AssetBundlesPath, BuildAssetBundleOptions.None, BuildTarget.Android);
            var bundleName = manifest.GetAllAssetBundles()[0];

            baseDescription.bundleName = bundleName;

            baseProperties.provider.UpdatePlayerBase(baseProperties.playerId.ToString(), baseDescription);
        }
Esempio n. 22
0
        public virtual SqlQuery GetUpdate(TEntity entity)
        {
            var properties =
                BaseProperties.Where(
                    p => !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.OrdinalIgnoreCase)));

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("UPDATE {0} SET {1} WHERE {2}", TableName,
                                    string.Join(", ",
                                                properties.Select(
                                                    p => string.Format("{0}={1}", p.ColumnName, GetPropertyValue(entity, p.PropertyInfo) ?? "NULL"))),
                                    string.Join(" AND ",
                                                KeyProperties.Select(
                                                    p => string.Format("{0}={1}", p.ColumnName, GetPropertyValue(entity, p.PropertyInfo) ?? "NULL"))));

            return(new SqlQuery(sqlBuilder.ToString().TrimEnd(), entity));
        }
Esempio n. 23
0
        private static void Main(string[] args)
        {
            var logFactory = GetLogFactory(args, @"C:\winserv\scanner.log");

            var logger   = HW.Logging.Logger.Current;
            var props    = BaseProperties.GetProperties(args);
            var logProps = new LogBaseProperties(props);

            logger.SetActualLogger(logFactory.GetLogger("HW.ScanService"), logProps.UseCodeRewritingLogs);


            logger.LogInfo("Main");
            foreach (var arg in args)
            {
                logger.LogInfo(arg);
            }

            var scanProperties = new ScanProperties(props);
            var container      = GetContainer(scanProperties, logProps);

            var serv = new ScannerService(container);

            if (args.Length > 0 && args[0].Equals("console"))
            {
                serv.StartScanning();

                Console.ReadKey();
                serv.StopScanning();
            }
            else //windows service
            {
                try
                {
                    ScannerService.Run(serv);
                }
                catch (Exception e)
                {
                    if (logger != null)
                    {
                        logger.LogError(e);
                    }
                }
            }
        }
Esempio n. 24
0
        public virtual string GetSearch(string columnName, string searchTerm)
        {
            //Projection function
            string ProjectionFunction(PropertyMetadata p) =>
            !string.IsNullOrEmpty(p.Alias)
                    ? $"[{TableName}].[{p.ColumnName}] AS [{p.Name}]"
                    : $"[{TableName}].[{p.ColumnName}]";

            var builder  = new SqlBuilder();
            var selector =
                builder.AddTemplate(
                    $"SELECT /**select**/ FROM [{Scheme}].[{TableName}] WITH (NOLOCK) /**like**/ ");
            var properties = string.Join(", ", BaseProperties.Select(ProjectionFunction));

            builder.Select(properties);
            builder.Like($" [{TableName}].[{columnName}] LIKE '{searchTerm}%'");

            return(selector.RawSql);
        }
Esempio n. 25
0
        /// <summary>
        /// Creates the temporary table.
        /// </summary>
        /// <returns></returns>
        public virtual string CreateTempTable()
        {
            var properties = BaseProperties.Where(p => !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase)));

            string ProjectionFunction(PropertyMetadata p)
            {
                return($"[{p.ColumnName}]  {GetSqlDataType(p.PropertyInfo.PropertyType)}");
            }

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("CREATE TABLE [dbo].[{0}]({1}{2}{3});",
                                    TempTableName,
                                    string.Join(", ", KeyProperties.Select(ProjectionFunction)),
                                    KeyProperties.Count() > 1 ? " " : ", ",
                                    string.Join(", ", properties.Select(ProjectionFunction)));

            return(sqlBuilder.ToString());
        }
        private static BaseProperties ExtractSuiteBasePropertiesClass(XElement node)
        {
            string     dId            = node.Attribute(NUnitXmlAttributeNames.Id).Value;
            string     dName          = node.Attribute(NUnitXmlAttributeNames.Name).Value;
            string     dFullname      = node.Attribute(NUnitXmlAttributeNames.Fullname).Value;
            var        dRunstate      = ExtractRunState(node);
            const char apo            = '\'';
            var        tcs            = node.Attribute(NUnitXmlAttributeNames.Testcasecount)?.Value.Trim(apo);
            int        dTestcasecount = int.Parse(tcs ?? "1", CultureInfo.InvariantCulture);
            var        bp             = new BaseProperties(dId, dName, dFullname, dTestcasecount, dRunstate);

            foreach (var propnode in node.Elements("properties").Elements("property"))
            {
                var prop = new NUnitProperty(
                    propnode.Attribute("name").Value,
                    propnode.Attribute("value").Value);
                bp.Properties.Add(prop);
            }
            return(bp);
        }
Esempio n. 27
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <returns></returns>
        public virtual string GetUpdate()
        {
            var properties = BaseProperties.Where(p =>
                                                  !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase)));
            var setProperties = properties.Select(p => $"[{TableName}].[{p.ColumnName}] = @{p.Name}");
            var builder       = new SqlBuilder();
            var update        = builder.AddTemplate($"UPDATE [{Scheme}].[{TableName}] /**set**/ /**where**/");

            foreach (var setProperty in setProperties)
            {
                builder.Set(setProperty);
            }

            foreach (var keyProperty in KeyProperties)
            {
                builder.Where($"[{TableName}].[{keyProperty.ColumnName}] = @{keyProperty.Name}");
            }

            return(update.RawSql);
        }
Esempio n. 28
0
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <param name="filters"></param>
        /// <param name="rowCount">Maximum number of rows to return</param>
        /// <returns></returns>
        public virtual string GetSelect(object filters, int?rowCount = null)
        {
            string ProjectionFunction(PropertyMetadata p)
            {
                return(!string.IsNullOrEmpty(p.Alias) ? $"[{TableName}].[{p.ColumnName}] AS [{p.Name}]" : $"[{TableName}].[{p.ColumnName}]");
            }

            var sqlBuilder  = new StringBuilder();
            var rowLimitSql = string.Empty;

            if (rowCount.HasValue)
            {
                rowLimitSql = $"TOP {rowCount} ";
            }

            sqlBuilder.AppendFormat("SELECT {0}{1} FROM [{2}].[{3}] WITH (NOLOCK)",
                                    rowLimitSql,
                                    string.Join(", ", BaseProperties.Select(ProjectionFunction)),
                                    Scheme,
                                    TableName
                                    );

            // Properties of the dynamic filters object
            var filterProperties = filters.GetType().GetProperties().Select(p => p.Name);
            var containsFilter   = (filterProperties.Any());

            if (containsFilter)
            {
                sqlBuilder.AppendFormat(" WHERE {0} ", ToWhere(filterProperties, filters));
            }

            // Evaluates if this repository implements logical delete
            if (!LogicalDelete)
            {
                return(sqlBuilder.ToString());
            }

            sqlBuilder.AppendFormat(containsFilter ? " AND [{0}].[{1}] != {2}" : " WHERE [{0}].[{1}] != {2}", TableName, StatusProperty.Name, LogicalDeleteValue);
            return(sqlBuilder.ToString());
        }
Esempio n. 29
0
        public virtual SqlQuery GetInsert(TEntity entity)
        {
            var properties = (IsIdentity
                ? BaseProperties.Where(
                                  p => !p.Name.Equals(IdentityProperty.Name, StringComparison.OrdinalIgnoreCase))
                : BaseProperties).ToList();

            var columNames = string.Join(", ", properties.Select(p => p.ColumnName));
            var values     = string.Join(", ", properties.Select(p => GetPropertyValue(entity, p.PropertyInfo) ?? "NULL"));
            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("INSERT INTO {0} {1} {2} ",
                                    TableName,
                                    string.IsNullOrEmpty(columNames) ? "" : "(" + columNames + ")",
                                    string.IsNullOrEmpty(values) ? "" : " VALUES (" + values + ")");

            if (IsIdentity)
            {
                switch (SqlConnector)
                {
                case ESqlConnector.Mssql:
                    sqlBuilder.Append("SELECT CAST(SCOPE_IDENTITY() AS INT) AS " + IdentityProperty.ColumnName);
                    break;

                case ESqlConnector.MySql:
                    sqlBuilder.Append("; SELECT CONVERT(LAST_INSERT_ID(), SIGNED INTEGER) AS " +
                                      IdentityProperty.ColumnName);
                    break;

                case ESqlConnector.PostgreSql:
                    sqlBuilder.Append("RETURNING " + IdentityProperty.ColumnName);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(new SqlQuery(sqlBuilder.ToString(), entity));
        }
Esempio n. 30
0
        /// <summary>
        /// Gets the bulk update.
        /// </summary>
        /// <returns></returns>
        public virtual string GetBulkUpdate()
        {
            // TODO: Include Alias
            var properties = BaseProperties.Where(p => !KeyProperties.Any(k => k.Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase)));

            string ProjectionFunction(PropertyMetadata p)
            {
                return($"[DEST].[{p.ColumnName}] = [T].[{p.ColumnName}]");
            }

            var sqlBuilder = new StringBuilder();

            sqlBuilder.AppendFormat("UPDATE DEST SET {0} \n FROM [{1}].[{2}] AS DEST INNER JOIN [dbo].[{3}] AS T ON {4}; \n IF OBJECT_ID('tempdb..{5}') IS NOT NULL \n DROP TABLE [dbo].[{6}];",
                                    string.Join(", ", properties.Select(ProjectionFunction)),
                                    Scheme,
                                    TableName,
                                    TempTableName,
                                    string.Join(", ", KeyProperties.Select(ProjectionFunction)),
                                    TempTableName,
                                    TempTableName);

            return(sqlBuilder.ToString());
        }