示例#1
0
        public static void Look <T>(ref T[] list, string label, params object[] ctorArgs) where T : IExposable
        {
            if (Scribe.EnterNode(label) == false)
            {
                return;
            }

            try
            {
                if (Scribe.mode == LoadSaveMode.Saving)
                {
                    if (list == null)
                    {
                        Scribe.saver.WriteAttribute("IsNull", "True");
                    }
                    else
                    {
                        foreach (var current in list)
                        {
                            var t2 = current;
                            Scribe_Deep.Look <T>(ref t2, false, "li", ctorArgs);
                        }
                    }
                }
                else if (Scribe.mode == LoadSaveMode.LoadingVars)
                {
                    var curXmlParent = Scribe.loader.curXmlParent;
                    var xmlAttribute = curXmlParent.Attributes["IsNull"];
                    if (xmlAttribute != null && xmlAttribute.Value.ToLower() == "true")
                    {
                        list = null;
                    }
                    else
                    {
                        list = new T[curXmlParent.ChildNodes.Count];
                        var i = 0;
                        foreach (var subNode2 in curXmlParent.ChildNodes)
                        {
                            list[i++] = ScribeExtractor.SaveableFromNode <T>((XmlNode)subNode2, ctorArgs);
                        }
                    }
                }
            }
            finally
            {
                Scribe.ExitNode();
            }
        }
        public static bool Prefix(ScribeSaver __instance, string filePath, string documentElementName)
        {
            if (!Enable)
            {
                return(true);
            }

            Loger.Log("ScribeSaver_InitSaving_Patch Start");
            var that = Traverse.Create(__instance);

            if (Scribe.mode != 0)
            {
                Log.Error("Called InitSaving() but current mode is " + Scribe.mode);
                Scribe.ForceStop();
            }
            if (that.Field("curPath").GetValue <string>() != null)
            {
                Log.Error("Current path is not null in InitSaving");
                that.Field("curPath").SetValue(null);
                that.Field("savedNodes").GetValue <HashSet <string> >().Clear();
                that.Field("nextListElementTemporaryId").SetValue(0);
            }
            try
            {
                Scribe.mode = LoadSaveMode.Saving;
                var saveStream = SaveData = new MemoryStream();
                //var saveStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                File.WriteAllText(filePath, "Online save");
                that.Field("saveStream").SetValue(saveStream);

                XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
                xmlWriterSettings.Indent      = true;
                xmlWriterSettings.IndentChars = "\t";
                var writer = XmlWriter.Create(saveStream, xmlWriterSettings);
                that.Field("writer").SetValue(writer);

                writer.WriteStartDocument();
                __instance.EnterNode(documentElementName);
            }
            catch (Exception ex)
            {
                Log.Error("Exception while init saving file: " + filePath + "\n" + ex);
                __instance.ForceStop();
                throw;
            }
            Loger.Log("ScribeSaver_InitSaving_Patch End");
            return(false);
        }
