Exemplo n.º 1
0
        public XElement Serialize <T>(T value)
        {
            var declaredType = typeof(T);
            var type         = value != null?value.GetType() : declaredType;

            var settings = new XmlWriterSettings();

            settings.CheckCharacters = false;
            settings.NewLineHandling = NewLineHandling.Entitize;
            using (var cms = ChunkedMemoryStream.Create())
                using (var xw = XmlWriter.Create(cms, settings))
                    using (var dw = XmlDictionaryWriter.CreateDictionaryWriter(xw))
                    {
                        var serializer = new DataContractSerializer(type);
                        serializer.WriteObject(dw, value, GenericResolver);
                        dw.Flush();
                        cms.Position = 0;
                        using (var sr = new StreamReader(cms))
                        {
                            var doc = XElement.Load(sr);
                            if (type != declaredType || !(declaredType.IsClass || declaredType.IsValueType))
                            {
                                doc.Add(new XAttribute("type", type.FullName));
                            }
                            return(doc);
                        }
                    }
        }
Exemplo n.º 2
0
        public object Deserialize(Stream s, Type target, StreamingContext context)
        {
            var serializer = new DataContractSerializer(target);
            var result     = serializer.ReadObject(s);

            if (context.Context == null)
            {
                return(result);
            }
            //TODO fix double serialization because of context
            using (var cms = ChunkedMemoryStream.Create())
            {
#if NETSTANDARD2_0
                Json.Serialize(result, cms, true);
                cms.Position = 0;
                return(Json.Deserialize(cms, target, context));
#else
                var ns = new NetDataContractSerializer(context);
                ns.Serialize(cms, result);
                ns.Binder    = GenericBinder;
                cms.Position = 0;
                return(ns.Deserialize(cms));
#endif
            }
        }
Exemplo n.º 3
0
 public static void Serialize(Image value, TextWriter sw)
 {
     if (value == null)
     {
         sw.Write("null");
     }
     else
     {
         sw.Write('"');
         using (var cms = ChunkedMemoryStream.Create())
         {
             if (Codecs.Contains(value.RawFormat.Guid))
             {
                 value.Save(cms, value.RawFormat);
             }
             else
             {
                 value.Save(cms, ImageFormat.Png);
             }
             cms.Position = 0;
             cms.ToBase64Writer(sw);
         }
         sw.Write('"');
     }
 }
Exemplo n.º 4
0
        public static Stream ParseStream(TextReader reader, int context)
        {
            var cur = reader.Read();

            if (cur == ',' || cur == ')')
            {
                return(null);
            }
            var len = context + (context << 1);

            for (int i = 0; i < len; i++)
            {
                reader.Read();
            }
            cur = reader.Read();
            var cms = ChunkedMemoryStream.Create();

            while (cur != -1 && cur != '\\' && cur != '"')
            {
                cms.WriteByte((byte)((CharLookup[cur] << 4) + CharLookup[reader.Read()]));
                cur = reader.Read();
            }
            for (int i = 0; i < context; i++)
            {
                reader.Read();
            }
            cms.Position = 0;
            return(cms);
        }
Exemplo n.º 5
0
 public static void Serialize(XElement value, TextWriter sw, bool minimal)
 {
     if (StringFormat || minimal)
     {
         using (var cms = ChunkedMemoryStream.Create())
         {
             var writer = cms.GetWriter();
             value.Save(writer, SaveOptions.DisableFormatting);
             writer.Flush();
             cms.Position = 0;
             var reader = cms.GetReader();
             var buf    = cms.CharBuffer;
             int len;
             sw.Write('"');
             while ((len = reader.Read(buf, 0, 4096)) > 0)
             {
                 StringConverter.SerializePart(buf, len, sw);
             }
             sw.Write('"');
         }
     }
     else
     {
         JsonNet.Serialize(sw, value, typeof(XElement));
     }
 }
Exemplo n.º 6
0
        protected Stream GenerateDocument(params object[] data)
        {
            var file = Path.Combine(DocumentFolder, TemplateFile);

            if (!File.Exists(file))
            {
                throw new IOException("Can't find template document: " + TemplateFile);
            }
            var ext = Path.GetExtension(TemplateFile);
            var cms = ChunkedMemoryStream.Create();

            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                fs.CopyTo(cms);
            }
            cms.Position = 0;
            using (var document = Factory.Open(cms, ext))
            {
                if (data != null)
                {
                    foreach (var d in data)
                    {
                        document.Process(d);
                    }
                }
            }
            cms.Position = 0;
            return(ToPdf ? PdfConverter.Convert(cms, ext, true) : cms);
        }
