Esempio n. 1
0
        public void AppendJoinTest()
        {
            var builder = new StringBuilder();

            builder.AppendJoin(Enumerable.Repeat("a", 4), "");
            Assert.AreEqual("aaaa", builder.ToString());
            builder.Append(" ");
            builder.AppendJoin(Enumerable.Range(0, 5).Select(i => (i * 2).ToString()), ";");
            Assert.AreEqual("aaaa 0;2;4;6;8", builder.ToString());
        }
Esempio n. 2
0
        private string FormatDelegate(Type type)
        {
            var builder = new StringBuilder();
            var invoke = type.GetMethod("Invoke");
            var parameters = invoke.GetParameters();

            if (parameters.Length > 1)
                builder.Append("(");

            builder.AppendJoin(",", parameters.Select(p => Format(p.ParameterType)));

            if (parameters.Length > 1)
                builder.Append(")");

            builder.Append(" => ");
            builder.Append(Format(invoke.ReturnType));
            return builder.ToString();
        }
        public static string DisplayLabel(this MethodInfo method)
        {
            var sb = new StringBuilder();

            sb
                .Append(method.ReturnType.FullName)
                .Append(" ")
                .Append(method.DeclaringType.FullName)
                .Append(".")
                .Append(method.Name);

            if (method.IsGenericMethod)
            {
                sb.Append("<");
                sb.AppendJoin(", ", method.GetGenericArguments().Select(x => x.Name));
                sb.Append(">");
            }

            sb.Append("(")
              .AppendJoin(", ", method.GetParameters().Select(x => (x.ParameterType.FullName ?? x.ParameterType.Name) + " " + x.Name))
              .Append(")");

            return sb.ToString();
        }