示例#3
0
        static void Main()
        {
            var scribe = new Scribe(new PersistedOptions
            {
                DirPath               = "ScribedEvents",
                StreamSource          = new FileStreamSource("ScribedEvents"),
                MaxTimeToWaitForFlush = TimeSpan.FromMilliseconds(200)
            });

            var sp = Stopwatch.StartNew();

            Task.Factory.StartNew(() =>
            {
                while (run)
                {
                    Console.WriteLine("{0:#,#} in {1:#,#} ms", count, sp.ElapsedMilliseconds);
                    Thread.Sleep(500);
                }
            });
            var data = new UserCreated {
                UserId = Guid.NewGuid(), Name = "Ayende"
            };

            Parallel.For(0, 1000 * 10, i =>
            {
                var tasks = new Task[1000];
                for (int j = 0; j < 1000; j++)
                {
                    tasks[j] = scribe.EnqueueEventAsync("users/" + j, data);
                    Interlocked.Increment(ref count);
                }
                Task.WaitAll(tasks);
            });

            run = false;

            Console.WriteLine(sp.ElapsedMilliseconds);

            for (int i = 124; i < 1000 * 10; i += 1293)
            {
                sp.Restart();

                scribe.ReadRaw("users/" + i).Count();

                Console.WriteLine(i + " " + sp.ElapsedMilliseconds);
            }
        }
        private void                    ExposeDataSave()
        {
            bool hidden;

            foreach (var minimap in Controller.Data.MiniMaps)
            {
                #region Minimap Header
                if (!Scribe.EnterNode(minimap.SaveKey))
                {
                    continue;
                }
                #endregion

                hidden = minimap.Hidden;
                Scribe_Values.LookValue(ref hidden, "hidden", minimap.miniMapDef.hiddenByDefault, true);

                #region Handle all MiniMap Overlays

                foreach (var overlay in minimap.overlayWorkers)
                {
                    #region Overlay Header
                    var saveKey = overlay.SaveKey;
                    if (
                        (string.IsNullOrEmpty(saveKey)) ||
                        (!Scribe.EnterNode(overlay.SaveKey))
                        )
                    {
                        continue;
                    }
                    #endregion

                    hidden = overlay.Hidden;
                    Scribe_Values.LookValue(ref hidden, "hidden", overlay.overlayDef.hiddenByDefault, true);

                    #region Finalize Overlay
                    Scribe.ExitNode();
                    #endregion
                }

                #endregion

                #region Finalize Minimap
                Scribe.ExitNode();
                #endregion
            }
        }
        public static bool Prefix(ScribeLoader __instance, string filePath)
        {
            if (!ScribeLoader_InitLoading_Patch.Enable)
            {
                return(true);
            }
            Loger.Log("ScribeLoader_InitLoadingMetaHeaderOnly_Patch Start");

            if (Scribe.mode != 0)
            {
                Log.Error("Called InitLoadingMetaHeaderOnly() but current mode is " + Scribe.mode);
                Scribe.ForceStop();
            }
            try
            {
                using (var input = new MemoryStream(ScribeLoader_InitLoading_Patch.LoadData))
                //using (StreamReader input = new StreamReader(filePath))
                {
                    using (XmlTextReader xmlTextReader = new XmlTextReader(input))
                    {
                        if (!ScribeMetaHeaderUtility.ReadToMetaElement(xmlTextReader))
                        {
                            return(false);
                        }
                        using (XmlReader reader = xmlTextReader.ReadSubtree())
                        {
                            XmlDocument xmlDocument = new XmlDocument();
                            xmlDocument.Load(reader);
                            XmlElement xmlElement = xmlDocument.CreateElement("root");
                            xmlElement.AppendChild(xmlDocument.DocumentElement);
                            __instance.curXmlParent = xmlElement;
                        }
                    }
                }
                Scribe.mode = LoadSaveMode.LoadingVars;
            }
            catch (Exception ex)
            {
                Log.Error("Exception while init loading meta header: " + filePath + "\n" + ex);
                __instance.ForceStop();
                throw;
            }

            Loger.Log("ScribeLoader_InitLoadingMetaHeaderOnly_Patch End");
            return(false);
        }
 public override void PostExposeData()
 {
     base.PostExposeData();
     Scribe.EnterNode("CompUpgrade_" + Props.referenceId);
     Scribe_Values.Look(ref complete, "complete");
     if (!(Scribe.mode == LoadSaveMode.Saving && complete))
     {
         Scribe_Values.Look(ref workDone, "workDone");
         Scribe_Values.Look(ref wantsWork, "wantsWork");
         Scribe_Deep.Look(ref ingredients, "ingredients", this);
     }
     if (ingredients == null)
     {
         ingredients = new ThingOwner <Thing>(this);
     }
     Scribe.ExitNode();
 }
示例#7
0
        static bool Prefix()
        {
            if (gameToLoad == null)
            {
                return(true);
            }

            SaveCompression.doSaveCompression = true;

            try
            {
                ScribeUtil.StartLoading(gameToLoad.SaveData);
                ScribeMetaHeaderUtility.LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode.Map, false);
                Scribe.EnterNode("game");
                Current.Game = new Game();
                Current.Game.LoadGame(); // calls Scribe.loader.FinalizeLoading()
                SemiPersistent.ReadSemiPersistent(gameToLoad.SemiPersistent);
            }
            finally
            {
                SaveCompression.doSaveCompression = false;
                gameToLoad = null;
            }

            Log.Message("Game loaded");

            if (Multiplayer.Client != null)
            {
                LongEventHandler.ExecuteWhenFinished(() =>
                {
                    // Inits all caches
                    foreach (ITickable tickable in TickPatch.AllTickables.Where(t => !(t is ConstantTicker)))
                    {
                        tickable.Tick();
                    }

                    if (!Current.Game.Maps.Any())
                    {
                        MemoryUtility.UnloadUnusedUnityAssets();
                        Find.World.renderer.RegenerateAllLayersNow();
                    }
                });
            }

            return(false);
        }
