Exemplo n.º 1
0
 public string Format(MethodInfo methodInfo, IEnumerable<string> arguments)
 {
     if (methodInfo.DeclaringType == typeof (DelegateCall))
     {
         return string.Format("Invoke({0})", arguments.Join(", "));
     }
     return string.Format("{0}{1}({2})", methodInfo.Name, FormatGenericType(methodInfo), arguments.Join(", "));
 }
Exemplo n.º 2
0
 /// <summary>
 /// Fixed:
 /// </summary>
 private static SqlSelect SelectByFullText(
     Context context,
     Dictionary <string, string> words,
     SqlColumnCollection column    = null,
     SqlOrderByCollection orderBy  = null,
     IEnumerable <long> siteIdList = null,
     string dataTableName          = null,
     int offset       = 0,
     int pageSize     = 0,
     bool countRecord = false)
 {
     return(!countRecord
         ? Rds.SelectItems(
                dataTableName : dataTableName,
                column : column,
                join : new SqlJoinCollection(
                    new SqlJoin(
                        tableBracket: "\"Sites\"",
                        joinType: SqlJoin.JoinTypes.Inner,
                        joinExpression: "\"Items\".\"SiteId\"=\"Sites\".\"SiteId\"")),
                where : Rds.ItemsWhere()
                .FullTextWhere(
                    context : context,
                    words : words)
                .Add(
                    raw : Def.Sql.CanRead,
                    _using : !context.HasPrivilege && !context.Publish)
                .Add(
                    raw : "\"Items\".\"SiteId\" in ({0})".Params(siteIdList?.Join()),
                    _using : siteIdList?.Any() == true)
                .Add(raw : $"{context.Sqls.IsNull}(\"Sites\".\"DisableCrossSearch\",'false')='false'")
                .Add(
                    raw : "\"Items\".\"ReferenceType\"<>'Sites'",
                    _using : Parameters.Search.DisableCrossSearchSites),
                param : FullTextParam(words),
                orderBy : orderBy,
                offset : offset,
                pageSize : pageSize)
            : Rds.SelectCount(
                tableName : "Items",
                join : new SqlJoinCollection(
                    new SqlJoin(
                        tableBracket : "\"Sites\"",
                        joinType : SqlJoin.JoinTypes.Inner,
                        joinExpression : "\"Items\".\"SiteId\"=\"Sites\".\"SiteId\"")),
                    where : Rds.ItemsWhere()
                .FullTextWhere(
                    context : context,
                    words : words)
                .Add(
                    raw : Def.Sql.CanRead,
                    _using : !context.HasPrivilege && !context.Publish)
                .Add(
                    raw : "\"Items\".\"SiteId\" in ({0})".Params(siteIdList?.Join()),
                    _using : siteIdList?.Any() == true),
                param : FullTextParam(words)));
 }
Exemplo n.º 3
0
 /// <summary>
 /// Fixed:
 /// </summary>
 private static SqlSelect SelectByFullText(
     Context context,
     List <string> words,
     SqlColumnCollection column    = null,
     SqlOrderByCollection orderBy  = null,
     IEnumerable <long> siteIdList = null,
     string dataTableName          = null,
     int offset       = 0,
     int pageSize     = 0,
     bool countRecord = false)
 {
     return(!countRecord
         ? Rds.SelectItems(
                dataTableName : dataTableName,
                column : column,
                join : new SqlJoinCollection(
                    new SqlJoin(
                        tableBracket: "[Sites]",
                        joinType: SqlJoin.JoinTypes.Inner,
                        joinExpression: "[Items].[SiteId]=[Sites].[SiteId]")),
                where : Rds.ItemsWhere()
                .Add(raw : FullTextWhere(words))
                .Add(
                    raw : Def.Sql.CanRead,
                    _using : !context.HasPrivilege && !context.Publish)
                .Add(
                    raw : "[Items].[SiteId] in ({0})".Params(siteIdList?.Join()),
                    _using : siteIdList?.Any() == true),
                param : FullTextParam(words),
                orderBy : orderBy,
                offset : offset,
                pageSize : pageSize)
            : Rds.SelectCount(
                tableName : "Items",
                join : new SqlJoinCollection(
                    new SqlJoin(
                        tableBracket : "[Sites]",
                        joinType : SqlJoin.JoinTypes.Inner,
                        joinExpression : "[Items].[SiteId]=[Sites].[SiteId]")),
                    where : Rds.ItemsWhere()
                .Add(raw : FullTextWhere(words))
                .Add(
                    raw : Def.Sql.CanRead,
                    _using : !context.HasPrivilege && !context.Publish)
                .Add(
                    raw : "[Items].[SiteId] in ({0})".Params(siteIdList?.Join()),
                    _using : siteIdList?.Any() == true),
                param : FullTextParam(words)));
 }
 /// <summary>
 /// Fixed:
 /// </summary>
 private static SqlSelect SelectBySearchIndexes(
     Context context,
     IEnumerable <string> searchIndexes,
     SqlColumnCollection column,
     SqlOrderByCollection orderBy,
     IEnumerable <long> siteIdList,
     string dataTableName = null,
     int offset           = 0,
     int pageSize         = 0,
     bool countRecord     = false)
 {
     return(Rds.SelectSearchIndexes(
                dataTableName: dataTableName,
                column: column,
                join: Rds.SearchIndexesJoinDefault(),
                where : Rds.SearchIndexesWhere()
                .Word(searchIndexes, multiParamOperator: " or ")
                .Add(
                    raw: Def.Sql.CanRead,
                    _using: !context.HasPrivilege)
                .Add(
                    raw: "[Items].[SiteId] in ({0})".Params(siteIdList?.Join()),
                    _using: siteIdList?.Any() == true),
                groupBy: Rds.SearchIndexesGroupBy()
                .ReferenceId()
                .ReferenceType(),
                having: Rds.SearchIndexesHaving()
                .SearchIndexesCount(
                    Concordance(searchIndexes),
                    _operator: ">="),
                orderBy: orderBy,
                offset: offset,
                pageSize: pageSize,
                countRecord: countRecord));
 }
 /// <summary>
 /// Fixed:
 /// </summary>
 private static SqlSelect SelectByFullText(
     SqlColumnCollection column,
     SqlOrderByCollection orderBy,
     IEnumerable <long> siteIdList,
     List <string> words,
     string dataTableName = null,
     int offset           = 0,
     int pageSize         = 0,
     bool countRecord     = false,
     string paramName     = "@Words_Param")
 {
     return(Rds.SelectItems(
                dataTableName: dataTableName,
                column: column,
                join: Rds.ItemsJoinDefault()
                .Add(new SqlJoin(
                         tableName: "[Sites]",
                         joinType: SqlJoin.JoinTypes.Inner,
                         joinExpression: "[Items].[SiteId]=[Sites].[SiteId]")),
                where : Rds.ItemsWhere()
                .Add(raw: "contains(FullText, '" + words.Join(" and ") + "')")
                .Add(raw: Def.Sql.CanRead)
                .Add(
                    raw: "[Items].[SiteId] in ({0})".Params(siteIdList?.Join()),
                    _using: siteIdList?.Any() == true),
                orderBy: orderBy,
                offset: offset,
                pageSize: pageSize,
                countRecord: countRecord));
 }
Exemplo n.º 6
0
			/// <summary>Runs a list of CMD commands.</summary>
			/// <param name="commands">List of commands to execute by CMD window.</param>
			/// <returns>The associated process.</returns>
			public static Task<Process> Run(IEnumerable<string> commands)
			{
				var procStartInfo = new ProcessStartInfo
									{
										RedirectStandardError = false,
										RedirectStandardOutput = true,
										UseShellExecute = false,
										FileName = "cmd",
										WindowStyle = ProcessWindowStyle.Hidden,
										CreateNoWindow = true,
										Arguments = "/c " + commands.Join("&"),
									};


				var process = new Process();
				process.EnableRaisingEvents = true;
				process.StartInfo = procStartInfo;
				var tcs = new TaskCompletionSource<Process>();
				process.Exited += (sender, args) => tcs.SetResult(process);
				try
				{
					process.Start();
				}
				catch (Exception e)
				{
					tcs.SetException(e);
				}


				return tcs.Task;
			}
