Exemple #1
0
        public static void BinaryToTree(String BinaryPath, String TreePath, String MainType)
        {
            var TypeName = ObjectSchemaExtensions.GetDotNetFullNameFromVersionedName(MainType);
            var a        = SchemaAssembly();
            var t        = a.GetType(TypeName);

            if (t == null)
            {
                throw new InvalidOperationException("TypeNotExist: " + TypeName);
            }
            var tbc = TreeBinaryConverter();

            Byte[] Data;
            using (var s = Streams.OpenReadable(BinaryPath))
            {
                Data = s.Read((int)(s.Length));
            }
            var x   = tbc.BinaryToTree(t, Data);
            var Dir = FileNameHandling.GetFileDirectory(TreePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            TreeFile.WriteFile(TreePath, x);
        }
Exemple #2
0
        public static void GenerateCSharp(String InputDirectory, String OutputDirectory)
        {
            var Files = new Dictionary <String, FileParserResult>();

            foreach (var FilePath in Directory.EnumerateFiles(InputDirectory, "*.tree", SearchOption.AllDirectories))
            {
                var AbsolutePath = FileNameHandling.GetAbsolutePath(FilePath, System.Environment.CurrentDirectory);
                var FileContent  = Txt.ReadFile(FilePath);
                var Text         = TokenParser.BuildText(FileContent, AbsolutePath);
                var Result       = FileParser.ParseFile(Text);
                Files.Add(AbsolutePath, Result);
            }

            foreach (var p in Files)
            {
                var RelativePath = FileNameHandling.GetRelativePath(p.Key, FileNameHandling.GetAbsolutePath(InputDirectory, System.Environment.CurrentDirectory));
                var FileName     = FileNameHandling.GetFileName(p.Key);
                var ecsg         = new EmbeddedCSharpGenerator();
                var Content      = String.Join("\r\n", ecsg.Generate(p.Value.File).Select(Line => Line.TrimEnd(' ')));
                var OutputPath   = FileNameHandling.GetPath(FileNameHandling.GetPath(OutputDirectory, FileNameHandling.GetFileDirectory(RelativePath)), FileNameHandling.GetMainFileName(FileName) + ".cs");
                var OutputDir    = FileNameHandling.GetFileDirectory(OutputPath);
                if (!Directory.Exists(OutputDir))
                {
                    Directory.CreateDirectory(OutputDir);
                }
                WriteToFileIfChanged(OutputPath, Content);
            }
        }
Exemple #3
0
            public Writer(RelationSchemaLoaderResult rslr, String Title, String CopyrightText)
            {
                this.Schema        = rslr.Schema;
                this.Title         = Title;
                this.CopyrightText = CopyrightText;

                TypeInfoDict = new Dictionary <String, TypeInfo>(StringComparer.OrdinalIgnoreCase);

                String Root = "";

                if (rslr.Positions.Count > 0)
                {
                    Func <String, String, String> GetCommonHead = (a, b) =>
                    {
                        var lc = new List <Char>();
                        var k  = 0;
                        while (true)
                        {
                            if (k >= a.Length || k >= b.Length)
                            {
                                break;
                            }
                            if (a[k] != b[k])
                            {
                                break;
                            }
                            lc.Add(a[k]);
                            k += 1;
                        }
                        return(new String(lc.ToArray()));
                    };
                    Root = rslr.Positions.Select(p => FileNameHandling.GetDirectoryPathWithTailingSeparator(FileNameHandling.GetFileDirectory(p.Value.Text.Path))).Aggregate((a, b) => GetCommonHead(a, b));
                    if (Root != FileNameHandling.GetDirectoryPathWithTailingSeparator(Root))
                    {
                        Root = FileNameHandling.GetFileDirectory(Root);
                    }
                }

                var Map = Schema.GetMap().ToDictionary(p => p.Key, p => p.Value);

                foreach (var t in Schema.Types)
                {
                    if (t.OnQueryList)
                    {
                        continue;
                    }
                    var Name = t.Name();
                    var Path = "Default.tree";
                    if (rslr.Positions.ContainsKey(t))
                    {
                        Path = FileNameHandling.GetRelativePath(rslr.Positions[t].Text.Path, Root);
                    }
                    var PathWithoutExt = FileNameHandling.GetPath(FileNameHandling.GetFileDirectory(Path), FileNameHandling.GetMainFileName(Path));
                    var DocFilePath    = PathWithoutExt.Replace(@"\", @"_").Replace(@"/", @"_").Replace(@".", "_").Replace(@":", @"_").Replace(@"#", @"_") + @".html";
                    var tli            = new TypeInfo {
                        Def = Map[Name], FriendlyPath = PathWithoutExt.Replace(@"\", @"/"), DocFilePath = DocFilePath, DocPath = String.Format("{0}#{1}", DocFilePath, Name)
                    };
                    TypeInfoDict.Add(Name, tli);
                }
            }
Exemple #4
0
        public static void ObjectSchemaToJavaBinaryCode(String JavaCodeDirPath, String PackageName)
        {
            var ObjectSchema  = GetObjectSchema();
            var CompiledFiles = ObjectSchema.CompileToJavaBinary(PackageName);

            foreach (var f in CompiledFiles)
            {
                var FilePath = FileNameHandling.GetPath(JavaCodeDirPath, f.Key.Replace('/', Path.DirectorySeparatorChar));
                var Compiled = f.Value;
                if (File.Exists(FilePath))
                {
                    var Original = Txt.ReadFile(FilePath);
                    if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                    {
                        continue;
                    }
                }
                var Dir = FileNameHandling.GetFileDirectory(FilePath);
                if (Dir != "" && !Directory.Exists(Dir))
                {
                    Directory.CreateDirectory(Dir);
                }
                Txt.WriteFile(FilePath, Compiled);
            }
        }
Exemple #5
0
        public static void TreeToBinary(String TreePath, String BinaryPath, String MainType)
        {
            var TypeName = ObjectSchemaExtensions.GetDotNetFullNameFromVersionedName(MainType);
            var a        = SchemaAssembly();
            var t        = a.GetType(TypeName);

            if (t == null)
            {
                throw new InvalidOperationException("TypeNotExist: " + TypeName);
            }
            var tbc = TreeBinaryConverter();

            var Data = TreeFile.ReadFile(TreePath);
            var b    = tbc.TreeToBinary(t, Data);
            var Dir  = FileNameHandling.GetFileDirectory(BinaryPath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            using (var s = Streams.CreateWritable(BinaryPath))
            {
                s.Write(b);
            }
        }
Exemple #6
0
        public static void SaveData(Schema s, String MemoryDatabaseFile, RelationVal Value, Firefly.Mapping.Binary.BinarySerializer bs)
        {
            var rvs = new RelationValueSerializer(s);

            var Dir = FileNameHandling.GetFileDirectory(MemoryDatabaseFile);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            using (var fs = Streams.CreateWritable(MemoryDatabaseFile))
            {
                fs.WriteSimpleString("KRUSDATA", 8);
                fs.WriteUInt64(s.Hash());
                var SchemaLengthPosition = fs.Position;
                fs.WriteInt64(0);
                var SchemaPosition = fs.Position;
                bs.Write(fs, s);
                var SchemaLength       = fs.Position - SchemaPosition;
                var DataLengthPosition = fs.Position;
                fs.WriteInt64(0);
                var DataPosition = fs.Position;
                rvs.Write(fs, Value);
                var DataLength = fs.Position - DataPosition;
                fs.Position = SchemaLengthPosition;
                fs.WriteInt64(SchemaLength);
                fs.Position = DataLengthPosition;
                fs.WriteInt64(DataLength);
            }
        }
Exemple #7
0
        public static void ObjectSchemaToXhtml(String XhtmlDir, String Title, String CopyrightText)
        {
            var oslr          = GetObjectSchemaLoaderResult();
            var CompiledFiles = oslr.CompileToXhtml(Title, CopyrightText);

            foreach (var f in CompiledFiles)
            {
                var Compiled = f.Content;
                var Path     = FileNameHandling.GetPath(XhtmlDir, f.Path);
                if (File.Exists(Path))
                {
                    var Original = Txt.ReadFile(Path);
                    if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                    {
                        continue;
                    }
                }
                var Dir = FileNameHandling.GetFileDirectory(Path);
                if (Dir != "" && !Directory.Exists(Dir))
                {
                    Directory.CreateDirectory(Dir);
                }
                Txt.WriteFile(Path, TextEncoding.UTF8, Compiled);
            }
        }
Exemple #8
0
        private static Func <String, IDbConnection> GetConnectionFactoryMySQL()
        {
            var Path = FileNameHandling.GetPath(FileNameHandling.GetFileDirectory(Assembly.GetEntryAssembly().Location), "MySql.Data.dll");
            var asm  = Assembly.Load(AssemblyName.GetAssemblyName(Path));
            var t    = asm.GetType("MySql.Data.MySqlClient.MySqlConnection");

            return(ConnectionString => (IDbConnection)Activator.CreateInstance(t, ConnectionString));
        }
Exemple #9
0
        public static void DumpSyntaxResult(String InputDirectory, String OutputDirectory)
        {
            var Files = new Dictionary <String, FileParserResult>();

            foreach (var FilePath in Directory.EnumerateFiles(InputDirectory, "*.tree", SearchOption.AllDirectories))
            {
                var AbsolutePath = FileNameHandling.GetAbsolutePath(FilePath, System.Environment.CurrentDirectory);
                var FileContent  = Txt.ReadFile(FilePath);
                var Text         = TokenParser.BuildText(FileContent, AbsolutePath);
                var Result       = FileParser.ParseFile(Text);
                Files.Add(AbsolutePath, Result);
            }

            //var arr = AmbiguousRemover.Reduce(Files, new List<String> { }, new TypeProvider());
            //if (arr.UnresolvableAmbiguousOrErrors.Count > 0)
            //{
            //    var l = new List<String> { };
            //    foreach (var p in arr.UnresolvableAmbiguousOrErrors)
            //    {
            //        var ErrorMessage = p.Key;
            //        var ErrorRange = p.Value;
            //        l.Add(p.Key + ": " + ErrorRange.Text.Path + (ErrorRange.Range.OnSome ? ": " + ErrorRange.Range.Value.ToString() : ""));
            //    }
            //    var OutputPath = FileNameHandling.GetPath(OutputDirectory, "Error.txt");
            //    var OutputDir = FileNameHandling.GetFileDirectory(OutputPath);
            //    if (!Directory.Exists(OutputDir)) { Directory.CreateDirectory(OutputDir); }
            //    Txt.WriteFile(OutputPath, String.Join("\r\n", l) + "\r\n");
            //    return;
            //}
            //Files = arr.Files;

            foreach (var p in Files)
            {
                var RelativePath = FileNameHandling.GetRelativePath(p.Key, FileNameHandling.GetAbsolutePath(InputDirectory, System.Environment.CurrentDirectory));
                var FileName     = FileNameHandling.GetFileName(p.Key);
                var fd           = new FileDumper();
                var Comment
                    = "==========================================================================" + "\r\n"
                      + "\r\n"
                      + "  SourceFile:  " + FileName + "\r\n"
                      + "\r\n"
                      + "==========================================================================";
                var f          = fd.Dump(p.Value, Comment);
                var OutputPath = FileNameHandling.GetPath(FileNameHandling.GetPath(OutputDirectory, FileNameHandling.GetFileDirectory(RelativePath)), FileNameHandling.GetMainFileName(FileName) + ".syn.tree");
                var OutputDir  = FileNameHandling.GetFileDirectory(OutputPath);
                if (!Directory.Exists(OutputDir))
                {
                    Directory.CreateDirectory(OutputDir);
                }
                TreeFile.WriteRaw(OutputPath, f);
            }
        }
Exemple #10
0
        public static void ExpressionSchemaToBinary(List <String> DataDirs, String BinaryPath)
        {
            var ExpressionSchema = GetExpressionSchema();
            var eal = new ExpressionAssemblyLoader(ExpressionSchema);

            foreach (var DataDir in DataDirs)
            {
                foreach (var tf in Directory.EnumerateFiles(DataDir, "*.tree", SearchOption.AllDirectories))
                {
                    eal.LoadAssembly(tf);
                }
            }
            var a  = eal.GetResult();
            var bs = BinarySerializerWithString.Create();

            Byte[] Compiled;
            using (var ms = Streams.CreateMemoryStream())
            {
                bs.Write(a, ms);
                ms.Position = 0;
                Compiled    = ms.Read((int)(ms.Length));
            }
            if (File.Exists(BinaryPath))
            {
                Byte[] Original;
                using (var fs = Streams.OpenReadable(BinaryPath))
                {
                    Original = fs.Read((int)(fs.Length));
                }
                if (Compiled.SequenceEqual(Original))
                {
                    return;
                }
            }
            var BinaryDir = FileNameHandling.GetFileDirectory(BinaryPath);

            if (BinaryDir != "" && !Directory.Exists(BinaryDir))
            {
                Directory.CreateDirectory(BinaryDir);
            }
            using (var fs = Streams.CreateWritable(BinaryPath))
            {
                fs.Write(Compiled);
            }
        }
Exemple #11
0
        public static void ObjectSchemaToCppBinaryCode(String CppCodePath, String NamespaceName, Boolean WithServer, Boolean WithClient)
        {
            var ObjectSchema = GetObjectSchema();
            var Compiled     = ObjectSchema.CompileToCppBinary(NamespaceName, WithServer, WithClient);

            if (File.Exists(CppCodePath))
            {
                var Original = Txt.ReadFile(CppCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CppCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CppCodePath, Compiled);
        }
Exemple #12
0
        public static void ObjectSchemaToCSharpVersionCode(String CsCodePath, String NamespaceName, IEnumerable <String> TypeNames)
        {
            var ObjectSchema = GetObjectSchema();
            var Compiled     = ObjectSchema.CompileToCSharpVersion(NamespaceName, TypeNames);

            if (File.Exists(CsCodePath))
            {
                var Original = Txt.ReadFile(CsCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CsCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CsCodePath, Compiled);
        }
Exemple #13
0
        public static void RelationSchemaToCSharpDatabasePlainCode(String CsCodePath, String EntityNamespaceName, Boolean WithFirefly)
        {
            var RelationSchema = GetRelationSchema();
            var Compiled       = RelationSchema.CompileToCSharpPlain(EntityNamespaceName, WithFirefly);

            if (File.Exists(CsCodePath))
            {
                var Original = Txt.ReadFile(CsCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CsCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CsCodePath, Compiled);
        }
Exemple #14
0
        public static void ObjectSchemaToPythonBinaryCode(String PythonCodePath)
        {
            var ObjectSchema = GetObjectSchema();
            var Compiled     = ObjectSchema.CompileToPythonBinary();

            if (File.Exists(PythonCodePath))
            {
                var Original = Txt.ReadFile(PythonCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(PythonCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(PythonCodePath, Compiled);
        }
Exemple #15
0
        public static void GenerateSchemaDiff(String MemoryDatabaseFileOld, String MemoryDatabaseFileNew, String SchemaDiffFile)
        {
            var bs        = Niveum.ObjectSchema.BinarySerializerWithString.Create();
            var SchemaOld = LoadSchema(MemoryDatabaseFileOld, bs);
            var SchemaNew = LoadSchema(MemoryDatabaseFileNew, bs);

            var Dir = FileNameHandling.GetFileDirectory(SchemaDiffFile);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }

            var d = RelationSchemaDiffGenerator.Generate(SchemaOld, SchemaNew);

            RelationSchemaDiffVerifier.Verifiy(SchemaOld, SchemaNew, d.Mappings);
            using (var sw = Txt.CreateTextWriter(SchemaDiffFile))
            {
                RelationSchemaDiffWriter.Write(sw, d);
            }
        }
Exemple #16
0
        public static void ObjectSchemaToCSharpCompatibleCode(String CsCodePath, String NamespaceName, String ImplementationNamespaceName, String ImplementationClassName)
        {
            var ObjectSchema = GetObjectSchema();
            var Compiled     = ObjectSchema.CompileToCSharpCompatible(NamespaceName, ImplementationNamespaceName, ImplementationClassName);

            if (File.Exists(CsCodePath))
            {
                var Original = Txt.ReadFile(CsCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CsCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CsCodePath, Compiled);
        }
Exemple #17
0
        public static void RelationSchemaToMySqlCode(String SqlCodePath, String DatabaseName)
        {
            var RelationSchema = GetRelationSchema();
            var Compiled       = RelationSchema.CompileToMySql(DatabaseName, true);

            if (File.Exists(SqlCodePath))
            {
                var Original = Txt.ReadFile(SqlCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var SqlCodeDir = FileNameHandling.GetFileDirectory(SqlCodePath);

            if (SqlCodeDir != "" && !Directory.Exists(SqlCodeDir))
            {
                Directory.CreateDirectory(SqlCodeDir);
            }
            Txt.WriteFile(SqlCodePath, Compiled);
        }
Exemple #18
0
        public static void RelationSchemaToCppDatabaseMemoryCode(String CppCodePath, String EntityNamespaceName, String ContextNamespaceName)
        {
            var RelationSchema = GetRelationSchema();
            var Compiled       = RelationSchema.CompileToCppMemory(EntityNamespaceName, ContextNamespaceName);

            if (File.Exists(CppCodePath))
            {
                var Original = Txt.ReadFile(CppCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CppCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CppCodePath, Compiled);
        }
Exemple #19
0
        public static void ExpressionSchemaToCppBinaryLoaderCode(String CppCodePath, String NamespaceName)
        {
            var ExpressionSchema = GetExpressionSchema();
            var Compiled         = ExpressionSchema.CompileToCppBinaryLoader(NamespaceName);

            if (File.Exists(CppCodePath))
            {
                var Original = Txt.ReadFile(CppCodePath);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CppCodePath);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CppCodePath, Compiled);
        }
Exemple #20
0
        public static void WriteLog(String Path, String Text)
        {
            var Dir = FileNameHandling.GetFileDirectory(Path);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            String[] Lines;
            if (!Text.Contains('\n'))
            {
                Lines = new String[] { Text };
            }
            else
            {
                var l = new List <String>();
                l.Add("****************");
                foreach (var m in Text.UnifyNewLineToLf().Split('\n'))
                {
                    l.Add(m);
                }
                l.Add("****************");
                Lines = l.ToArray();
            }
            var e = Encoding.UTF8;

            if (File.Exists(Path))
            {
                e = Txt.GetEncoding(Path, e);
            }
            using (var r = new StreamWriter(Path, true, e))
            {
                foreach (var Line in Lines)
                {
                    r.WriteLine(Line);
                }
            }
        }
Exemple #21
0
        public static void ApplySchemaDiff(String MemoryDatabaseFileOld, String MemoryDatabaseFileNew, String SchemaDiffFile, String MemoryDatabaseFileOutput)
        {
            var    bs = Niveum.ObjectSchema.BinarySerializerWithString.Create();
            Schema SchemaOld;
            var    SchemaNew = LoadSchema(MemoryDatabaseFileNew, bs);

            var Loader = new RelationSchemaDiffLoader(SchemaNew);

            Loader.LoadType(SchemaDiffFile);
            var l = Loader.GetResult();

            using (var fs = Streams.OpenReadable(MemoryDatabaseFileOld))
            {
                if (fs.ReadSimpleString(8) != "KRUSDATA")
                {
                    throw new InvalidOperationException("FileFormatMismatch");
                }
                fs.ReadUInt64();
                var OldSchemaLength = fs.ReadInt64();
                if (OldSchemaLength == 0)
                {
                    throw new InvalidOperationException("FileContainsNoSchema");
                }
                var OldSchemaPosition = fs.Position;
                SchemaOld = bs.Read <Schema>(fs);
                if (fs.Position != OldSchemaPosition + OldSchemaLength)
                {
                    throw new InvalidOperationException();
                }
                fs.ReadInt64();

                RelationSchemaDiffVerifier.Verifiy(SchemaOld, SchemaNew, l);
                var orvs = new RelationValueSerializer(SchemaOld);
                var nrvs = new RelationValueSerializer(SchemaNew);

                var OldEntities          = SchemaOld.Types.Where(t => t.OnEntity).Select(t => t.Entity).ToList();
                var OldEntityNameToIndex = OldEntities.Select((e, i) => new KeyValuePair <String, int>(e.Name, i)).ToDictionary(p => p.Key, p => p.Value);
                var NewEntities          = SchemaNew.Types.Where(t => t.OnEntity).Select(t => t.Entity).ToList();
                var dt = new RelationSchemaDiffTranslator(SchemaOld, SchemaNew, l);

                var Dir = FileNameHandling.GetFileDirectory(MemoryDatabaseFileOutput);
                if (Dir != "" && !Directory.Exists(Dir))
                {
                    Directory.CreateDirectory(Dir);
                }

                var OldEntityCount = OldEntities.Count;

                var Positions = new Dictionary <int, Int64>();
                var CurrentEntityTableIndex = 0;
                var CurrentCount            = 0;
                if (OldEntityCount > 0)
                {
                    Positions.Add(0, fs.Position);
                    CurrentCount = fs.ReadInt32();
                }
                Action <int> AdvanceTo = EntityTableIndex =>
                {
                    if (Positions.ContainsKey(EntityTableIndex))
                    {
                        fs.Position             = Positions[EntityTableIndex];
                        CurrentEntityTableIndex = EntityTableIndex;
                        CurrentCount            = fs.ReadInt32();
                    }
                    else
                    {
                        if ((EntityTableIndex < 0) || (EntityTableIndex >= OldEntityCount))
                        {
                            throw new InvalidOperationException();
                        }
                        while (CurrentEntityTableIndex < EntityTableIndex)
                        {
                            var rr = orvs.GetRowReader(OldEntities[CurrentEntityTableIndex]);
                            while (CurrentCount > 0)
                            {
                                rr(fs);
                                CurrentCount -= 1;
                            }
                            CurrentEntityTableIndex += 1;
                            if (CurrentEntityTableIndex >= OldEntityCount)
                            {
                                break;
                            }
                            Positions.Add(CurrentEntityTableIndex, fs.Position);
                            CurrentCount = fs.ReadInt32();
                        }
                    }
                };

                using (var fso = Streams.CreateResizable(MemoryDatabaseFileOutput))
                {
                    fso.WriteSimpleString("KRUSDATA", 8);
                    fso.WriteUInt64(SchemaNew.Hash());
                    var SchemaLengthPosition = fso.Position;
                    fso.WriteInt64(0);
                    var SchemaPosition = fso.Position;
                    bs.Write(SchemaNew, fso);
                    var SchemaLength       = fso.Position - SchemaPosition;
                    var DataLengthPosition = fso.Position;
                    fso.WriteInt64(0);
                    var DataPosition = fso.Position;

                    foreach (var ne in NewEntities)
                    {
                        var oOldEntityName = dt.GetOldEntityName(ne.Name);
                        if (oOldEntityName.OnNone)
                        {
                            fso.WriteInt32(0);
                            continue;
                        }
                        var Index = OldEntityNameToIndex[oOldEntityName.Some];
                        var rr    = orvs.GetRowReader(OldEntities[Index]);
                        var rw    = nrvs.GetRowWriter(ne);
                        var t     = dt.GetTranslator(ne.Name);
                        AdvanceTo(Index);

                        fso.WriteInt32(CurrentCount);
                        while (CurrentCount > 0)
                        {
                            rw(fso, t(rr(fs)));
                            CurrentCount -= 1;
                        }
                    }

                    var DataLength = fso.Position - DataPosition;
                    fso.Position = SchemaLengthPosition;
                    fso.WriteInt64(SchemaLength);
                    fso.Position = DataLengthPosition;
                    fso.WriteInt64(DataLength);
                }
            }
        }
Exemple #22
0
        public static void GenerateTypeCompatibilityTreeFile(List <KeyValuePair <String, String> > ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion, String CompatibilityObjectSchemaFile, bool CommunicationOnly = false)
        {
            var HeadObjectSchema = GetObjectSchema();
            var HeadSchema       = HeadObjectSchema.GetSubSchema(HeadObjectSchema.Types.Where(t => (!CommunicationOnly || (t.OnPrimitive || t.OnClientCommand || t.OnServerCommand)) && (t.Version() == "")), new TypeSpec[] { });
            var Versions         = ListOfObjectSchemaDirOrCookedObjectSchemaFileAndVersion.Select(p =>
            {
                var vosl = new ObjectSchemaLoader();
                if (File.Exists(p.Key))
                {
                    vosl.LoadSchema(p.Key);
                }
                else if (Directory.Exists(p.Key))
                {
                    foreach (var f in Directory.GetFiles(p.Key, "*.tree", SearchOption.AllDirectories).OrderBy(s => s, StringComparer.OrdinalIgnoreCase))
                    {
                        vosl.LoadType(f);
                    }
                }
                else
                {
                    throw new InvalidOperationException("InvalidPath: " + p.Key);
                }
                var Schema = vosl.GetResult().Schema;
                return(new KeyValuePair <String, Schema>(p.Value, Schema.GetSubSchema(Schema.Types.Where(t => (!CommunicationOnly || (t.OnPrimitive || t.OnClientCommand || t.OnServerCommand)) && (t.Version() == "")), new TypeSpec[] { })));
            }).ToList();

            var Comment = ""
                          + @"==========================================================================" + "\r\n"
                          + @"" + "\r\n"
                          + @"  Notice:      This file is automatically generated." + "\r\n"
                          + @"               Please don't modify this file." + "\r\n"
                          + @"" + "\r\n"
                          + @"  SchemaHash: Head 0x" + HeadSchema.GetNonattributed().Hash().ToString("X16") + "\r\n"
                          + String.Join("", Versions.AsEnumerable().Reverse().Select(v => @"              " + v.Key + " 0x" + v.Value.GetNonattributed().Hash().ToString("X16") + "\r\n"))
                          + @"" + "\r\n"
                          + @"==========================================================================" + "\r\n"
            ;

            var DiffGenerator = new ObjectSchemaDiffGenerator();
            var Result        = DiffGenerator.GetCompatibleTypes(Versions.Concat(new List <KeyValuePair <String, Schema> > {
                new KeyValuePair <String, Schema>("", HeadSchema)
            }).ToList());

            var osw      = new ObjectSchemaWriter();
            var Compiled = osw.Write(Result, Comment);

            if (File.Exists(CompatibilityObjectSchemaFile))
            {
                var Original = Txt.ReadFile(CompatibilityObjectSchemaFile);
                if (String.Equals(Compiled, Original, StringComparison.Ordinal))
                {
                    return;
                }
            }
            var Dir = FileNameHandling.GetFileDirectory(CompatibilityObjectSchemaFile);

            if (Dir != "" && !Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            Txt.WriteFile(CompatibilityObjectSchemaFile, TextEncoding.UTF8, Compiled);
        }
Exemple #23
0
 public void SaveAll()
 {
     lock (SaveLockee)
     {
         var InstancesSnapshot = new List <Lazy <InstanceInfo> >();
         lock (Instances)
         {
             InstancesSnapshot = Instances.Values.ToList();
         }
         foreach (var p in InstancesSnapshot)
         {
             var      i = p.Value;
             DateTime Time;
             Version  Version;
             using (var da = new KrustallosDataAccess(i.Instance, i.Data, IsolationLevel.Snapshot, (ITransactionLock)(null)))
             {
                 Version = da.GetReaderVersion();
                 Time    = DateTime.UtcNow;
                 var Dir = FileNameHandling.GetFileDirectory(i.FilePath);
                 if (!Directory.Exists(Dir))
                 {
                     Directory.CreateDirectory(Dir);
                 }
                 using (var s = new ReliableFileWriteStream(i.FilePath))
                 {
                     da.Save(i.sbs, i.bs, s, i.Schema);
                 }
             }
             if (i.BackupDir != "")
             {
                 if (!Directory.Exists(i.BackupDir))
                 {
                     Directory.CreateDirectory(i.BackupDir);
                 }
                 var FileName = FileNameHandling.GetFileName(i.FilePath);
                 var FilePath = FileNameHandling.GetPath(i.BackupDir, FileNameHandling.GetMainFileName(FileName) + Time.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture) + "-" + Version.ToString() + "." + FileNameHandling.GetExtendedFileName(FileName));
                 if (!File.Exists(FilePath))
                 {
                     File.Copy(i.FilePath, FilePath + ".new", true);
                     File.Move(FilePath + ".new", FilePath);
                 }
                 if (i.MaxBackupCount.OnSome)
                 {
                     var MaxBackupCount = i.MaxBackupCount.Value;
                     var FilesToDelete  = new List <String>();
                     var FilePaths      = new SortedSet <String>(StringComparer.OrdinalIgnoreCase);
                     foreach (var f in Directory.EnumerateFiles(i.BackupDir, "*", SearchOption.TopDirectoryOnly))
                     {
                         FilePaths.Add(f);
                         while (FilePaths.Count > MaxBackupCount)
                         {
                             var First = FilePaths.First();
                             FilePaths.Remove(First);
                             FilesToDelete.Add(First);
                         }
                     }
                     foreach (var f in FilesToDelete)
                     {
                         if (File.Exists(f))
                         {
                             try
                             {
                                 File.Delete(f);
                             }
                             catch
                             {
                             }
                         }
                     }
                 }
             }
         }
     }
 }