Esempio n. 4
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "feeds/{source}")] HttpRequest req, string source,
            ILogger log)
        {
            long afterTimestamp = 0;

            string afterTimestampString = req.Query["afterTimestamp"];

            if (afterTimestampString != null && !long.TryParse(afterTimestampString, out afterTimestamp))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "afterTimestamp must be an integer"));
            }
            string afterId = req.Query["afterId"];

            try
            {
                var sw = new Stopwatch();
                sw.Start();

                StringBuilder str       = new StringBuilder();
                int           itemCount = 0;
                LastItem      lastItem  = null;
                using (SqlConnection connection = new SqlConnection(SqlUtils.SqlDatabaseConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("READ_ITEM_PAGE", connection);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add(
                        new SqlParameter()
                    {
                        ParameterName = "@source",
                        SqlDbType     = SqlDbType.VarChar,
                        Value         = source,
                    });
                    cmd.Parameters.Add(
                        new SqlParameter()
                    {
                        ParameterName = "@id",
                        SqlDbType     = SqlDbType.NVarChar,
                        Value         = afterId ?? "",
                    });
                    cmd.Parameters.Add(
                        new SqlParameter()
                    {
                        ParameterName = "@modified",
                        SqlDbType     = SqlDbType.BigInt,
                        Value         = afterTimestamp,
                    });

                    connection.Open();

                    // This query will return one additional record (from the previous page) to check that the provided "source" value is valid
                    // (So even the last page will return at least 1 record)
                    SqlDataReader reader = await cmd.ExecuteReaderAsync();

                    // Call Read before accessing data.
                    if (await reader.ReadAsync())
                    {
                        var itemStrings = new List <string>();

                        //Skip the first row if it's the same as the query parameters (see comment above)
                        if ((reader.GetString((int)ResultColumns.id) != afterId &&
                             reader.GetInt64((int)ResultColumns.modified) != afterTimestamp) || reader.Read())
                        {
                            do
                            {
                                var timestamp = reader.GetInt64((int)ResultColumns.modified);
                                if (timestamp != Utils.LAST_PAGE_ITEM_RESERVED_MODIFIED)
                                {
                                    itemStrings.Add(reader.GetString((int)ResultColumns.data));

                                    // Get the last item values for the next URL
                                    afterTimestamp = timestamp;
                                    afterId        = reader.GetString((int)ResultColumns.id);
                                }
                                else
                                {
                                    lastItem = JsonConvert.DeserializeObject <LastItem>(reader.GetString((int)ResultColumns.data));
                                }
                            }while (await reader.ReadAsync());
                        }

                        itemCount = itemStrings.Count;

                        // Construct response using string concatenation instead of deserialisation for maximum efficiency
                        str.Append("{\"next\":");
                        str.Append(JsonConvert.ToString($"{Utils.GetFeedUrl(source)}?afterTimestamp={afterTimestamp}&afterId={afterId}"));
                        str.Append(",\"items\": [");
                        str.AppendJoin(',', itemStrings);
                        str.Append("],\"license\":");
                        str.Append(JsonConvert.ToString(Utils.CC_BY_LICENSE));
                        str.Append("}");

                        // Call Close when done reading.
                        reader.Close();
                    }
                    else
                    {
                        // Call Close when done reading.
                        reader.Close();

                        // Return 404 for invalid source, rather than just for last page
                        return(req.CreateErrorResponse(HttpStatusCode.NotFound, $"'{source}' feed not found"));
                    }
                }

                // Create response
                var resp = req.CreateJSONResponseFromString(HttpStatusCode.OK, str.ToString());

                // Leverage long-term caching in CDN for data payload
                if (itemCount > 0)
                {
                    // Partial pages for high-frequency data have a shorter expiry set, so that they can give way to full pages that will take their place after a time
                    // This speeds up reading of feeds for new data users to get fully up-to-date
                    if (lastItem?.RecommendedPollInterval != null && lastItem.RecommendedPollInterval < 60)
                    {
                        if (itemCount < 30)
                        {
                            // For the end of near-real-time feeds, use a short expiry time due to the high volume
                            resp = resp.AsCachable(TimeSpan.FromMinutes(15));
                        }
                        else
                        {
                            // For the beginning of near-real-time feeds, use a long-ish expiry to ensure data is not needlessly stockpiled
                            resp = resp.AsCachable(TimeSpan.FromHours(4));
                        }
                    }
                    else
                    {
                        // Fuller pages (likely earlier in the feed) have a long expiry set
                        resp = resp.AsCachable(TimeSpan.FromHours(12));
                    }
                }
                else
                {
                    // The last page has a minimal expiry based on the underlying data's refresh frequency
                    if (lastItem?.Expires != null)
                    {
                        // Add 2 seconds to expiry to account for proxy lag
                        const int ESTIMATED_PROXY_LATENCY_SECONDS = 2;
                        var       expiresFromProxy = lastItem?.Expires?.AddSeconds(ESTIMATED_PROXY_LATENCY_SECONDS);
                        if (expiresFromProxy < DateTimeOffset.UtcNow)
                        {
                            // If the expiry has passed, project it forward based on the poll interval if possible
                            if (lastItem.RecommendedPollInterval != null && lastItem.RecommendedPollInterval != 0)
                            {
                                resp = resp.AsCachable(ProjectExpiryForward((DateTimeOffset)expiresFromProxy, (int)lastItem.RecommendedPollInterval));
                                resp.Headers.Add(Utils.RECOMMENDED_POLL_INTERVAL_HEADER, Convert.ToString(lastItem.RecommendedPollInterval));
                            }
                            else
                            {
                                // Default cache expiry
                                resp = resp.AsCachable(TimeSpan.FromSeconds(Utils.DEFAULT_POLL_INTERVAL));
                            }
                        }
                        else
                        {
                            resp = resp.AsCachable(expiresFromProxy);
                        }
                    }
                    else if (lastItem?.MaxAge != null)
                    {
                        resp = resp.AsCachable((TimeSpan)lastItem.MaxAge);
                    }
                    else
                    {
                        // Default cache expiry
                        resp = resp.AsCachable(TimeSpan.FromSeconds(Utils.DEFAULT_POLL_INTERVAL));
                    }
                }

                sw.Stop();

                log.LogWarning($"GETPAGE TIMER {sw.ElapsedMilliseconds} ms.");

                return(resp);
            }
            catch (SqlException ex)
            {
                if (SqlUtils.SqlTransientErrorNumbers.Contains(ex.Number) || ex.Message.Contains("timeout", StringComparison.InvariantCultureIgnoreCase))
                {
                    log.LogWarning($"Throttle on GetPage, retry after {SqlUtils.SqlRetrySecondsRecommendation} seconds.");
                    return(req.CreateTooManyRequestsResponse(TimeSpan.FromSeconds(SqlUtils.SqlRetrySecondsRecommendation)));
                }
                else
                {
                    log.LogError("Error during GetPage: " + ex.ToString());
                    return(req.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
                }
            }
        }
 public static StringBuilder AppendJoin <T>(this StringBuilder sb, char separator, IEnumerable <T> values)
 => sb.AppendJoin(separator.ToString(), values);
Esempio n. 6
0
        private static void Main(string[] args)
        {
            var regions = new string[] {
                "WMO_Region_1_Africa",
                "WMO_Region_2_Asia",
                "WMO_Region_3_South_America",
                "WMO_Region_4_North_and_Central_America",
                "WMO_Region_5_Southwest_Pacific",
                "WMO_Region_6_Europe",
                "WMO_Region_7_Antarctica"
            };
            var LocationPatten = "<td><a href=\\\"([a-zA-Z0-9-._/]+?)\\.html";
            var zipFilePatten  = "href=\\\"([a-zA-Z0-9-._/]+?)\\.zip";

            var link = @"http://climate.onebuilding.org/";

            var selectedRegions = GetUsersChoice(regions);

            var dir = Directory.GetCurrentDirectory();

            var fd = Path.Combine(dir, "OneBuilding_EPW");

            Directory.CreateDirectory(fd);

            var regionsUrls  = selectedRegions.Select(_ => link + _);
            var locationUrls = ExtractInfo(regionsUrls, LocationPatten).Select(_ => _.Replace("/index.html", ""));;
            var zipUrls      = ExtractInfo(locationUrls, zipFilePatten);


            var tempFd = fd + "/temp";

            if (Directory.Exists(tempFd))
            {
                Directory.Delete(tempFd, true);
            }
            Directory.CreateDirectory(tempFd);
            var csvStrings = new List <string>()
            {
                "Name,Lat,Lon,Url"
            };

            //var testZips = zipUrls.Take(10);

            //foreach (var url in zipUrls)
            //{
            //    Console.WriteLine($"Now thread {System.Threading.Thread.CurrentThread.ManagedThreadId} extracting: \n\t{url.Split("/").Last()}\n");
            //    var result = DownloadAndRead(url, tempFd);
            //    if (!string.IsNullOrEmpty(result.name))
            //    {
            //        csvStrings.Add($"{result.name},{result.Lat},{result.Lon},{url}");
            //    }
            //}

            Parallel.ForEach(
                zipUrls,
                new ParallelOptions {
                MaxDegreeOfParallelism = 2
            },
                (url) =>
            {
                Console.WriteLine($"Now thread {System.Threading.Thread.CurrentThread.ManagedThreadId} extracting: \n\t{url.Split("/").Last()}\n");
                var result = DownloadAndRead(url, tempFd);
                if (!string.IsNullOrEmpty(result.name))
                {
                    csvStrings.Add($"{result.name},{result.Lat},{result.Lon},{url}");
                }
            }
                );



            var EpwZipUrlsCsv = Path.Combine(fd, "EpwZipUrls.csv");

            File.Delete(EpwZipUrlsCsv);
            var csv = new StringBuilder();

            csv.AppendJoin(Environment.NewLine, csvStrings);
            File.WriteAllText(EpwZipUrlsCsv, csv.ToString());


            Console.WriteLine("\n\nProcessing complete. Press any key to exit.");
            Console.WriteLine($"Check the folder:{fd}");

            Console.ReadKey();
        }
Esempio n. 7
0
        public string getCommaJoinedString()
        {
            var sb = new StringBuilder();

            return(sb.AppendJoin(',', pkgs).ToString());
        }
Esempio n. 8
0
 public static StringBuilder AppendLines(this StringBuilder builder, IEnumerable <string> lines)
 {
     builder.AppendJoin("\r\n", lines);
     return(builder.AppendLine());
 }
        public override ResultSetMapping AppendUpdateOperation(StringBuilder commandStringBuilder, ModificationCommand command, int commandPosition)
        {
            var sqlGenerationHelper = (IFbSqlGenerationHelper)SqlGenerationHelper;
            var name                = command.TableName;
            var operations          = command.ColumnModifications;
            var writeOperations     = operations.Where(o => o.IsWrite).ToList();
            var readOperations      = operations.Where(o => o.IsRead).ToList();
            var conditionOperations = operations.Where(o => o.IsCondition).ToList();
            var inputOperations     = GenerateParameters(operations.Where(o => o.IsWrite || o.IsCondition)).ToList();
            var anyRead             = readOperations.Any();

            commandStringBuilder.Append("EXECUTE BLOCK (");
            commandStringBuilder.AppendJoin(inputOperations, (b, p) =>
            {
                b.Append(p.name);
                b.Append(" ");
                b.Append(p.type);
                b.Append(" = ?");
            }, ", ");
            commandStringBuilder.AppendLine(")");
            commandStringBuilder.Append("RETURNS (");
            if (anyRead)
            {
                commandStringBuilder.AppendJoin(readOperations, (b, e) =>
                {
                    var type = GetColumnType(e);
                    b.Append(SqlGenerationHelper.DelimitIdentifier(e.ColumnName));
                    b.Append(" ");
                    b.Append(type);
                }, ", ");
            }
            else
            {
                commandStringBuilder.Append("ROWS_AFFECTED INT");
            }
            commandStringBuilder.AppendLine(")");
            commandStringBuilder.AppendLine("AS");
            commandStringBuilder.AppendLine("BEGIN");
            var oldParameterNameMarker = sqlGenerationHelper.ParameterNameMarker;

            sqlGenerationHelper.ParameterNameMarker = ":";
            try
            {
                AppendUpdateCommandHeader(commandStringBuilder, name, null, writeOperations);
                AppendWhereClause(commandStringBuilder, conditionOperations);
            }
            finally
            {
                sqlGenerationHelper.ParameterNameMarker = oldParameterNameMarker;
            }
            if (anyRead)
            {
                commandStringBuilder.AppendLine();
                commandStringBuilder.Append("RETURNING ");

                commandStringBuilder.AppendJoin(readOperations, (b, e) =>
                {
                    b.Append(SqlGenerationHelper.DelimitIdentifier(e.ColumnName));
                }, ", ");
                commandStringBuilder.Append(" INTO ");
                commandStringBuilder.AppendJoin(readOperations, (b, e) =>
                {
                    b.Append(" :");
                    b.Append(SqlGenerationHelper.DelimitIdentifier(e.ColumnName));
                }, ", ");
            }
            commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator).AppendLine();
            if (!anyRead)
            {
                commandStringBuilder.AppendLine("ROWS_AFFECTED = ROW_COUNT;");
                commandStringBuilder.AppendLine("SUSPEND;");
            }
            else
            {
                commandStringBuilder.AppendLine("IF (ROW_COUNT > 0) THEN");
                commandStringBuilder.AppendLine("SUSPEND;");
            }
            commandStringBuilder.AppendLine("END");
            commandStringBuilder.Append(SqlGenerationHelper.StatementTerminator).AppendLine();
            return(ResultSetMapping.LastInResultSet);
        }