示例#8
0
        //
        // Static Methods
        //
        public static void SaveToFile(PrepareCarefully data, string presetName)
        {
            try {
                Scribe.InitWriting(PresetFiles.FilePathForSavedPreset(presetName), "preset");
                string versionStringFull = "3";
                Scribe_Values.LookValue <string>(ref versionStringFull, "version", null, false);
                bool usePoints      = data.Config.pointsEnabled;
                int  startingPoints = PrepareCarefully.Instance.StartingPoints;
                Scribe_Values.LookValue <bool>(ref usePoints, "usePoints", false, true);
                Scribe_Values.LookValue <int>(ref startingPoints, "startingPoints", 0, true);
                string modString = GenText.ToCommaList(Enumerable.Select <ModContentPack, string>(LoadedModManager.RunningMods, (Func <ModContentPack, string>)(mod => mod.Name)), true);
                Scribe_Values.LookValue <string>(ref modString, "mods", null, false);
                Scribe.EnterNode("colonists");
                foreach (CustomPawn customPawn in data.Pawns)
                {
                    SaveRecordPawnV3 pawn = new SaveRecordPawnV3(customPawn);
                    Scribe_Deep.LookDeep <SaveRecordPawnV3>(ref pawn, "colonist");
                }
                Scribe.ExitNode();

                Scribe.EnterNode("relationships");
                foreach (var r in data.RelationshipManager.ExplicitRelationships)
                {
                    SaveRecordRelationshipV3 s = new SaveRecordRelationshipV3(r);
                    Scribe_Deep.LookDeep <SaveRecordRelationshipV3>(ref s, "relationship");
                }
                Scribe.ExitNode();

                Scribe.EnterNode("equipment");
                foreach (var e in data.Equipment)
                {
                    SelectedEquipment customPawn = e;
                    Scribe_Deep.LookDeep <SelectedEquipment>(ref customPawn, "equipment");
                }
                Scribe.ExitNode();
            }
            catch (Exception e) {
                Log.Error("Failed to save preset file");
                throw e;
            }
            finally {
                Scribe.FinalizeWriting();
                Scribe.mode = LoadSaveMode.Inactive;
            }
        }
 public static bool Prefix(ScribeLoader __instance, string filePath)
 {
     if (!Enable)
     {
         return(true);
     }
     Loger.Log("ScribeLoader_InitLoading_Patch Start");
     if (Scribe.mode != 0)
     {
         Log.Error("Called InitLoading() but current mode is " + Scribe.mode);
         Scribe.ForceStop();
     }
     if (__instance.curParent != null)
     {
         Log.Error("Current parent is not null in InitLoading");
         __instance.curParent = null;
     }
     if (__instance.curPathRelToParent != null)
     {
         Log.Error("Current path relative to parent is not null in InitLoading");
         __instance.curPathRelToParent = null;
     }
     try
     {
         using (var input = new MemoryStream(LoadData))
         //using (StreamReader input = new StreamReader(filePath))
         {
             using (XmlTextReader reader = new XmlTextReader(input))
             {
                 XmlDocument xmlDocument = new XmlDocument();
                 xmlDocument.Load(reader);
                 __instance.curXmlParent = xmlDocument.DocumentElement;
             }
         }
         Scribe.mode = LoadSaveMode.LoadingVars;
     }
     catch (Exception ex)
     {
         Log.Error("Exception while init loading file: " + filePath + "\n" + ex);
         __instance.ForceStop();
         throw;
     }
     Loger.Log("ScribeLoader_InitLoading_Patch End");
     return(false);
 }
        public bool Load(PrepareCarefully loadout, Page_ConfigureStartingPawnsCarefully charMakerPage, string colonistName)
        {
            SaveRecordPawnV3 pawnRecord = new SaveRecordPawnV3();
            string           modString  = "";
            string           version    = "";

            try {
                Scribe.InitLoading(ColonistFiles.FilePathForSavedColonist(colonistName));
                Scribe_Values.LookValue <string>(ref version, "version", "unknown", false);
                Scribe_Values.LookValue <string>(ref modString, "mods", "", false);

                try {
                    Scribe_Deep.LookDeep <SaveRecordPawnV3>(ref pawnRecord, "colonist", null);
                }
                catch (Exception e) {
                    Messages.Message(modString, MessageSound.Silent);
                    Messages.Message("EdB.ColonistLoadFailed".Translate(), MessageSound.RejectInput);
                    Log.Warning(e.ToString());
                    Log.Warning("Colonist was created with the following mods: " + modString);
                    return(false);
                }
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                Scribe.mode = LoadSaveMode.Inactive;
            }

            PresetLoaderVersion3 loader = new PresetLoaderVersion3();

            charMakerPage.AddColonist(loader.LoadPawn(pawnRecord));
            if (loader.Failed)
            {
                Messages.Message(loader.ModString, MessageSound.Silent);
                Messages.Message("EdB.ColonistThingDefFailed".Translate(), MessageSound.SeriousAlert);
                Log.Warning("Preset was created with the following mods: " + modString);
                return(false);
            }

            return(true);
        }
