public T CopyBySerialization <T>(T obj, SerializationBackend serializationBackend) { var result = default(T); if (serializationBackend == SerializationBackend.Binary) { var memoryStream = new MemoryStream(); var writer = new BinarySerializationWriter(memoryStream); writer.Write(obj); writer.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); var reader = new BinarySerializationReader(memoryStream); reader.Serialize(ref result, ArchiveMode.Deserialize); } //else if (serializationBackend == SerializationBackend.Xml) //{ // var xmlDoc = new XmlDocument(); // var xmlElement = xmlDoc.CreateElement("object"); // var writer = new XmlSerializationWriter(xmlElement); // writer.Write(obj); // writer.Flush(); // var reader = new XmlSerializationReader(xmlElement); // reader.Serialize(ref result, ArchiveMode.Deserialize); //} return(result); }
private Shader(GraphicsDevice device, ShaderStage shaderStage, byte[] shaderStageBytecode) : base(device) { this.stage = shaderStage; var shaderStageGl = ConvertShaderStage(shaderStage); // Decode shader StageBytecode var binarySerializationReader = new BinarySerializationReader(new MemoryStream(shaderStageBytecode)); var shaderBytecodeData = new OpenGLShaderBytecodeData(); shaderBytecodeData.Serialize(binarySerializationReader, ArchiveMode.Deserialize); using (GraphicsDevice.UseOpenGLCreationContext()) { resourceId = GL.CreateShader(shaderStageGl); if (shaderBytecodeData.IsBinary) { GL.ShaderBinary(1, ref resourceId, (BinaryFormat)shaderBytecodeData.BinaryFormat, shaderBytecodeData.Binary, shaderBytecodeData.Binary.Length); } else { GL.ShaderSource(resourceId, shaderBytecodeData.Source); GL.CompileShader(resourceId); var log = GL.GetShaderInfoLog(resourceId); int compileStatus; GL.GetShader(resourceId, ShaderParameter.CompileStatus, out compileStatus); if (compileStatus != 1) throw new InvalidOperationException(string.Format("Error while compiling GLSL shader: {0}", log)); } } }
internal void LoadSoundInMemory() { if (PreloadedBuffer.Ptr != IntPtr.Zero) { return; } using (var soundStream = ContentManager.FileProvider.OpenStream(CompressedDataUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable)) using (var decoder = new Celt(SampleRate, CompressedSoundSource.SamplesPerFrame, Channels, true)) { var reader = new BinarySerializationReader(soundStream); var samplesPerPacket = CompressedSoundSource.SamplesPerFrame * Channels; PreloadedBuffer = AudioLayer.BufferCreate(samplesPerPacket * NumberOfPackets * sizeof(short)); var memory = new UnmanagedArray <short>(samplesPerPacket * NumberOfPackets); var offset = 0; var outputBuffer = new short[samplesPerPacket]; for (var i = 0; i < NumberOfPackets; i++) { var len = reader.ReadInt16(); var compressedBuffer = reader.ReadBytes(len); var samplesDecoded = decoder.Decode(compressedBuffer, len, outputBuffer); memory.Write(outputBuffer, offset, 0, samplesDecoded * Channels); offset += samplesDecoded * Channels * sizeof(short); } AudioLayer.BufferFill(PreloadedBuffer, memory.Pointer, memory.Length * sizeof(short), SampleRate, Channels == 1); memory.Dispose(); } }
public CloneContext(CloneContext parent = null) { // Setup memoryStream = new MemoryStream(4096); writer = new BinarySerializationWriter(memoryStream); reader = new BinarySerializationReader(memoryStream); writer.Context.SerializerSelector = SerializerSelector.AssetWithReuse; reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; serializeReferences = writer.Context.Tags.Get(MemberSerializer.ObjectSerializeReferences); deserializeReferences = reader.Context.Tags.Get(MemberSerializer.ObjectDeserializeReferences); if (parent != null) { foreach (var item in parent.serializeReferences) { serializeReferences.Add(item.Key, item.Value); } foreach (var item in parent.deserializeReferences) { deserializeReferences.Add(item); } } }
/// <summary> /// Clones the current value of this cloner with the specified new shadow registry (optional) /// </summary> /// <param name="idRemapping">A dictionary containing the remapping of <see cref="IIdentifiable.Id"/> if <see cref="AssetClonerFlags.GenerateNewIdsForIdentifiableObjects"/> has been passed to the cloner.</param> /// <returns>A clone of the value associated with this cloner.</returns> private object Clone(out Dictionary <Guid, Guid> idRemapping) { var stream = streamOrValueType as Stream; if (stream != null) { stream.Position = 0; var reader = new BinarySerializationReader(stream); reader.Context.SerializerSelector = ClonerSelector; var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0 ? ContentSerializerContext.AttachedReferenceSerialization.AsNull : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion; reader.Context.Set(InvariantObjectListProperty, invariantObjects); reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag); reader.Context.Set(MemberSerializer.ObjectDeserializeCallback, OnObjectDeserialized); object newObject = null; reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize); if ((flags & AssetClonerFlags.RemoveUnloadableObjects) != 0) { UnloadableObjectRemover.Run(newObject); } idRemapping = cloningIdRemapping; return(newObject); } // Else this is a value type, so it is cloned automatically idRemapping = null; return(streamOrValueType); }
private void HandleEffectCompilerRequestedPacket(RemoteEffectCompilerEffectRequested packet, PackageViewModel package) { // Received a shader requested notification, add it to list of "pending shaders", and update count in UI dispatcher.InvokeAsync(() => { CheckEffectLogAsset(package); // Try to decode request try { // Deserialize as an object var binaryReader = new BinarySerializationReader(new MemoryStream(packet.Request)); EffectCompileRequest effectCompileRequest = null; binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; binaryReader.SerializeExtended(ref effectCompileRequest, ArchiveMode.Deserialize, null); // Record in list of pending effects and check if it would result in a new shader // (it is still recorded in list of pending effect, in case EffectLog asset is deleted in the meantime) if (pendingEffects.Add(effectCompileRequest) && !effectLogStore.Contains(effectCompileRequest)) { UpdateImportEffectLogPendingCount(session.ImportEffectLogPendingCount + 1); } } catch { // TODO Log error //Log.Warning("Received an effect compilation request which could not be decoded. Make sure Windows project compiled successfully and is up to date."); } }); }
private static bool ValidateHeader(Stream stream) { var binaryReader = new BinarySerializationReader(stream); // Read header var header = binaryReader.Read <Header>(); var result = new BundleDescription(); result.Header = header; // Check magic header if (header.MagicHeader != Header.MagicHeaderValid) { return(false); } // Ensure size has properly been set if (header.Size != stream.Length) { return(false); } return(true); }
public static AtmosphereData Load(GraphicsDevice device, Stream stream) { var reader = new BinarySerializationReader(stream); var settings = reader.Read <AtmosphereSettings>(); long transmittanceSize = reader.ReadInt64(); long irradianceSize = reader.ReadInt64(); long inscatterSize = reader.ReadInt64(); Texture transmittance, irradiance, inscatter; var buffer = reader.ReadBytes((int)transmittanceSize); using (var data = new MemoryStream(buffer)) transmittance = Texture.Load(device, data); buffer = reader.ReadBytes((int)irradianceSize); using (var data = new MemoryStream(buffer)) irradiance = Texture.Load(device, data); buffer = reader.ReadBytes((int)inscatterSize); using (var data = new MemoryStream(buffer)) inscatter = Texture.Load(device, data); return(new AtmosphereData(settings, transmittance, irradiance, inscatter)); }
public override void Serialize(ref Sound obj, ArchiveMode mode, SerializationStream stream) { if (mode == ArchiveMode.Deserialize) { var services = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey); var audioEngine = services.GetServiceAs <IAudioEngineProvider>()?.AudioEngine; obj.CompressedDataUrl = stream.ReadString(); obj.SampleRate = stream.ReadInt32(); obj.Channels = stream.ReadByte(); obj.StreamFromDisk = stream.ReadBoolean(); obj.Spatialized = stream.ReadBoolean(); obj.NumberOfPackets = stream.ReadInt16(); obj.MaxPacketLength = stream.ReadInt16(); if (!obj.StreamFromDisk && audioEngine != null && audioEngine.State != AudioEngineState.Invalidated && audioEngine.State != AudioEngineState.Disposed) //immediatelly preload all the data and decode { using (var soundStream = ContentManager.FileProvider.OpenStream(obj.CompressedDataUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable)) using (var decoder = new Celt(obj.SampleRate, CompressedSoundSource.SamplesPerFrame, obj.Channels, true)) { var reader = new BinarySerializationReader(soundStream); var samplesPerPacket = CompressedSoundSource.SamplesPerFrame * obj.Channels; obj.PreloadedBuffer = AudioLayer.BufferCreate(samplesPerPacket * obj.NumberOfPackets * sizeof(short)); var memory = new UnmanagedArray <short>(samplesPerPacket * obj.NumberOfPackets); var offset = 0; var outputBuffer = new short[samplesPerPacket]; for (var i = 0; i < obj.NumberOfPackets; i++) { var len = reader.ReadInt16(); var compressedBuffer = reader.ReadBytes(len); var samplesDecoded = decoder.Decode(compressedBuffer, len, outputBuffer); memory.Write(outputBuffer, offset, 0, samplesDecoded * obj.Channels); offset += samplesDecoded * obj.Channels * sizeof(short); } AudioLayer.BufferFill(obj.PreloadedBuffer, memory.Pointer, memory.Length * sizeof(short), obj.SampleRate, obj.Channels == 1); memory.Dispose(); } } if (audioEngine != null) { obj.Attach(audioEngine); } } else { stream.Write(obj.CompressedDataUrl); stream.Write(obj.SampleRate); stream.Write((byte)obj.Channels); stream.Write(obj.StreamFromDisk); stream.Write(obj.Spatialized); stream.Write((short)obj.NumberOfPackets); stream.Write((short)obj.MaxPacketLength); } }
private static object DecodeObject(byte[] serializedObject) { var reader = new BinarySerializationReader(new MemoryStream(serializedObject)); object command = null; reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null); return(command); }
public static List<EntityDefinition> LoadEntities(Stream stream) { List<EntityDefinition> entities = null; var rw = new BinarySerializationReader(stream); rw.Context.Serializer = Serializer; rw.SerializeClass(null, ref entities, ArchiveMode.Deserialize); return entities; }
/// <summary> /// Reads the bundle description from a <see cref="Stream"/>. /// </summary> /// <param name="stream">The stream.</param> /// <returns>A <see cref="BundleDescription"/> representing a description of the bundle.</returns> /// <exception cref="InvalidDataException">Invalid bundle header.</exception> /// <exception cref="InvalidDataException">The bundle has not been properly written.</exception> public static BundleDescription ReadBundleDescription(Stream stream) { var binaryReader = new BinarySerializationReader(stream); // Read header Header header; try { header = binaryReader.Read <Header>(); } catch (InvalidOperationException ex) { throw new InvalidDataException("Invalid bundle header.", ex); } var result = new BundleDescription { Header = header }; // Check magic header if (header.MagicHeader != Header.MagicHeaderValid) { throw new InvalidDataException("Invalid bundle header."); } // Ensure size has properly been set if (header.Size != stream.Length) { throw new InvalidDataException("Bundle has not been properly written."); } try { // Read dependencies var dependencies = result.Dependencies; binaryReader.Serialize(ref dependencies, ArchiveMode.Deserialize); // Read incremental bundles var incrementalBundles = result.IncrementalBundles; binaryReader.Serialize(ref incrementalBundles, ArchiveMode.Deserialize); // Read objects var objects = result.Objects; binaryReader.Serialize(ref objects, ArchiveMode.Deserialize); // Read assets var assets = result.Assets; binaryReader.Serialize(ref assets, ArchiveMode.Deserialize); } catch (InvalidOperationException ex) { throw new InvalidDataException("Bundle has not been properly written.", ex); } return(result); }
public static List <EntityDefinition> LoadEntities(Stream stream) { List <EntityDefinition> entities = null; var rw = new BinarySerializationReader(stream); rw.Context.Serializer = Serializer; rw.SerializeClass(null, ref entities, ArchiveMode.Deserialize); return(entities); }
private static object DecodeObject(byte[] serializedObject) { var reader = new BinarySerializationReader(new MemoryStream(serializedObject)); reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion); object command = null; reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null); return(command); }
/// <summary> /// Clones the specified object, taking special care of <see cref="Entity"/>, <see cref="EntityComponent"/> and external assets. /// User can optionally provides list of cloned objects (list of data reference objects that should be cloned) /// and mapped objects (list of data reference objects that should be ducplicated using the given instance). /// </summary> /// <typeparam name="T"></typeparam> /// <param name="clonedObjects">The cloned objects.</param> /// <param name="mappedObjects">The mapped objects.</param> /// <param name="entity">The entity.</param> /// <returns></returns> private static T Clone <T>(HashSet <object> clonedObjects, TryGetValueFunction <object, object> mappedObjects, T entity) where T : class { if (cloneSerializerSelector == null) { cloneSerializerSelector = new SerializerSelector(); cloneSerializerSelector.ReuseReferences = true; cloneSerializerSelector .RegisterProfile("Default") .RegisterProfile("Clone") .RegisterSerializer(new EntitySerializer()) .RegisterSerializer(new CloneSerializer <string>()) .RegisterSerializer(new CloneSerializer <Effect>()) .RegisterSerializer(new CloneSerializer <Mesh>()) .RegisterSerializer(new CloneSerializer <Model>()) .RegisterSerializer(new CloneSerializer <AnimationClip>()); } // Initialize CloneContext lock (cloneContext) { try { cloneContext.EntitySerializerSelector = cloneSerializerSelector; cloneContext.ClonedObjects = clonedObjects; cloneContext.MappedObjects = mappedObjects; // Serialize var memoryStream = cloneContext.MemoryStream; var writer = new BinarySerializationWriter(memoryStream); writer.Context.SerializerSelector = cloneSerializerSelector; writer.Context.Set(CloneContextProperty, cloneContext); writer.SerializeExtended(entity, ArchiveMode.Serialize, null); // Deserialization reuses this list and expect it to be empty at the beginning. cloneContext.SerializedObjects.Clear(); // Deserialize T result = null; memoryStream.Seek(0, SeekOrigin.Begin); var reader = new BinarySerializationReader(memoryStream); reader.Context.SerializerSelector = cloneSerializerSelector; reader.Context.Set(CloneContextProperty, cloneContext); reader.SerializeExtended(ref result, ArchiveMode.Deserialize, null); return(result); } finally { cloneContext.Cleanup(); } } }
protected override void InitializeInternal() { if (soundStreamUrl != null) { compressedSoundStream = fileProvider.OpenStream(soundStreamUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable); decoder = new Celt(sampleRate, SamplesPerFrame, channels, true); compressedBuffer = new byte[maxCompressedSize]; reader = new BinarySerializationReader(compressedSoundStream); base.InitializeInternal(); } }
public async Task MessageLoop() { try { while (true) { // Get next packet size var bufferSize = await context.ReadStream.ReadInt32Async(); // Get next packet data (until complete) var buffer = new byte[bufferSize]; await context.ReadStream.ReadAllAsync(buffer, 0, bufferSize); // Deserialize as an object var binaryReader = new BinarySerializationReader(new MemoryStream(buffer)); object obj = null; binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; binaryReader.SerializeExtended <object>(ref obj, ArchiveMode.Deserialize, null); // If it's a message, process it separately (StreamId) if (obj is SocketMessage) { var socketMessage = (SocketMessage)obj; ProcessMessage(socketMessage); } // Check if there is a specific handler for this packet type bool handlerFound; Tuple <Action <object>, bool> handler; lock (packetHandlers) { handlerFound = packetHandlers.TryGetValue(obj.GetType(), out handler); // one-time handler if (handlerFound && handler.Item2) { packetHandlers.Remove(obj.GetType()); } } if (handlerFound) { handler.Item1(obj); } } } catch (Exception) { context.Dispose(); throw; } }
private static object Decode(byte[] data, Serializer serializer = null) { object result = null; var stream = new BinarySerializationReader(new MemoryStream(data)); if (serializer != null) { stream.Context.Serializer = serializer; } stream.SerializeExtended(null, ref result, ArchiveMode.Deserialize); return(result); }
protected virtual List <T> ReadEntries(Stream localStream) { var reader = new BinarySerializationReader(localStream); var entries = new List <T>(); while (localStream.Position < localStream.Length) { var entry = new T(); reader.Serialize(ref entry, ArchiveMode.Deserialize); entries.Add(entry); } return(entries); }
public T Deserialize <T>(byte[] bytes) { if (null == bytes || bytes.Length == 0) { return(default(T)); } var reader = new BinarySerializationReader(new MemoryStream(bytes)); reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion); T command = default(T); reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null); return(command); }
/// <summary> /// Loads an <see cref="EffectBytecode" /> from a stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns>EffectBytecode or null if the magic header is not matching</returns> /// <exception cref="System.ArgumentNullException">stream</exception> public static EffectBytecode FromStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } var reader = new BinarySerializationReader(stream); var version = reader.Read <uint>(); // Version is not matching, return null if (version != MagicHeader) { return(null); } return(reader.Read <EffectBytecode>()); }
internal object DeserializeObjectRecursive(AssetReference parentAssetReference, out AssetReference assetReference, string url, Type objType, AssetManagerLoaderSettings settings, ContentSerializerContext otherContext, Stream stream, Type headerObjType, ConverterContext converterContext = null) { // Resolve URL ObjectId objectId; if (!FileProvider.AssetIndexMap.TryGetValue(url, out objectId)) { throw new InvalidOperationException(string.Format("Asset [{0}] not found.", url)); } // Find serializer var serializer = Serializer.GetSerializer(headerObjType, objType); if (serializer == null) { throw new InvalidOperationException(string.Format("Content serializer for {0}/{1} could not be found.", headerObjType, objType)); } var contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Deserialize, this); contentSerializerContext.chunkReferences.AddRange(otherContext.chunkReferences); // Create AssetReference assetReference = new AssetReference(objectId, url, parentAssetReference == null); contentSerializerContext.AssetReference = assetReference; var result = serializer.Construct(contentSerializerContext); var streamReader = new BinarySerializationReader(stream); PrepareSerializerContext(contentSerializerContext, streamReader.Context); contentSerializerContext.ConverterContext = converterContext; result = contentSerializerContext.SerializeContent(streamReader, serializer, result); SetAssetObject(assetReference, result); // Add reference if (parentAssetReference != null) { parentAssetReference.References.Add(assetReference); } return(result); }
/// <summary> /// Loads intermediate data used for building a navigation mesh /// </summary> /// <param name="objectId">The unique Id for this data in the object database</param> /// <returns>The found cached build or null if there is no previous build</returns> private NavigationMesh LoadIntermediateData(ObjectId objectId) { try { var objectDatabase = ContentManager.FileProvider.ObjectDatabase; using (var stream = objectDatabase.OpenStream(objectId)) { var reader = new BinarySerializationReader(stream); NavigationMesh result = new NavigationMesh(); reader.Serialize(ref result, ArchiveMode.Deserialize); return(result); } } catch (Exception ex) { return(null); } }
/// <summary> /// Clones the current value of this cloner with the specified new shadow registry (optional) /// </summary> /// <returns>A clone of the value associated with this cloner.</returns> private object Clone() { var stream = streamOrValueType as Stream; if (stream != null) { stream.Position = 0; var reader = new BinarySerializationReader(stream); reader.Context.SerializerSelector = ClonerSelector; var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0 ? ContentSerializerContext.AttachedReferenceSerialization.AsNull : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion; reader.Context.Set(InvariantObjectListProperty, invariantObjects); reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag); object newObject = null; reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize); // If there are any references, we would like to copy all dynamic properties from ShadowObject to the new instances if (objectReferences != null) { var newObjectReferences = reader.Context.Get(MemberSerializer.ObjectDeserializeReferences); foreach (var objRef in objectReferences) { var innerObject = objRef.Key; var newInnerObject = newObjectReferences[objRef.Value]; // Copy only when objects are non-null if (innerObject != null && newInnerObject != null) { ShadowObject.CopyDynamicProperties(innerObject, newInnerObject); if ((flags & AssetClonerFlags.RemoveOverrides) != 0) { Override.RemoveFrom(newInnerObject); } } } } return(newObject); } // Else this is a value type, so it is cloned automatically return(streamOrValueType); }
void MessageLoop() { while (true) { //var obj = formatter.Deserialize(socketStream); var remaining = socketBinaryReader.ReadInt32(); var buffer = new byte[remaining]; int offset = 0; while (remaining > 0) { int read = socketStream.Read(buffer, offset, remaining); remaining -= read; offset += read; } var binaryReader = new BinarySerializationReader(new MemoryStream(buffer)); object obj = null; binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; binaryReader.SerializeExtended <object>(ref obj, ArchiveMode.Deserialize, null); if (obj is SocketMessage) { var socketMessage = (SocketMessage)obj; ProcessMessage(socketMessage); } bool handlerFound; Tuple <Action <object>, bool> handler; lock (packetHandlers) { handlerFound = packetHandlers.TryGetValue(obj.GetType(), out handler); // one-time handler if (handlerFound && handler.Item2) { packetHandlers.Remove(obj.GetType()); } } if (handlerFound) { handler.Item1(obj); } } }
/// <summary> /// Clones the current value of this cloner with the specified new shadow registry (optional) /// </summary> /// <returns>A clone of the value associated with this cloner.</returns> public object Clone() { var stream = streamOrValueType as Stream; if (stream != null) { stream.Position = 0; var reader = new BinarySerializationReader(stream); reader.Context.SerializerSelector = ClonerSelector; var refFlag = referencesAsNull ? ContentSerializerContext.AttachedReferenceSerialization.AsNull : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion; reader.Context.Set(InvariantObjectListProperty, invariantObjects); reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag); object newObject = null; reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize); return(newObject); } // Else this is a value type, so it is cloned automatically return(streamOrValueType); }
public object Deserialize(byte[] bytes, string typeConfigName) { if (null == typeConfigName) { throw new ArgumentNullException(nameof(typeConfigName)); } var type = typeConfigName.ToType(); if (null == typeConfigName || null == bytes || bytes.Length == 0) { return(type.GetDefault()); } var reader = new BinarySerializationReader(new MemoryStream(bytes)); reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse; reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion); object command = null; reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null); return(command); }
private static T Clone <T>(HashSet <object> clonedObjects, T entity) where T : class { if (cloneSerializerSelector == null) { cloneSerializerSelector = new SerializerSelector(true, "Default", "Clone"); } // Initialize CloneContext lock (CloneContext) { try { CloneContext.EntitySerializerSelector = cloneSerializerSelector; CloneContext.ClonedObjects = clonedObjects; // Serialize var memoryStream = CloneContext.MemoryStream; var writer = new BinarySerializationWriter(memoryStream); writer.Context.SerializerSelector = cloneSerializerSelector; writer.Context.Set(EntityCloner.CloneContextProperty, CloneContext); writer.SerializeExtended(entity, ArchiveMode.Serialize); // Deserialization reuses this list and expect it to be empty at the beginning. CloneContext.SerializedObjects.Clear(); // Deserialize T result = null; memoryStream.Seek(0, SeekOrigin.Begin); var reader = new BinarySerializationReader(memoryStream); reader.Context.SerializerSelector = cloneSerializerSelector; reader.Context.Set(EntityCloner.CloneContextProperty, CloneContext); reader.SerializeExtended(ref result, ArchiveMode.Deserialize); return(result); } finally { CloneContext.Cleanup(); } } }
public static async Task UnpackAPK() { // get the apk last update time var packageManager = PlatformAndroid.Context.PackageManager; var packageInfo = packageManager.GetPackageInfo(PlatformAndroid.Context.PackageName, PackageInfoFlags.Activities); var lastUpdateTime = packageInfo.LastUpdateTime; var sourceDir = PlatformAndroid.Context.ApplicationInfo.SourceDir; // evaluate if asset data should be extracted from apk file var shouldExtractAssets = true; if (ApplicationTemporary.FileExists(LastExtractedApkFileName)) { Int64 extractedLastUpdateTime = 0; using (var file = ApplicationTemporary.OpenStream(LastExtractedApkFileName, VirtualFileMode.Open, VirtualFileAccess.Read)) { var binaryReader = new BinarySerializationReader(file); binaryReader.Serialize(ref extractedLastUpdateTime, ArchiveMode.Deserialize); } shouldExtractAssets = extractedLastUpdateTime != lastUpdateTime; } // Copy assets if (shouldExtractAssets) { var assets = PlatformAndroid.Context.Assets; // Make sure assets exists var logger = GlobalLogger.GetLogger("VFS"); CopyFileOrDirectory(logger, sourceDir, "assets/data/", string.Empty); // update value of extracted last update time using (var stream = ApplicationTemporary.OpenStream(LastExtractedApkFileName, VirtualFileMode.Create, VirtualFileAccess.Write, VirtualFileShare.None)) { var binaryWriter = new BinarySerializationWriter(stream); binaryWriter.Write(lastUpdateTime); } } }
/// <summary> /// Reads the bundle description. /// </summary> /// <param name="stream">The stream.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException"> /// Invalid bundle header /// or /// Bundle has not been properly written /// </exception> public static BundleDescription ReadBundleDescription(Stream stream) { var binaryReader = new BinarySerializationReader(stream); // Read header var header = binaryReader.Read <Header>(); var result = new BundleDescription(); result.Header = header; // Check magic header if (header.MagicHeader != Header.MagicHeaderValid) { throw new InvalidOperationException("Invalid bundle header"); } // Ensure size has properly been set if (header.Size != stream.Length) { throw new InvalidOperationException("Bundle has not been properly written"); } // Read dependencies List <string> dependencies = result.Dependencies; binaryReader.Serialize(ref dependencies, ArchiveMode.Deserialize); // Read objects List <KeyValuePair <ObjectId, ObjectInfo> > objects = result.Objects; binaryReader.Serialize(ref objects, ArchiveMode.Deserialize); // Read assets List <KeyValuePair <string, ObjectId> > assets = result.Assets; binaryReader.Serialize(ref assets, ArchiveMode.Deserialize); return(result); }
internal ChunkHeader ReadChunkHeader(string url) { if (!FileProvider.FileExists(url)) { HandleAssetNotFound(url); return(null); } using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Open, VirtualFileAccess.Read)) { // File does not exist // TODO/Benlitz: Add a log entry for that, it's not expected to happen if (stream == null) { return(null); } // Read header var streamReader = new BinarySerializationReader(stream); return(ChunkHeader.Read(streamReader)); } }
/// <summary> /// Synchronizes files to an android device. /// </summary> /// <param name="logger">The logger.</param> /// <param name="device">The device.</param> /// <param name="fileMapping">The file mapping (relative target path, source HDD filename).</param> /// <param name="androidPath">The android path.</param> /// <param name="cacheFile">The cache file.</param> public static void Synchronize(Logger logger, string device, Dictionary<string, string> fileMapping, string androidPath, string cacheFile) { // Ensure android path ends up with directory separator if (!androidPath.EndsWith("/")) androidPath = androidPath + "/"; // Search files var currentVersions = fileMapping .ToDictionary(x => x.Key, x => new FileVersion(x.Value)); // Try to read previous cache file var previousVersions = new Dictionary<string, FileVersion>(); try { using (var file = File.OpenRead(cacheFile)) { var binaryReader = new BinarySerializationReader(file); binaryReader.Serialize(ref previousVersions, ArchiveMode.Deserialize); } } catch (IOException) { } var filesToRemove = new List<string>(); var filesToUpload = new List<string>(); // Remove unecessary files (in previousVersions but not in currentVersions) foreach (var file in previousVersions.Where(x => !currentVersions.ContainsKey(x.Key))) { filesToRemove.Add(file.Key); } // Upload files that are either not uploaded yet, or not up to date foreach (var file in currentVersions) { FileVersion fileVersion; if (!previousVersions.TryGetValue(file.Key, out fileVersion) || fileVersion.FileSize != file.Value.FileSize || fileVersion.LastModifiedDate != file.Value.LastModifiedDate) { filesToUpload.Add(file.Key); } } // Upload files foreach (var file in filesToUpload) { if (logger != null) logger.Verbose("Copying file {0}", file); RunAdb(device, string.Format("push \"{0}\" \"{1}\"", fileMapping[file], androidPath + file.Replace('\\', '/'))); } // Remove files foreach (var file in filesToRemove) { if (logger != null) logger.Verbose("Deleting file {0}", file); RunAdb(device, string.Format("shell \"rm {0}\"", androidPath + file.Replace('\\', '/'))); } // Write new cache file using (var file = File.Create(cacheFile)) { var binaryWriter = new BinarySerializationWriter(file); binaryWriter.Write(currentVersions); } }
private static object Decode(byte[] data, Serializer serializer = null) { object result = null; var stream = new BinarySerializationReader(new MemoryStream(data)); if (serializer != null) stream.Context.Serializer = serializer; stream.SerializeExtended(null, ref result, ArchiveMode.Deserialize); return result; }