Esempio n. 10
0
        private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate)
        {
            var serviceId         = _serviceIdGenerator.GenerateServiceId(method);
            var attributes        = method.GetCustomAttributes().ToList();
            var serviceDescriptor = new ServiceDescriptor
            {
                Id        = serviceId,
                RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name)
            };
            var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>();

            foreach (var descriptorAttribute in descriptorAttributes)
            {
                descriptorAttribute.Apply(serviceDescriptor);
            }
            var           httpMethodAttributes = attributes.Where(p => p is HttpMethodAttribute).Select(p => p as HttpMethodAttribute).ToList();
            var           httpMethods          = new List <string>();
            StringBuilder httpMethod           = new StringBuilder();

            foreach (var attribute in httpMethodAttributes)
            {
                httpMethods.AddRange(attribute.HttpMethods);
                if (attribute.IsRegisterMetadata)
                {
                    httpMethod.AppendJoin(',', attribute.HttpMethods).Append(",");
                }
            }
            if (httpMethod.Length > 0)
            {
                httpMethod.Length = httpMethod.Length - 1;
            }
            serviceDescriptor.HttpMethod(httpMethod.ToString());
            var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault();

            if (authorization != null)
            {
                serviceDescriptor.EnableAuthorization(true);
            }
            if (authorization != null)
            {
                serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType)
                                           ?? AuthorizationType.AppSecret);
            }
            var fastInvoker = GetHandler(serviceId, method);

            return(new ServiceEntry
            {
                Descriptor = serviceDescriptor,
                RoutePath = serviceDescriptor.RoutePath,
                Methods = httpMethods,
                MethodName = method.Name,
                Type = method.DeclaringType,
                Attributes = attributes,
                Func = (key, parameters) =>
                {
                    object instance = null;
                    if (AppConfig.ServerOptions.IsModulePerLifetimeScope)
                    {
                        instance = _serviceProvider.GetInstancePerLifetimeScope(key, method.DeclaringType);
                    }
                    else
                    {
                        instance = _serviceProvider.GetInstances(key, method.DeclaringType);
                    }
                    var list = new List <object>();

                    foreach (var parameterInfo in method.GetParameters())
                    {
                        //加入是否有默认值的判断,有默认值,并且用户没传,取默认值
                        if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name))
                        {
                            list.Add(parameterInfo.DefaultValue);
                            continue;
                        }
                        var value = parameters[parameterInfo.Name];
                        var parameterType = parameterInfo.ParameterType;
                        var parameter = _typeConvertibleService.Convert(value, parameterType);
                        list.Add(parameter);
                    }
                    var result = fastInvoker(instance, list.ToArray());
                    return Task.FromResult(result);
                }
            });
        }
Esempio n. 11
0
        public void AddForwardPropCode(StringBuilder builder)
        {
            var varName = !string.IsNullOrEmpty(_processor) ? $"agg{Id}" : $"out{Id}";

            switch (_aggregator)
            {
            case "sum":
                var mults = _inputDescriptions
                            .Select(d => $"({(d.Key.FromInputVector ? "in" : "out")}{d.Key.InputId} * {d.Key.Weight})")
                            .Concat(new[] { $"{_weight}" })
                            .ToArray();

                builder.Append($"var {varName} = ");
                builder.AppendJoin("+", mults);
                builder.AppendLine(";");
                break;

            case "min":
                builder.AppendLine($"var {varName} = {_weight};");
                foreach (var input in _inputDescriptions)
                {
                    var inputName = $"{(input.Key.FromInputVector ? "in" : "out")}{input.Key.InputId}";
                    var multName  = $"mult{Id}_{inputName}";
                    builder.AppendLine($"var {multName} = (float)({inputName} * {input.Key.Weight});");
                    builder.AppendLine($"{varName} = {varName} < {multName} ? {varName} : {multName};");
                }
                break;

            case "max":
                builder.AppendLine($"var {varName} = {_weight};");
                foreach (var input in _inputDescriptions)
                {
                    var inputName = $"{(input.Key.FromInputVector ? "in" : "out")}{input.Key.InputId}";
                    var multName  = $"mult{Id}_{inputName}";
                    builder.AppendLine($"var {multName} = (float)({inputName} * {input.Key.Weight});");
                    builder.AppendLine($"{varName} = {varName} > {multName} ? {varName} : {multName};");
                }
                break;

            default:
                throw new Exception($"Unknown aggregator {_aggregator}");
            }

            if (string.IsNullOrEmpty(_processor))
            {
                return;
            }

            builder.Append($"var out{Id} = ");
            switch (_processor)
            {
            case "sigmoid":
                builder.AppendLine($"1 / (1 + Math.Pow(Math.E, -1 * agg{Id}));");
                break;

            case "softplus":
                builder.AppendLine($"Math.Log(1 + Math.Exp(agg{Id}));");
                break;

            default:
                throw new Exception($"Unknown processor {_processor}");
            }
        }
        public static string SpaceDelete(string a)
        {
            StringBuilder b = new StringBuilder();

            return(b.AppendJoin(' ', a.Split(), StringSplitOptions.RemoveEmptyEntries).ToString());
        }
        public static string Render(this Boards.Board board, bool enemy)
        {
            var sbFinal = new StringBuilder(14400);
            List <StringBuilder> sbs = new List <StringBuilder>();

            for (var y = 0; y < Options.OPTIONS["Board height"]; y++)
            {
                List <StringBuilder> sb = new List <StringBuilder>();
                for (int i = 0; i < BOX_HEIGHT; i++)
                {
                    sb.Add(new StringBuilder());
                }

                for (var x = 0; x < Options.OPTIONS["Board width"]; x++)
                {
                    int BOX_Y = (y == 0 ? 0 : 1);
                    int BOX_X = Convert.ToInt32(x != 0);

                    sb[0].Append(BOX[BOX_Y][BOX_X]);
                    sb[0].Append(new String(HOR, BOX_WIDTH - 2));
                    for (int i = 1; i < BOX_HEIGHT - 1; i++)
                    {
                        sb[i].Append(VERT);
                    }

                    for (int i = 1; i < BOX_HEIGHT - 1; i++)
                    {
                        if (i == (int)Math.Ceiling((float)(BOX_HEIGHT - 2) / 2))
                        {
                            sb[i].Append(GetTileValue(board.Map[y][x], enemy)); // tile value
                        }
                        else
                        {
                            sb[i].Append(new String(' ', BOX_WIDTH - 2));
                        }
                    }

                    if (y + 1 == Options.OPTIONS["Board height"])
                    {
                        sb.Last().Append(BOX[2][BOX_X]);
                        sb.Last().Append(new String(HOR, BOX_WIDTH - 2));
                        if (x + 1 == Options.OPTIONS["Board width"])
                        {
                            sb.Last().Append(BOX[2][2]);
                        }
                    }
                    if (x + 1 == Options.OPTIONS["Board width"])
                    {
                        sb[0].Append(BOX[BOX_Y][2]);
                        for (int i = 1; i < BOX_HEIGHT - 1; i++)
                        {
                            sb[i].Append(VERT);
                        }
                    }
                }
                sbs.Add(sb[0]);
                for (int i = 1; i < BOX_HEIGHT - 1; i++)
                {
                    sbs.Add(sb[i]);
                }
                if (y + 1 == Options.OPTIONS["Board height"])
                {
                    sbs.Add(sb.Last());
                }
            }

            if (!State.TurnEnded)
            {
                AddCursorTo(sbs, board);
            }

            sbFinal.AppendJoin('\n', sbs);
            while (sbFinal[sbFinal.Length - 1] == '\n')
            {
                sbFinal.Remove(sbFinal.Length - 1, 1);
            }
            return(sbFinal.ToString());
        }