示例#11
0
        public void Scibe_Write_Property_With_Custom_Padding_No_Char_Supplied_Writes_Values()
        {
            var expected = "ZZZ  ";

            var fieldFormatter = new FieldFormatter();
            var business       = new BusinessWithPropertyThatUsesCustomerPaddingNoPaddingChar()
            {
                BusinessDBA = "ZZZ"
            };

            using (var writer = new StringWriter())
            {
                IScribe scribe = new Scribe(writer, fieldFormatter);
                scribe.Write(business);
                var actual = writer.ToString();

                Assert.Equal(expected, actual);
            }
        }
示例#12
0
        public void Scibe_Write_Property_With_Custom_Char_Writes()
        {
            var expected = "ZZZZZXXXXX";

            var fieldFormatter = new FieldFormatter();
            var business       = new BusinessWithPropertyThatUsesCustomPadding()
            {
                BusinessName = "ZZZZZ"
            };

            using (var writer = new StringWriter())
            {
                IScribe scribe = new Scribe(writer, fieldFormatter);
                scribe.Write(business);
                var actual = writer.ToString();

                Assert.Equal(expected, actual);
            }
        }
示例#13
0
        public static void InitLoading(string[] filePaths)
        {
            if (Scribe.mode != LoadSaveMode.Inactive)
            {
                Log.Error("Called InitLoading() but current mode is " + Scribe.mode.ToString(), false);
                Scribe.ForceStop();
            }

            try
            {
                foreach (var filePath in filePaths)
                {
                    if (xmlParents.ContainsKey(filePath))
                    {
                        continue;
                    }

                    using (var streamReader = new StreamReader(filePath))
                    {
                        using (var xmlTextReader = new XmlTextReader(streamReader))
                        {
                            var xmlDocument = new XmlDocument();
                            xmlDocument.Load(xmlTextReader);
                            xmlParents.Add(filePath, xmlDocument.DocumentElement);
                        }
                    }
                }

                Scribe.mode = LoadSaveMode.LoadingVars;
            }
            catch (Exception e)
            {
                Log.Error(string.Concat(new object[]
                {
                    "Exception while init loading files: ",
                    filePaths.ToCommaList(),
                    "\n",
                    e
                }), false);

                throw;
            }
        }
示例#14
0
        private static void Main(string[] args)
        {
            Village  nile    = new Village("Nile River");
            Egyptian f1      = new FarmerSlave("Pashedu", "Farmer");
            Egyptian f2      = new FarmerSlave("Nykara", "Farmer");
            Egyptian c1      = new Craftsmen("Nikaure", "Craftsmen");
            Egyptian c2      = new Craftsmen("Djedi", "Craftsmen");
            Egyptian m1      = new Merchant("Paser", "Merchant");
            Egyptian scr1    = new Scribe("Pipi", "Scribe");
            Egyptian sld1    = new Soldier("Qen", "Soldier");
            Egyptian sld2    = new Soldier("Shoshenq", "Soldier");
            Egyptian pr1     = new PriestNoblesOfficials("Wennefer", "Priest");
            Egyptian pr2     = new PriestNoblesOfficials("Siese", "Treasurer");
            Egyptian pr3     = new PriestNoblesOfficials("Djedptahiufankh", "Prophet");
            Egyptian pharaoh = new Pharaoh("Tutankhamun", "Pharaoh");

            c1.Work();
            Console.WriteLine(pharaoh.ToString());
        }