Exemplo n.º 7
0
 private object Deserialize(Type type, XmlReader reader, StreamingContext context)
 {
     using (var dict = XmlDictionaryReader.CreateDictionaryReader(reader))
     {
         var serializer = new DataContractSerializer(type);
         var result     = serializer.ReadObject(dict, false, GenericResolver);
         if (context.Context == null)
         {
             return(result);
         }
         //TODO NO need for actual xml serializer now
         //implement recursive descent and provide context to all objects
         using (var cms = ChunkedMemoryStream.Create())
         {
             var ns = new NetDataContractSerializer(context);
             try
             {
                 ns.Serialize(cms, result);
                 cms.Position = 0;
                 ns.Binder    = GenericBinder;
                 return(ns.Deserialize(cms));
             }
             catch (Exception ex)
             {
                 TraceSource.TraceEvent(TraceEventType.Error, 5202, "{0}", ex);
                 TraceSource.TraceEvent(TraceEventType.Verbose, 5202, "{0}", cms);
                 throw;
             }
         }
     }
 }
Exemplo n.º 8
0
        public Stream Build(bool bulk, Action <StreamWriter, char> mappings)
        {
            if (Properties == null)
            {
                return(new MemoryStream(new byte[] { (byte)'N', (byte)'U', (byte)'L', (byte)'L' }));
            }
            var cms = ChunkedMemoryStream.Create();
            var sw  = cms.GetWriter();

            if (bulk)
            {
                for (int i = 0; i < Properties.Length; i++)
                {
                    var p = Properties[i];
                    if (p != null)
                    {
                        p.InsertRecord(sw, string.Empty, mappings);
                    }
                    else
                    {
                        sw.Write("\\N");
                    }
                    if (i < Properties.Length - 1)
                    {
                        sw.Write('\t');
                    }
                }
            }
            else
            {
                sw.Write('(');
                for (int i = 0; i < Properties.Length; i++)
                {
                    var p = Properties[i];
                    if (p != null)
                    {
                        if (p.MustEscapeRecord)
                        {
                            sw.Write('"');
                            //TODO string.Empty !?
                            p.InsertRecord(sw, "1", null);
                            sw.Write('"');
                        }
                        else
                        {
                            p.InsertRecord(sw, string.Empty, null);
                        }
                    }
                    if (i < Properties.Length - 1)
                    {
                        sw.Write(',');
                    }
                }
                sw.Write(')');
            }
            sw.Flush();
            cms.Position = 0;
            return(cms);
        }
Exemplo n.º 9
0
        TextReader ISerialization <TextReader> .Serialize <T>(T value)
        {
            var cms = ChunkedMemoryStream.Create();

            Serialize(value, cms, true);
            cms.Position = 0;
            return(cms.GetReader());
        }
Exemplo n.º 10
0
            public XmlTuple(XElement xml)
            {
                var cms = ChunkedMemoryStream.Create();

                xml.Save(cms);
                cms.Position = 0;
                Reader       = cms.GetReader();
            }
Exemplo n.º 11
0
        Stream ISerialization <Stream> .Serialize <T>(T value)
        {
            var cs = ChunkedMemoryStream.Create();

            Model.Serialize(cs, value);
            cs.Position = 0;
            return(cs);
        }
