Exemplo n.º 1
0
        private void GenerateFunctionStub(Routine function, RoutineModel model)
        {
            var paramStrings = function.Parameters
                               .Select(p => $"{Code.Reference(p.ClrType())} {(string.IsNullOrEmpty(p.Name) ? p.Name : Code.Identifier(p.Name))}");

            var identifier = GenerateIdentifierName(function, model);

            Sb.AppendLine();

            Sb.AppendLine($"[DbFunction(\"{function.Name}\", \"{function.Schema}\")]");

            if ((function as Function) !.IsScalar)
            {
                var returnType = paramStrings.First();
                var parameters = string.Empty;

                if (function.Parameters.Count > 1)
                {
                    parameters = string.Join(", ", paramStrings.Skip(1));
                }

                Sb.AppendLine($"public static {returnType}{identifier}({parameters})");

                Sb.AppendLine("{");
                using (Sb.Indent())
                {
                    Sb.AppendLine("throw new NotSupportedException(\"This method can only be called from Entity Framework Core queries\");");
                }

                Sb.AppendLine("}");
            }
        private void GenerateOnModelCreating(RoutineModel model)
        {
            Sb.AppendLine();
            Sb.AppendLine("protected void OnModelCreatingGeneratedProcedures(ModelBuilder modelBuilder)");
            Sb.AppendLine("{");

            using (Sb.Indent())
            {
                foreach (var procedure in model.Routines.Cast <Procedure>())
                {
                    if (procedure.NoResultSet)
                    {
                        continue;
                    }

                    int i = 1;
                    foreach (var resultSet in procedure.Results)
                    {
                        var suffix = $"{i++}";

                        if (!procedure.SupportsMultipleResultSet)
                        {
                            suffix = string.Empty;
                        }

                        var typeName = GenerateIdentifierName(procedure, model) + "Result" + suffix;

                        Sb.AppendLine($"modelBuilder.Entity<{typeName}>().HasNoKey().ToView(null);");
                    }
                }
            }

            Sb.AppendLine("}");
        }
Exemplo n.º 3
0
 private void ShowSubtotal(ISubtotalResult sub)
 {
     if (sub.Items == null)
     {
         Sb.AppendLine($"{m_Path}\t{m_Formatter.GetFundString(sub.Fund)}");
     }
     VisitChildren(sub);
 }
Exemplo n.º 4
0
        /// <summary>
        ///     Moves the specified blocks.
        /// </summary>
        /// <param name="blocks">The blocks.</param>
        private void Move(int blocks)
        {
            // Store starting point.
            string startPoint = Coordinates();

            for (var i = 0; i < blocks; i++)
            {
                // Move 1 block at a time - required for Part 2
                int x = CurrentPoint.X;
                int y = CurrentPoint.Y;
                switch (CurrentDirection)
                {
                case Direction.East:
                    x++;
                    break;

                case Direction.West:
                    x--;
                    break;

                case Direction.North:
                    y++;
                    break;

                case Direction.South:
                    y--;
                    break;

                default:
                    Console.WriteLine(
                        $"Huh? It seems that you're trying to move in a non-standard direction. ({CurrentDirection})");
                    break;
                }

                // Set current position.
                CurrentPoint = new Point(x, y);

                // If there are any points in our log of previously visited points (X and Y coordinates match),
                // and we have not found a previously-visited block, set this block as our first revisited block.
                if (Points.Any(point => CurrentPoint.X == point.X && CurrentPoint.Y == point.Y) &&
                    FirstRevisitedPoint.X == 0 &&
                    FirstRevisitedPoint.Y == 0)
                {
                    FirstRevisitedPoint = CurrentPoint;
                }

                // Add the current point to our log of positions.
                Points.Add(CurrentPoint);
            }

            // Add the current movement to our log.
            Sb.AppendLine(string.Join(",", CurrentDirection.ToString(), blocks.ToString(), CurrentPoint.X.ToString(),
                                      CurrentPoint.Y.ToString()));
            Console.WriteLine(
                $"Travelled {blocks.ToString().PadLeft(6)} blocks {CurrentDirection.ToString().PadRight(10)} from {startPoint.PadRight(5)} to {Coordinates().PadRight(8)}");
        }
        private void AppendValue(ModuleParameter parameter)
        {
            var value = parameter.Nullable ? $"{Code.Identifier(parameter.Name)} ?? Convert.DBNull" : $"{Code.Identifier(parameter.Name)}";

            if (parameter.Output)
            {
                value = parameter.Nullable ? $"{Code.Identifier(parameter.Name)}?._value ?? Convert.DBNull" : $"{Code.Identifier(parameter.Name)}?._value";
            }

            Sb.AppendLine($"Value = {value},");
        }
Exemplo n.º 6
0
        /// <summary>
        /// Export the graph associated to the specified data into a csv file.
        /// </summary>
        /// <param name="xLabel"></param>
        /// <param name="yLabel"></param>
        /// <param name="categories"></param>
        /// <param name="graphList"></param>
        public void ExportGraph(String xLabel, String yLabel, List <String> categories, IEnumerable <FusionChartsDataset> graphList)
        {
            var str = String.Concat(xLabel, Separator, yLabel);

            Sb.AppendLine(Format(str));

            for (var i = 0; i < categories.Count; i++)
            {
                var str2 = graphList.Aggregate(String.Empty, (current, d) => String.Concat(current, d.Values[i], Separator));

                str = String.Concat(categories[i], Separator, str2.TrimEnd(Separator));

                Sb.AppendLine(Format(str.Replace('.', ',')));
            }
        }
Exemplo n.º 7
0
        private void GenerateModelCreation(RoutineModel model)
        {
            Sb.AppendLine();
            Sb.AppendLine("protected void OnModelCreatingGeneratedFunctions(ModelBuilder modelBuilder)");
            Sb.AppendLine("{");

            using (Sb.Indent())
            {
                foreach (var function in model.Routines.Cast <Function>().Where(f => !f.IsScalar))
                {
                    var typeName = GenerateIdentifierName(function, model) + "Result";

                    Sb.AppendLine($"modelBuilder.Entity<{typeName}>().HasNoKey();");
                }
            }

            Sb.AppendLine("}");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Fills the report with the items of the grid beggining the row with the initialString.
        /// </summary>
        /// <param name="rowInitialStr"></param>
        /// <param name="grid"></param>
        private void ExportGridFields(String rowInitialStr, C1GridView grid)
        {
            foreach (C1GridViewRow row in grid.Rows)
            {
                var data = rowInitialStr;

                for (var i = 0; i < grid.Columns.Count; i++)
                {
                    if (grid.Columns[i].HeaderText != String.Empty)
                    {
                        data = String.Concat(data, String.Format("{0}" + Separator, row.Cells[i].Text.Equals(GridEmptyString) ? String.Empty : Format(row.Cells[i].Text).Replace(Separator, AlternateSeparator).Replace("\r", " ").Replace("\n", " ")));
                    }
                }

                Sb.AppendLine(data.TrimEnd(Separator));
            }

            Sb.AppendLine();
        }
 public StringBuilder CreateMatrixStructure()
 {
     for (int col = 0; col < Matrix.GetLength(0); col++)
     {
         for (int row = 0; row < Matrix.GetLength(1); row++)
         {
             //CreateBorder
             if ((col == 0) || (col == (Matrix.GetLength(0) - 1) || row == 0 || row == (Matrix.GetLength(1) - 1)))
             {
                 Sb.Append("X   ");
             }
             else
             {
                 CreatePath(col, row);
             }
         }
         Sb.AppendLine();
     }
     return(Sb);
 }
        private void GenerateParameter(ModuleParameter parameter, Routine procedure)
        {
            Sb.AppendLine("new SqlParameter");
            Sb.AppendLine("{");

            var sqlDbType = parameter.DbType();

            using (Sb.Indent())
            {
                Sb.AppendLine($"ParameterName = \"{Code.Identifier(parameter.Name)}\",");

                if (sqlDbType.IsScaleType())
                {
                    if (parameter.Precision > 0)
                    {
                        Sb.AppendLine($"Precision = {parameter.Precision},");
                    }

                    if (parameter.Scale > 0)
                    {
                        Sb.AppendLine($"Scale = {parameter.Scale},");
                    }
                }

                if (sqlDbType.IsVarTimeType() && parameter.Scale > 0)
                {
                    Sb.AppendLine($"Scale = {parameter.Scale},");
                }

                if (sqlDbType.IsLengthRequiredType())
                {
                    Sb.AppendLine($"Size = {parameter.Length},");
                }

                if (!parameter.IsReturnValue)
                {
                    if (parameter.Output)
                    {
                        Sb.AppendLine("Direction = System.Data.ParameterDirection.InputOutput,");
                        AppendValue(parameter);
                    }
                    else
                    {
                        AppendValue(parameter);
                    }
                }
                else
                {
                    if (procedure.SupportsMultipleResultSet)
                    {
                        Sb.AppendLine("Direction = System.Data.ParameterDirection.ReturnValue,");
                    }
                    else
                    {
                        Sb.AppendLine("Direction = System.Data.ParameterDirection.Output,");
                    }
                }

                Sb.AppendLine($"SqlDbType = System.Data.SqlDbType.{sqlDbType},");

                if (sqlDbType == SqlDbType.Structured)
                {
                    Sb.AppendLine($"TypeName = \"{parameter.TypeName}\",");
                }

                if (sqlDbType == SqlDbType.Udt)
                {
                    Sb.AppendLine($"UdtTypeName = \"{parameter.TypeName}\",");
                }
            }

            Sb.Append("}");
        }
 private void GenerateParameterVar(ModuleParameter parameter, Routine procedure)
 {
     Sb.Append($"var {ParameterPrefix}{parameter.Name} = ");
     GenerateParameter(parameter, procedure);
     Sb.AppendLine(";");
 }
Exemplo n.º 12
0
 public void AppendLine(string line)
 {
     Sb.AppendLine($"{GetIndentString()}{line}");
 }
        private void GenerateProcedure(Routine procedure, RoutineModel model, bool signatureOnly, bool useAsyncCalls)
        {
            var paramStrings = procedure.Parameters.Where(p => !p.Output)
                               .Select(p => $"{Code.Reference(p.ClrType(asMethodParameter: true))} {Code.Identifier(p.Name)}")
                               .ToList();

            var allOutParams = procedure.Parameters.Where(p => p.Output).ToList();

            var outParams = allOutParams.SkipLast(1).ToList();

            var retValueName = allOutParams.Last().Name;

            var outParamStrings = outParams
                                  .Select(p => $"OutputParameter<{Code.Reference(p.ClrType())}> {Code.Identifier(p.Name)}")
                                  .ToList();

            string fullExec = GenerateProcedureStatement(procedure, retValueName, useAsyncCalls);

            var multiResultId = GenerateMultiResultId(procedure, model);

            var identifier = GenerateIdentifierName(procedure, model);

            var returnClass = identifier + "Result";

            if (!string.IsNullOrEmpty(procedure.MappedType))
            {
                returnClass = procedure.MappedType;
            }

            var line = GenerateMethodSignature(procedure, outParams, paramStrings, retValueName, outParamStrings, identifier, multiResultId, signatureOnly, useAsyncCalls, returnClass);

            if (signatureOnly)
            {
                Sb.Append(line);
                return;
            }

            using (Sb.Indent())
            {
                Sb.AppendLine();

                Sb.AppendLine(line);
                Sb.AppendLine("{");

                using (Sb.Indent())
                {
                    foreach (var parameter in allOutParams)
                    {
                        GenerateParameterVar(parameter, procedure);
                    }

                    Sb.AppendLine();

                    Sb.AppendLine("var sqlParameters = new []");
                    Sb.AppendLine("{");
                    using (Sb.Indent())
                    {
                        foreach (var parameter in procedure.Parameters)
                        {
                            if (parameter.Output)
                            {
                                Sb.Append($"{ParameterPrefix}{parameter.Name}");
                            }
                            else
                            {
                                GenerateParameter(parameter, procedure);
                            }

                            Sb.AppendLine(",");
                        }
                    }

                    Sb.AppendLine("};");

                    if (procedure.HasValidResultSet && (procedure.Results.Count == 0 || procedure.Results[0].Count == 0))
                    {
                        Sb.AppendLine(useAsyncCalls
                            ? $"var _ = await _context.Database.ExecuteSqlRawAsync({fullExec});"
                            : $"var _ = _context.Database.ExecuteSqlRaw({fullExec});");
                    }
                    else
                    {
                        if (procedure.SupportsMultipleResultSet)
                        {
                            Sb.AppendLine();
                            Sb.AppendLine("var dynamic = CreateDynamic(sqlParameters);");
                            Sb.AppendLine($"{multiResultId}  _;");
                            Sb.AppendLine();
                            Sb.AppendLine($"using (var reader = {(useAsyncCalls ? "await GetMultiReaderAsync" : "GetMultiReader")}(_context, dynamic, \"[{procedure.Schema}].[{procedure.Name}]\"))");
                            Sb.AppendLine("{");

                            using (Sb.Indent())
                            {
                                var statements = GenerateMultiResultStatement(procedure, model, useAsyncCalls);
                                Sb.AppendLine($"_ = {statements};");
                            }

                            Sb.AppendLine("}");
                        }
                        else
                        {
                            Sb.AppendLine(useAsyncCalls
                                ? $"var _ = await _context.SqlQueryAsync<{returnClass}>({fullExec});"
                                : $"var _ = _context.SqlQuery<{returnClass}>({fullExec});");
                        }
                    }

                    Sb.AppendLine();

                    foreach (var parameter in outParams)
                    {
                        Sb.AppendLine($"{Code.Identifier(parameter.Name)}.SetValue({ParameterPrefix}{parameter.Name}.Value);");
                    }

                    if (procedure.SupportsMultipleResultSet)
                    {
                        Sb.AppendLine($"{retValueName}?.SetValue(dynamic.Get<int>(\"{retValueName}\"));");
                    }
                    else
                    {
                        Sb.AppendLine($"{retValueName}?.SetValue({ParameterPrefix}{retValueName}.Value);");
                    }

                    Sb.AppendLine();

                    Sb.AppendLine("return _;");
                }

                Sb.AppendLine("}");
            }
        }
        private void GenerateDapperSupport(bool useAsyncCalls)
        {
            Sb.AppendLine();
            using (Sb.Indent())
            {
                Sb.AppendLine("private static DynamicParameters CreateDynamic(SqlParameter[] sqlParameters)");
                Sb.AppendLine("{");
                using (Sb.Indent())
                {
                    Sb.AppendLine("var dynamic = new DynamicParameters();");
                    Sb.AppendLine("foreach (var sqlParameter in sqlParameters)");
                    Sb.AppendLine("{");
                    using (Sb.Indent())
                    {
                        Sb.AppendLine("dynamic.Add(sqlParameter.ParameterName, sqlParameter.Value, sqlParameter.DbType, sqlParameter.Direction, sqlParameter.Size, sqlParameter.Precision, sqlParameter.Scale);");
                    }

                    Sb.AppendLine("}");
                    Sb.AppendLine();
                    Sb.AppendLine("return dynamic;");
                }

                Sb.AppendLine("}");
            }

            Sb.AppendLine();

            using (Sb.Indent())
            {
                if (useAsyncCalls)
                {
                    Sb.AppendLine("private async Task<SqlMapper.GridReader> GetMultiReaderAsync(DbContext db, DynamicParameters dynamic, string sql)");
                }
                else
                {
                    Sb.AppendLine("private SqlMapper.GridReader GetMultiReader(DbContext db, DynamicParameters dynamic, string sql)");
                }

                Sb.AppendLine("{");
                using (Sb.Indent())
                {
                    Sb.AppendLine("IDbTransaction tran = null;");
                    Sb.AppendLine("if (db.Database.CurrentTransaction is IDbContextTransaction ctxTran)");
                    Sb.AppendLine("{");
                    using (Sb.Indent())
                    {
                        Sb.AppendLine("tran = ctxTran.GetDbTransaction();");
                    }

                    Sb.AppendLine("}");
                    Sb.AppendLine();
                    Sb.AppendLine($"return {(useAsyncCalls ? "await " : string.Empty)}((IDbConnection)db.Database.GetDbConnection())");
                    using (Sb.Indent())
                    {
                        Sb.AppendLine($".QueryMultiple{(useAsyncCalls ? "Async" : string.Empty)}(sql, dynamic, tran, db.Database.GetCommandTimeout(), CommandType.StoredProcedure);");
                    }
                }

                Sb.AppendLine("}");
            }
        }
Exemplo n.º 15
0
 public override Nothing Visit(ISubtotalRoot sub)
 {
     Sb.AppendLine($"{Idents}{Ts(sub.Fund)}");
     VisitChildren(sub);
     return(Nothing.AtAll);
 }
Exemplo n.º 16
0
 private void ShowSubtotal(ISubtotalResult sub, string str)
 {
     Sb.AppendLine($"{Idents}{str.CPadRight(38)}{Ts(sub.Fund).CPadLeft(12 + 2 * Depth)}");
     VisitChildren(sub);
 }
Exemplo n.º 17
0
            protected int OnExecute(CommandLineApplication app)
            {
                var prefix = ArchivePrefix ?? "BBS";

                if (!DoesContainBbsa(InputPath, prefix))
                {
                    throw new ArchiveNotFoundException(InputPath, 0);
                }

                var bbsaFileName = Path.Combine(InputPath, $"{prefix}{0}.DAT");

                using var stream = File.OpenRead(bbsaFileName);
                var bbsa = Bbs.Bbsa.Read(stream);

                StringBuilder Sb = null;

                if (Log)
                {
                    Sb = new StringBuilder();
                    Sb.Append($"OpenKingdomHearts BirthBySleep Archive Command Ansem Report\r\n{DateTime.Now.ToString("F")}\r\n\r\n");
                }

                foreach (var file in Index >= 0 ? bbsa.Files.Where(x => x.ArchiveIndex == Index) : bbsa.Files)
                {
                    Console.WriteLine(file.Name + $" -- {prefix}{file.ArchiveIndex}.DAT");
                    stream.Position = file.Location + 4;

                    Bbs.Bbsa.CalculateArchiveOffset(bbsa.GetHeader(), file.offset, out var nuind, out var coffs);

                    if (DetailedLog || Log)
                    {
                        var reader = new BinaryReader(stream).ReadUInt32();
                        var offs   = reader >> 12;
                        var siz    = reader & 0xFFF;
                        var info   = (offs << 12) + siz;

                        Console.WriteLine($"\nOffsetStr: 0x{file.Location.ToString("X2")} on BBS{file.ArchiveIndex}\n" +
                                          $"PointerValue: 0x{reader.ToString("X2")}\n" +
                                          $"CalculatedOffset: {coffs}\n" +
                                          $"Offset: {offs}\n" +
                                          $"Size: 0x{siz.ToString("X2")} Sectors\n" +
                                          $"\nSupraInfo: 0x{info.ToString("X2")}");
                        if (WaitEachFile)
                        {
                            Console.ReadLine();
                        }

                        if (Log)
                        {
                            Sb.AppendLine(file.Name + $" -- {prefix}{file.ArchiveIndex}.DAT" +
                                          $"\r\nOffsetStr: 0x{file.Location.ToString("X2")} on BBS{file.ArchiveIndex}\r\n" +
                                          $"PointerValue: 0x{reader.ToString("X2")}\r\n" +
                                          $"CalculatedOffset: {coffs}\r\n" +
                                          $"Offset: {offs}\r\n" +
                                          $"Size: 0x{siz.ToString("X2")} Sectors\r\n" +
                                          $"\nSupraInfo: 0x{info.ToString("X2")}\r\n-------------//--------------\r\n");
                        }
                    }
                }

                if (Log)
                {
                    Sb.AppendLine("---------END--------");
                    File.WriteAllText(Path.Combine(InputPath, "ReportLOG.txt"), Sb.ToString());
                }

                return(0);
            }
Exemplo n.º 18
0
            private static void ExtractArchives(IEnumerable <string> bbsaFileNames, string outputDir, string prefix, int index = -1, bool detailed = false, bool log = false)
            {
                var streams = bbsaFileNames
                              .Select(x => File.OpenRead(x))
                              .ToArray();

                var bbsa = Bbs.Bbsa.Read(streams[0]);

                StringBuilder Sb = null;

                if (log)
                {
                    Sb = new StringBuilder();
                    Sb.Append($"OpenKingdomHearts BirthBySleep Archive Command Ansem Report\r\n{DateTime.Now.ToString("F")}\r\n\r\n");
                }

                foreach (var file in index >= 0 ? bbsa.Files.Where(x => x.ArchiveIndex == index) : bbsa.Files)
                {
                    var name           = file.CalculateNameWithExtension(i => streams[i]);
                    var bbsaFileStream = file.OpenStream(i => streams[i]);
                    if (bbsaFileStream == null)
                    {
                        continue;
                    }

                    var destinationFileName = Path.Combine(Path.Combine(outputDir, $"{prefix}{file.ArchiveIndex}"), name);
                    var destinationFolder   = Path.GetDirectoryName(destinationFileName);
                    if (!Directory.Exists(destinationFolder))
                    {
                        Directory.CreateDirectory(destinationFolder);
                    }
                    streams[0].Position = file.Location + 4;

                    Bbs.Bbsa.CalculateArchiveOffset(bbsa.GetHeader(), file.offset, out var nuind, out var coffs);

                    Console.WriteLine(name + $" -- {prefix}{file.ArchiveIndex}.DAT");

                    if (detailed || log)
                    {
                        var reader = new BinaryReader(streams[0]).ReadUInt32();
                        var offs   = reader >> 12;
                        var siz    = reader & 0xFFF;
                        var info   = (offs << 12) + siz;

                        Console.WriteLine($"OffsetStr: 0x{file.Location.ToString("X2")} on BBS{file.ArchiveIndex}\n" +
                                          $"PointerValue: 0x{reader.ToString("X2")}\n" +
                                          $"CalculatedOffset: {coffs}\n" +
                                          $"Offset: {offs}\n" +
                                          $"Size: 0x{siz.ToString("X2")} Sectors\n" +
                                          $"\nSupraInfo: 0x{info.ToString("X2")}\n");

                        if (log)
                        {
                            Sb.AppendLine(file.Name + $" -- {prefix}{file.ArchiveIndex}.DAT" +
                                          $"\r\nOffsetStr: 0x{file.Location.ToString("X2")} on BBS{file.ArchiveIndex}\r\n" +
                                          $"PointerValue: 0x{reader.ToString("X2")}\r\n" +
                                          $"CalculatedOffset: {coffs}\r\n" +
                                          $"Offset: {offs}\r\n" +
                                          $"Size: 0x{siz.ToString("X2")} Sectors\r\n" +
                                          $"\nSupraInfo: 0x{info.ToString("X2")}\r\n-------------//--------------\r\n");
                        }
                    }


                    using (var outStream = File.Create(destinationFileName))
                        bbsaFileStream.CopyTo(outStream);
                }

                if (log)
                {
                    Sb.AppendLine("---------END--------");
                    File.WriteAllText(Path.Combine(outputDir, "ExtractReportLOG.txt"), Sb.ToString());
                }
            }