示例#15
0
        static ColonyLeadership()
        {
            try
            {
                Detour.Detours.TryDetourFromTo(typeof(ColonistBarColonistDrawer).GetMethod("DrawIcons", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance), typeof(Icon).GetMethod("DrawIconsModded"));
            }
            catch (Exception e)
            {
                //File.WriteAllText("logt.txt", e.Message.ToString());
            }

            govtypes.Add(new GovType("Democracy", "DemocracyDesc", "Leader"));
            govtypes.Add(new GovType("Dictatorship", "DictatorshipDesc", "Dictator"));
            //govtypes.Add(new GovType("Monarchy", "MonarchyDesc", "Ruler"));
            bool flag = File.Exists(Path.Combine(GenFilePaths.SaveDataFolderPath, "ColonyLeadershipGlobal.xml"));

            if (flag)
            {
                try
                {
                    Scribe.loader.InitLoading(Path.Combine(GenFilePaths.SaveDataFolderPath, "ColonyLeadershipGlobal.xml"));
                    Scribe_Values.Look <String>(ref lastReadVersion, "lastReadVersion", "none", false);
                    Scribe.loader.FinalizeLoading();


                    //PostLoadIniter.DoAllPostLoadInits();
                }
                catch (Exception ex)
                {
                    //File.WriteAllText("logt.txt", ex.Message.ToString());
                    Log.Error("Exception loading colony leadership userdata: " + ex.ToString());
                    Scribe.ForceStop();
                }
            }

            if (ColonyLeadership.lastReadVersion != ColonyLeadership.newVersion)
            {
                DefDatabase <MainButtonDef> .GetNamed("LeaderTab").label = "(!) " + "LeadershipTab";

                doUpdateNotes();
            }
            doHelpNotes();
        }
示例#16
0
 public static void SaveToFile(ref Blueprint bp, string fileName)
 {
     try
     {
         Scribe.InitWriting(BlueprintFiles.FilePathForSavedBlueprint(fileName), "blueprint");
         bp.BpName = fileName;
         Scribe_Deep.LookDeep(ref bp, "Blueprint");
     }
     catch (Exception e)
     {
         Log.Error("Failed to save blueprint");
         throw e;
     }
     finally
     {
         Scribe.FinalizeWriting();
         Scribe.mode = LoadSaveMode.Inactive;
     }
 }
示例#17
0
        public override void PostExposeData()
        {
            base.PostExposeData();

            if (Scribe.EnterNode("animalGenetics"))
            {
                Scribe_References.Look(ref GeneticInformation, "geneticInformation");

                GenesRecord legacyGenesRecord = null;
                Scribe_Collections.Look(ref legacyGenesRecord, "geneRecords");
                if (legacyGenesRecord != null)
                {
                    LegacyGenesRecords[this] = legacyGenesRecord;
                }

                if (Scribe.mode == LoadSaveMode.PostLoadInit)
                {
                    if (GeneticInformation == null)
                    {
                        if (LegacyGenesRecords.ContainsKey(this))
                        {
                            Log.Message("Migrating Legacy Genetic Information for " + parent.ToString());
                            GeneticInformation = new GeneticInformation(LegacyGenesRecords[this]);
                            LegacyGenesRecords.Remove(this);
                        }
                        else
                        {
                            Log.Message("Generating Genetic Information for " + parent.ToString());
                            GeneticInformation = new GeneticInformation(null);
                        }
                        GeneticCalculator.EnsureAllGenesExist(GeneticInformation.GeneRecords, null, null);
                    }
                    else
                    {
                        GeneticCalculator.EnsureAllGenesExist(GeneticInformation.GeneRecords, GeneticInformation.Mother, GeneticInformation.Father);
                    }
                }

                Scribe.ExitNode();
            }
        }