Exemplo n.º 12
0
 public string Serialize <T>(T value)
 {
     using (var cms = ChunkedMemoryStream.Create())
     {
         Serialize(value, cms, true);
         cms.Position = 0;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 13
0
        public Stream PlainText()
        {
            var cms = ChunkedMemoryStream.Create();

            cms.Write(HelloWorld, 0, HelloWorld.Length);
            cms.Position = 0;
            ThreadContext.Response.ContentType = "text/plain";
            return(cms);
        }
Exemplo n.º 14
0
 private static string SerializeToString(this IWireSerialization serializer, object instance)
 {
     using (var cms = ChunkedMemoryStream.Create())
     {
         var ct = serializer.Serialize(instance, ThreadContext.Request.Accept, cms);
         ThreadContext.Response.ContentType = ct;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 15
0
        public static Stream ParseStream(TextReader reader, int context)
        {
            var cur = reader.Read();

            if (cur == ',' || cur == ')')
            {
                return(null);
            }
            var cms = ChunkedMemoryStream.Create();
            var sw  = cms.GetWriter();

            if (cur != '"' && cur != '\\')
            {
                while (cur != -1 && cur != ',' && cur != ')')
                {
                    sw.Write((char)cur);
                    cur = reader.Read();
                }
            }
            else
            {
                for (int i = 0; i < context; i++)
                {
                    cur = reader.Read();
                }
                while (cur != -1)
                {
                    if (cur == '\\' || cur == '"')
                    {
                        for (int i = 0; i < context; i++)
                        {
                            cur = reader.Read();
                        }
                        if (cur == ',' || cur == ')')
                        {
                            sw.Flush();
                            cms.Position = 0;
                            return(cms);
                        }
                        for (int i = 0; i < context - 1; i++)
                        {
                            cur = reader.Read();
                        }
                    }
                    sw.Write((char)cur);
                    cur = reader.Read();
                }
                for (int i = 0; i < context; i++)
                {
                    reader.Read();
                }
            }
            sw.Flush();
            cms.Position = 0;
            return(cms);
        }
Exemplo n.º 16
0
 public string BuildTuple(bool quote)
 {
     using (var cms = ChunkedMemoryStream.Create())
     {
         var sw = cms.GetWriter();
         Action <TextWriter, char> mappings = null;
         if (quote)
         {
             mappings = PostgresTuple.EscapeQuote;
             sw.Write('\'');
         }
         sw.Write('(');
         var p = Properties[0];
         if (p != null)
         {
             if (p.MustEscapeRecord)
             {
                 sw.Write('"');
                 p.InsertRecord(sw, cms.SmallBuffer, "1", mappings);
                 sw.Write('"');
             }
             else
             {
                 p.InsertRecord(sw, cms.SmallBuffer, string.Empty, mappings);
             }
         }
         for (int i = 1; i < Properties.Length; i++)
         {
             sw.Write(',');
             p = Properties[i];
             if (p != null)
             {
                 if (p.MustEscapeRecord)
                 {
                     sw.Write('"');
                     p.InsertRecord(sw, cms.SmallBuffer, "1", mappings);
                     sw.Write('"');
                 }
                 else
                 {
                     p.InsertRecord(sw, cms.SmallBuffer, string.Empty, mappings);
                 }
             }
         }
         sw.Write(')');
         if (quote)
         {
             sw.Write('\'');
         }
         sw.Flush();
         cms.Position = 0;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 17
0
        public static ChunkedMemoryStream Memorize(StreamReader sr, ref int nextToken)
        {
            var cms    = ChunkedMemoryStream.Create();
            var writer = cms.GetWriter();

            writer.Write((char)nextToken);
            nextToken = Memorize(sr, nextToken, writer);
            writer.Flush();
            cms.Position = 0;
            return(cms);
        }
Exemplo n.º 18
0
        private Stream ReturnJSON(object value)
        {
            var cms = ChunkedMemoryStream.Create();

            //using baked in serialization since DSL is compiled with manual-json
            //world objects will have an extra field: URI
            Json.Serialize(value, cms, false);
            cms.Position = 0;
            ThreadContext.Response.ContentType = "application/json";
            return(cms);
        }
Exemplo n.º 19
0
        public static IPostgresTuple ToTuple(Image value)
        {
            if (value == null)
            {
                return(null);
            }
            var cms = ChunkedMemoryStream.Create();

            SaveImage(value, cms);
            cms.Position = 0;
            return(ByteaConverter.ToTuple(cms, true));
        }
Exemplo n.º 20
0
        public Stream Build()
        {
            var cms = ChunkedMemoryStream.Create();
            var sw  = cms.GetWriter();

            sw.Write('{');
            var e = Elements[0];

            if (e != null)
            {
                if (e.MustEscapeArray)
                {
                    sw.Write('"');
                    e.InsertArray(sw, cms.SmallBuffer, "0", null);
                    sw.Write('"');
                }
                else
                {
                    e.InsertArray(sw, cms.SmallBuffer, string.Empty, null);
                }
            }
            else
            {
                sw.Write("NULL");
            }
            for (int i = 1; i < Elements.Length; i++)
            {
                sw.Write(',');
                e = Elements[i];
                if (e != null)
                {
                    if (e.MustEscapeArray)
                    {
                        sw.Write('"');
                        e.InsertArray(sw, cms.SmallBuffer, "0", null);
                        sw.Write('"');
                    }
                    else
                    {
                        e.InsertArray(sw, cms.SmallBuffer, string.Empty, null);
                    }
                }
                else
                {
                    sw.Write("NULL");
                }
            }
            sw.Write('}');
            sw.Flush();
            cms.Position = 0;
            return(cms);
        }
Exemplo n.º 21
0
 public override string BuildTuple(bool quote)
 {
     if (Elements == null)
     {
         return("NULL");
     }
     using (var cms = ChunkedMemoryStream.Create())
     {
         var sw = cms.GetWriter();
         Action <StreamWriter, char> mappings = null;
         if (quote)
         {
             mappings = EscapeQuote;
             sw.Write('\'');
         }
         sw.Write('{');
         for (int i = 0; i < Elements.Length; i++)
         {
             var e = Elements[i];
             if (e != null)
             {
                 if (e.MustEscapeArray)
                 {
                     sw.Write('"');
                     e.InsertArray(sw, "0", mappings);
                     sw.Write('"');
                 }
                 else
                 {
                     e.InsertArray(sw, string.Empty, mappings);
                 }
             }
             else
             {
                 sw.Write("NULL");
             }
             if (i < Elements.Length - 1)
             {
                 sw.Write(',');
             }
         }
         sw.Write('}');
         if (quote)
         {
             sw.Write('\'');
         }
         sw.Flush();
         cms.Position = 0;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 22
0
 public void ConvertStream <TCommand, TArgument>(HttpContext contex, TArgument argument)
 {
     if (argument == null)
     {
         Application.Execute(typeof(TCommand), null, contex);
         return;
     }
     using (var ms = ChunkedMemoryStream.Create())
     {
         Serialization.Serialize(argument, contex.Request.ContentType, ms);
         ms.Position = 0;
         Application.Execute(typeof(TCommand), ms, contex);
     }
 }
Exemplo n.º 23
0
        public Stream Execute <TInput>(ISerialization <TInput> input, Argument <TInput> argument)
        {
            var file = Path.Combine(DocumentFolder, argument.File);

            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Can't locate file: {0}. Check if correct file is specified.".With(argument.File));
            }

            var cms = ChunkedMemoryStream.Create();

            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                fs.CopyTo(cms);
            }
            cms.Position = 0;
            var ext = Path.GetExtension(argument.File);

            using (var document = TemplaterFactory.Open(cms, ext))
            {
                if (argument.GetSources != null)
                {
                    foreach (var source in argument.GetSources)
                    {
                        var found = GetDomain.GetData(source);
                        document.Process(found);
                    }
                }
                if (argument.SearchSources != null)
                {
                    foreach (var source in argument.SearchSources)
                    {
                        var found = SearchDomain.FindData <TInput>(input, source);
                        document.Process(found);
                    }
                }
                var specification =
                    (from a in (argument.SearchSources ?? new SearchDomainObject.Argument <TInput> [0])
                     where a.Specification != null
                     select a.Specification)
                    .FirstOrDefault();
                if (specification != null)
                {
                    dynamic filter = input.Deserialize <TInput, dynamic>(specification);
                    document.Process(filter);
                }
            }
            cms.Position = 0;
            return(argument.ToPdf ? PdfConverter.Convert(cms, ext, true) : cms);
        }
Exemplo n.º 24
0
        public static void ConfigurePostgres(this IObjectFactoryBuilder builder, string connectionString)
        {
            var ci = new Revenj.DatabasePersistence.Postgres.ConnectionInfo(connectionString);

            builder.RegisterSingleton(ci);
            builder.RegisterType <PostgresConnectionPool, IConnectionPool>(InstanceScope.Singleton);
            builder.RegisterType <PostgresQueryManager, IDatabaseQueryManager>(InstanceScope.Context);
            builder.RegisterType <PostgresDatabaseQuery, IPostgresDatabaseQuery>();
            builder.RegisterFunc(c => c.Resolve <IDatabaseQueryManager>().CreateQuery(), InstanceScope.Context);
            builder.RegisterType <PostgresDatabaseNotification, IDataChangeNotification, IEagerNotification>(InstanceScope.Singleton);
            builder.RegisterType <PostgresObjectFactory, IPostgresConverterRepository, IPostgresConverterFactory>(InstanceScope.Singleton);
            builder.RegisterType <QueryExecutor>();
            builder.RegisterSingleton <IPostgresVersionInfo>(new PostgresVersionInfo(ci));
            builder.RegisterFunc(c => BulkReaderHelper.BulkRead(c, ChunkedMemoryStream.Create()), InstanceScope.Context);
        }
Exemplo n.º 25
0
 public static string ToArray <T>(IEnumerable <T> data, Func <T, string> converter)
 {
     if (data == null)
     {
         return("NULL");
     }
     using (var cms = ChunkedMemoryStream.Create())
     {
         Func <T, IPostgresTuple> toTuple = v => new ValueTuple(converter(v), false, true);
         var writer = cms.GetWriter();
         ToArray(writer, cms.SmallBuffer, data, toTuple);
         writer.Flush();
         cms.Position = 0;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 26
0
        private static string SerializeToString(this IWireSerialization serializer, object instance, HttpContext context)
        {
            StringValues headers;
            string       accept = null;

            if (context.Request.Headers.TryGetValue("accept", out headers) && headers.Count > 0)
            {
                accept = headers[0];
            }
            using (var cms = ChunkedMemoryStream.Create())
            {
                var ct = serializer.Serialize(instance, accept, cms);
                context.Response.ContentType = ct;
                return(cms.GetReader().ReadToEnd());
            }
        }
Exemplo n.º 27
0
        public DataTable Analyze(
            IEnumerable <string> dimensions,
            IEnumerable <string> facts,
            IEnumerable <KeyValuePair <string, bool> > order,
            ISpecification <TSource> filter,
            int?limit,
            int?offset)
        {
            var usedDimensions = new List <string>();
            var usedFacts      = new List <string>();

            if (dimensions != null)
            {
                usedDimensions.AddRange(dimensions);
            }
            if (facts != null)
            {
                usedFacts.AddRange(facts);
            }
            var sql   = PrepareSql(usedDimensions, usedFacts, order, filter, limit, offset);
            var table = new DataTable {
                CaseSensitive = true
            };
            var converters = PrepareConverters(usedDimensions, usedFacts, table);

            using (var cms = ChunkedMemoryStream.Create())
            {
                DatabaseQuery.Execute(sql, dr =>
                {
                    var obj = dr.GetValue(0);
                    var tr  = obj as TextReader;
                    var btr = tr != null ? cms.UseBufferedReader(tr) : cms.UseBufferedReader(obj.ToString());
                    btr.Read();
                    var args = new object[converters.Length];
                    for (int i = 0; i < converters.Length; i++)
                    {
                        args[i] = converters[i](btr);
                    }
                    table.Rows.Add(args);
                    if (tr != null)
                    {
                        tr.Dispose();
                    }
                });
            }
            return(table);
        }
Exemplo n.º 28
0
 public override string BuildTuple(bool quote)
 {
     if (Properties == null)
     {
         return("NULL");
     }
     using (var cms = ChunkedMemoryStream.Create())
     {
         var sw = cms.GetWriter();
         Action <StreamWriter, char> mappings = null;
         if (quote)
         {
             mappings = EscapeQuote;
             sw.Write('\'');
         }
         sw.Write('(');
         for (int i = 0; i < Properties.Length; i++)
         {
             var p = Properties[i];
             if (p != null)
             {
                 if (p.MustEscapeRecord)
                 {
                     sw.Write('"');
                     p.InsertRecord(sw, "1", mappings);
                     sw.Write('"');
                 }
                 else
                 {
                     p.InsertRecord(sw, string.Empty, mappings);
                 }
             }
             if (i < Properties.Length - 1)
             {
                 sw.Write(',');
             }
         }
         sw.Write(')');
         if (quote)
         {
             sw.Write('\'');
         }
         sw.Flush();
         cms.Position = 0;
         return(cms.GetReader().ReadToEnd());
     }
 }
Exemplo n.º 29
0
        private static ChunkedMemoryStream Decompress(byte[] data)
        {
            int n;
            var array = new byte[8192];

            using (var compressed = new MemoryStream(data))
                using (var zip = new GZipStream(compressed, CompressionMode.Decompress, true))
                {
                    var cms = ChunkedMemoryStream.Create();
                    while ((n = zip.Read(array, 0, array.Length)) > 0)
                    {
                        cms.Write(array, 0, n);
                    }
                    cms.Position = 0;
                    return(cms);
                }
        }
Exemplo n.º 30
0
        public Stream ConvertStream <TCommand, TArgument>(TArgument argument)
        {
            var request = ThreadContext.Request;
            var match   = new UriTemplateMatch();

            match.RelativePathSegments.Add(typeof(TCommand).FullName);
            request.UriTemplateMatch = match;
            if (argument == null)
            {
                return(Application.Get());
            }
            using (var ms = ChunkedMemoryStream.Create())
            {
                Serialization.Serialize(argument, request.ContentType, ms);
                ms.Position = 0;
                return(Application.Post(ms));
            }
        }