Esempio n. 14
0
        public async Task Process()
        {
            var currentDestinationIndex = 0;
            var uniqueOutputs           = new Dictionary <string, ChiaPlotOutput>();
            var outputChannel           = Channel.CreateUnbounded <ChiaPlotOutput>();
            var ignoredDrives           = new List <string>();
            var staticText = new StringBuilder();
            var maxParallelPlotsPerStagger = 1;

            // initialization process to start 2 plots per temp drive
            // don't ignore plot drives but do check plot drives are not on the ignoreDrives list.  This will allow us to have the same temp and dest drive and ignore when full.
// where do I add the logic to stagger?
            foreach (var tempDrive in chiaPlotManagerContextConfiguration.TempPlotDrives)
            {
                var destinations = new List <string>();
                while (destinations.Count < maxParallelPlotsPerStagger)
                {
                    var destination = chiaPlotManagerContextConfiguration.DestinationPlotDrives.Skip(currentDestinationIndex).FirstOrDefault();
                    if (destination == null)
                    {
                        currentDestinationIndex = 0;
                        destination             = chiaPlotManagerContextConfiguration.DestinationPlotDrives.Skip(currentDestinationIndex).First();
                    }
                    destinations.Add(destination);
                    currentDestinationIndex++;
                }
                var innerForEachBreaker = false;
                foreach (var dest in destinations)
                {
                    if (innerForEachBreaker)
                    {
                        continue;
                    }

                    var process = await startProcess(dest, tempDrive);

                    if (process != null)
                    {
                        var first = await process.Reader.ReadAsync();

                        if (!string.IsNullOrWhiteSpace(first.InvalidDrive))
                        {
                            if (first.InvalidDrive == tempDrive && tempDrive != dest)
                            {
                                innerForEachBreaker = true;
                                continue;
                            }

                            if (!ignoredDrives.Any(id => id == first.InvalidDrive))
                            {
                                ignoredDrives.Add(first.InvalidDrive);
                            }
                        }
                        else
                        {
                            await foreach (var value in process.Reader.ReadAllAsync())
                            {
                                if (!string.IsNullOrWhiteSpace(value.Id))
                                {
                                    uniqueOutputs[value.Id] = value;
                                    break;
                                }
                            }
                            Task task = Task.Run(async() => {
                                await foreach (var value in process.Reader.ReadAllAsync())
                                {
                                    await outputChannel.Writer.WriteAsync(value);
                                }
                            });
                        }
                    }
                }
            }

            // watching process that keeps at least 2 running and will start one when transfer starts

            var keepRunning = true;

            while (keepRunning)
            {
                await foreach (var output in outputChannel.Reader.ReadAllAsync())
                {
                    if (string.IsNullOrWhiteSpace(output.Id))
                    {
                        continue;
                    }
                    if (output.Id == "static")
                    {
                        staticText.AppendLine(output.Output);
                        continue;
                    }
                    uniqueOutputs[output.Id] = output;
                    var outputs = uniqueOutputs.Values;
                    if (output.IsTransferError)
                    {
                        // add destination to ignored
                        var process = processRepo.GetAll().Where(p => p.Id == output.ProcessId).FirstOrDefault();
                        process.Kill(true);
                        process.Close();

                        if (!ignoredDrives.Any(id => id == output.DestinationDrive))
                        {
                            ignoredDrives.Add(output.DestinationDrive);
                        }

                        // start new transfer process to alternative destination
                        foreach (var destination in chiaPlotManagerContextConfiguration.DestinationPlotDrives)
                        {
                            //var tempFile = Path.Combine(output.TempDrive, $"{output.Id}");
                            if (!ignoredDrives.Any(id => id == destination))
                            {
                                var driveInfo    = new DriveInfo(destination);
                                var tempFileName = Directory.GetFiles(output.TempDrive, output.Id).FirstOrDefault();

                                if (string.IsNullOrEmpty(tempFileName))
                                {
                                    // throw?
                                }
                                var tempFile = new FileInfo(tempFileName);
                                if (driveInfo.AvailableFreeSpace > tempFile.Length)
                                {
                                    var trimmedFileName = tempFileName.Substring(tempFileName.IndexOf("plot-k"));
                                    trimmedFileName = trimmedFileName.Substring(0, trimmedFileName.IndexOf(".plot.") + 5);
                                    tempFile.MoveTo(Path.Combine(destination, trimmedFileName), true);
                                    break;
                                }
                            }
                        }

                        output.IsTransferError = false;
                    }

                    if (!ignoredDrives.Any(d => d == output.DestinationDrive || d == output.TempDrive))
                    {
                        var startNewProcess = false;
                        var related         = outputs.Where(o => o.TempDrive == output.TempDrive);
                        var completed       = related.Where(o => o.IsPlotComplete);
                        var remaining       = related.Where(o => !o.IsPlotComplete);

                        //1) where get all remaining that is transfering and do not count those
                        if (remaining.Count() < chiaPlotManagerContextConfiguration.PlotsPerDrive &&
                            remaining
                            .Where(o => string.IsNullOrWhiteSpace(o.CurrentPhase) || (o.CurrentPhase == "1" || o.CurrentPhase == "2"))
                            .Count() < maxParallelPlotsPerStagger &&
                            completed.Where(c => c.IsTransferComplete == false).Count() < chiaPlotManagerContextConfiguration.PlotsPerDrive)
                        {
                            startNewProcess = true;
                        }

                        if (startNewProcess)
                        {
                            var process = await startProcess(output.DestinationDrive, output.TempDrive);

                            var first = await process.Reader.ReadAsync();

                            if (!string.IsNullOrWhiteSpace(first.InvalidDrive))
                            {
                                if ((first.InvalidDrive == first.TempDrive && first.TempDrive != first.DestinationDrive) &&
                                    (!ignoredDrives.Any(id => id == first.InvalidDrive)))
                                {
                                    ignoredDrives.Add(first.InvalidDrive);
                                }
                            }
                            else
                            {
                                // await outputChannel.Writer.WriteAsync(new ChiaPlotOutput { Id = "static", Output = "started new plot"});
                                await foreach (var value in process.Reader.ReadAllAsync())
                                {
                                    if (!string.IsNullOrWhiteSpace(value.Id))
                                    {
                                        uniqueOutputs[value.Id] = value;
                                        break;
                                    }
                                }
                                Task task = Task.Run(async() => {
                                    await foreach (var value in process.Reader.ReadAllAsync())
                                    {
                                        await outputChannel.Writer.WriteAsync(value);
                                    }
                                });
                                break;
                            }
                        }
                    }

                    var ignoredDrivesOutput = new StringBuilder();
                    ignoredDrivesOutput.Append("Ingored Drives: ");
                    ignoredDrivesOutput.AppendJoin(',', ignoredDrives);
                    ignoredDrivesOutput.AppendLine(staticText.ToString());
                    allOutputsDelegate.Invoke(outputs, ignoredDrivesOutput);
                }
                keepRunning = (chiaPlotManagerContextConfiguration.TempPlotDrives.All(t => ignoredDrives.Any(i => i == t)) || chiaPlotManagerContextConfiguration.DestinationPlotDrives.All(t => ignoredDrives.Any(i => i == t))) == false;

                if (!keepRunning)
                {
                    Console.WriteLine("WHY?");
                }
            }
        }
Esempio n. 15
0
        //Creates labels for errors.
        internal void CreateErrors()
        {
            GUILayout.Label("General:", this.skins.label);
            StringBuilder builder = new StringBuilder();
            builder.AppendJoin(GetErrors(true), "\n");
            GUILayout.Label(builder.ToString(), GUIUtils.redLabel);
            GUILayout.Space(10);

            GUILayout.Label("Chutes:", this.skins.label);
            builder = new StringBuilder();
            builder.AppendJoin(GetErrors(false), "\n");
            GUILayout.Label(builder.ToString(), GUIUtils.redLabel);
            GUILayout.Space(10);
        }