示例#18
0
        public T FromXml <T>(string dataXML)
            where T : new()
        {
            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(dataXML);
            Scribe.loader.curXmlParent = xmlDocument.DocumentElement;
            Scribe.mode = LoadSaveMode.LoadingVars;
            try
            {
                Scribe.EnterNode(rootElementName);
                var thing = new T();
                Scribe_Deep.Look <T>(ref thing, "saveable", new object[0]);
                return(thing);
            }
            finally
            {
                //Finish()
                Scribe.loader.FinalizeLoading();
            }
        }
        //
        // Static Methods
        //
        public static void SaveToFile(PrepareCarefully loadout, Page_ConfigureStartingPawnsCarefully page, string colonistName)
        {
            try {
                Scribe.InitWriting(ColonistFiles.FilePathForSavedColonist(colonistName), "colonist");
                string versionStringFull = "3";
                Scribe_Values.LookValue <string>(ref versionStringFull, "version", null, false);
                string modString = GenText.ToCommaList(Enumerable.Select <ModContentPack, string>(LoadedModManager.RunningMods, (Func <ModContentPack, string>)(mod => mod.Name)), true);
                Scribe_Values.LookValue <string>(ref modString, "mods", null, false);

                SaveRecordPawnV3 pawn = new SaveRecordPawnV3(page.SelectedPawn);
                Scribe_Deep.LookDeep <SaveRecordPawnV3>(ref pawn, "colonist");
            }
            catch (Exception e) {
                Log.Error("Failed to save preset file");
                throw e;
            }
            finally {
                Scribe.FinalizeWriting();
                Scribe.mode = LoadSaveMode.Inactive;
            }
        }
示例#20
0
        public static bool HasPossibleSameWorldName(string[] names, string filePath)
        {
            var worldName = "";

            Scribe.loader.InitLoading(filePath);

            if (Scribe.EnterNode("game"))
            {
                if (Scribe.EnterNode("world"))
                {
                    if (Scribe.EnterNode("info"))
                    {
                        Scribe_Values.Look <string>(ref worldName, "name");
                    }
                }
            }

            Scribe.loader.ForceStop();

            return(names.Any(name => worldName.EqualsIgnoreCase(name)));
        }
示例#21
0
        public T FromXml <T>(string dataXML)
            where T : new()
        {
            lock (SuncObj)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(dataXML);
                Scribe.loader.curXmlParent = xmlDocument.DocumentElement;
                Scribe.mode = LoadSaveMode.LoadingVars;
                try
                {
                    /*
                     * bool flag = typeof(T).IsValueType || typeof(Name).IsAssignableFrom(typeof(T));
                     * if (!flag)
                     * {
                     *  Scribe.loader.crossRefs.RegisterForCrossRefResolve(exposable);
                     * }*/
                    FromXmlIsActive = true;
                    Scribe.EnterNode(rootElementName);
                    var thing = new T();
                    Scribe_Deep.Look <T>(ref thing, "saveable", new object[0]);

                    // Scribe.loader.crossRefs.ResolveAllCrossReferences()

                    return(thing);
                }
                finally
                {
                    try
                    {
                        //Finish()
                        Scribe.loader.FinalizeLoading();
                    }
                    finally
                    {
                        FromXmlIsActive = false;
                    }
                }
            }
        }
示例#22
0
        public void Scribe_Write_Class_Writes_Properties_To_String_Value()
        {
            var expected       = "12345000000000000000BusinessName        5555555555          4567890000000000000000000000000000010000";
            var fieldFormatter = new FieldFormatter();
            var business       = new SimpleBusiness()
            {
                BusinessId              = 12345,
                BusinessName            = "BusinessName",
                BusinessTelephoneNumber = "5555555555",
                TaxId      = "456789",
                CashOnHand = "10000"
            };

            using (var writer = new StringWriter())
            {
                IScribe scribe = new Scribe(writer, fieldFormatter);
                scribe.Write(business);
                var actual = writer.ToString();

                Assert.Equal(expected, actual);
            }
        }
