protected override XmlElement WriteChild (ObjectWriter writer, Widget wrapper) { XmlElement child_elem = base.WriteChild (writer, wrapper); if (tabs.Contains (wrapper.Wrapped)) GladeUtils.SetChildProperty (child_elem, "type", "tab"); return child_elem; }
protected override XmlElement WriteChild (ObjectWriter writer, Widget wrapper) { if (writer.Format == FileFormat.Glade || Type == ButtonType.Custom) return base.WriteChild (writer, wrapper); else return null; }
public override void WriteTo(Encoding encoding, ObjectWriter writer, CancellationToken cancellationToken) { if (encoding == null) { base.WriteTo(encoding, writer, cancellationToken); return; } cancellationToken.ThrowIfCancellationRequested(); writer.WriteByte(EncodingSerialization); byte[] value; if (!s_encodingCache.TryGetValue(encoding, out value)) { // we don't have cache, cache it var formatter = new BinaryFormatter(); using (var stream = SerializableBytes.CreateWritableStream()) { // unfortunately, this is only way to properly clone encoding formatter.Serialize(stream, encoding); value = stream.ToArray(); // add if not already exist. otherwise, noop s_encodingCache.TryAdd(encoding, value); } } // write data out writer.WriteValue(value); }
protected override XmlElement WriteChild (ObjectWriter writer, Widget wrapper) { XmlElement child_elem = base.WriteChild (writer, wrapper); if (wrapper.Wrapped == expander.LabelWidget) GladeUtils.SetChildProperty (child_elem, "type", "label_item"); return child_elem; }
public void Write(ObjectWriter writer) { writer.PrimitiveWriter.Write(Name); writer.PrimitiveWriter.Write(Version); writer.PrimitiveWriter.Write(CultureName); writer.PrimitiveWriter.Write((byte)Token.Length); writer.PrimitiveWriter.Write(Token); }
protected override XmlElement WriteProperties (ObjectWriter writer) { XmlElement elem = base.WriteProperties (writer); string group = GroupManager.GladeGroupName (Wrapped); if (group != Wrapped.Name) GladeUtils.SetProperty (elem, "group", group); return elem; }
/// <exception cref="System.Exception"></exception> public virtual void TestStringFragment() { string fragment = "01234567890"; ObjectWriter mapper = new ObjectWriter(); byte[] json = mapper.WriteValueAsBytes(fragment); JsonDocument jsdoc = new JsonDocument(json); NUnit.Framework.Assert.AreEqual(fragment, jsdoc.JsonObject()); }
static void Main(string[] args) { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 4040); Socket ss = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var productos = new ObservableCollection<Producto>(); for (int i = 0; i < 20; i++) { productos.Add(new Producto() { ProductId = i, Nombre = "Producto servidor" + i, Precio = (decimal)i, CantidadDisponible = i * 10, Descripcion = "The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. Usually it is best to" }); } try { ss.Bind(localEndPoint); ss.Listen(10); while (true) { Console.WriteLine("Servidor escuchando por conexiones"); Socket cliente = ss.Accept(); string descCliente = cliente.LocalEndPoint.ToString(); Console.WriteLine("Conexion aceptada " + descCliente); ObjectWriter w = new ObjectWriter(cliente); ObjectReader r = new ObjectReader(cliente); Transacciones transaccion = (Transacciones)r.ReadInt32(); switch (transaccion) { case Transacciones.SolicitarCarrito: Console.WriteLine("\tSolicitud de carrito por: " + descCliente); w.WriteInt32(productos.Count); for (int i = 0; i < productos.Count; i++) { w.WriteObject<Producto>(productos[i]); } break; case Transacciones.RealizarCompra: Console.WriteLine("\tOrden de compra de " + descCliente); Orden o = r.ReadObject<Orden>(); productos[o.ProductId].CantidadDisponible -= o.Cantidad; break; } Console.WriteLine("Conexion terminada " + descCliente); cliente.Shutdown(SocketShutdown.Both); cliente.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); } }
protected override XmlElement WriteProperties (ObjectWriter writer) { XmlElement elem = base.WriteProperties (writer); if (menuInfo != null) elem.AppendChild (writer.XmlDocument.ImportNode (menuInfo, true)); else elem.AppendChild (actionTree.Write (writer.XmlDocument, writer.Format)); return elem; }
public override XmlElement Write (ObjectWriter writer) { XmlElement group = writer.XmlDocument.CreateElement ("action-group"); group.SetAttribute ("name", name); if (writer.CreateUndoInfo) group.SetAttribute ("undoId", UndoId); foreach (Action ac in actions) { if (ac.Name.Length > 0) group.AppendChild (writer.WriteObject (ac)); } return group; }
private object Load(XamlXmlReader reader) { XamlObjectWriter writer = new ObjectWriter(); while (reader.Read()) { writer.WriteNode(reader); } writer.Close(); reader.Close(); if (writer.Result is DependencyObject && !(writer is INameScope)) ((DependencyObject)writer.Result).SetValue(NameScope.NameScopeProperty, writer.RootNameScope); return writer.Result; }
/// <exception cref="System.Exception"></exception> public virtual void TestJsonObject() { IDictionary<string, object> dict = new Dictionary<string, object>(); dict.Put("id", "01234567890"); dict.Put("foo", "bar"); dict.Put("int", 5); dict.Put("double", 3.5); dict.Put("bool", true); dict.Put("date", new DateTime().ToString()); ObjectWriter mapper = new ObjectWriter(); byte[] json = mapper.WriteValueAsBytes(dict); JsonDocument jsdoc = new JsonDocument(json); NUnit.Framework.Assert.AreEqual(dict, jsdoc.JsonObject()); }
/// <exception cref="System.Exception"></exception> public virtual void TestJsonArray() { IList<object> array = new AList<object>(); array.AddItem("01234567890"); array.AddItem("bar"); array.AddItem(5); array.AddItem(3.5); array.AddItem(true); array.AddItem(new DateTime().ToString()); ObjectWriter mapper = new ObjectWriter(); byte[] json = mapper.WriteValueAsBytes(array); JsonDocument jsdoc = new JsonDocument(json); NUnit.Framework.Assert.AreEqual(array, jsdoc.JsonObject()); }
// create the same JSON encoding used by TouchDB // this lets us test comparisons as they would be encoded public virtual string Encode(object obj) { ObjectWriter mapper = new ObjectWriter(); try { byte[] bytes = mapper.WriteValueAsBytes(obj); string result = Sharpen.Runtime.GetStringForBytes(bytes); return result; } catch (Exception e) { Log.E(Tag, "Error encoding JSON", e); return null; } }
public int RealizaCompra(int productId, int cantidad) { IPEndPoint remotePoint = new IPEndPoint(IPAddress.Loopback, 4040); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(remotePoint); ObjectReader r = new ObjectReader(s); ObjectWriter w = new ObjectWriter(s); w.WriteInt32((int)Transacciones.RealizarCompra); Orden o = new Orden { ProductId = productId, Cantidad = cantidad }; w.WriteObject<Orden>(o); s.Shutdown(SocketShutdown.Both); s.Close(); return 1; }
public ObjectSerializer(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); Type = type; //TODO: remove version info var typeName = type.GetShortAssemblyQualifiedName(); // ReSharper disable once PossibleNullReferenceException // ReSharper disable once AssignNullToNotNullAttribute var typeNameBytes = typeName.ToUtf8Bytes(); var fields = type.GetFieldInfosForType(); var fieldNames = fields.Select(field => field.Name.ToUtf8Bytes()).ToList(); var versionInfo = TypeEx.GetTypeManifest(fieldNames); //precalculate the entire manifest for this serializer //this helps us to minimize calls to Stream.Write/WriteByte _manifest = new[] {ManifestFull} .Concat(BitConverter.GetBytes(typeNameBytes.Length)) .Concat(typeNameBytes) .ToArray(); //serializer id 255 + assembly qualified name //TODO: this should only work this way for standard poco objects //custom object serializers should not emit their inner fields //this is the same as the above, but including all field names of the type, in alphabetical order _manifestWithVersionInfo = new[] {ManifestVersion} .Concat(BitConverter.GetBytes(typeNameBytes.Length)) .Concat(typeNameBytes) .Concat(versionInfo) .ToArray(); //serializer id 255 + assembly qualified name + versionInfo //initialize reader and writer with dummy handlers that wait until the serializer is fully initialized _writer = (stream, o, session) => { SpinWait.SpinUntil(() => _isInitialized); WriteValue(stream, o, session); }; _reader = (stream, session) => { SpinWait.SpinUntil(() => _isInitialized); return ReadValue(stream, session); }; }
public void ShouldHandleTwoWritesAndReads() { var strings = new [] { "One", "Two" }; var stream = new MemoryStream(); var writer = new ObjectWriter(stream); writer.WriteObject(strings[0]); writer.WriteObject(strings[1]); var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); var reader = new ObjectReader(stream); Assert.AreEqual(strings[0], reader.ReadObject<string>()); Assert.AreEqual(strings[1], reader.ReadObject<string>()); Assert.AreEqual(position, stream.Position); }
public void Write(ObjectWriter writer) { writer.TouchAndWriteTypeId(UnderlyingMethod.ReflectedType); var methodParameters = UnderlyingMethod.GetParameters(); if(UnderlyingMethod.IsGenericMethod) { var genericDefinition = UnderlyingMethod.GetGenericMethodDefinition(); var genericArguments = UnderlyingMethod.GetGenericArguments(); var genericMethodParamters = genericDefinition.GetParameters(); writer.PrimitiveWriter.Write(genericDefinition.Name); writer.PrimitiveWriter.Write(genericArguments.Length); for(int i = 0; i < genericArguments.Length; i++) { writer.TouchAndWriteTypeId(genericArguments[i]); } writer.PrimitiveWriter.Write(genericMethodParamters.Length); for(int i = 0; i < genericMethodParamters.Length; i++) { writer.PrimitiveWriter.Write(genericMethodParamters[i].ParameterType.IsGenericParameter); if(genericMethodParamters[i].ParameterType.IsGenericParameter) { writer.PrimitiveWriter.Write(genericMethodParamters[i].ParameterType.GenericParameterPosition); } else { writer.TouchAndWriteTypeId(methodParameters[i].ParameterType); } } } else { writer.PrimitiveWriter.Write(UnderlyingMethod.Name); writer.PrimitiveWriter.Write(0); // no generic arguments writer.PrimitiveWriter.Write(methodParameters.Length); foreach(var p in methodParameters) { writer.TouchAndWriteTypeId(p.ParameterType); } } }
public void ShouldHandleTwoWritesAndReads() { var strings = new [] { "One", "Two" }; var stream = new MemoryStream(); var writer = new ObjectWriter(stream, Serializer.GetReflectionBasedWriteMethods()); writer.WriteObject(strings[0]); writer.WriteObject(strings[1]); writer.Flush(); var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); var reader = new ObjectReader(stream, Serializer.GetReflectionBasedReadMethods(false)); Assert.AreEqual(strings[0], reader.ReadObject<string>()); Assert.AreEqual(strings[1], reader.ReadObject<string>()); reader.Flush(); Assert.AreEqual(position, stream.Position); }
protected override XmlElement WriteProperties (ObjectWriter writer) { XmlElement elem = base.WriteProperties (writer); if (type != ButtonType.StockItem && imageInfo != null) { if (writer.Format == FileFormat.Glade) { switch (imageInfo.Source) { case ImageSource.File: GladeUtils.SetProperty (elem, "icon", imageInfo.Name); break; case ImageSource.Theme: GladeUtils.SetProperty (elem, "stock_id", imageInfo.Name); break; default: throw new System.NotSupportedException ("Image source not supported by Glade."); } } } return elem; }
public void ShouldHandleTwoWritesAndReads() { var strings = new [] { "One", "Two" }; var typeIndices = new List<Type> { typeof(string) }; var stream = new MemoryStream(); var writer = new ObjectWriter(stream, typeIndices); writer.WriteObject(strings[0]); writer.WriteObject(strings[1]); var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); var types = typeIndices.ToArray(); var reader = new ObjectReader(stream, types, false); Assert.AreEqual(strings[0], reader.ReadObject<string>()); Assert.AreEqual(strings[1], reader.ReadObject<string>()); Assert.AreEqual(position, stream.Position); }
public ObservableCollection<Producto> RecuperaProductos() { var resultado = new ObservableCollection<Producto>(); IPEndPoint remotePoint = new IPEndPoint(IPAddress.Loopback, 4040); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(remotePoint); ObjectReader r = new ObjectReader(s); ObjectWriter w = new ObjectWriter(s); w.WriteInt32((int)Transacciones.SolicitarCarrito); int cont = r.ReadInt32(); for (int i = 0; i < cont; i++) { Producto p = r.ReadObject<Producto>(); if (p != null) resultado.Add(p); } s.Shutdown(SocketShutdown.Both); s.Close(); return resultado; }
protected override XmlElement WriteProperties (ObjectWriter writer) { XmlElement elem = base.WriteProperties (writer); if (imageInfo != null) { if (writer.Format == FileFormat.Glade) { // The generated pixbuf property doesn't have a valid value, it needs to be replaced. GladeUtils.ExtractProperty (elem, "pixbuf", ""); switch (imageInfo.Source) { case ImageSource.File: GladeUtils.SetProperty (elem, "pixbuf", imageInfo.Name); break; case ImageSource.Theme: GladeUtils.SetProperty (elem, "stock", imageInfo.Name); GladeUtils.SetProperty (elem, "icon_size", ((int)imageInfo.ThemeIconSize).ToString ()); break; default: throw new System.NotSupportedException ("Image source not supported by Glade."); } } } return elem; }
public void test022_createCommitTag() { ObjectId emptyId = new ObjectWriter(db).WriteBlob(new byte[0]); var almostEmptyTree = new Tree(db); almostEmptyTree.AddEntry(new FileTreeEntry(almostEmptyTree, emptyId, Constants.encodeASCII("empty"), false)); ObjectId almostEmptyTreeId = new ObjectWriter(db).WriteTree(almostEmptyTree); var almostEmptyCommit = new Commit(db) { Author = new PersonIdent(jauthor, 1154236443L, -2*60), Committer = new PersonIdent(jauthor, 1154236443L, -2*60), Message = "test022\n", TreeId = almostEmptyTreeId }; ObjectId almostEmptyCommitId = new ObjectWriter(db).WriteCommit(almostEmptyCommit); var t = new Tag(db) { Id = almostEmptyCommitId, TagType = "commit", TagName = "test022", Author = new PersonIdent(jauthor, 1154236443L, -4*60), Message = "test022 tagged\n" }; t.Save(); Assert.AreEqual("0ce2ebdb36076ef0b38adbe077a07d43b43e3807", t.TagId.ToString()); Tag mapTag = db.MapTag("test022"); Assert.AreEqual("commit", mapTag.TagType); Assert.AreEqual("test022 tagged\n", mapTag.Message); Assert.AreEqual(new PersonIdent(jauthor, 1154236443L, -4 * 60), mapTag.Author); Assert.AreEqual("b5d3b45a96b340441f5abb9080411705c51cc86c", mapTag.Id.ToString()); }
protected void WriteOptionTo <T>(OptionSet options, Option <CodeStyleOption <T> > option, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var value = options.GetOption(option); writer.WriteString(value.ToXElement().ToString()); }
private void WriteOptionTo <T>(OptionSet options, string language, PerLanguageOption <CodeStyleOption <T> > option, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var value = options.GetOption(option, language); writer.WriteString(value.ToXElement().ToString()); }
private Task WriteNoAssetAsync(ObjectWriter writer) { writer.WriteInt32(0); return(SpecializedTasks.EmptyTask); }
protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteCompressedUInt((uint)this.xmlErrorCode); }
private void WriteOptionTo(OptionSet options, string language, PerLanguageOption <NamingStylePreferences> option, ObjectWriter writer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var value = options.GetOption(option, language); writer.WriteString(value.CreateXElement().ToString()); }
internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteString(this.TextField); }
internal protected new virtual void WriteTo(ObjectWriter writer) { base.WriteTo(writer); }
public void Compile() { NodeFactory.NameMangler = NameMangler; string systemModuleName = ((IAssemblyDesc)_typeSystemContext.SystemModule).GetName().Name; // TODO: just something to get Runtime.Base compiled if (systemModuleName != "System.Private.CoreLib") { NodeFactory.CompilationUnitPrefix = systemModuleName.Replace(".", "_"); } else { NodeFactory.CompilationUnitPrefix = NameMangler.SanitizeName(Path.GetFileNameWithoutExtension(Options.OutputFilePath)); } if (_options.IsCppCodeGen) { _nodeFactory = new CppCodegenNodeFactory(_typeSystemContext, _compilationModuleGroup); } else { _nodeFactory = new RyuJitNodeFactory(_typeSystemContext, _compilationModuleGroup); } // Choose which dependency graph implementation to use based on the amount of logging requested. if (_options.DgmlLog == null) { // No log uses the NoLogStrategy _dependencyGraph = new DependencyAnalyzer <NoLogStrategy <NodeFactory>, NodeFactory>(_nodeFactory, null); } else { if (_options.FullLog) { // Full log uses the full log strategy _dependencyGraph = new DependencyAnalyzer <FullGraphLogStrategy <NodeFactory>, NodeFactory>(_nodeFactory, null); } else { // Otherwise, use the first mark strategy _dependencyGraph = new DependencyAnalyzer <FirstMarkLogStrategy <NodeFactory>, NodeFactory>(_nodeFactory, null); } } _nodeFactory.AttachToDependencyGraph(_dependencyGraph); if (_options.IsCppCodeGen) { _cppWriter = new CppCodeGen.CppWriter(this); _dependencyGraph.ComputeDependencyRoutine += CppCodeGenComputeDependencyNodeDependencies; var nodes = _dependencyGraph.MarkedNodeList; _cppWriter.OutputCode(nodes, _compilationModuleGroup.StartupCodeMain, _nodeFactory); } else { _corInfo = new CorInfoImpl(this, new JitConfigProvider(_options.CodegenOptions)); _dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies; var nodes = _dependencyGraph.MarkedNodeList; ObjectWriter.EmitObject(_options.OutputFilePath, nodes, _nodeFactory); } if (_options.DgmlLog != null) { using (FileStream dgmlOutput = new FileStream(_options.DgmlLog, FileMode.Create)) { DgmlWriter.WriteDependencyGraphToStream(dgmlOutput, _dependencyGraph); dgmlOutput.Flush(); } } }
/// <summary> /// Generalized function for loading/creating/persisting data. Used as the common core /// code for serialization of SymbolTreeInfos and SpellCheckers. /// </summary> private static async Task <T> LoadOrCreateAsync <T>( Solution solution, Checksum checksum, string filePath, bool loadOnly, Func <T> create, string keySuffix, Func <T, Checksum> getPersistedChecksum, Func <ObjectReader, T> readObject, CancellationToken cancellationToken) where T : class, IObjectWritable { if (checksum == null) { return(loadOnly ? null : create()); } // Ok, we can use persistence. First try to load from the persistence service. var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService <IPersistentStorageService>(); T result; using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false)) { // Get the unique key to identify our data. var key = PrefixMetadataSymbolTreeInfo + keySuffix + "_" + filePath; using (var stream = await storage.ReadStreamAsync(key, cancellationToken).ConfigureAwait(false)) using (var reader = ObjectReader.TryGetReader(stream)) { if (reader != null) { // We have some previously persisted data. Attempt to read it back. // If we're able to, and the version of the persisted data matches // our version, then we can reuse this instance. result = readObject(reader); if (result != null && checksum == getPersistedChecksum(result)) { return(result); } } } cancellationToken.ThrowIfCancellationRequested(); // Couldn't read from the persistence service. If we've been asked to only load // data and not create new instances in their absense, then there's nothing left // to do at this point. if (loadOnly) { return(null); } // Now, try to create a new instance and write it to the persistence service. result = create(); if (result != null) { using (var stream = SerializableBytes.CreateWritableStream()) using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken)) { result.WriteTo(writer); stream.Position = 0; await storage.WriteStreamAsync(key, stream, cancellationToken).ConfigureAwait(false); } } } return(result); }
private bool WriteIdentifierLocations(EsentStorage.Key key, Document document, VersionStamp version, SyntaxNode root, CancellationToken cancellationToken) { // delete any existing data if (!DeleteIdentifierLocations(key, cancellationToken)) { return(false); } var identifierMap = SharedPools.StringIgnoreCaseDictionary <int>().AllocateAndClear(); Dictionary <string, List <int> > map = null; try { map = CreateIdentifierLocations(document, root, cancellationToken); // okay, write new data using (var accessor = _esentStorage.GetIdentifierLocationTableAccessor()) { // make sure I have all identifier ready before starting big insertion int identifierId; foreach (var identifier in map.Keys) { if (!TryGetUniqueIdentifierId(identifier, out identifierId)) { return(false); } identifierMap[identifier] = identifierId; } // save whole map var uncommittedCount = 0; foreach (var kv in map) { cancellationToken.ThrowIfCancellationRequested(); var identifier = kv.Key; var positions = kv.Value; if ((uncommittedCount + positions.Count) > FlushThreshold) { accessor.Flush(); uncommittedCount = 0; } accessor.PrepareBatchOneInsert(); identifierId = identifierMap[identifier]; using (var stream = accessor.GetWriteStream(key, identifierId)) using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken)) { writer.WriteString(IdentifierSetSerializationVersion); WriteList(writer, positions); } accessor.FinishBatchOneInsert(); uncommittedCount += positions.Count; } // save special identifier that indicates version for this document if (!TrySaveIdentifierSetVersion(accessor, key, version)) { return(false); } return(accessor.ApplyChanges()); } } finally { SharedPools.StringIgnoreCaseDictionary <int>().ClearAndFree(identifierMap); Free(map); } }
private Task WriteNoAssetAsync(ObjectWriter writer) { writer.WriteInt32(0); return(Task.CompletedTask); }
protected override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteUInt32((uint)_xmlErrorCode); }
public override Task WriteObjectToAsync(ObjectWriter writer, CancellationToken cancellationToken) { _serializer.Serialize(_value, writer, cancellationToken); return(Task.CompletedTask); }
public void WriteTo(ObjectWriter writer) => _literalsFilter.WriteTo(writer);
public override Task WriteObjectToAsync(ObjectWriter writer, CancellationToken cancellationToken) => throw new NotImplementedException("should not be called");
internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_child0); writer.WriteValue(_child1); }
public void WriteTypeStamp(ObjectWriter writer) { writer.Modules.TouchAndWriteId(TypeModule); writer.PrimitiveWriter.Write(GenericFullName); }
/// <summary> /// Generalized function for loading/creating/persisting data. Used as the common core /// code for serialization of SymbolTreeInfos and SpellCheckers. /// </summary> private static async Task <T> LoadOrCreateAsync <T>( Solution solution, IAssemblySymbol assembly, string filePath, bool loadOnly, Func <VersionStamp, T> create, string keySuffix, Func <T, VersionStamp> getVersion, Func <ObjectReader, T> readObject, Action <ObjectWriter, T> writeObject, CancellationToken cancellationToken) where T : class { // See if we can even use serialization. If not, we'll just have to make the value // from scratch. string prefix; VersionStamp version; if (ShouldCreateFromScratch(solution, assembly, filePath, out prefix, out version, cancellationToken)) { return(loadOnly ? null : create(VersionStamp.Default)); } // Ok, we can use persistence. First try to load from the persistence service. var persistentStorageService = solution.Workspace.Services.GetService <IPersistentStorageService>(); T result; using (var storage = persistentStorageService.GetStorage(solution)) { // Get the unique key to identify our data. var key = PrefixMetadataSymbolTreeInfo + prefix + keySuffix; using (var stream = await storage.ReadStreamAsync(key, cancellationToken).ConfigureAwait(false)) { if (stream != null) { using (var reader = new ObjectReader(stream)) { // We have some previously persisted data. Attempt to read it back. // If we're able to, and the version of the persisted data matches // our version, then we can reuse this instance. result = readObject(reader); if (result != null && VersionStamp.CanReusePersistedVersion(version, getVersion(result))) { return(result); } } } } cancellationToken.ThrowIfCancellationRequested(); // Couldn't read from the persistence service. If we've been asked to only load // data and not create new instances in their absense, then there's nothing left // to do at this point. if (loadOnly) { return(null); } // Now, try to create a new instance and write it to the persistence service. result = create(version); if (result != null) { using (var stream = SerializableBytes.CreateWritableStream()) using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken)) { writeObject(writer, result); stream.Position = 0; await storage.WriteStreamAsync(key, stream, cancellationToken).ConfigureAwait(false); } } } return(result); }
public override void Write(ObjectWriter writer) { WriteTypeStamp(writer); WriteStructureStampIfNeeded(writer); }
public override Task WriteObjectToAsync(ObjectWriter writer, CancellationToken cancellationToken) { _serializer.Serialize(_value, writer, cancellationToken); return(SpecializedTasks.EmptyTask); }
void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance }
internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(_trailing); }
public void test024_createCommitNonAscii() { ObjectId emptyId = new ObjectWriter(db).WriteBlob(new byte[0]); var almostEmptyTree = new Tree(db); almostEmptyTree.AddEntry(new FileTreeEntry(almostEmptyTree, emptyId, Constants.encodeASCII("empty"), false)); ObjectId almostEmptyTreeId = new ObjectWriter(db).WriteTree(almostEmptyTree); var commit = new Commit(db) { TreeId = almostEmptyTreeId, Author = new PersonIdent("Joe H\u00e4cker", "*****@*****.**", 4294967295L, 60), Committer = new PersonIdent("Joe Hacker", "*****@*****.**", 4294967295L, 60), Encoding = Encoding.GetEncoding("ISO-8859-1"), Message = "\u00dcbergeeks" }; ObjectId cid = new ObjectWriter(db).WriteCommit(commit); var s = new Inspector(db).Inspect(cid); Assert.AreEqual("2979b39d385014b33287054b87f77bcb3ecb5ebf", cid.ToString()); }
public void Compute_SHA() { byte[] data = Encoding.GetEncoding("ISO-8859-1").GetBytes("test025 some data, more than 16 bytes to get good coverage"); ObjectId id = new ObjectWriter(db).ComputeBlobSha1(data.Length, new MemoryStream(data)); Assert.AreEqual("4f561df5ecf0dfbd53a0dc0f37262fef075d9dde", id.ToString()); }
protected void WriteVersion(ObjectWriter writer, string formatVersion) { writer.WriteString(formatVersion); this.Version.WriteTo(writer); }
/** * Write all index trees to the object store, returning the root tree. * * @param ow * the writer to use when serializing to the store. * @return identity for the root tree. * @throws UnmergedPathException * one or more paths contain higher-order stages (stage > 0), * which cannot be stored in a tree object. * @ * an unexpected error occurred writing to the object store. */ public ObjectId writeTree(ObjectWriter ow) { return getCacheTree(true).writeTree(sortedEntries, 0, 0, ow); }
public void WriteJS(IndentedTextWriter textWriter) { using (ObjectWriter writer = new ObjectWriter(textWriter)) { writer.Write("name", this.name); writer.Write("type", this.type); writer.Write("id", this.id); if (this.source != null) { writer.Write("source", this.source); } string url = CompendiumUrl; if (url != null) { writer.Write("compendiumUrl", url); } if (Specifics.Count > 0) { writer.WritePrefix("specifics", ""); textWriter.Indent++; using (ObjectWriter specificWriter = new ObjectWriter(textWriter)) { foreach (KeyValuePair <string, string> specific in Specifics) { specificWriter.Write(specific.Key, specific.Value); } } textWriter.Indent--; } if (Categories.Count > 0) { writer.WritePrefix("categories", "["); Identifier[] categories = Categories.ToArray(); for (int i = 0; i < categories.Length; i++) { if (i != 0) { textWriter.Write(", "); } textWriter.Write("\"{0}\"", Converter.QuoteString(categories[i])); } textWriter.Write("]"); } if (Rules.Count > 0) { writer.WritePrefix("rules", "function(model) {"); textWriter.Indent++; textWriter.WriteLine(); foreach (Rule rule in Rules) { rule.WriteJS(textWriter); } textWriter.Indent -= 1; textWriter.Write("}"); } } }
public abstract void WriteTo(OptionSet options, ObjectWriter writer, CancellationToken cancellationToken);
public void test023_createCommitNonAnullii() { ObjectId emptyId = new ObjectWriter(db).WriteBlob(new byte[0]); var almostEmptyTree = new Tree(db); almostEmptyTree.AddEntry(new FileTreeEntry(almostEmptyTree, emptyId, Constants.encodeASCII("empty"), false)); ObjectId almostEmptyTreeId = new ObjectWriter(db).WriteTree(almostEmptyTree); var commit = new Commit(db) { TreeId = almostEmptyTreeId, Author = new PersonIdent("Joe H\u00e4cker", "*****@*****.**", 4294967295L, 60), Committer = new PersonIdent("Joe Hacker", "*****@*****.**", 4294967295L, 60), Encoding = Constants.CHARSET, Message = "\u00dcbergeeks" }; ObjectId cid = new ObjectWriter(db).WriteCommit(commit); Assert.AreEqual("4680908112778718f37e686cbebcc912730b3154", cid.ToString()); }
public override ValueSerializer BuildSerializer(Serializer serializer, Type type, CachedReadConcurrentDictionary <Type, ValueSerializer> typeMapping) { var x = new ObjectSerializer(type); typeMapping.TryAdd(type, x); var preserveObjectReferences = serializer.Options.PreserveObjectReferences; var elementType = GetEnumerableType(type) ?? typeof(object); var elementSerializer = serializer.GetSerializerByType(elementType); var countProperty = type.GetProperty("Count"); var addMethod = type.GetMethod("Add", BindingFlagsEx.All); var enumerableConstructor = GetEnumerableConstructor(type); Func <object, int> countGetter = o => (int)countProperty.GetValue(o); ObjectReader reader = null; if (HasParameterlessConstructor(type) && addMethod != null) { var add = CompileMethodToDelegate(addMethod, type, elementType); reader = (stream, session) => { var instance = Activator.CreateInstance(type, true); if (preserveObjectReferences) { session.TrackDeserializedObject(instance); } var count = stream.ReadInt32(session); for (var i = 0; i < count; i++) { var value = stream.ReadObject(session); add(instance, value); } return(instance); }; } else if (enumerableConstructor != null) { var construct = CompileCtorToDelegate(enumerableConstructor, elementType.MakeArrayType()); reader = (stream, session) => { var count = stream.ReadInt32(session); var items = Array.CreateInstance(elementType, count); for (var i = 0; i < count; i++) { var value = stream.ReadObject(session); items.SetValue(value, i); } var instance = construct(items); if (preserveObjectReferences) { session.TrackDeserializedObject(instance); } return(instance); }; } ObjectWriter writer = (stream, o, session) => { if (preserveObjectReferences) { session.TrackSerializedObject(o); } Int32Serializer.WriteValueImpl(stream, countGetter(o), session); var enumerable = o as IEnumerable; // ReSharper disable once PossibleNullReferenceException foreach (var value in enumerable) { stream.WriteObject(value, elementType, elementSerializer, preserveObjectReferences, session); } }; x.Initialize(reader, writer); return(x); }
public void Write_Blob() { ObjectId id = new ObjectWriter(db).WriteBlob(new FileInfo("Resources/single_file_commit/i-am-a-file")); Assert.AreEqual("95ea6a6859af6791464bd8b6de76ad5a6f9fad81", id.ToString()); Assert.AreEqual(Inspector.Inspect("Resources/single_file_commit", "95ea6a6859af6791464bd8b6de76ad5a6f9fad81"), new Inspector(db).Inspect(id)); writeTrashFile("i-am-a-file", "and this is the data in me\r\n\r\n"); id = new ObjectWriter(db).WriteBlob(new FileInfo(trash+"/i-am-a-file")); Assert.AreEqual("95ea6a6859af6791464bd8b6de76ad5a6f9fad81", id.ToString()); }
protected override PhpString CommonSerialize(Context ctx, PhpValue variable, RuntimeTypeHandle caller) { return(ObjectWriter.Serialize(ctx, variable, _encodeOptions, caller)); }
public override XmlElement Write (ObjectWriter writer) { XmlElement elem = writer.XmlDocument.CreateElement ("action"); elem.SetAttribute ("id", Name); WidgetUtils.GetProps (this, elem); WidgetUtils.GetSignals (this, elem); if (writer.CreateUndoInfo) elem.SetAttribute ("undoId", UndoId); return elem; }
/// <summary> /// Write all index trees to the object store, returning the root tree. /// </summary> /// <param name="ow"> /// The writer to use when serializing to the store. /// </param> /// <returns> identity for the root tree. </returns> /// <exception cref="UnmergedPathException"> /// One or more paths contain higher-order stages (stage > 0), /// which cannot be stored in a tree object. /// </exception> /// <exception cref="InvalidOperationException"> /// One or more paths contain an invalid mode which should never /// appear in a tree object. /// </exception> /// <exception cref="IOException"> /// An unexpected error occurred writing to the object store. /// </exception> public ObjectId writeTree(ObjectWriter ow) { return(getCacheTree(true).writeTree(_sortedEntries, 0, 0, ow)); }
internal override void WriteTo(ObjectWriter writer) { base.WriteTo(writer); writer.WriteValue(this.LeadingField); writer.WriteValue(this.TrailingField); }
public abstract void WriteTo(CompilationOptions options, ObjectWriter writer, CancellationToken cancellationToken);