Esempio n. 16
0
        /// <summary>
        /// Base for rendering a class.
        /// </summary>
        /// <param name="name">The name of the namespace. The name can't contain spaces.</param>
        /// <param name="displayName">Optional display name. The display name can contain spaces.</param>
        /// <param name="generics">Optional class extension.</param>
        /// <param name="stereotype">Optional stereo type.</param>
        /// <param name="customSpot">Optional custom spot.</param>
        /// <param name="tag">Optional tag.</param>
        /// <param name="url">Optional URL.</param>
        /// <param name="backgroundColor">Optional background color.</param>
        /// <param name="lineColor">Optional line color.</param>
        /// <param name="lineStyle">Optional line style.</param>
        /// <param name="extends">Optional extends.</param>
        /// <param name="implements">Optional implementations.</param>
        /// <exception cref="ArgumentException">Thrown when <paramref name="name"/> is <c>null</c>, empty of only white space.</exception>
        internal static void ClassBase(this StringBuilder stringBuilder, ClassType type, string name, string displayName, string generics, string stereotype, CustomSpot customSpot, string tag, Uri url, Color backgroundColor, Color lineColor, LineStyle lineStyle, string[] extends, string[] implements)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("A non-empty value should be provided", nameof(name));
            }

            stringBuilder.Append(type.ToString().ToLowerInvariant());
            stringBuilder.Append(Constant.Space);

            if (!(displayName is null))
            {
                stringBuilder.Append(Constant.Quote);
                stringBuilder.Append(displayName);
                stringBuilder.Append(Constant.Quote);
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.As);
                stringBuilder.Append(Constant.Space);
            }

            stringBuilder.Append(name);

            if (!(generics is null))
            {
                stringBuilder.Append(Constant.GenericsStart);
                stringBuilder.Append(generics);
                stringBuilder.Append(Constant.GenericsEnd);
            }

            if (!(stereotype is null))
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.StereoType(stereotype, customSpot);
            }

            if (!(tag is null))
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.TagPrefix);
                stringBuilder.Append(tag);
            }

            if (!(url is null))
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.UrlStart);
                stringBuilder.Append(url);
                stringBuilder.Append(Constant.UrlEnd);
            }

            if (!(backgroundColor is null))
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(backgroundColor);
            }

            if (!(lineColor is null) || lineStyle != LineStyle.None)
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.ColorPrefix);
                stringBuilder.Append(Constant.ColorPrefix);

                if (lineStyle > LineStyle.None)
                {
                    stringBuilder.Append(Constant.BorderStyleStart);
                    stringBuilder.Append(lineStyle.ToString().ToLowerInvariant());
                    stringBuilder.Append(Constant.BorderStyleEnd);
                }

                if (!(lineColor is null))
                {
                    stringBuilder.Append(lineColor.ToString().TrimStart(Constant.ColorPrefix));
                }
            }

            if (!(extends is null) && extends.Length > 0)
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.Extends);
                stringBuilder.Append(Constant.Space);
                stringBuilder.AppendJoin(',', extends);
            }

            if (!(implements is null) && implements.Length > 0)
            {
                stringBuilder.Append(Constant.Space);
                stringBuilder.Append(Constant.Implements);
                stringBuilder.Append(Constant.Space);
                stringBuilder.AppendJoin(',', implements);
            }
        }