示例#23
0
        public void Scribe_Write_Only_Writes_Public_Properties_Of_Classes()
        {
            var expected = "12345000000000000000BusinessName        5555555555          45678900000000000000";

            var fieldFormatter = new FieldFormatter();
            var business       = new BusinessWithPrivateProperty()
            {
                BusinessId              = 12345,
                BusinessName            = "BusinessName",
                BusinessTelephoneNumber = "5555555555",
                TaxId = "456789",
            };

            using (var writer = new StringWriter())
            {
                IScribe scribe = new Scribe(writer, fieldFormatter);
                scribe.Write(business);
                var actual = writer.ToString();

                Assert.Equal(expected, actual);
            }
        }
示例#24
0
        public override void ExposeData()
        {
            if (Verse.Scribe.mode == LoadSaveMode.Saving)
            {
                BackwardsCompatData = new Dictionary <Thing, StatGroup>();
                _Things             = new List <Thing>();
                _StatGroups         = new List <StatGroup>();
                System.GC.Collect();
                foreach (GeneticInformation gi in GeneticInformation.Instances)
                {
                    BackwardsCompatData[gi.parent] = new StatGroup(gi);
                }
            }

            Scribe_Collections.Look(ref BackwardsCompatData, "data", LookMode.Reference, LookMode.Deep, ref _Things, ref _StatGroups);

            if (Scribe.EnterNode("settings"))
            {
                Settings.ExposeData();
                Scribe.ExitNode();
            }
        }
示例#25
0
        public static bool LoadFromFile(PrepareCarefully loadout, string presetName)
        {
            string version = "";
            bool   result  = false;

            try {
                Scribe.InitLoading(PresetFiles.FilePathForSavedPreset(presetName));
                Scribe_Values.LookValue <string>(ref version, "version", "unknown", false);
            }
            catch (Exception e) {
                Log.Error("Failed to load preset file");
                throw e;
            }
            finally {
                Scribe.mode = LoadSaveMode.Inactive;
            }

            if ("1".Equals(version))
            {
                Messages.Message("EdB.PrepareCarefully.PresetVersionNotSupported".Translate(), MessageSound.SeriousAlert);
                return(false);
            }
            else if ("2".Equals(version))
            {
                Messages.Message("EdB.PrepareCarefully.PresetVersionNotSupported".Translate(), MessageSound.SeriousAlert);
                return(false);
            }
            else if ("3".Equals(version))
            {
                result = new PresetLoaderVersion3().Load(loadout, presetName);
            }
            else
            {
                throw new Exception("Invalid preset version");
            }

            return(result);
        }
示例#26
0
        internal static void _CheckVersionAndLoad(string path, ScribeMetaHeaderUtility.ScribeHeaderMode mode, Action loadAct)
        {
            bool mismatchWarnings;

            try
            {
                try
                {
                    Scribe.InitLoadingMetaHeaderOnly(path);
                }
                catch (Exception ex)
                {
                    Log.Warning(string.Concat(new object[4]
                    {
                        (object)"Exception loading ",
                        (object)path,
                        (object)": ",
                        (object)ex
                    }));
                }
                ScribeMetaHeaderUtility.LoadGameDataHeader(mode, false);
                mismatchWarnings = ScribeMetaHeaderUtility.TryCreateDialogsForVersionMismatchWarnings(loadAct);
                CrossRefResolver.ResolveAllCrossReferences();
                PostLoadInitter.DoAllPostLoadInits();
            }
            catch
            {
                CrossRefResolver.Clear();
                PostLoadInitter.Clear();
                throw;
            }
            Controller.Data.ResetInjectionSubController();
            if (mismatchWarnings)
            {
                return;
            }
            loadAct();
        }