Exemplo n.º 7
0
        public virtual IEnumerable <object> LoadKeys(IEnumerable <string> tags = null, IEnumerable <Criteria> criterias = null)
        {
            if (Options.EnableLogging)
            {
                Log.Debug($"{TableName} count: tags={tags?.Join("||")}");
            }

            using (var conn = CreateConnection())
            {
                var sql = new StringBuilder($@"{SqlBuilder.BuildUseDatabase(Options.DatabaseName)} SELECT [key] FROM {TableName} WHERE [id]>0");
                foreach (var t in tags.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildTagSelect(t));
                }
                foreach (var c in criterias.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
                }
                //var sql = $@"SELECT [key] FROM {TableName} WHERE [id]>0";
                //tags.NullToEmpty().ForEach(t => sql += SqlBuilder.BuildTagSelect(t));
                //criterias.NullToEmpty().ForEach(c => sql += SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
                conn.Open();
                return(conn.Query <object>(sql.ToString()));
            }
        }
        public virtual string UpdateAndReturn(IClassMapper classMap, IDictionary <string, object> parameters, IDictionary <string, object> existsParameters, string schema, IEnumerable <string> cols = null)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("Parameters");
            }

            IEnumerable <IPropertyMap> columns = null;

            if (cols == null)
            {
                columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity));
            }
            else
            {
                columns = cols?.Join(classMap.Properties, x => x.ToLowerInvariant(), y => y.ColumnName.ToLowerInvariant(), (x, y) => y)?.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity));
            }

            if (!columns?.Any() ?? true)
            {
                throw new ArgumentException("No columns were mapped.");
            }

            var setSql =
                columns.Select(
                    p =>
                    string.Format(
                        "{0} = {1}{2}", p.Name, "@", p.Name));

            return(GetUpdateAndReturn("features.Like",
                                      AppendStrings(setSql), $"ArticleId={parameters["ArticleId"]} AND UserId = {parameters["UserId"]}"));
        }
Exemplo n.º 9
0
        IEnumerable<Result> DiffRows(IEnumerable<Row> rows1, IEnumerable<Row> rows2)
        {
            var rows = rows1.Join(rows2, r => r.Name, r => r.Name, (r1, r2) => new Tuple<Row, Row>(r1, r2));
            var errors = rows.Select(t => DiffRows(t.Item1, t.Item2)).SelectMany(i => i);

            return errors.GroupBy(e => e.Column).Select(g => new Result { Title = g.Key, Errors = g.Select(e => e.Message).Distinct().ToList() });
        }
Exemplo n.º 10
0
 /// <summary>
 /// Fixed:
 /// </summary>
 private static SqlSelect SelectByFullText(
     SqlColumnCollection column,
     SqlOrderByCollection orderBy,
     IEnumerable <long> siteIdList,
     List <string> words,
     string dataTableName = null,
     int offset           = 0,
     int pageSize         = 0,
     bool countRecord     = false,
     string paramName     = "@Words_Param")
 {
     return(Rds.SelectItems(
                dataTableName: dataTableName,
                column: column,
                join: new SqlJoinCollection(
                    new SqlJoin(
                        tableBracket: "[Sites]",
                        joinType: SqlJoin.JoinTypes.Inner,
                        joinExpression: "[Items].[SiteId]=[Sites].[SiteId]")),
                where : Rds.ItemsWhere()
                .Add(raw: "contains(FullText, @SearchText_Param#CommandCount#)")
                .Add(
                    raw: Def.Sql.CanRead,
                    _using: !Permissions.HasPrivilege())
                .Add(
                    raw: "[Items].[SiteId] in ({0})".Params(siteIdList?.Join()),
                    _using: siteIdList?.Any() == true),
                param: Rds.ItemsParam()
                .Add(name: "SearchText", value: words.Join(" and ")),
                orderBy: orderBy,
                offset: offset,
                pageSize: pageSize,
                countRecord: countRecord));
 }
Exemplo n.º 11
0
 public ForeignKeyException(int referredid, IEnumerable<int> referrerids, string tablename)
     : base(String.Format("The entity with Id={0} is referred to by {1} entities with Id={2} and cannot be deleted.", referredid, tablename, referrerids.Join(", ")))
 {
     ReferredId = referredid;
     ReferrerIds = referrerids.ToList();
     ReferrersType = tablename;
 }
