public static SaveGame Load() { BinaryFormatter bf = new BinaryFormatter(); //surrogate serializer setup. SurrogateSelector ss = new SurrogateSelector(); ColorSerializationSurrogate css = new ColorSerializationSurrogate(); ss.AddSurrogate(typeof(Color),new StreamingContext(StreamingContextStates.All),css); //use surrogate selector. bf.SurrogateSelector = ss; FileStream file = File.Open(Application.persistentDataPath+"/saveGame.serious",FileMode.Open); SaveGame loadedGame = (SaveGame)bf.Deserialize(file); file.Close(); return loadedGame; }
public static void Save(SaveGame save) { BinaryFormatter bf = new BinaryFormatter(); //surrogate serializer setup. SurrogateSelector ss = new SurrogateSelector(); ColorSerializationSurrogate css = new ColorSerializationSurrogate(); ss.AddSurrogate(typeof(Color),new StreamingContext(StreamingContextStates.All),css); //use surrogate selector. bf.SurrogateSelector = ss; FileStream file = File.Create(Application.persistentDataPath+"/saveGame.serious"); bf.Serialize(file, save); file.Close (); Debug.Log(Application.persistentDataPath+"/saveGame.serious"); }
public void Properties_Roundtrip() { var f = new BinaryFormatter(); Assert.Null(f.Binder); var binder = new DelegateBinder(); f.Binder = binder; Assert.Same(binder, f.Binder); Assert.NotNull(f.Context); Assert.Null(f.Context.Context); Assert.Equal(StreamingContextStates.All, f.Context.State); var context = new StreamingContext(StreamingContextStates.Clone); f.Context = context; Assert.Equal(StreamingContextStates.Clone, f.Context.State); Assert.Null(f.SurrogateSelector); var selector = new SurrogateSelector(); f.SurrogateSelector = selector; Assert.Same(selector, f.SurrogateSelector); Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat); f.AssemblyFormat = FormatterAssemblyStyle.Full; Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat); Assert.Equal(TypeFilterLevel.Full, f.FilterLevel); f.FilterLevel = TypeFilterLevel.Low; Assert.Equal(TypeFilterLevel.Low, f.FilterLevel); Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat); f.TypeFormat = FormatterTypeStyle.XsdString; Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat); }
public virtual bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strBaseLoc = ""; try { LABEL_860_GENERAL: do { SurrogateSelector surSel; strLoc = "Loc_100aa"; surSel = new SurrogateSelector(); iCountTestcases++; if(surSel == null) { iCountErrors++; printerr("Error_100bb! SurrogateSelector not created"); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void ISerializationSurrogate() { dbContext.Configuration.ProxyCreationEnabled = false; var surrogateSelector = new SurrogateSelector(); surrogateSelector.AddSurrogate(typeof(Order_Detail), new StreamingContext(), new OrderDetailsSerializationSurrogate()); var tester = new XmlDataContractSerializerTester <IEnumerable <Order_Detail> >(new NetDataContractSerializer() { SurrogateSelector = surrogateSelector }, true); var orderDetails = dbContext.Order_Details.ToList(); var t = (dbContext as IObjectContextAdapter).ObjectContext; foreach (var od in orderDetails) { t.LoadProperty(od, p => p.Product); t.LoadProperty(od, p => p.Order); } tester.SerializeAndDeserialize(orderDetails); }
public static void DeserializeState(RecallableState S, Boolean ReinstantiatePast) { if (ReinstantiatePast) { ScriptProcessor.PastStates.Clear(); ScriptProcessor.PastStates.Push(S); } ArrayList ReconstructEnts = new ArrayList(); IFormatter SerFormatter = new BinaryFormatter(); SurrogateSelector SS = new SurrogateSelector(); Surrogates.Vector2SS V2SS = new Surrogates.Vector2SS(); Surrogates.PointSS PSS = new Surrogates.PointSS(); Surrogates.RectangleSS RSS = new Surrogates.RectangleSS(); Surrogates.Texture2DSS T2DSS = new Surrogates.Texture2DSS(); Surrogates.ColorSS CSS = new Surrogates.ColorSS(); Surrogates.SpriteFontSS SFSS = new Surrogates.SpriteFontSS(); SS.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), V2SS); SS.AddSurrogate(typeof(Point), new StreamingContext(StreamingContextStates.All), PSS); SS.AddSurrogate(typeof(Rectangle), new StreamingContext(StreamingContextStates.All), RSS); SS.AddSurrogate(typeof(Texture2D), new StreamingContext(StreamingContextStates.All), T2DSS); SS.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), CSS); SS.AddSurrogate(typeof(SpriteFont), new StreamingContext(StreamingContextStates.All), SFSS); SerFormatter.SurrogateSelector = SS; foreach (byte[] Br in S.SerializedEnts) { MemoryStream DecodeStream = new MemoryStream(Br); WorldEntity WE = (WorldEntity)SerFormatter.Deserialize(DecodeStream); DecodeStream.Close(); ReconstructEnts.Add(WE); } ArrayList NewUEnts = new ArrayList(); ArrayList NewREnts = new ArrayList(); foreach (VoidDel V in MouseLeftClick.GetInvocationList()) { MouseLeftClick -= V; } RunQueue = new ArrayList(); foreach (WorldEntity W in NonSerializables) { W.AddEventTriggers(); } ArrayList TempList = new ArrayList(); foreach (WorldEntity W in DeleteQueue) { if (NonSerializables.Contains(W)) { TempList.Add(W); } } DeleteQueue = TempList; foreach (WorldEntity W in ReconstructEnts) { if (S.UpdateIDs.Contains(W.EntityID)) { NewUEnts.Add(W); } if (S.RenderIDs.Contains(W.EntityID)) { NewREnts.Add(W); } W.ReissueID(); W.OnDeserializeDo(); } ScriptProcessor.LabelEntity = S.LabelEntity; if (ScriptProcessor.SongCom != S.SongCom && S.SongCom != null && S.SongCom.Split('|').Length > 1) { ScriptProcessor.ActivateScriptElement(S.SongCom); } if (S.Flags != null) { Flags = (Hashtable)S.Flags.Clone(); } foreach (WorldEntity W in UpdateQueue) { if (NonSerializables.Contains(W)) { NewUEnts.Add(W); } } foreach (WorldEntity W in RenderQueue) { if (NonSerializables.Contains(W)) { NewREnts.Add(W); } } UpdateQueue = new ArrayList(NewUEnts); RenderQueue = new ArrayList(NewREnts); foreach (WorldEntity W in ReconstructEnts) { W.ResubscribeEvents(); } ButtonScripts.UnHideUI(); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect1, surrSelect2, surrSelect3, surrSelect4, surrSelect5; TestSerializationClass testclass; TestSerializationSurrogate testss1, testss2, testss3, testss4, testss5; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; strLoc = "Loc_100aa"; surrSelect1 = new SurrogateSelector(); iCountTestcases++; try { surrSelect1.GetSurrogate(null, context, out ss); iCountErrors++; printerr("Error_100bb!! Expected ArgumentException not thrown"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_100dd!! Incorrect Exception thrown : " + exc.ToString()); } strLoc = "Loc_300aa"; surrSelect1 = new SurrogateSelector(); testss1 = new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect1.AddSurrogate(testclass.GetType(), context, testss1); iCountTestcases++; if (!surrSelect1.GetSurrogate(testclass.GetType(), context, out ss).Equals(testss1)) { iCountErrors++; printerr("Error_300bb! Incorrect ISerializationSurrogate returned"); } strLoc = "Loc_350aa"; testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if (!surrSelect1.GetSurrogate(typeof(Int64), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if (!surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); strLoc = "Loc_400aa"; surrSelect1 = new SurrogateSelector(); surrSelect2 = new SurrogateSelector(); surrSelect3 = new SurrogateSelector(); surrSelect4 = new SurrogateSelector(); surrSelect5 = new SurrogateSelector(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); testss4 = new TestSerializationSurrogate(); testss5 = new TestSerializationSurrogate(); surrSelect3.ChainSelector(surrSelect5); surrSelect3.ChainSelector(surrSelect4); surrSelect2.ChainSelector(surrSelect3); surrSelect1.ChainSelector(surrSelect2); surrSelect5.AddSurrogate(typeof(Single), context, testss5); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if (!(surrSelect3.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400cc!! Did not find the surrogate through the chain"); } iCountTestcases++; if (!(surrSelect4.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400dd!! Did not find the surrogate through the chain"); } strLoc = "Loc_401aa"; surrSelect1.AddSurrogate(typeof(Guid), context, testss1); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Guid), context, out ss).Equals(testss1))) { iCountErrors++; printerr("Error_401bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if (surrSelect2.GetSurrogate(typeof(Guid), context, out ss) != null) { iCountErrors++; printerr("Error_401cc!! Found surrogate that is above in the chain"); } strLoc = "Loc_402aa"; surrSelect2.AddSurrogate(typeof(Decimal), context, testss2); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss2))) { iCountErrors++; printerr("Error_402bb!! Didn't find surrogate of child"); } strLoc = "Loc_403aa"; surrSelect3.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3))) { iCountErrors++; printerr("Error_403bb!! Didn't find surrogate of child"); } strLoc = "Loc_404aa"; surrSelect4.AddSurrogate(typeof(Exception), context, testss4); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Exception), context, out ss).Equals(testss4))) { iCountErrors++; printerr("Error_404bb!! Didn't find surrogate of child"); } strLoc = "Loc_405aa"; if (surrSelect1.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_405bb!! Found surrogate not in chain"); } } while (false); } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases); return(true); } else { Console.WriteLine("FAiL! " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums); return(false); } }
public static void Reg(SurrogateSelector selector) { selector.AddSurrogate(typeof(T), new StreamingContext(StreamingContextStates.All), new Serializator_Empty()); }
/// <summary> /// Registers all serialization surrogates defined in this assembly with the specified formatter. /// </summary> /// <typeparam name="TFormatter"> The type of formatter to register for. </typeparam> /// <param name="formatter"> The formatter to register for. </param> /// <returns> An instance of the formatter. </returns> public static TFormatter IncludeId3SerializationSupport <TFormatter>(this TFormatter formatter) where TFormatter : IFormatter { if (ReferenceEquals(formatter, null)) { throw new ArgumentNullException("formatter"); } var selector = new SurrogateSelector(); //Id3Tag selector.AddSurrogate(typeof(Id3Tag), new StreamingContext(StreamingContextStates.All), new Id3TagSurrogate()); //TextFrame-derived classes selector.AddSurrogate(typeof(AlbumFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(BandFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(ConductorFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(ContentGroupDescriptionFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(CopyrightFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(CustomTextFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(EncoderFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(EncodingSettingsFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(FileOwnerFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(GenreFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(PublisherFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(SubtitleFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(TitleFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); //NumericFrame-derived classes selector.AddSurrogate(typeof(BeatsPerMinuteFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(YearFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); //DateTimeFrame-derived classes selector.AddSurrogate(typeof(RecordingDateFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); //ListTextFrame-derived classes selector.AddSurrogate(typeof(ArtistsFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(ComposersFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(LyricistsFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); //Other TextFrameBase<>-derived classes selector.AddSurrogate(typeof(FileTypeFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(LengthFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); selector.AddSurrogate(typeof(TrackFrame), new StreamingContext(StreamingContextStates.All), new TextFrameSurrogate()); //UrlLinkFrame-derived classes selector.AddSurrogate(typeof(ArtistUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(AudioFileUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(AudioSourceUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(CommercialUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(CopyrightUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(CustomUrlLinkFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); selector.AddSurrogate(typeof(PaymentUrlFrame), new StreamingContext(StreamingContextStates.All), new UrlLinkFrameSurrogate()); //All other frames selector.AddSurrogate(typeof(CommentFrame), new StreamingContext(StreamingContextStates.All), new CommentFrameSurrogate()); selector.AddSurrogate(typeof(LyricsFrame), new StreamingContext(StreamingContextStates.All), new LyricsFrameSurrogate()); selector.AddSurrogate(typeof(PictureFrame), new StreamingContext(StreamingContextStates.All), new PictureFrameSurrogate()); selector.AddSurrogate(typeof(PrivateFrame), new StreamingContext(StreamingContextStates.All), new PrivateFrameSurrogate()); selector.AddSurrogate(typeof(UnknownFrame), new StreamingContext(StreamingContextStates.All), new UnknownFrameSurrogate()); formatter.SurrogateSelector = selector; return(formatter); }
protected virtual void AddSurrogateSelectors(SurrogateSelector surrogateSelector) { surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), new Vector3SerializationSurrogate()); surrogateSelector.AddSurrogate(typeof(Quaternion), new StreamingContext(StreamingContextStates.All), new QuaternionSerializationSurrogate()); }
/// <summary> /// Initializes a new instance of the <see cref="SurrogateSelectorAttribute"/> class. /// </summary> /// /// <param name="surrogateSelectorType">The surrogate selector to be used to deserialize objects of this type.</param> /// public SurrogateSelectorAttribute(Type surrogateSelectorType) { Selector = (SurrogateSelector)Activator.CreateInstance(surrogateSelectorType); }
public void AddSurrogate(SurrogateSelector toSelector) { toSelector.AddSurrogate(typeof(FirstPacket), new StreamingContext(StreamingContextStates.All), this); }
/// <summary> /// Saves the map content to a file. /// </summary> public void SaveMap() { if (!Directory.Exists(Application.dataPath + "/Maps/")) { Directory.CreateDirectory(Application.dataPath + "/Maps/"); } BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector surrogateSelector = new SurrogateSelector(); Vector3SerializationSurrogate vector3SS = new Vector3SerializationSurrogate(); surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), vector3SS); bf.SurrogateSelector = surrogateSelector; FileStream file = File.Create(Application.dataPath + "/Maps/" + path + ".map"); MapData mapData = new MapData(); mapData.FloorPosition = GameObject.Find("Floor").transform.position; GameObject[] temp; temp = GameObject.FindGameObjectsWithTag("Movable"); Vector3[] blockPositions = new Vector3 [temp.Length]; for (int i = 0; i < temp.Length; i++) { blockPositions [i] = temp [i].transform.position; } temp = GameObject.FindGameObjectsWithTag("ElectricDoor"); Vector3[] electricDoorPositions = new Vector3[temp.Length]; string[] electricDoorNames = new string[temp.Length]; string[][] attachedPadNames = new string[temp.Length][]; int maximumPadsAttached = 3; for (int i = 0; i < temp.Length; i++) { attachedPadNames [i] = new string [maximumPadsAttached]; electricDoorNames [i] = temp [i].name; } for (int i = 0; i < temp.Length; i++) { electricDoorPositions [i] = temp [i].transform.position; for (int j = 0; j < temp [i].GetComponent <ElectricDoor> ().attachedPads.Length; j++) { if (temp [i].GetComponent <ElectricDoor> ().attachedPads [j] != null) { attachedPadNames [i] [j] = temp [i].GetComponent <ElectricDoor> ().attachedPads [j].name; } } } temp = GameObject.FindGameObjectsWithTag("Pad"); Vector3[] padPositions = new Vector3[temp.Length]; string[] padNames = new string[temp.Length]; string[] attachedMaterialNames = new string[temp.Length]; string[] attachedDoorNames = new string[temp.Length]; for (int i = 0; i < temp.Length; i++) { attachedDoorNames [i] = temp [i].GetComponent <ElectricDoorPad> ().electricDoor.gameObject.name; attachedMaterialNames [i] = temp [i].GetComponent <Renderer> ().material.name.Replace(" (Instance)", ""); padPositions [i] = temp [i].transform.position; padNames [i] = temp [i].name; } mapData.BlockPositions = blockPositions; mapData.ElectricDoorPositions = electricDoorPositions; mapData.PadPositions = padPositions; mapData.PadNames = padNames; mapData.ElectricDoorNames = electricDoorNames; mapData.AttachedPadNames = attachedPadNames; mapData.AttachedDoorNames = attachedDoorNames; mapData.AttachedMaterialNames = attachedMaterialNames; bf.Serialize(file, mapData); file.Close(); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect1, surrSelect2, surrSelect3, surrSelect4, surrSelect5; TestSerializationSurrogate testss1, testss2, testss3, testss4, testss5; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; SurrogateSelector[] arrSelectors; Int32 iHowDeep; strLoc = "Loc_100aa"; surrSelect1 = new SurrogateSelector(); iCountTestcases++; try { surrSelect1.ChainSelector(null); iCountErrors++; printerr("Error_100bb!! Expected ArgumentException not thrown"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_100dd!! Incorrect Exception thrown : " + exc.ToString()); } strLoc = "Loc_300aa"; iCountTestcases++; surrSelect1 = new SurrogateSelector(); try { surrSelect1.ChainSelector(surrSelect1); }catch (SerializationException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_432fs!! Incorrect Exception thrown : " + ex.ToString()); } if (surrSelect1.GetSurrogate(typeof(Int64), context, out ss) != null) { iCountErrors++; printerr("Error_2139d!!!!"); } strLoc = "Loc_350aa"; testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if (!surrSelect1.GetSurrogate(typeof(Int64), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if (!surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); strLoc = "Loc_400aa"; surrSelect1 = new SurrogateSelector(); surrSelect2 = new SurrogateSelector(); surrSelect3 = new SurrogateSelector(); surrSelect4 = new SurrogateSelector(); surrSelect5 = new SurrogateSelector(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); testss4 = new TestSerializationSurrogate(); testss5 = new TestSerializationSurrogate(); surrSelect3.ChainSelector(surrSelect5); surrSelect3.ChainSelector(surrSelect4); surrSelect2.ChainSelector(surrSelect3); surrSelect1.ChainSelector(surrSelect2); surrSelect5.AddSurrogate(typeof(Single), context, testss5); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if (!(surrSelect3.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400cc!! Did not find the surrogate through the chain"); } iCountTestcases++; if (!(surrSelect4.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400dd!! Did not find the surrogate through the chain"); } strLoc = "Loc_401aa"; surrSelect1.AddSurrogate(typeof(Guid), context, testss1); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Guid), context, out ss).Equals(testss1))) { iCountErrors++; printerr("Error_401bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if (surrSelect2.GetSurrogate(typeof(Guid), context, out ss) != null) { iCountErrors++; printerr("Error_401cc!! Found surrogate that is above in the chain"); } strLoc = "Loc_402aa"; surrSelect2.AddSurrogate(typeof(Decimal), context, testss2); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss2))) { iCountErrors++; printerr("Error_402bb!! Didn't find surrogate of child"); } strLoc = "Loc_403aa"; surrSelect3.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3))) { iCountErrors++; printerr("Error_403bb!! Didn't find surrogate of child"); } strLoc = "Loc_404aa"; surrSelect4.AddSurrogate(typeof(Exception), context, testss4); iCountTestcases++; if (!(surrSelect1.GetSurrogate(typeof(Exception), context, out ss).Equals(testss4))) { iCountErrors++; printerr("Error_404bb!! Didn't find surrogate of child"); } strLoc = "Loc_405aa"; if (surrSelect1.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_405bb!! Found surrogate not in chain"); } iHowDeep = 10; arrSelectors = new SurrogateSelector[iHowDeep]; arrSelectors[0] = new SurrogateSelector(); for (int i = 1; i < iHowDeep; i++) { arrSelectors[i] = new SurrogateSelector(); arrSelectors[0].ChainSelector(arrSelectors[i]); } iCountTestcases++; if (arrSelectors[0].GetNextSelector() != arrSelectors[iHowDeep - 1]) { iCountErrors++; printerr("Error_03842vdsd! Incorrect ISerializationSurrgate returned"); } for (int i = iHowDeep - 1; i > 1; i--) { iCountTestcases++; if (arrSelectors[i].GetNextSelector() != arrSelectors[i - 1]) { iCountErrors++; printerr("Err_74239cd_" + i + "! Incorrect ISerializationSurrgate returned"); } } iCountTestcases++; if (arrSelectors[1].GetNextSelector() != null) { iCountErrors++; printerr("Error_0483vf! Incorrect ISerializationSurrgate returned"); } try { iCountTestcases++; arrSelectors[2].ChainSelector(arrSelectors[8]); context = new StreamingContext(StreamingContextStates.All); testss1 = (TestSerializationSurrogate)arrSelectors[0].GetSurrogate(typeof(Int64), context, out ss); iCountErrors++; Console.WriteLine("Err_74239cd!! Expected Exception not thrown"); }catch (ArgumentException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_652df!! Incorrect Exception thrown : " + ex.ToString()); } } while (false); } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases); return(true); } else { Console.WriteLine("FAiL! " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums); return(false); } }
public static void SerializationMain() { //1-BinaryFormatter //2-SoapFormatter //3-XmlSerializer //A myFirstA = new A() { SomeString = "abc", SomeValue = 123 }; //A mySecondA; //using (FileStream fs = new FileStream("data.dat", FileMode.Create, //FileAccess.ReadWrite, //FileShare.None)) //{ // IFormatter formatter = new BinaryFormatter(); // formatter.Serialize(fs, myFirstA); // fs.Seek(0, SeekOrigin.Begin); // mySecondA = (A)formatter.Deserialize(fs); // fs.Close(); //} //Person p1 = new Person(); //Person p2; //p1.Birthday = DateTime.Now; //p1.Name = "SomeName"; //using (FileStream fs = new FileStream("data_soap.dat", FileMode.Create, //FileAccess.ReadWrite, //FileShare.None)) //{ // IFormatter formatter = new SoapFormatter(); // formatter.Serialize(fs, p1); // fs.Seek(0, SeekOrigin.Begin); // p2 = (Person)formatter.Deserialize(fs); // fs.Close(); //} //Person p5 = new Person(); //Person p6; //p5.Birthday = DateTime.Now; //p5.Name = "SomeName"; //using (FileStream fs = new FileStream("data_binary.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) //{ // IFormatter formatter = new BinaryFormatter(); // formatter.Serialize(fs, p5); // fs.Seek(0, SeekOrigin.Begin); // p6 = (Person)formatter.Deserialize(fs); // fs.Close(); //} //Person p3 = new Person(); //Person p4; //p3.Birthday = DateTime.Now; //p3.Name = "SomeName"; //using (FileStream fs = new FileStream("data_xml.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) //{ // XmlSerializer formatter = new XmlSerializer(typeof(Person)); // formatter.Serialize(fs, p3); // fs.Seek(0, SeekOrigin.Begin); // p4 = (Person)formatter.Deserialize(fs); // fs.Close(); //} //Surrogate Person p1 = new Person(); Person p2; p1.Birthday = DateTime.Now; p1.Name = "SomeName"; using (FileStream fs = new FileStream("data_surrogate.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { SurrogateSelector ss = new SurrogateSelector(); ss.AddSurrogate(typeof(Person), new StreamingContext(StreamingContextStates.All), new PersonSerializationSurrogate()); IFormatter formatter = new BinaryFormatter(); formatter.SurrogateSelector = ss; formatter.Serialize(fs, p1); fs.Flush(); fs.Seek(0, SeekOrigin.Begin); p2 = (Person)formatter.Deserialize(fs); fs.Close(); } //ISerializable //Person p5 = new Person(); //Person p6; //p5.Birthday = DateTime.Now; //p5.Name = "SomeName"; //using (FileStream fs = new FileStream("data_iserializable.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None)) //{ // IFormatter formatter = new BinaryFormatter(); // formatter.Serialize(fs, p5); // fs.Seek(0, SeekOrigin.Begin); // p6 = (Person)formatter.Deserialize(fs); // fs.Close(); //} }
protected override void OnSerialize(IFormatter formatter, SurrogateSelector selector) { selector.AddSurrogate(typeof(Flowchart), new StreamingContext(StreamingContextStates.All), new FlowchartSerialize()); base.OnSerialize(formatter, selector); }
public static void Go() { using (var stream = new MemoryStream()) { // 1. Construct the desired formatter IFormatter formatter = new SoapFormatter(); // 2. Construct a SurrogateSelector object SurrogateSelector ss = new SurrogateSelector(); // 3. Tell the surrogate selector to use our surrogate for DateTime objects ISerializationSurrogate utcToLocalTimeSurrogate = new UniversalToLocalTimeSerializationSurrogate(); #if GetSurrogateForCyclicalReference utcToLocalTimeSurrogate = FormatterServices.GetSurrogateForCyclicalReference(utcToLocalTimeSurrogate); #endif ss.AddSurrogate(typeof(DateTime), formatter.Context, utcToLocalTimeSurrogate); // NOTE: AddSurrogate can be called multiple times to register multiple surrogates // 4. Tell the formatter to use our surrogate selector formatter.SurrogateSelector = ss; // Create a DateTime that represents the local time on the machine & serialize it DateTime localTimeBeforeSerialize = DateTime.Now; formatter.Serialize(stream, localTimeBeforeSerialize); // The Soap-formatted stream displays the Universal time as a string to prove it worked stream.Position = 0; Console.WriteLine(new StreamReader(stream).ReadToEnd()); // Deserialize the Universal time string & convert it to a local DateTime for this machine stream.Position = 0; DateTime localTimeAfterDeserialize = (DateTime)formatter.Deserialize(stream); // Prove it worked correctly: Console.WriteLine("LocalTimeBeforeSerialize ={0}", localTimeBeforeSerialize); Console.WriteLine("LocalTimeAfterDeserialize={0}", localTimeAfterDeserialize); } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; IFormatter formatter; SurrogateSelector selector; MySerializationSurrogate surrogate; StreamingContext context = new StreamingContext(StreamingContextStates.All); MemoryStream stream; Int32 iValue; A a; ObjectManager manager; ObjectIDGenerator generator; Int64 rootId; Int64 childId; Boolean firstTime; MemberInfo[] members; try { strLoc = "Loc_29457sdg"; iCountTestcases++; selector = new SurrogateSelector(); surrogate = new MySerializationSurrogate(); selector.AddSurrogate(typeof(A), context, surrogate); formatter = new BinaryFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); a = new A(); a.I = 10; formatter.Serialize(stream, a); stream.Position = 0; A a1 = (A)formatter.Deserialize(stream); if (a1.I != 30) { iCountErrors++; Console.WriteLine("Err_753ffd! Unexpected value returned, Value: <{0}>", a1.I); } strLoc = "Loc_8394tfsg"; iCountTestcases++; generator = new ObjectIDGenerator(); a = new A(); iValue = 500; rootId = generator.GetId(a, out firstTime); childId = generator.GetId(iValue, out firstTime); selector = new SurrogateSelector(); surrogate = new MySerializationSurrogate(); selector.AddSurrogate(typeof(A), context, surrogate); manager = new ObjectManager(selector, context); members = FormatterServices.GetSerializableMembers(typeof(A)); manager.RecordDelayedFixup(rootId, "Int32Twist", childId); try{ SerializationInfo serInfo1 = new SerializationInfo(typeof(A), new FormatterConverter()); manager.RegisterObject(a, rootId, serInfo1); manager.RegisterObject(iValue, childId); Console.WriteLine(a.I); }catch (Exception ex) { iCountErrors++; Console.WriteLine(ex); } strLoc = "Loc_87sgsfd"; iCountTestcases++; generator = new ObjectIDGenerator(); a = new A(); iValue = 500; rootId = generator.GetId(a, out firstTime); childId = generator.GetId(iValue, out firstTime); manager = new ObjectManager(null, context); members = FormatterServices.GetSerializableMembers(typeof(A)); manager.RecordFixup(rootId, members[0], childId); manager.RegisterObject(a, rootId); manager.RegisterObject(iValue, childId); if (a.I != 500) { iCountErrors++; Console.WriteLine("Err_93745sg! Unexpected value returned, Value: <{0}>", a1.I); } } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==\n" + exc_general.StackTrace); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases); return(true); } else { Console.WriteLine("FAiL! " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums); return(false); } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; IFormatter formatter; SurrogateSelector selector; MySerializationSurrogate surrogate; StreamingContext context = new StreamingContext(StreamingContextStates.All); MemoryStream stream; Int32 iValue; A a; ObjectManager manager; ObjectIDGenerator generator; Int64 rootId; Int64 childId; Boolean firstTime; MemberInfo[] members; try { strLoc = "Loc_29457sdg"; iCountTestcases++; selector = new SurrogateSelector(); surrogate = new MySerializationSurrogate(); selector.AddSurrogate(typeof(A), context, surrogate); formatter = new BinaryFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); a = new A(); a.I = 10; formatter.Serialize(stream, a); stream.Position = 0; A a1 = (A)formatter.Deserialize(stream); if(a1.I != 30){ iCountErrors++; Console.WriteLine("Err_753ffd! Unexpected value returned, Value: <{0}>", a1.I); } strLoc = "Loc_8394tfsg"; iCountTestcases++; generator = new ObjectIDGenerator(); a = new A(); iValue = 500; rootId = generator.GetId(a, out firstTime); childId = generator.GetId(iValue, out firstTime); selector = new SurrogateSelector(); surrogate = new MySerializationSurrogate(); selector.AddSurrogate(typeof(A), context, surrogate); manager = new ObjectManager(selector, context); members = FormatterServices.GetSerializableMembers(typeof(A)); manager.RecordDelayedFixup(rootId, "Int32Twist", childId); try{ SerializationInfo serInfo1 = new SerializationInfo(typeof(A), new FormatterConverter()); manager.RegisterObject(a, rootId, serInfo1); manager.RegisterObject(iValue, childId); Console.WriteLine(a.I); }catch(Exception ex){ iCountErrors++; Console.WriteLine(ex); } strLoc = "Loc_87sgsfd"; iCountTestcases++; generator = new ObjectIDGenerator(); a = new A(); iValue = 500; rootId = generator.GetId(a, out firstTime); childId = generator.GetId(iValue, out firstTime); manager = new ObjectManager(null, context); members = FormatterServices.GetSerializableMembers(typeof(A)); manager.RecordFixup(rootId, members[0], childId); manager.RegisterObject(a, rootId); manager.RegisterObject(iValue, childId); if(a.I != 500){ iCountErrors++; Console.WriteLine("Err_93745sg! Unexpected value returned, Value: <{0}>", a1.I); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general==\n"+exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect; SurrogateSelector surrSelect_next; TestSerializationClass testclass; TestSerializationSurrogate testss, testss1, testss2; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; SurrogateSelector[] arrSelectors; Int32 iHowDeep; strLoc = "Loc_100aa"; surrSelect = new SurrogateSelector(); iCountTestcases++; try { surrSelect.AddSurrogate(this.GetType(), context, null); iCountErrors++; printerr("Error_100bb! Expected exception not thrown"); } catch (ArgumentException){} catch (Exception exc) { iCountErrors++; printerr("Error_100dd! Incorrect Exception thrown: "+exc.ToString()); } strLoc = "Loc_200aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); iCountTestcases++; try { surrSelect.AddSurrogate(null, context, testss); iCountErrors++; printerr("Error_200bb! Expected exception not thrown"); } catch (ArgumentException){} catch (Exception exc) { iCountErrors++; printerr("Error_200dd! Incorrect exception thrown: "+exc.ToString()); } strLoc = "Loc_300aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect.AddSurrogate(testclass.GetType(), context, testss); iCountTestcases++; if(!surrSelect.GetSurrogate(testclass.GetType(), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_300bb! Incorrect ISerializationSurrogate returned"); } strLoc = "Loc_350aa"; testss = new TestSerializationSurrogate(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); surrSelect = new SurrogateSelector(); surrSelect.AddSurrogate(typeof(Decimal), context, testss); surrSelect.AddSurrogate(typeof(Int64),context, testss1); surrSelect.AddSurrogate(typeof(Int32),context, testss2); iCountTestcases++; if(!surrSelect.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_350bb! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if(surrSelect != ss) { iCountErrors++; printerr("Error_0453cd! Incorrect ISurrogateSelector returned"); } iCountTestcases++; if(!surrSelect.GetSurrogate(typeof(Int64), context, out ss).Equals(testss1)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if(!surrSelect.GetSurrogate(typeof(Int32), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss = new TestSerializationSurrogate(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); surrSelect = new SurrogateSelector(); surrSelect.AddSurrogate(typeof(Decimal), context, testss); surrSelect.AddSurrogate(typeof(Int64),context, testss1); surrSelect.AddSurrogate(typeof(Int32),context, testss2); iCountTestcases++; if(surrSelect.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_370bb! Type not in surrogateselector was actually found???"); } strLoc = "Loc_400aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect.AddSurrogate(testclass.GetType(),context, testss); try { surrSelect.AddSurrogate(testclass.GetType(),context, new TestSerializationSurrogate()); iCountErrors++; printerr("Error_400bb! Expected Exception not thrown"); }catch (ArgumentException){ }catch (Exception exc){ iCountErrors++; printerr("Error_400cc! Incorrect Exception thrown : "+exc.ToString()); } surrSelect = new SurrogateSelector(); surrSelect_next = new SurrogateSelector(); surrSelect.ChainSelector(surrSelect_next); testss = new TestSerializationSurrogate(); context = new StreamingContext(StreamingContextStates.All); surrSelect_next.AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if(!surrSelect.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_04582fd! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if(surrSelect == ss) { iCountErrors++; printerr("Error_0478523vdf! Incorrect ISurrogateSelector returned"); } iCountTestcases++; if(surrSelect_next != ss) { iCountErrors++; printerr("Error_934721cd! Incorrect ISurrogateSelector returned"); } iHowDeep = 100; arrSelectors = new SurrogateSelector[iHowDeep]; arrSelectors[0] = new SurrogateSelector(); for(int i=1;i<iHowDeep;i++){ arrSelectors[i] = new SurrogateSelector(); arrSelectors[0].ChainSelector(arrSelectors[i]); } testss = new TestSerializationSurrogate(); context = new StreamingContext(StreamingContextStates.All); arrSelectors[1].AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if(!arrSelectors[0].GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_743cd! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if(arrSelectors[1] != ss) { iCountErrors++; printerr("Error_10573cd! Incorrect ISurrogateSelector returned"); } arrSelectors[0].AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if(!arrSelectors[0].GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_0472ds! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if(arrSelectors[0] != ss) { iCountErrors++; printerr("Error_0342dfg! Incorrect ISurrogateSelector returned"); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void Constructor () { SurrogateSelector ss = new SurrogateSelector (); BinaryFormatter bf = new BinaryFormatter (ss, new StreamingContext (StreamingContextStates.CrossMachine)); Assert.AreEqual (FormatterAssemblyStyle.Simple, bf.AssemblyFormat, "AssemblyFormat"); Assert.IsNull (bf.Binder, "Binder"); Assert.AreEqual (StreamingContextStates.CrossMachine, bf.Context.State, "Context"); Assert.AreEqual (TypeFilterLevel.Full, bf.FilterLevel, "FilterLevel"); Assert.AreSame (ss, bf.SurrogateSelector, "SurrogateSelector"); Assert.AreEqual (FormatterTypeStyle.TypesAlways, bf.TypeFormat, "TypeFormat"); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect; SurrogateSelector surrSelect_next; TestSerializationClass testclass; TestSerializationSurrogate testss, testss1, testss2; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; SurrogateSelector[] arrSelectors; Int32 iHowDeep; strLoc = "Loc_100aa"; surrSelect = new SurrogateSelector(); iCountTestcases++; try { surrSelect.AddSurrogate(this.GetType(), context, null); iCountErrors++; printerr("Error_100bb! Expected exception not thrown"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_100dd! Incorrect Exception thrown: " + exc.ToString()); } strLoc = "Loc_200aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); iCountTestcases++; try { surrSelect.AddSurrogate(null, context, testss); iCountErrors++; printerr("Error_200bb! Expected exception not thrown"); } catch (ArgumentException) {} catch (Exception exc) { iCountErrors++; printerr("Error_200dd! Incorrect exception thrown: " + exc.ToString()); } strLoc = "Loc_300aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect.AddSurrogate(testclass.GetType(), context, testss); iCountTestcases++; if (!surrSelect.GetSurrogate(testclass.GetType(), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_300bb! Incorrect ISerializationSurrogate returned"); } strLoc = "Loc_350aa"; testss = new TestSerializationSurrogate(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); surrSelect = new SurrogateSelector(); surrSelect.AddSurrogate(typeof(Decimal), context, testss); surrSelect.AddSurrogate(typeof(Int64), context, testss1); surrSelect.AddSurrogate(typeof(Int32), context, testss2); iCountTestcases++; if (!surrSelect.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_350bb! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if (surrSelect != ss) { iCountErrors++; printerr("Error_0453cd! Incorrect ISurrogateSelector returned"); } iCountTestcases++; if (!surrSelect.GetSurrogate(typeof(Int64), context, out ss).Equals(testss1)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if (!surrSelect.GetSurrogate(typeof(Int32), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss = new TestSerializationSurrogate(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); surrSelect = new SurrogateSelector(); surrSelect.AddSurrogate(typeof(Decimal), context, testss); surrSelect.AddSurrogate(typeof(Int64), context, testss1); surrSelect.AddSurrogate(typeof(Int32), context, testss2); iCountTestcases++; if (surrSelect.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_370bb! Type not in surrogateselector was actually found???"); } strLoc = "Loc_400aa"; surrSelect = new SurrogateSelector(); testss = new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect.AddSurrogate(testclass.GetType(), context, testss); try { surrSelect.AddSurrogate(testclass.GetType(), context, new TestSerializationSurrogate()); iCountErrors++; printerr("Error_400bb! Expected Exception not thrown"); }catch (ArgumentException) { }catch (Exception exc) { iCountErrors++; printerr("Error_400cc! Incorrect Exception thrown : " + exc.ToString()); } surrSelect = new SurrogateSelector(); surrSelect_next = new SurrogateSelector(); surrSelect.ChainSelector(surrSelect_next); testss = new TestSerializationSurrogate(); context = new StreamingContext(StreamingContextStates.All); surrSelect_next.AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if (!surrSelect.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_04582fd! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if (surrSelect == ss) { iCountErrors++; printerr("Error_0478523vdf! Incorrect ISurrogateSelector returned"); } iCountTestcases++; if (surrSelect_next != ss) { iCountErrors++; printerr("Error_934721cd! Incorrect ISurrogateSelector returned"); } iHowDeep = 100; arrSelectors = new SurrogateSelector[iHowDeep]; arrSelectors[0] = new SurrogateSelector(); for (int i = 1; i < iHowDeep; i++) { arrSelectors[i] = new SurrogateSelector(); arrSelectors[0].ChainSelector(arrSelectors[i]); } testss = new TestSerializationSurrogate(); context = new StreamingContext(StreamingContextStates.All); arrSelectors[1].AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if (!arrSelectors[0].GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_743cd! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if (arrSelectors[1] != ss) { iCountErrors++; printerr("Error_10573cd! Incorrect ISurrogateSelector returned"); } arrSelectors[0].AddSurrogate(typeof(Decimal), context, testss); iCountTestcases++; if (!arrSelectors[0].GetSurrogate(typeof(Decimal), context, out ss).Equals(testss)) { iCountErrors++; printerr("Error_0472ds! Incorrect ISerializationSurrogate returned"); } iCountTestcases++; if (arrSelectors[0] != ss) { iCountErrors++; printerr("Error_0342dfg! Incorrect ISurrogateSelector returned"); } } while (false); } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases); return(true); } else { Console.WriteLine("FAiL! " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums); return(false); } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; SurrogateSelector selector1; SurrogateSelector selector2; SurrogateSelector[] selectorArr; Int32 numberOfSelectors; SurrogateSelector selectorReturned; try { strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); selector2 = new SurrogateSelector(); selector1.ChainSelector(selector2); selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if(selectorReturned != selector2){ iCountErrors++; Console.WriteLine("Err_34905wdsg! Wrong value returned"); } strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if(selectorReturned != null){ iCountErrors++; Console.WriteLine("Err_93475sdg! Wrong value returned"); } strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); numberOfSelectors = 50; selectorArr = new SurrogateSelector[numberOfSelectors]; for(int i=0; i<numberOfSelectors; i++){ selectorArr[i] = new SurrogateSelector(); selector1.ChainSelector(selectorArr[i]); } for(int i=numberOfSelectors-1; i>=0; i--){ selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if(selectorReturned != selectorArr[i]){ iCountErrors++; Console.WriteLine("Err_8345sdg_" + i + "! Wrong value returned"); } selector1 = selectorReturned; } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
protected override void OnDeserializeComplete(object graph, IFormatter formatter, SurrogateSelector selector) { FlowchartSerialize surrogate = (FlowchartSerialize)Serialization.Serialize.GetSurrogate(graph, selector); Flowchart flowchart = (Flowchart)graph; //Apply surrogate settings SuspendEvents = true; Suspend(); Resume(); SuspendEvents = false; base.OnDeserializeComplete(graph, formatter, selector); }
public static void Load() { SurrogateSelector surrogateSelector = new SurrogateSelector(); SerializationSurrogates.Vector2IntSerializationSurrogate vector2I = new SerializationSurrogates.Vector2IntSerializationSurrogate(); SerializationSurrogates.Vector2SerializationSurrogate vector2 = new SerializationSurrogates.Vector2SerializationSurrogate(); SerializationSurrogates.Vector3SerializationSurrogate vector3 = new SerializationSurrogates.Vector3SerializationSurrogate(); SerializationSurrogates.Vector3IntSerializationSurrogate vector3I = new SerializationSurrogates.Vector3IntSerializationSurrogate(); surrogateSelector.AddSurrogate(typeof(Vector2Int), new StreamingContext(StreamingContextStates.All), vector2I); surrogateSelector.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), vector2); surrogateSelector.AddSurrogate(typeof(Vector3Int), new StreamingContext(StreamingContextStates.All), vector3I); surrogateSelector.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), vector3); XmlDocument xml = new XmlDocument(); xml.LoadXml(File.ReadAllText(Application.persistentDataPath + "/world.xml")); XmlNode world = xml.GetElementsByTagName("World")[0]; foreach (XmlNode worldEntry in world.ChildNodes) { if (worldEntry.Name == "Mods") { XmlNodeList mods = worldEntry.ChildNodes; foreach (XmlNode mod in mods) { bool found = false; foreach (var modInstance in ModManager.ModInstances) { if (modInstance.Value.InternalName == mod.Attributes.GetNamedItem("InternalName").InnerText&& modInstance.Value.Version == mod.Attributes.GetNamedItem("Version").InnerText) { found = true; } if (!found) { Debug.LogError("A Mod by the name of " + mod.Attributes.GetNamedItem("InternalName").InnerText + " version " + mod.Attributes.GetNamedItem("Version").InnerText + "is not loaded"); } } } } else if (worldEntry.Name == "Blocks") { XmlNodeList blocks = worldEntry.ChildNodes; foreach (XmlNode block in blocks) { if (BlockRegister.IsRegitered(block.Attributes.GetNamedItem("InternalName").InnerText)) { BaseClasses.Block blockInstance = (BaseClasses.Block)StringToObject(block.InnerText, surrogateSelector); World.SetBlock(blockInstance.Position, blockInstance); } } } else if (worldEntry.Name == "Player") { BaseClasses.Player player = (BaseClasses.Player)StringToObject(worldEntry.InnerText, surrogateSelector); PlayerRegister.Player = player; player.Init(); } } }
public MyDeserializationBinder(SurrogateSelector surrogateSelector) { this.surrogateSelector = surrogateSelector; }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Int32 iValue; A a1; V v1; S s1; V_I vi1; Surrogate_1 surrogate; SurrogateSelector selector; SoapFormatter formatter; MemoryStream stream; StreamingContext context = new StreamingContext(StreamingContextStates.All); Object objRet; ReflectionPermission perm; try { strLoc = "Loc_9347sg"; iCountTestcases++; iValue = 5; formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, iValue); iCountErrors++; Console.WriteLine("Err_7349sg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_348tdg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_2407sdg"; iCountTestcases++; stream.Position = 0; formatter.Serialize(stream, iValue); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_207tdsg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_3947tfdg"; iCountTestcases++; a1 = new A(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, a1); iCountErrors++; Console.WriteLine("Err_39475sdg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_2047tsfgb! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, a1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_9347tsfg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_0347tsfg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; v1 = new V(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, v1); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_3047tfxg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, v1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_7349sg! No exception thrown, "); } catch (SecurityException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_29437tsg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; s1 = new S(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, s1); iCountErrors++; Console.WriteLine("Err_3946tsdg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_9347tsdg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, s1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch (SecurityException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_93745sdg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; vi1 = new V_I(6); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, vi1); iCountErrors++; Console.WriteLine("Err_2075sdg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_294375sdg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, vi1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch (SecurityException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_24907tsdfg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; selector = new SurrogateSelector(); surrogate = new Surrogate_1(); selector.AddSurrogate(typeof(A), context, surrogate); selector.AddSurrogate(typeof(V), context, surrogate); formatter = new SoapFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); a1 = new A(5); try{ Serialize(formatter, stream, a1); iCountErrors++; Console.WriteLine("Err_93475sdg! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_3947tsg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, a1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch (SecurityException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_39047tsg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_3048sdg"; iCountTestcases++; v1 = new V(7); formatter = new SoapFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); try{ Serialize(formatter, stream, v1); iCountErrors++; Console.WriteLine("Err_9347tsgf! No exception thrown, "); }catch (SecurityException) { }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_2947tsgd! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, v1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch (SecurityException) { } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_89734trfsg! Exception thrown, " + ex.GetType().Name); } perm = new ReflectionPermission(PermissionState.Unrestricted); perm.Deny(); strLoc = "Loc_83245tsg"; iCountTestcases++; a1 = new A(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ formatter.Serialize(stream, a1); stream.Position = 0; objRet = formatter.Deserialize(stream); if (((A)objRet).I != 5) { iCountErrors++; Console.WriteLine("Err_3947tsdg! wrong value returned, " + (Int32)objRet); } }catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_29746tsfdg! Exception thrown, " + ex.GetType().Name); } } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFName + " ,iCountTestcases==" + iCountTestcases.ToString()); return(true); } else { Console.WriteLine("FAiL! " + s_strTFName + " ,inCountErrors==" + iCountErrors.ToString() + " , BugNums?: " + s_strActiveBugNums); return(false); } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect1, surrSelect2, surrSelect3, surrSelect4, surrSelect5; TestSerializationClass testclass; TestSerializationSurrogate testss1, testss2, testss3, testss4, testss5; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; strLoc = "Loc_100aa"; surrSelect1 = new SurrogateSelector(); iCountTestcases++; try { surrSelect1.GetSurrogate(null, context, out ss); iCountErrors++; printerr("Error_100bb!! Expected ArgumentException not thrown"); } catch (ArgumentException){} catch (Exception exc) { iCountErrors++; printerr("Error_100dd!! Incorrect Exception thrown : "+exc.ToString()); } strLoc = "Loc_300aa"; surrSelect1 = new SurrogateSelector(); testss1= new TestSerializationSurrogate(); testclass = new TestSerializationClass(); surrSelect1.AddSurrogate(testclass.GetType(), context, testss1); iCountTestcases++; if(!surrSelect1.GetSurrogate(testclass.GetType(), context, out ss).Equals(testss1)) { iCountErrors++; printerr("Error_300bb! Incorrect ISerializationSurrogate returned"); } strLoc = "Loc_350aa"; testss1= new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if(!surrSelect1.GetSurrogate(typeof(Int64), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if(!surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss1= new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); strLoc = "Loc_400aa"; surrSelect1 = new SurrogateSelector(); surrSelect2 = new SurrogateSelector(); surrSelect3 = new SurrogateSelector(); surrSelect4 = new SurrogateSelector(); surrSelect5 = new SurrogateSelector(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); testss4 = new TestSerializationSurrogate(); testss5 = new TestSerializationSurrogate(); surrSelect3.ChainSelector(surrSelect5); surrSelect3.ChainSelector(surrSelect4); surrSelect2.ChainSelector(surrSelect3); surrSelect1.ChainSelector(surrSelect2); surrSelect5.AddSurrogate(typeof(Single), context, testss5); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if(!(surrSelect3.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400cc!! Did not find the surrogate through the chain"); } iCountTestcases++; if(!(surrSelect4.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400dd!! Did not find the surrogate through the chain"); } strLoc = "Loc_401aa"; surrSelect1.AddSurrogate(typeof(Guid), context, testss1); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Guid), context, out ss).Equals(testss1))) { iCountErrors++; printerr("Error_401bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if(surrSelect2.GetSurrogate(typeof(Guid), context, out ss) != null) { iCountErrors++; printerr("Error_401cc!! Found surrogate that is above in the chain"); } strLoc = "Loc_402aa"; surrSelect2.AddSurrogate(typeof(Decimal), context, testss2); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss2))) { iCountErrors++; printerr("Error_402bb!! Didn't find surrogate of child"); } strLoc = "Loc_403aa"; surrSelect3.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3))) { iCountErrors++; printerr("Error_403bb!! Didn't find surrogate of child"); } strLoc = "Loc_404aa"; surrSelect4.AddSurrogate(typeof(Exception), context, testss4); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Exception), context, out ss).Equals(testss4))) { iCountErrors++; printerr("Error_404bb!! Didn't find surrogate of child"); } strLoc = "Loc_405aa"; if(surrSelect1.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_405bb!! Found surrogate not in chain"); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
static public void RegSerializator(Type objType, SurrogateSelector selector) { selector.AddSurrogate(objType, new StreamingContext(StreamingContextStates.All), new WriteSurrogate()); }
//Reads an object from the XML and initializes the object. private object InitializeObject(XmlTextReader reader, FormatterConverter converter) { Type actualType; int id; //Check if a type or ref attribute is present if (!reader.HasAttributes) { throw new SerializationException("A non-primitive element was found without attributes."); } //Check for a ref attribute string reference = reader.GetAttribute("ref"); //, "http://www.w3.org/2001/XMLSchema-instance"); //References require a previously deserialized object if (reference != null) { if (!int.TryParse(reference, out id)) { throw new SerializationException("Non numeric reference id found."); } object existing = null; if (!_idObjects.TryGetValue(id, out existing)) { throw new SerializationException(string.Format("An object reference with id {0} was not previously deserialized.", reference)); } return(existing); } //Get the type name string actualTypeName = reader.GetAttribute("type"); // "http://www.w3.org/2001/XMLSchema-instance"); actualType = Binder.BindToType("", actualTypeName); //Get the id attribute string objectId = reader.GetAttribute("id"); //, "http://www.w3.org/2001/XMLSchema-instance"); //If the id is null then the object reference is null so return null if (objectId == null) { return(null); } //Convert to an integer value if (!int.TryParse(objectId, out id)) { throw new SerializationException("An object id could not be converted to an integer value."); } ISurrogateSelector selector1 = null; ISerializationSurrogate serializationSurrogate = null; SerializationInfo info = null; if (SurrogateSelector == null) { throw new NullReferenceException("An error occurred deserializing an object. The SurrogateSelector property may not be null."); } serializationSurrogate = SurrogateSelector.GetSurrogate(actualType, Context, out selector1); if (serializationSurrogate == null) { throw new NullReferenceException(string.Format("An error occurred deserializing an object. A surrogate was not found for type {0}", actualType.Name)); } //Use surrogate info = new SerializationInfo(actualType, converter); //Create a instance of the type, or use the existing object graph object initializedObject; if (Target == null) { initializedObject = FormatterServices.GetUninitializedObject(actualType); //Call the default constructor //Formatter could be expanded to use non default constructors at some later stage ConstructorInfo ci = actualType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, System.Type.EmptyTypes, null); if (ci == null) { throw new SerializationException(string.Format("Type {0} must implement a parameterless constructor.", actualType.FullName)); } ci.Invoke(initializedObject, null); } else { initializedObject = Target; Target = null; //Reset target so that it cannot be used recursively } //Add the object to the list of id objects _idObjects.Add(id, initializedObject); //Determine if a list or collection IDictionary dictionary = null; IList list = null; int index = 0; //Read the first element reader.ReadStartElement(); while (reader.IsStartElement()) { //Determine type string typeName = reader.GetAttribute("type"); //, "http://www.w3.org/2001/XMLSchema-instance"); Type childType = Binder.BindToType("", typeName); //Get a key, if any string key = reader.GetAttribute("key"); //Check for a uri attribute string uri = reader.GetAttribute("uri"); //Check if a collection if (reader.Name == "Collection" && reader.IsStartElement()) { if (typeName == "IDictionary") { dictionary = initializedObject as IDictionary; list = null; } else if (typeName == "IList") { list = initializedObject as IList; dictionary = null; } reader.ReadStartElement(); } //Check for a resource entry else if (uri != null) { //Uris require a resource preloaded in the _resources collection ResourceEntry resourceEntry; if (!_resources.TryGetValue(uri, out resourceEntry)) { throw new SerializationException(string.Format("A resource with uri {0} was not found in the resources collection.", uri)); } info.AddValue(resourceEntry.Name, resourceEntry.Value); reader.Read(); } //Process all other elements else { object parsedObject = null; //Check if the value can be directly determined or that the type is a complex type. if (childType.IsPrimitive || childType == typeof(string) || childType.IsEnum || childType == typeof(DateTime) || childType == typeof(object)) { //Directly parse parsedObject = converter.Convert(reader.ReadString(), childType); } else { //Recurse down the object graph parsedObject = InitializeObject(reader, converter); } //Add to parent collection or add the key value pair to the info object for the serialization surrogate to use if (dictionary != null && key != null) { dictionary.Add(key, parsedObject); } else if (list != null) { list.Add(parsedObject); } else { info.AddValue(reader.Name, parsedObject); //Use info object } //Move to next element reader.Read(); //Read past collection if (reader.Name == "Collection" && !reader.IsStartElement()) { reader.Read(); } } } //Use the surrogate to populate the instance initializedObject = serializationSurrogate.SetObjectData(initializedObject, info, Context, SurrogateSelector); return(initializedObject); }
static public void RegReadSerializatorEmpty(SurrogateSelector selector) { selector.AddSurrogate(typeof(WRITE_DATA), new StreamingContext(StreamingContextStates.All), new EmptyReadSurrogate()); }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; SurrogateSelector selector1; SurrogateSelector selector2; SurrogateSelector[] selectorArr; Int32 numberOfSelectors; SurrogateSelector selectorReturned; try { strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); selector2 = new SurrogateSelector(); selector1.ChainSelector(selector2); selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if (selectorReturned != selector2) { iCountErrors++; Console.WriteLine("Err_34905wdsg! Wrong value returned"); } strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if (selectorReturned != null) { iCountErrors++; Console.WriteLine("Err_93475sdg! Wrong value returned"); } strLoc = "Loc_98374sdg"; iCountTestcases++; selector1 = new SurrogateSelector(); numberOfSelectors = 50; selectorArr = new SurrogateSelector[numberOfSelectors]; for (int i = 0; i < numberOfSelectors; i++) { selectorArr[i] = new SurrogateSelector(); selector1.ChainSelector(selectorArr[i]); } for (int i = numberOfSelectors - 1; i >= 0; i--) { selectorReturned = (SurrogateSelector)selector1.GetNextSelector(); if (selectorReturned != selectorArr[i]) { iCountErrors++; Console.WriteLine("Err_8345sdg_" + i + "! Wrong value returned"); } selector1 = selectorReturned; } } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if (iCountErrors == 0) { Console.WriteLine("paSs. " + s_strTFPath + " " + s_strTFName + " ,iCountTestcases==" + iCountTestcases); return(true); } else { Console.WriteLine("FAiL! " + s_strTFPath + " " + s_strTFName + " ,iCountErrors==" + iCountErrors + " , BugNums?: " + s_strActiveBugNums); return(false); } }
static void CreateSurrogates() { ss = new SurrogateSelector(); //VECTOR2 Vector2SerializationSurrogate v2_ss = new Vector2SerializationSurrogate(); ss.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), v2_ss); //VECTOR3 Vector3SerializationSurrogate v3_ss = new Vector3SerializationSurrogate(); ss.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), v3_ss); //VECTOR4 Vector4SerializationSurrogate v4_ss = new Vector4SerializationSurrogate(); ss.AddSurrogate(typeof(Vector4), new StreamingContext(StreamingContextStates.All), v4_ss); //QUATERNION QuaternionSerializationSurrogate q_ss = new QuaternionSerializationSurrogate(); ss.AddSurrogate(typeof(Quaternion), new StreamingContext(StreamingContextStates.All), q_ss); //COLOR AND COLOR32 ColorSerializationSurrogate color_ss = new ColorSerializationSurrogate(); ss.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), color_ss); ss.AddSurrogate(typeof(Color32), new StreamingContext(StreamingContextStates.All), color_ss); //TEXTURE2D Texture2DSerializationSurrogate texture_ss = new Texture2DSerializationSurrogate(); ss.AddSurrogate(typeof(Texture2D), new StreamingContext(StreamingContextStates.All), texture_ss); Texture2DCompressionType_old = Texture2DCompressionType; }
//Saving and Loading public void SaveData() { Debug.Log("PlayerInfo Saved"); PlayerStats.SaveTemp (); BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); FileStream file = File.Create(Application.persistentDataPath + "/" + FileName + ".dat"); // Vector3SerializationSurrogate v3ss = new Vector3SerializationSurrogate(); ss.AddSurrogate(typeof(Vector3), new StreamingContext(StreamingContextStates.All), v3ss); bf.SurrogateSelector = ss; // PlayerData data = new PlayerData(); data.PickupCount = Pickups; data.ChestCount = ChestsOpened; data.SwitchCount = SwitchesUsed; data.DeathCount = Deaths; data.checkpoint = checkpoint; data.playerHealth = playerHealth; data.currentscene = currentscene; // bf.Serialize(file, data); file.Close(); }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Int32 iValue; A a1; V v1; S s1; V_I vi1; Surrogate_1 surrogate; SurrogateSelector selector; SoapFormatter formatter; MemoryStream stream; StreamingContext context = new StreamingContext(StreamingContextStates.All); Object objRet; ReflectionPermission perm; try { strLoc = "Loc_9347sg"; iCountTestcases++; iValue = 5; formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, iValue); iCountErrors++; Console.WriteLine("Err_7349sg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_348tdg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_2407sdg"; iCountTestcases++; stream.Position = 0; formatter.Serialize(stream, iValue); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_207tdsg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_3947tfdg"; iCountTestcases++; a1 = new A(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, a1); iCountErrors++; Console.WriteLine("Err_39475sdg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_2047tsfgb! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, a1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_9347tsfg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_0347tsfg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; v1 = new V(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, v1); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_3047tfxg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, v1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_7349sg! No exception thrown, "); } catch(SecurityException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_29437tsg! Wrong exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; s1 = new S(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, s1); iCountErrors++; Console.WriteLine("Err_3946tsdg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_9347tsdg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, s1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch(SecurityException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_93745sdg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; vi1 = new V_I(6); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ Serialize(formatter, stream, vi1); iCountErrors++; Console.WriteLine("Err_2075sdg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_294375sdg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, vi1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch(SecurityException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_24907tsdfg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_34975sg"; iCountTestcases++; selector = new SurrogateSelector(); surrogate = new Surrogate_1(); selector.AddSurrogate(typeof(A), context, surrogate); selector.AddSurrogate(typeof(V), context, surrogate); formatter = new SoapFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); a1 = new A(5); try{ Serialize(formatter, stream, a1); iCountErrors++; Console.WriteLine("Err_93475sdg! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_3947tsg! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, a1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch(SecurityException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_39047tsg! Exception thrown, " + ex.GetType().Name); } strLoc = "Loc_3048sdg"; iCountTestcases++; v1 = new V(7); formatter = new SoapFormatter(); formatter.SurrogateSelector = selector; stream = new MemoryStream(); try{ Serialize(formatter, stream, v1); iCountErrors++; Console.WriteLine("Err_9347tsgf! No exception thrown, "); }catch(SecurityException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_2947tsgd! Wrong exception thrown, " + ex.GetType().Name); } stream.Position = 0; formatter.Serialize(stream, v1); stream.Position = 0; try{ objRet = Deserialize(formatter, stream); iCountErrors++; Console.WriteLine("Err_98324sdg! No exception thrown, "); } catch(SecurityException) { } catch(Exception ex) { iCountErrors++; Console.WriteLine("Err_89734trfsg! Exception thrown, " + ex.GetType().Name); } perm = new ReflectionPermission(PermissionState.Unrestricted); perm.Deny(); strLoc = "Loc_83245tsg"; iCountTestcases++; a1 = new A(5); formatter = new SoapFormatter(); stream = new MemoryStream(); try{ formatter.Serialize(stream, a1); stream.Position = 0; objRet = formatter.Deserialize(stream); if(((A)objRet).I!=5){ iCountErrors++; Console.WriteLine("Err_3947tsdg! wrong value returned, " + (Int32)objRet); } }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_29746tsfdg! Exception thrown, " + ex.GetType().Name); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,inCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; try { do { SurrogateSelector surrSelect1, surrSelect2, surrSelect3, surrSelect4, surrSelect5; TestSerializationSurrogate testss1, testss2, testss3, testss4, testss5; StreamingContext context = new StreamingContext(StreamingContextStates.CrossMachine); ISurrogateSelector ss; SurrogateSelector[] arrSelectors; Int32 iHowDeep; strLoc = "Loc_100aa"; surrSelect1 = new SurrogateSelector(); iCountTestcases++; try { surrSelect1.ChainSelector(null); iCountErrors++; printerr("Error_100bb!! Expected ArgumentException not thrown"); } catch (ArgumentException){} catch (Exception exc) { iCountErrors++; printerr("Error_100dd!! Incorrect Exception thrown : "+exc.ToString()); } strLoc = "Loc_300aa"; iCountTestcases++; surrSelect1 = new SurrogateSelector(); try { surrSelect1.ChainSelector(surrSelect1); }catch (SerializationException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_432fs!! Incorrect Exception thrown : "+ex.ToString()); } if(surrSelect1.GetSurrogate(typeof(Int64), context, out ss) != null) { iCountErrors++; printerr("Error_2139d!!!!"); } strLoc = "Loc_350aa"; testss1= new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if(!surrSelect1.GetSurrogate(typeof(Int64), context, out ss).Equals(testss2)) { iCountErrors++; printerr("Error_350cc! Incorrect ISerializationSurrgate returned"); } iCountTestcases++; if(!surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3)) { iCountErrors++; printerr("Error_350dd! Incorrect IserializationSurrogate returned"); } strLoc = "Loc_370aa"; testss1= new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); surrSelect1 = new SurrogateSelector(); surrSelect1.AddSurrogate(typeof(Int64), context, testss2); surrSelect1.AddSurrogate(typeof(Int32), context, testss3); strLoc = "Loc_400aa"; surrSelect1 = new SurrogateSelector(); surrSelect2 = new SurrogateSelector(); surrSelect3 = new SurrogateSelector(); surrSelect4 = new SurrogateSelector(); surrSelect5 = new SurrogateSelector(); testss1 = new TestSerializationSurrogate(); testss2 = new TestSerializationSurrogate(); testss3 = new TestSerializationSurrogate(); testss4 = new TestSerializationSurrogate(); testss5 = new TestSerializationSurrogate(); surrSelect3.ChainSelector(surrSelect5); surrSelect3.ChainSelector(surrSelect4); surrSelect2.ChainSelector(surrSelect3); surrSelect1.ChainSelector(surrSelect2); surrSelect5.AddSurrogate(typeof(Single), context, testss5); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if(!(surrSelect3.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400cc!! Did not find the surrogate through the chain"); } iCountTestcases++; if(!(surrSelect4.GetSurrogate(typeof(Single), context, out ss).Equals(testss5))) { iCountErrors++; printerr("Error_400dd!! Did not find the surrogate through the chain"); } strLoc = "Loc_401aa"; surrSelect1.AddSurrogate(typeof(Guid), context, testss1); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Guid), context, out ss).Equals(testss1))) { iCountErrors++; printerr("Error_401bb!! Did not find the surrogate through the chain"); } iCountTestcases++; if(surrSelect2.GetSurrogate(typeof(Guid), context, out ss) != null) { iCountErrors++; printerr("Error_401cc!! Found surrogate that is above in the chain"); } strLoc = "Loc_402aa"; surrSelect2.AddSurrogate(typeof(Decimal), context, testss2); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Decimal), context, out ss).Equals(testss2))) { iCountErrors++; printerr("Error_402bb!! Didn't find surrogate of child"); } strLoc = "Loc_403aa"; surrSelect3.AddSurrogate(typeof(Int32), context, testss3); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Int32), context, out ss).Equals(testss3))) { iCountErrors++; printerr("Error_403bb!! Didn't find surrogate of child"); } strLoc = "Loc_404aa"; surrSelect4.AddSurrogate(typeof(Exception), context, testss4); iCountTestcases++; if(!(surrSelect1.GetSurrogate(typeof(Exception), context, out ss).Equals(testss4))) { iCountErrors++; printerr("Error_404bb!! Didn't find surrogate of child"); } strLoc = "Loc_405aa"; if(surrSelect1.GetSurrogate(typeof(Int16), context, out ss) != null) { iCountErrors++; printerr("Error_405bb!! Found surrogate not in chain"); } iHowDeep = 10; arrSelectors = new SurrogateSelector[iHowDeep]; arrSelectors[0] = new SurrogateSelector(); for(int i=1;i<iHowDeep;i++){ arrSelectors[i] = new SurrogateSelector(); arrSelectors[0].ChainSelector(arrSelectors[i]); } iCountTestcases++; if(arrSelectors[0].GetNextSelector() != arrSelectors[iHowDeep-1]) { iCountErrors++; printerr("Error_03842vdsd! Incorrect ISerializationSurrgate returned"); } for(int i=iHowDeep-1;i>1;i--){ iCountTestcases++; if(arrSelectors[i].GetNextSelector() != arrSelectors[i-1]){ iCountErrors++; printerr("Err_74239cd_" + i + "! Incorrect ISerializationSurrgate returned"); } } iCountTestcases++; if(arrSelectors[1].GetNextSelector() != null) { iCountErrors++; printerr("Error_0483vf! Incorrect ISerializationSurrgate returned"); } try { iCountTestcases++; arrSelectors[2].ChainSelector(arrSelectors[8]); context = new StreamingContext(StreamingContextStates.All); testss1 = (TestSerializationSurrogate)arrSelectors[0].GetSurrogate(typeof(Int64), context, out ss); iCountErrors++; Console.WriteLine("Err_74239cd!! Expected Exception not thrown"); }catch(ArgumentException){ }catch(Exception ex){ iCountErrors++; Console.WriteLine("Err_652df!! Incorrect Exception thrown : "+ex.ToString()); } } while (false); } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); Console.WriteLine(exc_general.StackTrace); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
/// <summary> /// Loads the Levels in a previously generated World. /// </summary> /// <param name="i_path">The World path.</param> /// <param name="i_worldCallback">The callback used to catch the loaded world.</param> /// <param name="i_progressCallback">The callback used to catch the progress value.</param> public IEnumerator LoadLevels(string i_path, Action <World> i_worldCallback, Action <float> i_progressCallback) { if (!Directory.Exists(i_path)) { yield break; } string[] files = Directory.GetFiles(i_path); if (files.Length != 2 || !(Path.GetExtension(files[0]).ToLower().Equals(".jpg") || Path.GetExtension(files[0]).ToLower().Equals(WORLD_EXT)) || !(Path.GetExtension(files[1]).ToLower().Equals(".jpg") || Path.GetExtension(files[1]).ToLower().Equals(WORLD_EXT)) || Path.GetExtension(files[0]).ToLower().Equals(Path.GetExtension(files[1]).ToLower())) { yield break; } string path1 = files[0].Remove(files[0].Length - Path.GetExtension(files[0]).Length, Path.GetExtension(files[0]).Length); string path2 = files[1].Remove(files[1].Length - Path.GetExtension(files[1]).Length, Path.GetExtension(files[1]).Length); if (!path1.Equals(path2)) { yield break; } //Sets up the FileStream and BinaryFormatter. FileStream file = File.Open(path1 + WORLD_EXT, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); //Used for World serialization. WorldSerializationSurrogate worldSs = new WorldSerializationSurrogate(); //Used for Level serialization. Vector2SerializationSurrogate v2Ss = new Vector2SerializationSurrogate(); LevelSerializationSurrogate levelSs = new LevelSerializationSurrogate(); StreamingContext sc = new StreamingContext(StreamingContextStates.All); ss.AddSurrogate(typeof(World), sc, worldSs); ss.AddSurrogate(typeof(Vector2), sc, v2Ss); ss.AddSurrogate(typeof(Level), sc, levelSs); World aux; bf.SurrogateSelector = ss; //Loads the World. using (file) { aux = ((World)(bf.Deserialize(file))); } yield return(null); //Creates the Level dictionary. aux._levels = new Dictionary <Vector2, Level>(); float progress = 0; //For each column. for (int x = 0; x < aux._imageDivisionConfig[0]; x++) { //For each row. for (int y = 0; y < aux._imageDivisionConfig[1]; y++) { Level auxLevel; //Loads the Level. file = File.Open(i_path + Path.DirectorySeparatorChar + "Levels" + Path.DirectorySeparatorChar + x + "x" + y + Path.DirectorySeparatorChar + x + "x" + y + LEVEL_EXT, FileMode.Open); using (file) { auxLevel = ((Level)(bf.Deserialize(file))); } //Passes the progress value to the callback. progress += 1 / (float)(aux._imageDivisionConfig[0] * aux._imageDivisionConfig[1]); i_progressCallback(progress); yield return(null); //Adds the Level to the dictionary. aux._levels.Add(new Vector2(x, y), auxLevel); //Loads the Level image. Texture2D auxText = new Texture2D(4, 4); auxText.LoadImage(File.ReadAllBytes(i_path + Path.DirectorySeparatorChar + "Levels" + Path.DirectorySeparatorChar + x + "x" + y + Path.DirectorySeparatorChar + x + "x" + y + ".jpg")); auxLevel._img = auxText; } } //Passes the world to the callback. i_worldCallback(aux); }
public static void AddBruTileSurrogates(this IFormatter formatter) { var ss = new SurrogateSelector(); // Base types ss.AddSurrogate(typeof(Extent), new StreamingContext(StreamingContextStates.All), new ExtentSurrogate()); ss.AddSurrogate(typeof(Resolution), new StreamingContext(StreamingContextStates.All), new ResolutionSurrogate()); ss.AddSurrogate(typeof(TileSchema), new StreamingContext(StreamingContextStates.All), new TileSchemaSurrogate()); // Caches ss.AddSurrogate(typeof(NullCache), new StreamingContext(StreamingContextStates.All), new NullCacheSurrogate()); ss.AddSurrogate(typeof(MemoryCache <byte[]>), new StreamingContext(StreamingContextStates.All), new MemoryCacheSurrogate <byte[]>()); ss.AddSurrogate(typeof(MemoryCache <System.Drawing.Bitmap>), new StreamingContext(StreamingContextStates.All), new MemoryCacheSurrogate <System.Drawing.Bitmap>()); // Predefined var tss1 = new TileSchemaSurrogate(); ss.AddSurrogate(typeof(GlobalMercator), new StreamingContext(StreamingContextStates.All), tss1); ss.AddSurrogate(typeof(GlobalSphericalMercator), new StreamingContext(StreamingContextStates.All), tss1); //ss.AddSurrogate(typeof(SphericalMercatorWorldSchema), new StreamingContext(StreamingContextStates.All), tss1); //ss.AddSurrogate(typeof (SphericalMercatorInvertedWorldSchema), // new StreamingContext(StreamingContextStates.All),tss1); //ss.AddSurrogate(typeof (BingSchema), new StreamingContext(StreamingContextStates.All), tss1); ss.AddSurrogate(typeof(WkstNederlandSchema), new StreamingContext(StreamingContextStates.All), tss1); ss.AddSurrogate(typeof(WmtsTileSchema), new StreamingContext(StreamingContextStates.All), new WmtsTileSchemaSurrogate()); //Web var tss2 = new TileSourceSurrogate(); ss.AddSurrogate(typeof(TileSource), new StreamingContext(StreamingContextStates.All), tss2); ss.AddSurrogate(typeof(ArcGisTileRequest), new StreamingContext(StreamingContextStates.All), new ArcGisTileRequestSurrogate()); ss.AddSurrogate(typeof(ArcGisTileSource), new StreamingContext(StreamingContextStates.All), new ArcGisTileSourceSurrogate()); ss.AddSurrogate(typeof(BasicRequest), new StreamingContext(StreamingContextStates.All), new BasicRequestSurrogate()); ss.AddSurrogate(typeof(TmsRequest), new StreamingContext(StreamingContextStates.All), new TmsRequestSurrogate()); ss.AddSurrogate(typeof(TmsTileSource), new StreamingContext(StreamingContextStates.All), tss2); ss.AddSurrogate(typeof(HttpTileProvider), new StreamingContext(StreamingContextStates.All), new HttpTileProviderSurrogate()); ss.AddSurrogate(typeof(WmscTileSource), new StreamingContext(StreamingContextStates.All), tss2); ss.AddSurrogate(typeof(WmscRequest), new StreamingContext(StreamingContextStates.All), new WmscRequestSurrogate()); ss.AddSurrogate(typeof(HttpTileSource), new StreamingContext(StreamingContextStates.All), new HttpTileSourceSurrogate()); //Wmts ss.AddSurrogate(typeof(ResourceUrl), new StreamingContext(StreamingContextStates.All), new ResourceUrlSurrogate()); ss.AddSurrogate(typeof(WmtsRequest), new StreamingContext(StreamingContextStates.All), new WmtsRequestSurrogate()); if (formatter.SurrogateSelector != null) { formatter.SurrogateSelector.ChainSelector(ss); } else { formatter.SurrogateSelector = ss; } }
/// <summary> /// Saves the a World that has been previously processed. /// </summary> /// <param name="i_world">The World to save.</param> public IEnumerator SaveWorld(World i_world) { //Creates the folder name. string dirName; do { dirName = Path.GetRandomFileName().Replace(".", string.Empty); }while (Directory.Exists(Application.persistentDataPath + Path.DirectorySeparatorChar + dirName)); dirName = Application.persistentDataPath + Path.DirectorySeparatorChar + dirName; Directory.CreateDirectory(dirName); //Sets up the FileStream and BinaryFormatter. FileStream file = null; BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); //Used for World serialization. WorldSerializationSurrogate worldSs = new WorldSerializationSurrogate(); //Used for Level serialization. Vector2SerializationSurrogate v2Ss = new Vector2SerializationSurrogate(); LevelSerializationSurrogate levelSs = new LevelSerializationSurrogate(); //Used for LevelCell serialization. ColorSerializationSurrogate colorSs = new ColorSerializationSurrogate(); LevelCellSerializationSurrogate levelCellSs = new LevelCellSerializationSurrogate(); StreamingContext sc = new StreamingContext(StreamingContextStates.All); ss.AddSurrogate(typeof(World), sc, worldSs); ss.AddSurrogate(typeof(Vector2), sc, v2Ss); ss.AddSurrogate(typeof(Level), sc, levelSs); ss.AddSurrogate(typeof(Color), sc, colorSs); ss.AddSurrogate(typeof(LevelCell), sc, levelCellSs); bf.SurrogateSelector = ss; file = File.Create(dirName + Path.DirectorySeparatorChar + i_world._name + WORLD_EXT); //Saves the World object. using (file) { bf.Serialize(file, i_world); } yield return(null); //Saves the World image. File.WriteAllBytes(dirName + Path.DirectorySeparatorChar + i_world._name + ".jpg", i_world._img.EncodeToJPG()); yield return(null); //Creates the "Levels" directory. dirName = dirName + Path.DirectorySeparatorChar + "Levels"; Directory.CreateDirectory(dirName); //For each Level in the World. foreach (KeyValuePair <Vector2, Level> levelDictEntry in i_world._levels) { //Creates the "columnxrow" directory for the Level. Directory.CreateDirectory(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y); //Saves the Level object. file = File.Create(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + LEVEL_EXT); using (file) { bf.Serialize(file, levelDictEntry.Value); } yield return(null); //Saves the Level image. File.WriteAllBytes(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + ".jpg", levelDictEntry.Value._img.EncodeToJPG()); yield return(null); //Creates the "Cells" directory. Directory.CreateDirectory(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + "Cells"); //For each LevelCell. foreach (KeyValuePair <Vector2, LevelCell> levelCellDictEntry in levelDictEntry.Value._cells) { //Creates the "columnxrow" directory for the LevelCell. Directory.CreateDirectory(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + "Cells" + Path.DirectorySeparatorChar + (int)levelCellDictEntry.Key.x + "x" + (int)levelCellDictEntry.Key.y); //Saves the LevelCell object. file = File.Create(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + "Cells" + Path.DirectorySeparatorChar + (int)levelCellDictEntry.Key.x + "x" + (int)levelCellDictEntry.Key.y + Path.DirectorySeparatorChar + (int)levelCellDictEntry.Key.x + "x" + (int)levelCellDictEntry.Key.y + LEVEL_CELL_EXT); using (file) { bf.Serialize(file, levelCellDictEntry.Value); } yield return(null); //Saves the LevelCell image. File.WriteAllBytes(dirName + Path.DirectorySeparatorChar + (int)levelDictEntry.Key.x + "x" + (int)levelDictEntry.Key.y + Path.DirectorySeparatorChar + "Cells" + Path.DirectorySeparatorChar + (int)levelCellDictEntry.Key.x + "x" + (int)levelCellDictEntry.Key.y + Path.DirectorySeparatorChar + (int)levelCellDictEntry.Key.x + "x" + (int)levelCellDictEntry.Key.y + ".jpg", levelCellDictEntry.Value._img.EncodeToJPG()); yield return(null); } } }
public static RecallableState?SerializeState(List <WorldEntity> Skip) { ArrayList UpdateIDs = new ArrayList(); ArrayList RenderIDs = new ArrayList(); ArrayList SerializedIDs = new ArrayList(); IFormatter SerFormatter = new BinaryFormatter(); ArrayList Streams = new ArrayList(); SurrogateSelector SS = new SurrogateSelector(); Surrogates.Vector2SS V2SS = new Surrogates.Vector2SS(); Surrogates.PointSS PSS = new Surrogates.PointSS(); Surrogates.RectangleSS RSS = new Surrogates.RectangleSS(); Surrogates.Texture2DSS T2DSS = new Surrogates.Texture2DSS(); Surrogates.ColorSS CSS = new Surrogates.ColorSS(); Surrogates.SpriteFontSS SFSS = new Surrogates.SpriteFontSS(); SS.AddSurrogate(typeof(Vector2), new StreamingContext(StreamingContextStates.All), V2SS); SS.AddSurrogate(typeof(Point), new StreamingContext(StreamingContextStates.All), PSS); SS.AddSurrogate(typeof(Rectangle), new StreamingContext(StreamingContextStates.All), RSS); SS.AddSurrogate(typeof(Texture2D), new StreamingContext(StreamingContextStates.All), T2DSS); SS.AddSurrogate(typeof(Color), new StreamingContext(StreamingContextStates.All), CSS); SS.AddSurrogate(typeof(SpriteFont), new StreamingContext(StreamingContextStates.All), SFSS); SerFormatter.SurrogateSelector = SS; try { foreach (WorldEntity W in UpdateQueue) { if (Skip.Contains(W)) { continue; } UpdateIDs.Add(W.EntityID); W.OnSerializeDo(); MemoryStream EntityStream = new MemoryStream(); SerFormatter.Serialize(EntityStream, W); EntityStream.Close(); Streams.Add(EntityStream.ToArray()); SerializedIDs.Add(W.EntityID); } foreach (WorldEntity W in RenderQueue) { if (Skip.Contains(W)) { continue; } RenderIDs.Add(W.EntityID); if (!SerializedIDs.Contains(W.EntityID)) { W.OnSerializeDo(); MemoryStream EntityStream = new MemoryStream(); SerFormatter.Serialize(EntityStream, W); EntityStream.Close(); Streams.Add(EntityStream.ToArray()); SerializedIDs.Add(W.EntityID); } } } catch (Exception e) { WriteLine("Failed to serialize state due to " + e.GetType().Name + ": " + e.Message); return(null); } RecallableState Out = new RecallableState(); Out.RenderIDs = RenderIDs.ToArray().Select(x => (ulong)x).ToArray(); Out.UpdateIDs = UpdateIDs.ToArray().Select(x => (ulong)x).ToArray(); Out.SerializedEnts = Streams.ToArray().Select(x => (byte[])x).ToArray(); Out.LabelEntity = ScriptProcessor.LabelEntity; Out.SongCom = ScriptProcessor.SongCom; Out.Flags = (Hashtable)Flags.Clone(); return(Out); }
/// <summary> /// Loads a Level in a previously generated World. /// </summary> /// <param name="i_path">The World path.</param> /// <param name="i_pos">>The Level position.</param> /// <param name="i_worldCallback">The callback used to catch the loaded world.</param> /// <param name="i_progressCallback">The callback used to catch the progress value.</param> public IEnumerator LoadLevel(string i_path, Vector2 i_pos, Action <World> i_worldCallback, Action <float> i_progressCallback) { if (!Directory.Exists(i_path)) { yield break; } string[] files = Directory.GetFiles(i_path); if (files.Length != 2 || !(Path.GetExtension(files[0]).ToLower().Equals(".jpg") || Path.GetExtension(files[0]).ToLower().Equals(WORLD_EXT)) || !(Path.GetExtension(files[1]).ToLower().Equals(".jpg") || Path.GetExtension(files[1]).ToLower().Equals(WORLD_EXT)) || Path.GetExtension(files[0]).ToLower().Equals(Path.GetExtension(files[1]).ToLower())) { yield break; } string path1 = files[0].Remove(files[0].Length - Path.GetExtension(files[0]).Length, Path.GetExtension(files[0]).Length); string path2 = files[1].Remove(files[1].Length - Path.GetExtension(files[1]).Length, Path.GetExtension(files[1]).Length); if (!path1.Equals(path2)) { yield break; } //Sets up the FileStream and BinaryFormatter. FileStream file = File.Open(path1 + WORLD_EXT, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); SurrogateSelector ss = new SurrogateSelector(); //Used for World serialization. WorldSerializationSurrogate worldSs = new WorldSerializationSurrogate(); //Used for Level serialization. Vector2SerializationSurrogate v2Ss = new Vector2SerializationSurrogate(); LevelSerializationSurrogate levelSs = new LevelSerializationSurrogate(); //Used for LevelCell serialization. ColorSerializationSurrogate colorSs = new ColorSerializationSurrogate(); LevelCellSerializationSurrogate levelCellSs = new LevelCellSerializationSurrogate(); StreamingContext sc = new StreamingContext(StreamingContextStates.All); ss.AddSurrogate(typeof(World), sc, worldSs); ss.AddSurrogate(typeof(Vector2), sc, v2Ss); ss.AddSurrogate(typeof(Level), sc, levelSs); ss.AddSurrogate(typeof(Color), sc, colorSs); ss.AddSurrogate(typeof(LevelCell), sc, levelCellSs); bf.SurrogateSelector = ss; World aux; //Loads the World. using (file) { aux = ((World)(bf.Deserialize(file))); } yield return(null); //Creates the Level dictionary. aux._levels = new Dictionary <Vector2, Level>(); Level auxLevel; //Loads the Level. file = File.Open(i_path + Path.DirectorySeparatorChar + "Levels" + Path.DirectorySeparatorChar + (int)i_pos.x + "x" + (int)i_pos.y + Path.DirectorySeparatorChar + (int)i_pos.x + "x" + (int)i_pos.y + LEVEL_EXT, FileMode.Open); using (file) { auxLevel = ((Level)(bf.Deserialize(file))); } aux._levels.Add(i_pos, auxLevel); yield return(null); //Creates the LevelCell dictionary. auxLevel._cells = new Dictionary <Vector2, LevelCell>(); float progress = 0; //For each column for (int i = 0; i < ImgProcessManager.Instance._mapSize; i++) { //For each row. for (int j = 0; j < ImgProcessManager.Instance._mapSize; j++) { LevelCell auxCell; Texture2D auxText; //Loads the LevelCell. file = File.Open(i_path + Path.DirectorySeparatorChar + "Levels" + Path.DirectorySeparatorChar + (int)i_pos.x + "x" + (int)i_pos.y + Path.DirectorySeparatorChar + "Cells" + Path.DirectorySeparatorChar + i + "x" + j + Path.DirectorySeparatorChar + i + "x" + j + LEVEL_CELL_EXT, FileMode.Open); using (file) { auxCell = ((LevelCell)(bf.Deserialize(file))); } auxLevel._cells.Add(new Vector2(i, j), auxCell); //Passes the progress value to the callback. progress += 1 / (float)(ImgProcessManager.Instance._mapSize * ImgProcessManager.Instance._mapSize); i_progressCallback(progress); yield return(null); //Loads the LevelCell image. auxText = new Texture2D(4, 4); auxText.LoadImage(File.ReadAllBytes(i_path + Path.DirectorySeparatorChar + "Levels" + Path.DirectorySeparatorChar + (int)i_pos.x + "x" + (int)i_pos.y + Path.DirectorySeparatorChar + "Cells" + Path.DirectorySeparatorChar + i + "x" + j + Path.DirectorySeparatorChar + i + "x" + j + ".jpg")); auxCell._img = auxText; yield return(null); } } //Passes the World to the callback. i_worldCallback(aux); }
public void Execute() { // // 普通のシリアライズ処理. // var obj = MakeSerializableObject(); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); // 成功する. formatter.Serialize(stream, obj); stream.Position = 0; Output.WriteLine(formatter.Deserialize(stream)); } // // シリアライズ不可 (Serializable属性をつけていない) // var obj2 = MakeNotSerializableObject(); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); try { // 対象クラスにSerializable属性が付与されていないので // 以下を実行すると例外が発生する. formatter.Serialize(stream, obj2); stream.Position = 0; Output.WriteLine(formatter.Deserialize(stream)); } catch (SerializationException ex) { Output.WriteLine("[ERROR]: {0}", ex.Message); } } // // シリアル化サロゲート. (SerializationSurrogate) // var obj3 = MakeNotSerializableObject(); using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); // // シリアル化サロゲートを行うために、以下の手順で設定を行う. // // 1.SurrogateSelectorオブジェクトを用意. // 2.自作Surrogateクラスを用意. // 3.SurrogateSelector.AddSurrogateでSurrogateオブジェクトを設定 // 4.SurrogateSelectorをFormatterに設定. // // これにより、シリアライズ不可なオブジェクトをFormatterにてシリアライズ/デシリアライズ // する際にシリアル化サロゲートが行われるようになる。 // var selector = new SurrogateSelector(); var surrogate = new CanNotSerializeSurrogate(); var context = new StreamingContext(StreamingContextStates.All); selector.AddSurrogate(typeof(CanNotSerialize), context, surrogate); formatter.SurrogateSelector = selector; try { // 通常、以下を実行すると例外が発生するが // シリアル化サロゲートを行うので、エラーとならずシリアライズが成功する. formatter.Serialize(stream, obj3); stream.Position = 0; Output.WriteLine(formatter.Deserialize(stream)); } catch (SerializationException ex) { Output.WriteLine("[ERROR]: {0}", ex.Message); } } }
public LegacyPackedMemorySnapshot ReadFromFile(string path) { LegacyPackedMemorySnapshot snapshot = null; string json = null; string extension = Path.GetExtension(path); switch (extension) { case k_Memsnap: var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (Stream stream = File.Open(path, FileMode.Open)) { using (MemoryStream memStr = new MemoryStream()) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); memStr.Write(bytes, 0, (int)stream.Length); memStr.Seek(0, SeekOrigin.Begin); SurrogateSelector ss = new SurrogateSelector(); ss.AddSurrogate(typeof(UnityEditor.MemoryProfiler.PackedMemorySnapshot), new StreamingContext(StreamingContextStates.All), new LegacyFormats.Serialization.LegacyPackedMemorySnapshotSerializationSurrogate(true)); binaryFormatter.SurrogateSelector = ss; object obj = null; try { obj = binaryFormatter.Deserialize(memStr); } catch (SerializationException) { memStr.Seek(0, SeekOrigin.Begin); ss = new SurrogateSelector(); ss.AddSurrogate(typeof(UnityEditor.MemoryProfiler.PackedMemorySnapshot), new StreamingContext(StreamingContextStates.All), new LegacyFormats.Serialization.LegacyPackedMemorySnapshotSerializationSurrogate(false)); binaryFormatter.SurrogateSelector = ss; obj = binaryFormatter.Deserialize(memStr); } snapshot = obj as LegacyPackedMemorySnapshot; } } break; case k_Memsnap2: json = File.ReadAllText(path); //fix binary compatibility for GCHandles json = JsonUtil.JsonFindAndReplace(json, JsonFormatTokenChanges.kGcHandles.OldField, JsonFormatTokenChanges.kGcHandles.NewField); snapshot = UnityEngine.JsonUtility.FromJson <LegacyPackedMemorySnapshot>(json); break; case k_Memsnap3: json = File.ReadAllText(path); //fix binary compatibility for GCHandles json = JsonUtil.JsonFindAndReplace(json, JsonFormatTokenChanges.kGcHandles.OldField, JsonFormatTokenChanges.kGcHandles.NewField); JsonNetConverter converter = new JsonNetConverter(); json = converter.Convert(json); snapshot = UnityEngine.JsonUtility.FromJson <LegacyPackedMemorySnapshot>(json); break; default: throw new System.Exception("Not a supported file format, provided extension was: " + extension); } return(snapshot); }