示例#27
0
        internal static Blueprint LoadFromXML(SaveFileInfo file)
        {
            // set up empty blueprint
            Blueprint blueprint = new Blueprint();

#if DEBUG
            Log.Message("Attempting to load from: " + file.FileInfo.FullName);
#endif

            // load stuff
            try
            {
                Scribe.InitLoading(BlueprintSaveLocation + "/" + file.FileInfo.Name);
                ScribeMetaHeaderUtility.LoadGameDataHeader(ScribeMetaHeaderUtility.ScribeHeaderMode.Map, true);
                Scribe.EnterNode("Blueprint");
                blueprint.ExposeData();
                Scribe.ExitNode();
            }
            catch (Exception e)
            {
                Log.Error("Exception while loading blueprint: " + e);
            }
            finally
            {
                // done loading
                Scribe.FinalizeLoading();
                Scribe.mode = LoadSaveMode.Inactive;
            }

            // if a def used in the blueprint doesn't exist, exposeData will throw an error,
            // which is fine. in addition, it'll set the field to null - which may result in problems down the road.
            // Make sure each item in the blueprint has a def set, if not - remove it.
            // This check itself will throw another error, which is also fine. User will have to resolve the issue manually.
            blueprint.contents = blueprint.contents.Where(item => item.BuildableDef != null).ToList();

            // return blueprint.
            return(blueprint);
        }
示例#28
0
 public static void FinalizeLoading()
 {
     if (Scribe.mode != LoadSaveMode.LoadingVars)
     {
         Log.Error("Called FinalizeLoading() but current mode is " + Scribe.mode, false);
         return;
     }
     try {
         Scribe.ExitNode();
         Scribe.loader.curXmlParent       = null;
         Scribe.loader.curParent          = null;
         Scribe.loader.curPathRelToParent = null;
         Scribe.mode = LoadSaveMode.Inactive;
         ResolveAllCrossReferences();
         //Scribe.loader.crossRefs.ResolveAllCrossReferences();
         Scribe.loader.initer.DoAllPostLoadInits();
     }
     catch (Exception arg) {
         Log.Error("Exception in FinalizeLoading(): " + arg, false);
         Scribe.loader.ForceStop();
         throw;
     }
 }
示例#29
0
        public static void load(ref List <Thing> thingsToLoad, string fileLocation, Thing currentSource)
        {
            Log.Message("ScribeINIT, loding from:" + fileLocation);
            Scribe.InitLoading(fileLocation);

            //Scribe.EnterNode("Stargate");

            Log.Message("DeepProfiler.Start()");
            DeepProfiler.Start("Load non-compressed things");

            // List<Thing> list2 = (List<Thing>)null;
            Log.Message("Scribe_Collections.LookList");
            Scribe_Collections.LookList <Thing>(ref thingsToLoad, "things", LookMode.Deep);
            Log.Message("List1Count:" + thingsToLoad.Count);

            Log.Message("DeepProfiler.End()");
            DeepProfiler.End();

            //Scribe.ExitNode();
            Scribe.mode = LoadSaveMode.Inactive;

            //Log.Message("list: " + thingsToLoad.Count.ToString());


            Log.Message("Exit Node");
            //Scribe.ExitNode();


            Log.Message("ResolveAllCrossReferences");
            CrossRefResolver.ResolveAllCrossReferences();


            Log.Message("DoAllPostLoadInits");
            PostLoadInitter.DoAllPostLoadInits();

            Log.Message("Return");
        }
示例#30
0
 // Performs the setup needed to begin a scribe loading operation, similar to ScribeLoader.InitLoad(), but
 // uses a StringReader instead of reading from a file.
 private static void InitLoadFromString(String value)
 {
     if (Scribe.mode != LoadSaveMode.Inactive)
     {
         Logger.Error("Called InitLoading() but current mode is " + Scribe.mode);
         Scribe.ForceStop();
     }
     if (Scribe.loader.curParent != null)
     {
         Logger.Error("Current parent is not null in InitLoading");
         Scribe.loader.curParent = null;
     }
     if (Scribe.loader.curPathRelToParent != null)
     {
         Logger.Error("Current path relative to parent is not null in InitLoading");
         Scribe.loader.curPathRelToParent = null;
     }
     try {
         using (TextReader textReader = new StringReader(value)) {
             using (XmlTextReader xmlTextReader = new XmlTextReader(textReader)) {
                 XmlDocument xmlDocument = new XmlDocument();
                 xmlDocument.Load(xmlTextReader);
                 Scribe.loader.curXmlParent = xmlDocument.DocumentElement;
             }
         }
         Scribe.mode = LoadSaveMode.LoadingVars;
     }
     catch (Exception ex) {
         Logger.Error(string.Concat(new object[] {
             "Exception while unmarshalling XML",
             "\n",
             ex
         }));
         Scribe.loader.ForceStop();
         throw;
     }
 }