Exemplo n.º 12
0
 public virtual StorageAction Delete(IEnumerable <string> tags,
                                     IEnumerable <Criteria> criterias = null)
 {
     if (Options.EnableLogging)
     {
         Log.Debug($"{TableName} delete: tags={tags?.Join("||")}");
     }
     if (tags.IsNullOrEmpty())
     {
         return(StorageAction.None);
     }
     using (var conn = CreateConnection())
     {
         var sql = new StringBuilder($"{SqlBuilder.BuildUseDatabase(Options.DatabaseName)} {SqlBuilder.BuildDeleteByTags(TableName)}");
         foreach (var t in tags.NullToEmpty())
         {
             sql.Append(SqlBuilder.BuildTagSelect(t));
         }
         foreach (var c in criterias.NullToEmpty())
         {
             sql.Append(SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
         }
         //var sql = SqlBuilder.BuildDeleteByTags(TableName);
         //tags.NullToEmpty().ForEach(t => sql += SqlBuilder.BuildTagSelect(t));
         //criterias.NullToEmpty().ForEach(c => sql += SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
         conn.Open();
         var num = conn.Execute(sql.ToString());
         return(num > 0 ? StorageAction.Deleted : StorageAction.None);
     }
 }
Exemplo n.º 13
0
Arquivo: CMD.cs Projeto: heinzsack/DEV
			public static Task<Process> RunElevated(IEnumerable<string> commands)
			{
				var procStartInfo = new ProcessStartInfo()
				{
					RedirectStandardError = false,
					RedirectStandardOutput = false,
					FileName = "cmd",
					Verb = "runas",
					Arguments = "/C " + commands.Join("&"),
				};

				var process = new Process();
				process.EnableRaisingEvents = true;
				process.StartInfo = procStartInfo;
				var tcs = new TaskCompletionSource<Process>();
				process.Exited += (sender, args) => tcs.SetResult(process);
				try
				{
					process.Start();
				}
				catch (Exception e)
				{
					tcs.SetException(e);
				}


				return tcs.Task;
			}
Exemplo n.º 14
0
 public NounNotFound(IEnumerable<string> nouns)
 {
     nouns = nouns.ToList();
     if (nouns.Count() == 0)
         _message = "Noun not found.";
     else
         _message = "Ambiguous noun. Possible matches: " + nouns.Join(", ");
 }
Exemplo n.º 15
0
 private static void validateMatchingMimetypes(MimeType mimeType, AssetTagPlan plan, IEnumerable<string> names)
 {
     if (plan.Subjects.Any(x => x.MimeType != mimeType))
     {
         var message = "Files {0} have mixed mimetype's".ToFormat(names.Join(", "));
         throw new MixedMimetypeException(message);
     }
 }
        private string ReadAcceptType(IEnumerable<string> header)
        {
            if (header == null || header.Count() == 0) return "*/*";

            if (header.Count() == 1) return header.Single();

            return header.Join(", ");
        }
Exemplo n.º 17
0
 public static IEnumerable<string> MapScope(IEnumerable<ReferenceDataItem> collection, IEnumerable<string> config)
 {
     return collection.Join(
         config,
         s => s.Name,
         r => r,
         (s, r) => s.Id,
         StringComparer.OrdinalIgnoreCase);
 }
Exemplo n.º 18
0
 public TestSuite(IEnumerable<ITestee> parsers, IEnumerable<ITest> tests, IOutput output, IWarmup warmup = null)
 {
     _reruns = 1;
     _repeats = 10;
     _parsers = parsers;
     _tests = tests;
     _output = output;
     _warmup = warmup;
     _results = new List<TestResult>(parsers.Join(tests, m => 0, m => 0, (a, b) => new TestResult(b, a)));
 }
Exemplo n.º 19
0
        public static void SetUniqueNamesForForeignKeyProperties(IEnumerable<ForeignKey> foreignKeys)
        {
            IEnumerable<string> refsUsedMoreThanOnce = foreignKeys.Select(f => f.References).Distinct()
                .GroupJoin(foreignKeys, a => a, b => b.References, (a, b) => new { References = a, Count = b.Count() })
                .Where(@t => t.Count > 1)
                .Select(@t => t.References);

            foreignKeys.Join(refsUsedMoreThanOnce, a => a.References, b => b, (a, b) => a).ToList()
                .ForEach(fk => { fk.UniquePropertyName = fk.Name + "_" + fk.References; });
        }
Exemplo n.º 20
0
        public AssetNamesKey(IEnumerable<string> names)
        {
            _names = names.OrderBy(x => x);

            _hashcode = new Lazy<int>(() =>
            {
                var combined = names.Join("*");
                return combined.ToHash().GetHashCode();
            });
        }
Exemplo n.º 21
0
        private IEnumerable<Node> CheckMetadataStringOperator(MappingToolDatabaseDataContext dbContext, IEnumerable<Node> nodes, GraphQueryMetadata metadataTest)
        {
            List<Node> filteredNodes = null;

            if (metadataTest.Operator.Equals("Contains", StringComparison.InvariantCultureIgnoreCase))
            {
                IQueryable<Node> queryableNodes = nodes.AsQueryable();
                var filteredMetadata = from dbMetadata in dbContext.udf_SearchMetadataContains(metadataTest.Name, metadataTest.Value) select dbMetadata;
                int counter = filteredMetadata.Count();
                filteredNodes = nodes.Join(filteredMetadata, x => x.NodeUid, y => y.NodeUid, (a, b) => a).ToList();
            }
            else if (metadataTest.Operator.Equals("FreeText", StringComparison.InvariantCultureIgnoreCase))
            {
                IQueryable<Node> queryableNodes = nodes.AsQueryable();
                var filteredMetadata = from dbMetadata in dbContext.udf_SearchMetadataFreeText(metadataTest.Name, metadataTest.Value) select dbMetadata;
                int counter = filteredMetadata.Count();
                filteredNodes = nodes.Join(filteredMetadata, x => x.NodeUid, y => y.NodeUid, (a, b) => a).ToList();
            }
            else
            {
                filteredNodes = new List<Node>();

                foreach (Node node in nodes)
                {
                    if (metadataTest.Operator.Equals("Equals", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (node.Metadatas.Where(metadata => metadata.MetadataName == metadataTest.Name && metadata.MetadataValue.Contains(metadataTest.Value)).Count() > 0)
                        {
                            filteredNodes.Add(node);
                        }
                    }
                    else if (metadataTest.Operator.Equals("NotEquals", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (node.Metadatas.Where(metadata => metadata.MetadataName == metadataTest.Name && metadata.MetadataValue != metadataTest.Value).Count() > 0)
                        {
                            filteredNodes.Add(node);
                        }
                    }
                }
            }

            return filteredNodes;
        }
Exemplo n.º 22
0
        /// <summary>
        ///     Creates a default index name based on the supplied column names.
        /// </summary>
        /// <param name="columns">The column names used to create a default index name.</param>
        /// <returns>A default index name.</returns>
        public static string BuildDefaultName(IEnumerable<string> columns)
        {
            Check.NotNull(columns, "columns");

            return string.Format(
                CultureInfo.InvariantCulture,
                "IX_{0}",
                columns.Join(separator: "_"))
                .RestrictTo(128);
        }
Exemplo n.º 23
0
        public DictionaryPath(string path)
        {
            var parts = path.Trim().Split('.');
            _parentParts = parts.Reverse().Skip(1).Reverse();
            _parent = parts.Any()
                          ? _parentParts.Join(".")
                          : String.Empty;

            _key = parts.Last();
        }
Exemplo n.º 24
0
        public void TestJoinWithPostExpression(IEnumerable<Foo> foos, IEnumerable<Bar> bars)
        {
            var joined = Factory.MemoryJoin(foos.AsQueryable(), bars.AsQueryable(), f => f.Id, b => b.Id, (f, b) => new { f.Id, FooName = f.Name, BarName = b.Name })
                .Where(x => x.FooName != null) // todo: Влияет на сложность слияния, хочется, чтобы выполнялось до материализации.
                .Select(x => x.BarName) // todo: Влияет на объём материализуемых данных
                .ToArray();

            var expected = foos.Join(bars, f => f.Id, b => b.Id, (f, b) => new { FooName = f.Name, BarName = b.Name })
                .Where(x => x.FooName != null)
                .Select(x => x.BarName)
                .ToArray();

            Assert.That(joined.ToArray(), Is.EquivalentTo(expected));
        }
        internal override void Upgrade(
            IEnumerable<string> pendingMigrations, string targetMigrationId, string lastMigrationId)
        {
            var count = pendingMigrations.Count();

            _logger.Info(
                (count > 0)
                    ? Strings.LoggingPendingMigrations(count, pendingMigrations.Join())
                    : string.IsNullOrWhiteSpace(targetMigrationId)
                          ? Strings.LoggingNoExplicitMigrations
                          : Strings.LoggingAlreadyAtTarget(targetMigrationId));

            base.Upgrade(pendingMigrations, targetMigrationId, lastMigrationId);
        }
Exemplo n.º 26
0
        public virtual IEnumerable <Stream> LoadData(object key, IEnumerable <string> tags = null,
                                                     IEnumerable <Criteria> criterias      = null,
                                                     DateTime?fromDateTime = null, DateTime?tillDateTime = null,
                                                     int skip = 0, int take = 0)
        {
            if (Options.EnableLogging)
            {
                Log.Debug(
                    $"{TableName} load: key={key}, tags={tags?.Join("||")}, criterias={criterias?.Select(c => c.Name + ":" + c.Value).Join("||")}");
            }

            using (var conn = CreateConnection())
            {
                var sql = new StringBuilder($"{SqlBuilder.BuildUseDatabase(Options.DatabaseName)} {SqlBuilder.BuildDataSelectByKey(TableName)}");
                foreach (var t in tags.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildTagSelect(t));
                }
                foreach (var c in criterias.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
                }
                sql.Append(SqlBuilder.BuildFromTillDateTimeSelect(fromDateTime, tillDateTime));
                sql.Append(SqlBuilder.BuildSortingSelect(Options.DefaultSortColumn));
                sql.Append(SqlBuilder.BuildPagingSelect(skip, take, Options.DefaultTakeSize, Options.MaxTakeSize));
                //var sql = SqlBuilder.BuildDataSelectByKey(TableName);
                //tags.NullToEmpty().ForEach(t => sql += SqlBuilder.BuildTagSelect(t));
                //criterias.NullToEmpty().ForEach(c => sql += SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
                //sql += SqlBuilder.BuildFromTillDateTimeSelect(fromDateTime, tillDateTime);
                //sql += SqlBuilder.BuildSortingSelect(Options.DefaultSortColumn);
                //sql += SqlBuilder.BuildPagingSelect(skip, take, Options.DefaultTakeSize, Options.MaxTakeSize);
                conn.Open();
                var results = conn.Query <byte[]>(sql.ToString(), new { key }, buffered: Options.BufferedLoad);
                if (results == null)
                {
                    yield break;
                }
                foreach (var data in results.Where(data => data != null))
                {
                    yield return(new MemoryStream(data.Decompress()));
                }
            }
        }
Exemplo n.º 27
0
        private StorageAction Insert(object key, TDoc document, Stream data, IEnumerable <string> tags, StringBuilder sql)
        {
            // INSERT ===
            if (Options.EnableLogging)
            {
                Log.Debug($"{TableName} insert: key={key},tags={tags?.Join("||")}");
            }
            var insertColumns = "[value]";

            if (document != null && data != null)
            {
                insertColumns = $"{insertColumns},[data]" /*+= ",[data]"*/;
            }
            if (document == null && data != null)
            {
                insertColumns = "[data]";
            }
            var insertValues = "@value";

            if (document != null && data != null)
            {
                insertValues = $"{insertValues},@data" /*",@data"*/;
            }
            if (document == null && data != null)
            {
                insertValues = "@data";
            }
            sql.Append(
                $@"
    {SqlBuilder.BuildUseDatabase(Options.DatabaseName)}
    INSERT INTO {TableName
                    }
        ([key],[tags],[hash],[timestamp],{insertColumns}{
                    IndexMaps.NullToEmpty()
                        .Select(i => ",[" + i.Name.ToLower() + SqlBuilder.IndexColumnNameSuffix + "]")
                        .Join("")})
        VALUES(@key,@tags,@hash,@timestamp,{insertValues}{
                    IndexMaps.NullToEmpty()
                        .Select(i => ",@" + i.Name.ToLower() + SqlBuilder.IndexColumnNameSuffix)
                        .Join("")})");
            return(StorageAction.Inserted);
        }
        private string ToString(IEnumerable <string> formattedRefs, string prefix, string textIfEmpty, string refsType, bool truncated)
        {
            string?linksJoined = formattedRefs?.Join(Environment.NewLine);

            if (string.IsNullOrEmpty(linksJoined))
            {
                return(WebUtility.HtmlEncode(textIfEmpty));
            }

            var sb = new StringBuilder()
                     .AppendLine(WebUtility.HtmlEncode(prefix))
                     .Append(linksJoined);

            if (truncated)
            {
                sb.AppendLine()
                .AppendLine(_linkFactory.CreateShowAllLink(refsType));
            }

            return(sb.ToString());
        }
Exemplo n.º 29
0
 //*********** COURSE_build
 public static void COURSE_build(BuildIds buildId, IEnumerable<Langs> locs, dictTypes dictType = dictTypes.no) {
   runTask("COURSE_build", () => {
     Trace.TraceWarning("BuildId: {0}, locs: {1}, dictType: {2}", buildId, locs.Join(), dictType);
     LoggerMemory log = new LoggerMemory(true);
     try {
       CourseMeta.Lib.init(log, @"d:\lmcom\", false);
       if (!log.hasError) {
         //vytvoreni WebDataBatch, vse je pripraveno nahradit DATA-{0}.xml pouhymi seznamy produkt IDS
         var productIds = File.ReadAllLines(string.Format(@"D:\LMCom\rew\DeployGUI\Web4CourseProducts\{0}.txt", buildId));
         Trace.TraceWarning("Start build {0} products", productIds.Length);
         var batch = new WebDataBatch { dictType = dictType, locs = locs.ToArray(), products = productIds.Select(id => new BatchProduct { id = id }).ToArray() };
         WebDataBatch.FinishAfterLoad(batch);
         //seznam souboru, v product adresari jsou metainformace o produktech, v envelope jsou aktualizovane informace.
         var files = batch.getWebBatchFilesNew(buildId, log, @"d:\LMCom\rew\Web4\products\");
         buildLib.writeVirtualFiles(buildId, files);
       }
     } catch (Exception exp) {
       log.ErrorLine("Exception", LowUtils.ExceptionToString(exp));
     }
     return log.hasError ? log.Log() : null;
   });
 }
Exemplo n.º 30
0
        private StorageAction Update(object key, TDoc document, Stream data, IEnumerable <string> tags, StringBuilder sql)
        {
            // UPDATE ===
            if (Options.EnableLogging)
            {
                Log.Debug($"{TableName} update: key={key},tags={tags?.Join("||")}");
            }
            var updateColumns = "[value]=@value";

            if (document != null && data != null)
            {
                updateColumns = $"{updateColumns},[data]=@data";
            }
            if (document == null && data != null)
            {
                updateColumns = "[data]=@data";
            }
            sql.Append(
                $@"
    {SqlBuilder.BuildUseDatabase(Options.DatabaseName)}
    UPDATE {TableName
                    }
    SET [tags]=@tags,[hash]=@hash,[timestamp]=@timestamp,{updateColumns
                    }
        {
                    IndexMaps.NullToEmpty()
                        .Select(
                            i =>
                                ",[" + i.Name.ToLower() + SqlBuilder.IndexColumnNameSuffix + "]=@" +
                                i.Name.ToLower() + SqlBuilder.IndexColumnNameSuffix)
                        .Join("")}
    WHERE [key]=@key");
            foreach (var t in tags.NullToEmpty())
            {
                sql.Append(SqlBuilder.BuildTagSelect(t));
            }
            return(StorageAction.Updated);
        }
Exemplo n.º 31
0
 //*********** AZURE_publish
 public static void AZURE_publish(
   string container, //napr. "js-v001" nebo "mm-v001"
   bool isJS, //JS soubory nebo multimedia soubory
   IEnumerable<BuildIds> buildIds, //napr. English,Skrivanek, ...
   IEnumerable<Langs> locs //lokalizace
   ) {
   runTask("AZURE_publish", () => {
     Trace.TraceWarning("container: {1}, isJS: {2}, buildIds: {3}, locs: {4}, connection: {0}",
       Cfg.cfg.azure.connectionString,
       container,
       isJS,
       buildIds.Join(),
       locs.Join()
       );
     var msg = SynchronizeDirs.synchronize(
       isJS,
       new azureDriver(Cfg.cfg.azure.connectionString, container),
       buildIds,
       locs
     );
     Trace.WriteLine("Synchronize info: " + msg);
     return null;
   });
 }
        private static void SyncModifiedPosts(
            IEnumerable<BlogPost> sourcePosts,
            IEnumerable<BlogPostBase> dataStoragePosts,
            BlogSyncPostsChangeSet changeSet)
        {
            var modifiedPosts =
                dataStoragePosts.Join(
                    sourcePosts,
                    dbPost => dbPost.SourceId,
                    sourcePost => sourcePost.SourceId,
                    (dbPost, sourcePost) => new { DbPost = dbPost, SourcePost = sourcePost }).ToList();

            foreach (var modifiedPost in modifiedPosts)
            {
                var dbPost = modifiedPost.DbPost;
                var sourcePost = modifiedPost.SourcePost;

                bool isModified = (dbPost.Hash != sourcePost.Hash || sourcePost.UpdatedAt > dbPost.UpdatedAt);
                if (isModified)
                {
                    changeSet.UpdatedBlogPosts.Add(sourcePost);
                }
            }
        }
Exemplo n.º 33
0
        public virtual IEnumerable <TDoc> LoadValues(IEnumerable <string> tags        = null,
                                                     IEnumerable <Criteria> criterias = null,
                                                     DateTime?fromDateTime            = null, DateTime?tillDateTime = null,
                                                     int skip = 0, int take = 0)
        {
            if (Options.EnableLogging)
            {
                Log.Debug($"{TableName} load: tags={tags?.Join("||")}, criterias={criterias?.Select(c => c.Name + ":" + c.Value).Join("||")}");
            }

            using (var conn = CreateConnection())
            {
                var sql = new StringBuilder($"{SqlBuilder.BuildUseDatabase(Options.DatabaseName)} {SqlBuilder.BuildValueSelectByTags(TableName)}");
                foreach (var t in tags.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildTagSelect(t));
                }
                foreach (var c in criterias.NullToEmpty())
                {
                    sql.Append(SqlBuilder.BuildCriteriaSelect(IndexMaps, c));
                }
                sql.Append(SqlBuilder.BuildFromTillDateTimeSelect(fromDateTime, tillDateTime));
                sql.Append(SqlBuilder.BuildSortingSelect(Options.DefaultSortColumn));
                sql.Append(SqlBuilder.BuildPagingSelect(skip, take, Options.DefaultTakeSize, Options.MaxTakeSize));
                conn.Open();
                var documents = conn.Query <string>(sql.ToString(), buffered: Options.BufferedLoad);
                if (documents == null)
                {
                    yield break;
                }
                foreach (var document in documents)
                {
                    yield return(Serializer.FromJson <TDoc>(document));
                }
            }
        }
        /// <summary>
        /// Generates code to specify a set of column names using a lambda expression.
        /// </summary>
        /// <param name="columns"> The columns to generate code for. </param>
        /// <param name="writer"> Text writer to add the generated code to. </param>
        protected virtual void Generate(IEnumerable<string> columns, IndentedTextWriter writer)
        {
            Check.NotNull(columns, "columns");
            Check.NotNull(writer, "writer");

            writer.Write("Function(t) ");

            if (columns.Count() == 1)
            {
                writer.Write("t." + ScrubName(columns.Single()));
            }
            else
            {
                writer.Write("New With { " + columns.Join(c => "t." + ScrubName(c)) + " }");
            }
        }
Exemplo n.º 35
0
        public ActionResult Search(string genreID, string membershipTypeID, string date)
        {
            int      queryParams = 0;
            int      membershipCheck;
            int      genreCheck;
            DateTime dateCheck;

            if (Int32.TryParse(membershipTypeID, out membershipCheck))
            {
                if (membershipCheck > 0)
                {
                    queryParams += 1;
                }
            }
            if (Int32.TryParse(genreID, out genreCheck))
            {
                if (genreCheck > 0)
                {
                    queryParams += 2;
                }
            }
            if (DateTime.TryParse(date, out dateCheck))
            {
                queryParams += 4;
            }

            var books = db.Books.Include(m => m.genre);
            IEnumerable <Books> booksQuery = books;
            var rentals = db.Rentals;
            IEnumerable <Rentals> rentalsQuery = rentals;

            switch (queryParams)
            {
            case 1:
                booksQuery = books.Where(m => m.membershipType == membershipCheck);
                break;

            case 2:
                booksQuery = books.Where(m => m.genreID == genreCheck);
                break;

            case 3:
                booksQuery = books.Where(m => m.membershipType == membershipCheck && m.genreID == genreCheck);
                break;

            case 4:
                rentalsQuery = rentals.Where(m => m.rentalExpiration >= dateCheck);
                break;

            case 5:
                booksQuery   = books.Where(m => m.membershipType == membershipCheck);
                rentalsQuery = rentals.Where(m => m.rentalExpiration >= dateCheck);
                break;

            case 6:
                booksQuery   = books.Where(m => m.genreID == genreCheck);
                rentalsQuery = rentals.Where(m => m.rentalExpiration >= dateCheck);
                break;

            case 7:
                booksQuery   = books.Where(m => m.membershipType == membershipCheck && m.genreID == genreCheck);
                rentalsQuery = rentals.Where(m => m.rentalExpiration >= dateCheck);
                break;

            default:
                break;
            }

            var rentalsGenre = rentalsQuery.Join(booksQuery, r => r.rentalBook, m => m.bookName, (r, m) => new RentalViewModel {
                book = r.rentalBook, genre = m.genre.genreName, rentalUser = r.rentalUser, rentalExpiration = r.rentalExpiration
            });

            return(View("Index", rentalsGenre.ToList()));
        }
Exemplo n.º 36
0
        protected override long InternalExecute()
        {
            long   iTotalRows   = 0L;
            long   iRows        = 0L;
            string queryColumns = "(";
            string queryValues  = "(";

            Dictionary <string, SQLiteParameter> parametersCache =
                new Dictionary <string, SQLiteParameter>();

            if (this.TableDefinition != null)
            {
                IEnumerable <string> uniques =
                    (from field in this.TableDefinition.Fields.Values
                     where field.Unique
                     select field.Name.AsSqlClausePair());

                string uniquePairs = uniques.Join(" AND ");

                bool ifFirst = true;

                foreach (FieldDefinition field in this.TableDefinition.Fields.Values)
                {
                    parametersCache.Add(
                        field.Name,
                        new SQLiteParameter(field.Name.AsParamName(), field.SqlType.ToDbType())
                        );

                    string paramValue = field.Name.AsParamName();

                    if (
                        this.TableDefinition.Triggers.Any(
                            trigger => trigger is PreserveTrigger && ((PreserveTrigger)trigger).Column == field.Name))
                    {
                        paramValue = string.Format(
                            "COALESCE((SELECT {0} FROM {1} WHERE {2}), {3})",
                            field.Name,
                            this.TableDefinition.Name.AsDbName(),
                            uniquePairs,
                            field.Name.AsParamName()
                            );
                    }

                    if (ifFirst)
                    {
                        queryColumns += field.Name.AsDbName();
                        queryValues  += paramValue;

                        ifFirst = false;
                    }
                    else
                    {
                        queryColumns += "," + field.Name.AsDbName();
                        queryValues  += "," + paramValue;
                    }
                }

                queryColumns += ")";
                queryValues  += ")";

                string sql = string.Format(
                    "INSERT OR REPLACE INTO {0} {1} VALUES {2};",
                    this.TableDefinition.Name.AsDbName(),
                    queryColumns,
                    queryValues
                    );

                for (int i = 0; i < this._rows.Count; i++)
                {
                    ITableRow row = this._rows[i];

                    foreach (KeyValuePair <string, object> pair in row.Values)
                    {
                        parametersCache[pair.Key].Value = pair.Value;
                    }

                    iRows = this.ExecuteNonQuery(
                        sql,
                        parametersCache.Values,
                        this._transaction
                        );

                    iTotalRows += iRows;
                }

                this._rows.Clear();
            }

            return(iTotalRows);
        }
Exemplo n.º 37
0
        /// <summary>
        /// update database with localized quests information
        /// </summary>
        /// <param name="quests">quests with information to update</param>
        /// <param name="culture">culture for localization</param>
        /// <returns>updated quests from database</returns>
        public IEnumerable<Quest> UpdateQuests(IEnumerable<Quest> quests, CultureInfo culture)
        {
            using (MangosEntities context = GetContext())
            {
                var quest_templates = quests.Join(context.quest_template, o => o.Id, o => o.entry, (i, it) => new { it, i });
                var locales_quests = quests.Join(context.locales_quest, o => o.Id, o => o.entry, (i, li) => new { li, i });

                switch (LocalizationHelper.GetOffset(culture))
                {
                    case 0: quest_templates.ToList().ForEach(o => { o.it.Title = o.i.Title; o.it.Details = o.i.Details; o.it.Objectives = o.i.Objectives; o.it.OfferRewardText = o.i.OfferRewardText; o.it.RequestItemsText = o.i.RequestItemsText; o.it.EndText = o.i.EndText; o.it.CompletedText = o.i.CompletedText; o.it.ObjectiveText1 = o.i.ObjectiveText1; o.it.ObjectiveText2 = o.i.ObjectiveText2; o.it.ObjectiveText3 = o.i.ObjectiveText3; o.it.ObjectiveText4 = o.i.ObjectiveText4; }); break;
                    case 1: locales_quests.ToList().ForEach(o => { o.li.Title_loc1 = o.i.Title; o.li.Details_loc1 = o.i.Details; o.li.Objectives_loc1 = o.i.Objectives; o.li.OfferRewardText_loc1 = o.i.OfferRewardText; o.li.RequestItemsText_loc1 = o.i.RequestItemsText; o.li.EndText_loc1 = o.i.EndText; o.li.CompletedText_loc1 = o.i.CompletedText; o.li.ObjectiveText1_loc1 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc1 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc1 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc1 = o.i.ObjectiveText4; }); break;
                    case 2: locales_quests.ToList().ForEach(o => { o.li.Title_loc2 = o.i.Title; o.li.Details_loc2 = o.i.Details; o.li.Objectives_loc2 = o.i.Objectives; o.li.OfferRewardText_loc2 = o.i.OfferRewardText; o.li.RequestItemsText_loc2 = o.i.RequestItemsText; o.li.EndText_loc2 = o.i.EndText; o.li.CompletedText_loc2 = o.i.CompletedText; o.li.ObjectiveText1_loc2 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc2 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc2 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc2 = o.i.ObjectiveText4; }); break;
                    case 3: locales_quests.ToList().ForEach(o => { o.li.Title_loc3 = o.i.Title; o.li.Details_loc3 = o.i.Details; o.li.Objectives_loc3 = o.i.Objectives; o.li.OfferRewardText_loc3 = o.i.OfferRewardText; o.li.RequestItemsText_loc3 = o.i.RequestItemsText; o.li.EndText_loc3 = o.i.EndText; o.li.CompletedText_loc3 = o.i.CompletedText; o.li.ObjectiveText1_loc3 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc3 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc3 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc3 = o.i.ObjectiveText4; }); break;
                    case 4: locales_quests.ToList().ForEach(o => { o.li.Title_loc4 = o.i.Title; o.li.Details_loc4 = o.i.Details; o.li.Objectives_loc4 = o.i.Objectives; o.li.OfferRewardText_loc4 = o.i.OfferRewardText; o.li.RequestItemsText_loc4 = o.i.RequestItemsText; o.li.EndText_loc4 = o.i.EndText; o.li.CompletedText_loc4 = o.i.CompletedText; o.li.ObjectiveText1_loc4 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc4 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc4 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc4 = o.i.ObjectiveText4; }); break;
                    case 5: locales_quests.ToList().ForEach(o => { o.li.Title_loc5 = o.i.Title; o.li.Details_loc5 = o.i.Details; o.li.Objectives_loc5 = o.i.Objectives; o.li.OfferRewardText_loc5 = o.i.OfferRewardText; o.li.RequestItemsText_loc5 = o.i.RequestItemsText; o.li.EndText_loc5 = o.i.EndText; o.li.CompletedText_loc5 = o.i.CompletedText; o.li.ObjectiveText1_loc5 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc5 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc5 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc5 = o.i.ObjectiveText4; }); break;
                    case 6: locales_quests.ToList().ForEach(o => { o.li.Title_loc6 = o.i.Title; o.li.Details_loc6 = o.i.Details; o.li.Objectives_loc6 = o.i.Objectives; o.li.OfferRewardText_loc6 = o.i.OfferRewardText; o.li.RequestItemsText_loc6 = o.i.RequestItemsText; o.li.EndText_loc6 = o.i.EndText; o.li.CompletedText_loc6 = o.i.CompletedText; o.li.ObjectiveText1_loc6 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc6 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc6 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc6 = o.i.ObjectiveText4; }); break;
                    case 7: locales_quests.ToList().ForEach(o => { o.li.Title_loc7 = o.i.Title; o.li.Details_loc7 = o.i.Details; o.li.Objectives_loc7 = o.i.Objectives; o.li.OfferRewardText_loc7 = o.i.OfferRewardText; o.li.RequestItemsText_loc7 = o.i.RequestItemsText; o.li.EndText_loc7 = o.i.EndText; o.li.CompletedText_loc7 = o.i.CompletedText; o.li.ObjectiveText1_loc7 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc7 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc7 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc7 = o.i.ObjectiveText4; }); break;
                    case 8: locales_quests.ToList().ForEach(o => { o.li.Title_loc8 = o.i.Title; o.li.Details_loc8 = o.i.Details; o.li.Objectives_loc8 = o.i.Objectives; o.li.OfferRewardText_loc8 = o.i.OfferRewardText; o.li.RequestItemsText_loc8 = o.i.RequestItemsText; o.li.EndText_loc8 = o.i.EndText; o.li.CompletedText_loc8 = o.i.CompletedText; o.li.ObjectiveText1_loc8 = o.i.ObjectiveText1; o.li.ObjectiveText2_loc8 = o.i.ObjectiveText2; o.li.ObjectiveText3_loc8 = o.i.ObjectiveText3; o.li.ObjectiveText4_loc8 = o.i.ObjectiveText4; }); break;
                    default: throw new NotImplementedException("Unsupported culture " + culture.Name);
                }

                context.SaveChanges();
            }

            List<int> ids = quests.Select(o => o.Id).ToList();
            var updatedQuests = _context.quest_template.Where(o => ids.Contains(o.entry));
            return GetQuests(updatedQuests, culture);
        }
Exemplo n.º 38
0
        public async Task HandleAsync(
            IMethodDiscoveryRequest request,
            IAppConnection sourceConnection,
            ITransportChannel sourceChannel)
        {
            Log.Info("Handling method discovery request {{{0}}} from {{{1}}}", request, sourceConnection);
            var appId = sourceConnection.Info.ApplicationId;
            IEnumerable <IProvidedMethod> matchingProvidedMethods =
                request.ConsumedMethod.HasValue
                    ? _registryService.GetMatchingProvidedMethods(appId, request.ConsumedMethod.Value)
                    : _registryService.GetMatchingProvidedMethods(appId);

            if (request.InputMessageId.HasValue)
            {
                matchingProvidedMethods = matchingProvidedMethods
                                          .Where(x => string.Equals(x.Method.InputMessage.Id, request.InputMessageId.Value));
            }
            if (request.OutputMessageId.HasValue)
            {
                matchingProvidedMethods = matchingProvidedMethods
                                          .Where(x => string.Equals(x.Method.OutputMessage.Id, request.OutputMessageId.Value));
            }
            IEnumerable <IDiscoveredMethod> discoveredMethods;

            if (request.DiscoveryMode == DiscoveryMode.Online)
            {
                var onlineConnections = _appLifecycleManager.GetOnlineConnections();
                discoveredMethods = matchingProvidedMethods
                                    .Join(
                    onlineConnections,
                    x => x.ProvidedService.Application.Id,
                    y => y.Info.ApplicationId,
                    (method, connection) => (method, connection))
                                    .Select(pm => Convert(pm.method, pm.connection.Id));
            }
            else
            {
                var providedMethods       = matchingProvidedMethods.ToArray();
                var providerApps          = providedMethods.Select(x => x.ProvidedService.Application.Id).Distinct().ToArray();
                var availableProviderApps = FilterAvailableApps(providerApps);
                discoveredMethods = providedMethods
                                    .Join(availableProviderApps, x => x.ProvidedService.Application.Id, y => y, (x, y) => x)
                                    .Select(pm => Convert(pm, Maybe <UniqueId> .Nothing));
            }
            using (var response = _protocol.MessageFactory.CreateMethodDiscoveryResponse(discoveredMethods.ToList()))
            {
                Log.Info("Completed method discovery request {{{0}}} from {{{1}}}: {2}", request, sourceConnection, response);
                var serializedResponse = _protocol.Serializer.Serialize(response);
                try
                {
                    await sourceChannel.Out
                    .WriteAsync(new TransportMessageFrame(serializedResponse))
                    .ConfigureAwait(false);
                }
                catch
                {
                    serializedResponse.Dispose();
                    throw;
                }
            }
        }
        private static string StatRefLivre(IEnumerable<BibliothequeBO> lstBibliotheque, BibliothequeBO objActualBibliotheque)
        {
            // Référence de livre
            var lstLivre = CGlobalCache.LstLivreSelectAll;
            String refLivreAll = "", refLivreManaged = "", refLivreBibliotheque = "";
            var reflivreUniq = lstLivre.GroupBy(xx => xx.RefLivreId).Select(grp => grp.First()).ToList();
            refLivreAll += "Toutes les références: " + reflivreUniq.Count().ToString(CultureInfo.InvariantCulture);
            var grpAllBibliotheque = reflivreUniq.GroupBy(yy => yy.BibliothequeId).Select(grp => new { bibliothequeId = grp.Key, Count = grp.Count() }).ToList();
            var query = lstBibliotheque.Join(grpAllBibliotheque, myBiblio => myBiblio.BibliothequeId, allBiblio => allBiblio.bibliothequeId, (biblio1, biblio2) => new { biblioId = biblio1.BibliothequeId, biblio2.Count });

            refLivreManaged += string.Format("dans vos bibliothèques: {0}", query.Sum(result => result.Count));
            if (objActualBibliotheque != null) {
                var result = grpAllBibliotheque.FirstOrDefault(xx => xx.bibliothequeId == objActualBibliotheque.BibliothequeId);
                refLivreBibliotheque += "dans la bibliothèque " + objActualBibliotheque.BibliothequeName + ": " + ((result != null)?result.Count : 0).ToString(CultureInfo.InvariantCulture) ;
            } else {
                refLivreBibliotheque += "Vous n'avez pas choisi de bibliothèque à gérer";
            }

            return refLivreAll + "\n" + refLivreManaged + "\n" + refLivreBibliotheque + "\n";
        }
        private static string StatEmprunt(IEnumerable<BibliothequeBO> lstBibliotheque, BibliothequeBO objActualBibliotheque)
        {
            // Réservation
            var lstEmprunt = CGlobalCache.LstEmpruntSelectAll;

            var maxActionId = lstEmprunt.GroupBy(xx => xx.LivreId).Select(dd => new{LivreId = dd.Key, ActionId = dd.Max(qq => qq.ActionId)});

            var clientEmpruntEnCours = maxActionId.Select(dataInMaxActionResult => CGlobalCache.LstEmpruntSelectAll.ToList().Find(xx => xx.ActionId == dataInMaxActionResult.ActionId && xx.LivreId == dataInMaxActionResult.LivreId)).Where(result => result != null && result.State == "emp").ToList();

            String empruntAll = "", empruntManaged = "", empruntBibliotheque = "";

            empruntAll += "Tous les emprunts: " + clientEmpruntEnCours.Count.ToString(CultureInfo.InvariantCulture);
            var grpAllBibliotheque = clientEmpruntEnCours.GroupBy(xx => xx.Livre.BibliothequeId).Select(group => new { bibliothequeId = group.Key, Count = group.Count() }).ToList();
            var query = lstBibliotheque.Join(grpAllBibliotheque, myBiblio => myBiblio.BibliothequeId, allBiblio => allBiblio.bibliothequeId, (biblio1, biblio2) => new { biblioId = biblio1.BibliothequeId, biblio2.Count });

            empruntManaged += string.Format("dans vos bibliothèques: {0}", query.Sum(result => result.Count));
            if (objActualBibliotheque != null) {
                var result = grpAllBibliotheque.FirstOrDefault(xx =>xx.bibliothequeId == objActualBibliotheque.BibliothequeId);
                empruntBibliotheque += "dans la bibliothèque " + objActualBibliotheque.BibliothequeName + ": " + ((result != null)?result.Count : 0).ToString(CultureInfo.InvariantCulture) ;
            } else {
                empruntBibliotheque += "Vous n'avez pas choisi de bibliothèque à gérer";
            }

            return empruntAll + "\n" + empruntManaged + "\n" + empruntBibliotheque + "\n";
        }
Exemplo n.º 41
0
 // Helpers/String
 private static string Join(this IEnumerable <SyntaxNode> values)
 {
     return(values.Join(i => i.Kind()));
 }
Exemplo n.º 42
0
 /// <summary>
 /// Finds a type which matches one of the elements in the sequence of names.
 /// </summary>
 public static Type FindTypeByNames(IEnumerable <string> names)
 {
     return(names?
            .Join(Assemblies.SelectMany(a => a.GetExportedTypes()), name => name, exportedType => exportedType.FullName, (name, exportedType) => exportedType)
            .FirstOrDefault());
 }
Exemplo n.º 43
0
        public virtual Task SendAsync(string to, string subject, string body, bool isHtml, IEnumerable <string> cc, IEnumerable <string> bcc)
        {
            return(Task.Run(() =>
            {
                var data = $"To: {to}\r\nSubject: {subject}\r\nIsHtml:{isHtml}\r\nCC: {cc?.Join(",")}\r\nBCC: {bcc?.Join(",")}\r\nBody:{body}";

                Log(data);
            }));
        }
Exemplo n.º 44
0
 /// <summary>
 /// Filter a dictionary based on the passed keys in orderedFilter argument.
 /// Then return the values those keys represents ordered in the order of the given orderFilter keys
 /// </summary>
 /// <typeparam name="TKey"></typeparam>
 /// <typeparam name="TValue"></typeparam>
 /// <param name="dictionary"></param>
 /// <param name="orderedFilter"></param>
 /// <returns></returns>
 public static IEnumerable <TValue> OrdinalFilter <TKey, TValue>(
     this IDictionary <TKey, TValue> dictionary, IEnumerable <TKey> orderedFilter)
 => orderedFilter?.Join(dictionary, o => o, d => d.Key, (o, d) => d.Value);
Exemplo n.º 45
0
 public static string Join(this IEnumerable <string> source)
 {
     return(source.Join(""));
 }
        private static void HandleError(Exception ex, string path, IEnumerable <string> list)
        {
            string str = list.Join(", ", "'", "'");

            Log.Warn(ex, "Failed merging '{0}' with successfully merged {1}. {2}", (object)path, (object)str, (object)ex.Message);
        }
        private static String StatLivre(IEnumerable<BibliothequeBO> lstBibliotheque, BibliothequeBO objActualBibliotheque)
        {
            // Livre
            var lstLivre = CGlobalCache.LstLivreSelectAll;
            String livreAll = "", livreManaged = "", livreBibliotheque = "";
            livreAll += "Tous les livres disponibles: " + lstLivre.Count.ToString(CultureInfo.InvariantCulture);
            var grpAllBibliotheque = lstLivre.GroupBy(xx => xx.BibliothequeId).Select(group => new { bibliothequeId = group.Key, Count = group.Count() }).ToList();
            var query = lstBibliotheque.Join(grpAllBibliotheque, myBiblio => myBiblio.BibliothequeId, allBiblio => allBiblio.bibliothequeId, (biblio1, biblio2) => new { biblioId = biblio1.BibliothequeId, biblio2.Count });

            livreManaged += string.Format("dans vos bibliothèques: {0}", query.Sum(result => result.Count));
            if (objActualBibliotheque != null) {
                var result = grpAllBibliotheque.FirstOrDefault(xx =>xx.bibliothequeId == objActualBibliotheque.BibliothequeId);
                livreBibliotheque += "dans la bibliothèque " + objActualBibliotheque.BibliothequeName + ": " + ((result != null)?result.Count : 0).ToString(CultureInfo.InvariantCulture) ;
            } else {
                livreBibliotheque += "Vous n'avez pas choisi de bibliothèque à gérer";
            }

            return String.Format("{0}\n{1}\n{2}\n", livreAll, livreManaged, livreBibliotheque);
        }
Exemplo n.º 48
0
 public static IEnumerable <TResult> Join <TOuter, TInner, TKey, TResult>(this IEnumerable <TOuter> outer, IEnumerable <TInner> inner, Func <TOuter, TKey> outerKeySelector, Func <TInner, TKey> innerKeySelector, Func <TOuter, TInner, TResult> resultSelector)
 {
     return(outer.Join(inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer <TKey> .Default));
 }
        private static string StatDemandeReservation(IEnumerable<BibliothequeBO> lstBibliotheque, BibliothequeBO objActualBibliotheque)
        {
            // Demande de réservation
            var lstReservation = CGlobalCache.LstDemandeReservationSelectAll;
            String demandeReservationAll = "", demandeReservationManaged = "", demandeReservationBibliotheque = "";
            demandeReservationAll += "Toutes les demandes de réservation: " + lstReservation.Count(xx => xx.Valide == 1).ToString(CultureInfo.InvariantCulture);
            var grpAllBibliotheque = lstReservation.Where(condition => condition.Valide == 1).GroupBy(xx => xx.Client.BibliothequeId).Select(group => new { bibliothequeId = group.Key, Count = group.Count() }).ToList();
            var query = lstBibliotheque.Join(grpAllBibliotheque, myBiblio => myBiblio.BibliothequeId, allBiblio => allBiblio.bibliothequeId, (biblio1, biblio2) => new { biblioId = biblio1.BibliothequeId, biblio2.Count });

            demandeReservationManaged += string.Format("dans vos bibliothèques: {0}", query.Sum(result => result.Count));
            if (objActualBibliotheque != null) {
                //var lstOldReservation = CGlobalCache.LstOldDemandeReservationByClient;
                //var grpAllOldBibliotheque = lstOldReservation.Where(condition => condition.Valide == 1).GroupBy(xx => xx.Client.BibliothequeId).Select(group => new { bibliothequeId = group.Key, Count = group.Count() });

                var newReservation = grpAllBibliotheque.FirstOrDefault(xx => xx.bibliothequeId == objActualBibliotheque.BibliothequeId);
                //var oldReservation = grpAllOldBibliotheque.FirstOrDefault(xx => xx.bibliothequeId == objActualBibliotheque.BibliothequeId);

                demandeReservationBibliotheque += "dans la bibliothèque " + objActualBibliotheque.BibliothequeName + ": " + ((newReservation != null)?newReservation.Count : 0).ToString(CultureInfo.InvariantCulture);
                //demandeReservationBibliothequeDepasse += "dépassée dans la bibliothèque " + objActualBibliotheque.BibliothequeName + ": " + ((oldReservation != null)?oldReservation.Count : 0).ToString(CultureInfo.InvariantCulture);
            } else {
                demandeReservationBibliotheque += "Vous n'avez pas choisi de bibliothèque à gérer";
            }

            return String.Format("{0}\n{1}\n{2}\n", demandeReservationAll,  demandeReservationManaged, demandeReservationBibliotheque);
        }
Exemplo n.º 50
0
        /// <summary>
        /// Event fired when the stream commands need to be update.
        /// </summary>
        private void OnUpdate()
        {
            if (!this.IsConnected)
            {
                return;
            }

            try
            {
                lock (this.VoteLock)
                {
                    if (!this.IsConnected || !BrowseViewModel.GetInstance().IsLoggedIn)
                    {
                        return;
                    }

                    AccessTokens             accessTokens    = SettingsViewModel.GetInstance().AccessTokens;
                    IEnumerable <CheatVotes> cheatVotes      = SqualrApi.GetStreamActivationIds(accessTokens.AccessToken);
                    IEnumerable <Cheat>      candidateCheats = LibraryViewModel.GetInstance().CheatsInLibrary;

                    if (candidateCheats == null || this.PreviousCheatVotes == null || cheatVotes == null || this.PreviousCheatVotes.Count() != cheatVotes.Count())
                    {
                        this.PreviousCheatVotes = cheatVotes;
                        return;
                    }

                    // Get cheat IDs to activate based on increased vote counts
                    IEnumerable <Int32> cheatIdsToActivate = cheatVotes
                                                             .Join(
                        this.PreviousCheatVotes,
                        currentVote => currentVote.CheatId,
                        previousVote => previousVote.CheatId,
                        (currentVote, previousVote) => new { cheatId = currentVote.CheatId, currentCount = currentVote.VoteCount, previousCount = previousVote.VoteCount })
                                                             .Where(combinedVote => combinedVote.currentCount != combinedVote.previousCount)
                                                             .Select(combinedVote => combinedVote.cheatId);

                    // Add in new votes with no previous vote count
                    cheatIdsToActivate = cheatVotes
                                         .Select(vote => vote.CheatId)
                                         .Except(this.PreviousCheatVotes.Select(vote => vote.CheatId))
                                         .Concat(cheatIdsToActivate)
                                         .Distinct();

                    IEnumerable <Cheat> projectItemsToActivate = cheatIdsToActivate
                                                                 .Join(
                        candidateCheats,
                        cheatId => cheatId,
                        projectItem => projectItem?.CheatId,
                        (cheatId, projectItem) => projectItem);

                    IEnumerable <Cheat> projectItemsToDeactivate = cheatVotes
                                                                   .Join(
                        candidateCheats,
                        cheatVote => cheatVote.CheatId,
                        projectItem => projectItem?.CheatId,
                        (cheatId, projectItem) => projectItem)
                                                                   .Except(projectItemsToActivate);

                    // Handle activations
                    projectItemsToActivate.ForEach(item =>
                    {
                        item.IsActivated = true;

                        // Reset duration always
                        item.Duration = 0.0f;
                    });

                    // Notify which project items were activated such that Squalr can update the stream overlay
                    if (projectItemsToActivate.Count() > 0)
                    {
                        Task.Run(() =>
                        {
                            IEnumerable <Cheat> activatedProjectItems = candidateCheats
                                                                        .Select(item => item)
                                                                        .Where(item => !item.IsStreamDisabled)
                                                                        .Where(item => item.IsActivated);

                            IEnumerable <OverlayMeta> overlayMeta = activatedProjectItems
                                                                    .Select(item => new OverlayMeta(item.CheatId, item.Cooldown, item.Duration));

                            if (overlayMeta.Count() > 0)
                            {
                                try
                                {
                                    SqualrApi.UpdateOverlayMeta(accessTokens.AccessToken, overlayMeta.ToArray());
                                }
                                catch (Exception ex)
                                {
                                    OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Error, "Error updating overlay cooldowns and durations", ex);
                                }
                            }
                        });
                    }

                    this.PreviousCheatVotes = cheatVotes;
                }
            }
            catch (Exception ex)
            {
                OutputViewModel.GetInstance().Log(OutputViewModel.LogLevel.Warn, "Error fetching activated cheats", ex);
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// update database with localized items information
        /// </summary>
        /// <param name="items">items with information to update</param>
        /// <param name="culture">culture for localization</param>
        /// <returns>updated items from database</returns>
        public IEnumerable<Item> UpdateItems(IEnumerable<Item> items, CultureInfo culture)
        {
            using (MangosEntities context = GetContext())
            {
                var item_templates = items.Join(context.item_template, o => o.Id, o => o.entry, (i, it) => new { it, i });
                var locales_items = items.Join(context.locales_item, o => o.Id, o => o.entry, (i, li) => new { li, i });

                switch (LocalizationHelper.GetOffset(culture))
                {
                    case 0: item_templates.ToList().ForEach(o => { o.it.name = o.i.Name; o.it.description = o.i.Description; }); break;
                    case 1: locales_items.ToList().ForEach(o => { o.li.name_loc1 = o.i.Name; o.li.description_loc1 = o.i.Description; }); break;
                    case 2: locales_items.ToList().ForEach(o => { o.li.name_loc2 = o.i.Name; o.li.description_loc2 = o.i.Description; }); break;
                    case 3: locales_items.ToList().ForEach(o => { o.li.name_loc3 = o.i.Name; o.li.description_loc3 = o.i.Description; }); break;
                    case 4: locales_items.ToList().ForEach(o => { o.li.name_loc4 = o.i.Name; o.li.description_loc4 = o.i.Description; }); break;
                    case 5: locales_items.ToList().ForEach(o => { o.li.name_loc5 = o.i.Name; o.li.description_loc5 = o.i.Description; }); break;
                    case 6: locales_items.ToList().ForEach(o => { o.li.name_loc6 = o.i.Name; o.li.description_loc6 = o.i.Description; }); break;
                    case 7: locales_items.ToList().ForEach(o => { o.li.name_loc7 = o.i.Name; o.li.description_loc7 = o.i.Description; }); break;
                    case 8: locales_items.ToList().ForEach(o => { o.li.name_loc8 = o.i.Name; o.li.description_loc8 = o.i.Description; }); break;
                    default: throw new NotImplementedException("Unsupported culture " + culture.Name);
                }

                context.SaveChanges();
            }

            List<int> ids = items.Select(o => o.Id).ToList();
            var updatedItems = _context.item_template.Where(o => ids.Contains(o.entry));
            return GetItems(updatedItems, culture);
        }
 /// <summary>
 /// Concatenates the members of a constructed <see cref="IEnumerable{T}"/> collection of type <see cref="String"/>,
 /// using <see cref="Environment.NewLine"/> between each member.
 /// </summary>
 /// <param name="lines">A collection that contains the strings to concatenate.</param>
 /// <returns>A string that consists of the members of values delimited by the <see cref="Environment.NewLine"/>.
 /// If values has no members, the method returns <see cref="String.Empty"/>.
 /// </returns>
 /// <exception cref="ArgumentNullException"><paramref name="lines"/> is null.</exception>
 public static string JoinLines(this IEnumerable <string> lines)
 {
     return(lines.Join(Environment.NewLine));
 }
Exemplo n.º 53
0
 static void PerformInnerJoin(IEnumerable<XElement> seq1, IEnumerable<XElement> seq2, string[] args1, string[] args2, string filename, string wrapper)
 {
     var innerJoin = seq1.Join(seq2, x => selector(x, args1[kpath]), y => selector(y, args2[kpath]),
                     (x, y) => new XElement("Join", x, y));
     var wrappedInnerJoin = new XElement(wrapper, innerJoin);
     wrappedInnerJoin.Save(filename);
 }
Exemplo n.º 54
0
 public static IEnumerable <T> Prints <T>(this IEnumerable <T> t)
 {
     global::System.Console.WriteLine(t.Count().ToString() + ": " + t.Join(", "));
     return(t);
 }
Exemplo n.º 55
0
 public AssetPath(IEnumerable<string> pathParts) : this(pathParts.Join("/"))
 {
 }
Exemplo n.º 56
0
        public async Task <IEnumerable <SysResource> > GetAllListAsync(IEnumerable <long> resids)
        {
            string sql = $"SELECT * FROM sys_resource WHERE isdel=0 AND resourceid IN({resids.Join()})";

            return(await this.QueryAsync(sql));
        }
Exemplo n.º 57
0
 /// <summary>
 /// �����޸Ķ�����¼
 /// </summary>
 /// <param name="settingIDList">���ñ���б���á�,���ŷָ�</param>
 /// <param name="sendSetting">����ʵ����</param>
 /// <param name="where">�޸�ʱ����������ͳһ��ǰ��Ҫ�����ӷ���and��or�ȵȣ�</param>
 /// <param name="delCache">�޸ijɹ��������CACHE key��֧������</param>
 /// <param name="dbkey">�������ݿ����ӳ��е�����key��Ϊ��ʱʹ��ConnString����</param>
 /// <returns>�޸��Ƿ�ɹ�</returns>
 public static bool UpdateByIDList(IEnumerable<int> settingIDList,  SendSetting sendSetting, string dbkey = "", Where where = null, string[] delCache = null)
 {
     int value = new SQL().Database(dbkey).Update(SendSetting._)
         .SetP(SendSetting._TemplateID, sendSetting.TemplateID)
         .SetP(SendSetting._ConnectType, sendSetting.ConnectType)
         .SetP(SendSetting._SendInterval, sendSetting.SendInterval)
         .SetP(SendSetting._IPInterval, sendSetting.IPInterval)
         .SetP(SendSetting._SmtpInterval, sendSetting.SmtpInterval)
         .SetP(SendSetting._DeleteInterval, sendSetting.DeleteInterval)
         .SetP(SendSetting._MaxRetryCount, sendSetting.MaxRetryCount)
         .SetP(SendSetting._SendRetryCount, sendSetting.SendRetryCount)
         .SetP(SendSetting._Status, sendSetting.Status)
         .Where(new Where()
             .And(SendSetting._SettingID, "(" + settingIDList .Join(",") + ")", Operator.In)
         ).Where(where).ToExec();
     if (value <= 0) return false;
     if (delCache.IsNull()) return true;
     Cache2.Remove("TH.Mailer.SendSettingCache_", delCache);
     return true;
 }
Exemplo n.º 58
0
        public async Task <List <SysResource> > GetListAsync(IEnumerable <long> resids)
        {
            string sql  = $"SELECT * FROM sys_resource WHERE isshow=1 AND isbutton=0 AND isdel=0 AND resourceid IN({resids.Join()})";
            var    list = await this.QueryAsync(sql);

            return(list.ToList());
        }
Exemplo n.º 59
0
        public virtual void Send(string to, string subject, string body, bool isHtml, IEnumerable <string> cc, IEnumerable <string> bcc)
        {
            var data = $"To: {to}\r\nSubject: {subject}\r\nIsHtml:{isHtml}\r\nCC: {cc?.Join(",")}\r\nBCC: {bcc?.Join(",")}\r\nBody:{body}";

            Log(data);
        }
Exemplo n.º 60
0
 public static string JoinLines(this IEnumerable <string> source)
 {
     return(source.Join("\r\n"));
 }