Esempio n. 17
0
        private async Task DigestLuisResult(DialogContext dc, PointOfInterestLuis luisResult)
        {
            try
            {
                var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

                if (luisResult != null)
                {
                    state.Clear();
                    state.LuisResult = luisResult;

                    var entities = luisResult.Entities;

                    if (entities.Keyword != null)
                    {
                        state.Keyword = string.Join(" ", entities.Keyword);
                    }

                    if (entities.Address != null)
                    {
                        state.Address = string.Join(" ", entities.Address);
                    }
                    else
                    {
                        // ADDRESS overwrites geographyV2
                        var sb = new StringBuilder();

                        if (entities.geographyV2 != null)
                        {
                            sb.AppendJoin(" ", entities.geographyV2.Select(geography => geography.Location));
                        }

                        if (sb.Length > 0)
                        {
                            state.Address = sb.ToString();
                        }
                    }

                    // TODO only first is used now
                    if (entities.RouteDescription != null)
                    {
                        state.RouteType = entities.RouteDescription[0][0];
                    }

                    if (entities.PoiDescription != null)
                    {
                        state.PoiType = entities.PoiDescription[0][0];
                    }

                    // TODO unused
                    if (entities.number != null)
                    {
                        try
                        {
                            var value = entities.number[0];
                            if (Math.Abs(value - (int)value) < double.Epsilon)
                            {
                                state.UserSelectIndex = (int)value - 1;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
            catch
            {
                // put log here
            }
        }
Esempio n. 18
0
 /// <summary>
 ///     Concatenates the string of the provided object array,
 ///     using the specified separator between each string.
 ///     Then appends the result to the designated instance of the StringBuilder.
 /// </summary>
 /// <param name="source">A object array for concatenates.</param>
 /// <param name="stringBuilder">A StringBuilder to be appended.</param>
 /// <param name="separator">Specify the separator.</param>
 /// <returns>A reference to the designated instance after the append operation has completed.</returns>
 public static StringBuilder AppendToStringBuilder(this object[] source, StringBuilder stringBuilder,
                                                   string separator) => stringBuilder.AppendJoin(separator, source);
Esempio n. 19
0
        private async Task DigestLuisResult(DialogContext dc, PointOfInterestLuis luisResult)
        {
            try
            {
                var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

                if (luisResult != null)
                {
                    state.Clear();

                    var entities = luisResult.Entities;

                    // TODO since we can only search one per search, only the 1st one is considered
                    if (entities.Keyword != null)
                    {
                        if (entities._instance.KeywordCategory == null || !entities._instance.KeywordCategory.Any(c => c.Text.Equals(entities.Keyword[0], StringComparison.InvariantCultureIgnoreCase)))
                        {
                            state.Keyword = entities.Keyword[0];
                        }
                    }

                    // TODO if keyword exists and category exists, whether keyword contains category or a keyword of some category. We will ignore category in these two cases
                    if (string.IsNullOrEmpty(state.Keyword) && entities._instance.KeywordCategory != null)
                    {
                        state.Category = entities._instance.KeywordCategory[0].Text;
                    }

                    if (entities.Address != null)
                    {
                        state.Address = string.Join(" ", entities.Address);
                    }
                    else
                    {
                        // ADDRESS overwrites geographyV2
                        var sb = new StringBuilder();

                        if (entities.geographyV2 != null)
                        {
                            sb.AppendJoin(" ", entities.geographyV2.Select(geography => geography.Location));
                        }

                        if (sb.Length > 0)
                        {
                            state.Address = sb.ToString();
                        }
                    }

                    // TODO only first is used now
                    if (entities.RouteDescription != null)
                    {
                        state.RouteType = entities.RouteDescription[0][0];
                    }

                    if (entities.PoiDescription != null)
                    {
                        state.PoiType = entities.PoiDescription[0][0];
                    }

                    // TODO unused
                    if (entities.number != null)
                    {
                        try
                        {
                            var value = entities.number[0];
                            if (Math.Abs(value - (int)value) < double.Epsilon)
                            {
                                state.UserSelectIndex = (int)value - 1;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
            catch
            {
                // put log here
            }
        }
 public StringBuilder AppendJoin(string separator, params object[] values)
 {
     return(sb.AppendJoin(separator, values));
 }
Esempio n. 21
0
        private void Log <T>(Levels pLevel, string prefix, bool append, params T[] args)
        {
            if ((FLAG & Flags.DEBUG) == Flags.DEBUG && (int)pLevel >= (int)level)
            {
                // Output format is: indentprefix[yyyymmdd|level|TAG::CallingMethodName] arg1 arg2 arg3 ...
                StringBuilder output = new StringBuilder();
                foreach (var _ in Enumerable.Range(0, indentLevel))
                {
                    output.Append(indentSequence);
                }
                // No .Trim() because prefix could have whitespace/newline
                if (!prefix.Equals(""))
                {
                    output.Append(prefix);
                }
                output.Append("[");
                output.Append(DateTime.Now.ToString("yyyymmdd"));
                output.Append("|");
                output.Append(pLevel.ToString());
                output.Append("|");
                output.Append(TAG);
                output.Append("::");
                output.Append(GetCallingMethodName());
                output.Append("] ");
                // AppendJoin is found in .NET 5 only, see extension method if not .NET 5 project
                output.AppendJoin(' ', args);

                // Visual Studio Debug Console Output
                if ((FLAG & Flags.DEBUGCONSOLE) == Flags.DEBUGCONSOLE)
                {
                    if (append)
                    {
                        Debug.Write(output.ToString());
                    }
                    else
                    {
                        Debug.WriteLine(output.ToString());
                    }
                }

                // Standard Console Output
                if ((FLAG & Flags.CLICONSOLE) == Flags.CLICONSOLE)
                {
                    ConsoleColor prevClr = Console.ForegroundColor;

                    if ((FLAG & Flags.CLICOLORS) == Flags.CLICOLORS)
                    {
                        switch (pLevel)
                        {
                        case Levels.VERBOSE:
                            Console.ForegroundColor = ConsoleColor.DarkGray;
                            break;

                        case Levels.INFO:
                            Console.ForegroundColor = ConsoleColor.Blue;
                            break;

                        case Levels.WARNING:
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            break;

                        case Levels.ERROR:
                            Console.ForegroundColor = ConsoleColor.Red;
                            break;
                        }
                    }

                    if (level == Levels.WARNING || level == Levels.ERROR)
                    {
                        if (append)
                        {
                            Console.Error.Write(output.ToString());
                        }
                        else
                        {
                            Console.Error.WriteLine(output.ToString());
                        }
                    }
                    else
                    {
                        if (append)
                        {
                            Console.Out.Write(output.ToString());
                        }
                        else
                        {
                            Console.Out.WriteLine(output.ToString());
                        }
                    }

                    Console.ForegroundColor = prevClr;
                }

                if ((FLAG & Flags.LOGFILE) == Flags.LOGFILE)
                {
                    logStream?.Write(Encoding.Unicode.GetBytes($"{output}{NewLine}"));
                    logStream?.Flush();
                }
            }
        }
Esempio n. 22
0
        public string GetActions(User user)
        {
            StringBuilder panel = new StringBuilder();

            // Husk system
            if (user?.Husk != null)
            {
                bool canMove = Engine.CanMove(user.Husk, out string notification);

                if (!string.IsNullOrWhiteSpace(notification))
                {
                    user.Notifier.Append(notification);
                }

                Husk husk   = user.Husk;
                bool canAct = Engine.CanAct(ref husk, user.Brain);
                user.Husk = husk;
                panel.AppendLine();
                panel.AppendLine("**Actions**");
                panel.Append("• ");

                Locator location = user.Husk.Location;
                // you need to implement movement info.

                if (user.Husk.Destination != null)
                {
                    location = user.Husk.Destination;
                }

                panel.AppendLine(Engine.WriteLocationInfo(location.Id, user.Husk.Destination != null));

                ModuleInfo         main    = _commands.Modules.FirstOrDefault(x => x.Name == "Actions");
                List <CommandNode> actions = new List <CommandNode>();

                foreach (CommandInfo action in main?.Commands)
                {
                    if (actions.Any(x => x.Name == action.Name))
                    {
                        continue;
                    }

                    // Flag checking
                    OnlyWhenAttribute precondition = action.Preconditions.FirstOrDefault <OnlyWhenAttribute>();
                    // replace with BindToRegion when ready
                    BindToRegionAttribute check = action.Attributes.FirstOrDefault <BindToRegionAttribute>();

                    if (precondition != null)
                    {
                        if (!precondition.Judge(user.Brain, user.Stats))
                        {
                            continue;
                        }
                    }

                    if (check != null)
                    {
                        if (!canMove)
                        {
                            continue;
                        }

                        if (!canAct)
                        {
                            continue;
                        }

                        if (!check.Judge(user.Husk))
                        {
                            continue;
                        }
                    }

                    actions.Add(new CommandNode(GetCommands(action.Name, main)));
                }

                panel.AppendJoin(" • ", actions.Select(delegate(CommandNode x)
                {
                    string term = $"`{x.Name}`";

                    if (x.Overloads.Count > 1)
                    {
                        term += $"**+{x.Overloads.Count - 1}**";
                    }

                    return(term);
                }));
            }
            else
            {
                panel.Append("Where are you?");
            }
            return(panel.ToString());
        }
Esempio n. 23
0
        public long Insert <T>(ICollection <T> items)
        {
            if (items.Count == 0)
            {
                return(-1);
            }

            var tableName  = Utils.GetTableName <T>();
            var properties = Utils.GetProperties <T>();
            // Get the rowid property (if it is null, the query will be shortened)
            var rowid = Utils.GetRowIdProperty <T>(properties);

            using var command = Connection.CreateCommand();

            #region Query Building
            var sb = new StringBuilder();

            // Begin with another command to get the highest ROWID if AutoAssignRowId is false
            // or if there is no rowid property
            if (AutoAssignRowId && rowid != null)
            {
                sb.Append("SELECT MAX(ROWID) FROM");
                sb.Append(tableName);
                sb.Append("LIMIT 1;");
            }

            // Begin actual insert query
            sb.Append("INSERT INTO");
            sb.Append(tableName);
            sb.Append('(');
            // Join all column names with commas in between
            sb.Append(string.Join(',', properties.Select(x => x.Name)));
            sb.Append(")VALUES");

            // Build the parameter section for every given element.
            int i = 0;
            foreach (var item in items)
            {
                if (i != 0)
                {
                    sb.Append(',');
                }
                sb.Append('(');

                // Append the column parameter names and simultaneously create the SQLiteParameter objects
                sb.AppendJoin(',', properties.Select((x, j) =>
                {
                    var value = x.GetValue(item);
                    // Skip creating the SQLiteParameter if the value is null
                    if (value == null)
                    {
                        return("NULL");
                    }
                    var paramName = $"@{j}_{i}";
                    command.Parameters.Add(new SQLiteParameter(paramName, value));
                    return(paramName);
                }));

                sb.Append(')');
                ++i;
            }
            sb.Append(';');

            // Add another query to get the scalar if false or if there is no rowid property
            if (!AutoAssignRowId || rowid == null)
            {
                sb.Append("SELECT LAST_INSERT_ROWID();");
            }
            #endregion

            // Execute the command and return the scalar with the max ROWID
            command.CommandText = sb.ToString();
            object _      = command.ExecuteScalar();
            var    scalar = (long)(_ == DBNull.Value ?  0L : _);           // DBNull gets replaced with 0

            // Skip assigning rowids if false
            if (!AutoAssignRowId)
            {
                return(scalar);
            }

            // Assign the scalar for every inserted element if there is a ROWID property
            if (rowid != null)
            {
                ++scalar;
                foreach (var item in items)
                {
                    object oldValue = rowid.GetValue(item);
                    // Skip the rowid assigning if it is not null and recalculate the scalar if necessary
                    if (oldValue != null)
                    {
                        long oldRowId = Convert.ToInt64(oldValue);
                        if (oldRowId >= scalar)
                        {
                            scalar = oldRowId + 1;
                        }
                        continue;
                    }
                    // Change the type of the scalar to the type of the rowid property and set it
                    rowid.SetValue(item, Convert.ChangeType(scalar++, Nullable.GetUnderlyingType(rowid.PropertyType) ?? rowid.PropertyType));
                }
            }

            return(scalar);
        }
        private async Task DigestLuisResult(DialogContext dc, PointOfInterestLuis luisResult)
        {
            try
            {
                var state = await _stateAccessor.GetAsync(dc.Context, () => new PointOfInterestSkillState());

                if (luisResult != null)
                {
                    state.ClearLuisResults();

                    var entities = luisResult.Entities;

                    if (entities.KEYWORD != null)
                    {
                        state.Keyword = string.Join(" ", entities.KEYWORD);
                    }

                    if (entities.ADDRESS != null)
                    {
                        state.Address = string.Join(" ", entities.ADDRESS);
                    }
                    else
                    {
                        // ADDRESS overwrites geographyV2
                        var sb = new StringBuilder();

                        if (entities.geographyV2_poi != null)
                        {
                            sb.AppendJoin(" ", entities.geographyV2_poi);
                        }

                        if (entities.geographyV2_city != null)
                        {
                            sb.AppendJoin(" ", entities.geographyV2_city);
                        }

                        if (sb.Length > 0)
                        {
                            state.Address = sb.ToString();
                        }
                    }

                    if (entities.ROUTE_TYPE != null)
                    {
                        state.RouteType = entities.ROUTE_TYPE[0][0];
                    }

                    if (entities.number != null)
                    {
                        try
                        {
                            var value = entities.number[0];
                            if (Math.Abs(value - (int)value) < double.Epsilon)
                            {
                                state.UserSelectIndex = (int)value - 1;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
            catch
            {
                // put log here
            }
        }
Esempio n. 25
0
        public int Update <T>(ICollection <T> items)
        {
            if (!items.Any())
            {
                return(0);
            }

            var properties = Utils.GetProperties <T>().ToArray();

            // Try to get the primary key attributes. If empty, throw an exception
            var primaries = Utils.GetProperties <PrimaryAttribute>(properties).ToArray();

            if (!primaries.Any())
            {
                throw new ArgumentException("The given generic type does not contain a primary key property.", "T");
            }

            // Remove the primary properties from the properties list
            properties = properties.Except(primaries).ToArray();

            var tableName = Utils.GetTableName <T>();

            using var command = Connection.CreateCommand();

            #region Query Building
            var sb = new StringBuilder();
            int i  = 0;
            foreach (var item in items)
            {
                sb.Append("UPDATE");
                sb.Append(tableName);
                sb.Append("SET ");

                // Append the setters for every non-primary-key property and simultaneously create
                // the SQLiteParameter objects
                sb.AppendJoin(',', properties.Select((x, j) =>
                {
                    var value = x.GetValue(item);
                    // Skip creating the SQLiteParameter if the value is null
                    if (value is null)
                    {
                        return($"{x.Name}=NULL");
                    }

                    var paramName = $"@{i}_{j}";
                    command.Parameters.Add(new SQLiteParameter(paramName, value));

                    // Return the setter for this column
                    return($"{x.Name}={paramName}");
                }));
                sb.Append(" WHERE ");

                // Append the conditions that match the primary key values of the item
                sb.AppendJoin(" AND ", primaries.Select((x, j) =>
                {
                    var value = x.GetValue(item);
                    // Skip creating an SQLiteParameter if the value is null
                    if (value == null)
                    {
                        return($"{x.Name} IS NULL");
                    }

                    var paramName = $"@{i}_c{j}";
                    command.Parameters.Add(new SQLiteParameter(paramName, value));

                    // Return a comparison between the column and the new parameter
                    return($"{x.Name}={paramName}");
                }));

                sb.Append(';');
                ++i;
            }
            #endregion

            // Execute the command and return the amount of affected rows
            command.CommandText = sb.ToString();
            return(command.ExecuteNonQuery());
        }
 public CodeBuilder AppendJoin(char separator, params object?[] values)
 {
     builder.AppendJoin(separator, values);
     return(this);
 }
        public override string ToString()
        {
            var numberOfChildren = InternalChildren.Count;
            var sb = new StringBuilder();

            if (numberOfChildren > 10)
                sb.Append(numberOfChildren).Append(" children\n");
            else
                sb.Append("Children:\n    ").AppendJoin("\n    ", InternalChildren.AllMinToMax, ChildStatsAppender).Append('\n');

            var numberToDie = _toDie.Count;
            sb.Append(numberToDie).Append(" children terminating:\n    ");
            sb.AppendJoin("\n    ", _toDie.AllMinToMax);

            return sb.ToString();
        }
        public virtual ResultSetMapping AppendBatchInsertOperation(
            StringBuilder commandStringBuilder,
            Dictionary <string, string> variablesInsert,
            IReadOnlyList <ModificationCommand> modificationCommands,
            int commandPosition,
            ref int cursorPosition)
        {
            commandStringBuilder.Clear();
            var resultSetMapping = ResultSetMapping.NoResultSet;

            var name   = modificationCommands[0].TableName;
            var schema = modificationCommands[0].Schema;
            var reads  = modificationCommands[0].ColumnModifications.Where(o => o.IsRead).ToArray();

            var nameVariable = $"{name}_{commandPosition}";

            if (reads.Any())
            {
                if (!variablesInsert.Any(p => p.Key == nameVariable))
                {
                    var variblesBuilder = new StringBuilder();

                    variblesBuilder.AppendLine($"TYPE efRow{nameVariable} IS RECORD")
                    .AppendLine("(");
                    variblesBuilder.AppendJoin(
                        reads,
                        (sb, cm) =>
                        sb.Append(cm.ColumnName)
                        .Append(" ")
                        .AppendLine(GetVariableType(cm))
                        , ",")
                    .Append(")")
                    .AppendLine(SqlGenerationHelper.StatementTerminator);

                    variblesBuilder.Append($"TYPE ef{nameVariable} IS TABLE OF efRow{nameVariable}")
                    .AppendLine(SqlGenerationHelper.StatementTerminator)
                    .Append($"list{nameVariable} ef{nameVariable}")
                    .AppendLine(SqlGenerationHelper.StatementTerminator);

                    variablesInsert.Add(nameVariable, variblesBuilder.ToString());
                }

                commandStringBuilder.Append("list")
                .Append(nameVariable)
                .Append(" := ")
                .Append($"ef{nameVariable}")
                .Append("()")
                .AppendLine(SqlGenerationHelper.StatementTerminator);

                commandStringBuilder.Append($"list{nameVariable}.extend(")
                .Append(modificationCommands.Count)
                .Append(")")
                .AppendLine(SqlGenerationHelper.StatementTerminator);
            }

            for (var i = 0; i < modificationCommands.Count; i++)
            {
                var operations      = modificationCommands[i].ColumnModifications;
                var readOperations  = operations.Where(o => o.IsRead).ToArray();
                var writeOperations = operations.Where(o => o.IsWrite).ToArray();
                AppendInsertCommand(commandStringBuilder, name, schema, writeOperations, readOperations);
                AppendReturnInsert(commandStringBuilder, nameVariable, readOperations, i);
            }

            for (var i = 0; i < modificationCommands.Count; i++)
            {
                var operations     = modificationCommands[i].ColumnModifications;
                var readOperations = operations.Where(o => o.IsRead).ToArray();
                if (readOperations.Any())
                {
                    AppendReturnCursor(commandStringBuilder, nameVariable, readOperations, i, cursorPosition);
                    resultSetMapping = ResultSetMapping.LastInResultSet;
                    cursorPosition++;
                }
            }

            return(resultSetMapping);
        }
Esempio n. 29
0
        static Regex CreateParser()
        {
            StringBuilder text = new StringBuilder(@"^\s*");
            text.Append(@"(");

            text.AppendJoin(
                RelationMatchers
                    .Select(r => r.ToString().TrimStart('^').TrimEnd('$'))	//Remove the anchors
                    .OrderByDescending(r => r.Length),
                "|"
            ).Append('|').Append(Regex.Escape(EmptyRelative));

            text.Append(@")?");
            text.Append(@"\s*[,.;/\\]?\s*");
            text.Append(@"(מתנה|Matanah?)?");	//TODO: Allow prefix מתנה
            text.Append(@"\s*[,.;/\\]?\s*");
            text.Append(@"(.*)");
            text.Append(@"\s*$");
            return new Regex(text.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }
 public static StringBuilder AppendJoin(this StringBuilder sb, char separator, params string[] values)
 => sb.AppendJoin(separator.ToString(), values);
Esempio n. 31
0
 /// <summary>
 ///     Concatenates the string of the provided string array,
 ///     using the specified separator between each string.
 ///     Then appends the result to the designated instance of the StringBuilder.
 /// </summary>
 /// <param name="source">A string array for concatenates.</param>
 /// <param name="stringBuilder">A StringBuilder to be appended.</param>
 /// <param name="separator">Specify the separator.</param>
 /// <returns>A reference to the designated instance after the append operation has completed.</returns>
 public static StringBuilder AppendToStringBuilder(this string[] source, StringBuilder stringBuilder,
                                                   char separator) => stringBuilder.AppendJoin(separator, source);
Esempio n. 32
0
 public HyperStringBuilder AppendJoin(char separator, params object?[] values)
 {
     _builder.AppendJoin(separator, values);
     return(this);
 }
Esempio n. 33
0
 public static StringBuilder AppendJoin(
     this StringBuilder stringBuilder, IEnumerable <string> values, string separator = ", ")
 => stringBuilder.AppendJoin(values, (sb, value) => sb.Append(value), separator);
Esempio n. 34
0
        public IEnumerable <SqlFile> GetSql()
        {
            var builder = new StringBuilder();

            builder.Append($"CREATE TABLE {_classInfo.SqlTableName} ({_nl}");
            builder.AppendJoin(
                _nl,
                _orderedProperties.Select(x => GetColumnDefinition(x))
                );
            builder.Append(_nl);
            builder.Append(
                $"\tCONSTRAINT pk_{_classInfo.SqlTableName} PRIMARY KEY ("
                );
            builder.AppendJoin(", ", _idProperties.Select(x => x.SqlName));
            builder.Append($"){_nl}");
            builder.Append(')');
            yield return(new SqlFile
            {
                Name = $"{_schemaName}.{_classInfo.SqlTableName}.sql",
                Content = builder.ToString()
            });

            builder.Clear();

            var getByIdProcName = GetProcedureName("get_by_id");

            builder.Append(
                GetProcedureStart(getByIdProcName, _idProperties)
                );
            builder.Append(GetSelectSql());
            builder.Append(GetWhereByIdClause());
            builder.Append("END");
            yield return(new SqlFile
            {
                Name = $"{getByIdProcName}.sql",
                Content = builder.ToString()
            });

            builder.Clear();

            var getAllProcName = GetProcedureName("get_all");

            builder.Append(
                GetProcedureStart(getAllProcName, new List <PropertyInfo>())
                );
            builder.Append(GetSelectSql());
            builder.Append("END");
            yield return(new SqlFile
            {
                Name = $"{getAllProcName}.sql",
                Content = builder.ToString()
            });

            builder.Clear();

            var createProcName = GetProcedureName("insert");

            builder.Append(
                GetProcedureStart(createProcName, _nonIdProperties)
                );
            builder.Append(
                $"\tINSERT {_schemaName}.{_classInfo.SqlTableName} ({_nl}"
                );
            builder.AppendJoin(
                $",{_nl}",
                _nonIdProperties.Select(x => $"\t\t[{x.SqlName}]")
                );
            builder.Append($"{_nl}\t){_nl}");
            builder.Append($"\tVALUES ({_nl}");
            builder.AppendJoin(
                $",{_nl}",
                _nonIdProperties.Select(x => $"\t\t@{x.SqlName}")
                );
            builder.Append($"{_nl}\t);{_nl}{_nl}");
            builder.Append($"\tSELECT SCOPE_IDENTITY(){_nl}");
            builder.Append("END");
            yield return(new SqlFile
            {
                Name = $"{createProcName}.sql",
                Content = builder.ToString()
            });

            builder.Clear();

            var updateProcName = GetProcedureName("update");

            builder.Append(GetProcedureStart(
                               updateProcName,
                               _orderedProperties
                               ));
            builder.Append(
                $"\tUPDATE {_schemaName}.{_classInfo.SqlTableName}{_nl}"
                );
            builder.Append($"\tSET{_nl}");
            builder.AppendJoin(
                $",{_nl}",
                _nonIdProperties.Select(x => $"\t\t[{x.SqlName}] = @{x.SqlName}")
                );
            builder.Append($"{_nl}");
            builder.Append(GetWhereByIdClause());
            builder.Append("END");
            yield return(new SqlFile
            {
                Name = $"{updateProcName}.sql",
                Content = builder.ToString()
            });

            builder.Clear();

            var deleteProcName = GetProcedureName("delete");

            builder.Append(GetProcedureStart(
                               deleteProcName,
                               _idProperties
                               ));
            builder.Append($"\tDELETE{_nl}");
            builder.Append(
                $"\tFROM {_schemaName}.{_classInfo.SqlTableName}{_nl}"
                );
            builder.Append(GetWhereByIdClause());
            builder.Append("END");
            yield return(new SqlFile
            {
                Name = $"{deleteProcName}.sql",
                Content = builder.ToString()
            });
        }
Esempio n. 35
0
 /// <summary>
 ///     Concatenates the string representation of an specified objects,
 ///     using the specified separator between each string.
 ///     Then appends the result to the designated instance of the StringBuilder.
 /// </summary>
 /// <typeparam name="T">A object type.</typeparam>
 /// <param name="source">A sequence of object</param>
 /// <param name="stringBuilder">A StringBuilder to be appended.</param>
 /// <param name="separator">Specify the separator.</param>
 /// <returns>A reference to the designated instance after the append operation has completed.</returns>
 public static StringBuilder AppendToStringBuilder <T>(this IEnumerable <T> source, StringBuilder stringBuilder,
                                                       string separator) => stringBuilder.AppendJoin(separator, source);
Esempio n. 36
0
 public static StringBuilder AppendJoin(
     this StringBuilder stringBuilder, string separator, params string[] values)
 => stringBuilder.AppendJoin(values, (sb, value) => sb.Append(value), separator);
        ///<summary>Builds a SELECT command for the given schema.</summary>
        ///<returns>
        ///SELECT [FirstColumn], [SecondColumn], [RowVersion]
        ///FROM [SchemaName].[TableName]
        ///</returns>
        protected StringBuilder BuildSelectCommand(SchemaMapping schema)
        {
            if (schema == null) throw new ArgumentNullException("schema");

            var sql = new StringBuilder();

            sql.Append("SELECT ");
            sql.AppendJoin(
                schema.Columns.Select(c => c.SqlName.EscapeSqlIdentifier()), ", "
            );
            sql.AppendLine(", [RowVersion]");
            sql.Append("FROM ").Append(QualifyTable(schema));

            return sql;
        }