Пример #1
0
        public void GivenExpressionHasSerializerWhenSerializeCalledThenShouldSerialize()
        {
            var serialized = target.Serialize(Expression.Constant(5), new SerializationState());

            Assert.NotNull(serialized);
            Assert.Equal(ExpressionType.Constant, (ExpressionType)serialized.Type);
        }
Пример #2
0
        private static void Binary()
        {
            GC.Collect();

            Console.WriteLine("Binary");

            var ser = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);

            var N = 10000;
            var M = 10000;

            var e = (Expression <Func <IEnumerable <int> > >)(() => Enumerable.Range(0, 10).Where(x => x > 0).Select(x => x * x));

            Console.WriteLine("  Serialize");

            var sw = Stopwatch.StartNew();
            var gc = GarbageCollectionWatch.StartNew();

            var res = default(byte[]);

            for (var i = 0; i < N; i++)
            {
#if USE_SLIM
                res = ser.Serialize(e.ToExpressionSlim());
#else
                res = ser.Serialize(e);
#endif
            }

            Console.WriteLine("    Elapsed (ms): " + sw.Elapsed.TotalMilliseconds / M);
            Console.WriteLine("    " + gc.Elapsed);
            Console.WriteLine("    Length (bytes): " + res.Length);

            Console.WriteLine("  Deserialize");

            sw.Restart();
            gc.Restart();

            for (var i = 0; i < M; i++)
            {
#if USE_SLIM
                e = (Expression <Func <IEnumerable <int> > >)ser.Deserialize(res).ToExpression();
#else
                e = (Expression <Func <IEnumerable <int> > >)ser.Deserialize(res);
#endif
            }

            Console.WriteLine("    Elapsed (ms): " + sw.Elapsed.TotalMilliseconds / M);
            Console.WriteLine("    " + gc.Elapsed);

            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            const string fileName = "sumRange.bin";

            ExpressionSerializer serializer = new ExpressionSerializer(
                new TypeResolver(new[] { Assembly.GetExecutingAssembly() })
                );

            serializer.Serialize(sumRange).Save(fileName);

            Expression <Func <int, int, int> > deserializedSumRange =
                serializer.Deserialize <Func <int, int, int> >(
                    XElement.Load(fileName)
                    );

            Func <int, int, int> funcSumRange =
                deserializedSumRange.Compile();

            Console.WriteLine(
                "Deserialized func returned: {0}",
                funcSumRange(1, 4)
                );

            Console.ReadKey();
        }
Пример #4
0
        public void Test12()
        {
            Order order1 = new Order {
                Customer = Hans, ID = 302, Freight = 2001.99m, OrderDate = DateTime.Now.AddMonths(-20)
            };

            var assemblies = new Assembly[] { typeof(Order).Assembly, typeof(UnitTests).Assembly, typeof(ExpressionType).Assembly, typeof(IQueryable).Assembly };
            var resolver   = new ExpressionSerializationTypeResolver(assemblies, new Type[] { typeof(Customer), typeof(Order), typeof(Product), typeof(Supplier), typeof(Shipper) });
            ExpressionSerializer serializer = new ExpressionSerializer(resolver);

            IEnumerable <Customer> customers = GetCustomers().ToArray();
            Expression <Func <int, IEnumerable <Order[]> > > e12 =
                n =>
                from c in customers //instance == null : IEnumerable.Where/.Select
                where c.ID < n
                select c.Orders.ToArray();

            e12 = (Expression <Func <int, IEnumerable <Order[]> > >)ObjectServices.Evaluator.PartialEval(e12);
            MethodCallExpression m1        = ((MethodCallExpression)e12.Body).Arguments[0] as MethodCallExpression;
            ConstantExpression   cx        = ((ConstantExpression)m1.Arguments[0]);
            LambdaExpression     lambdaarg = ((LambdaExpression)m1.Arguments[1]);
            //Expression arg1 = ((MethodCallExpression)e12.Body).Arguments[1];
            XElement xml12 = serializer.Serialize(e12);

            Expression result12 = serializer.Deserialize(xml12);

            Assert.AreEqual(e12.ToString(), result12.ToString());
            Console.WriteLine(((result12 as Expression <Func <int, IEnumerable <Order[]> > >).Compile())(5));
        }
Пример #5
0
        private static void bench()
        {
            var sw = Stopwatch.StartNew();

            for (var i = 0; i < 5_000_000; i++)
            {
                //Expression<Func<string, string, int>> exp = (x, y) => x.Length + y.Length;
                //exp.Compile()("a", "b");

                //Func<string, string, int> foo = (x, y) => x.Length + y.Length;
                //foo("a", "b");

                //new Context().Eval("(x,y) => x.length + y.length").As<Function>().Call(new Arguments { "a", "b" });

                Expression <Func <string, string, long> > exp = (x, y) => x.Length + y.Length;
                var serializer   = new ExpressionSerializer();
                var deserializer = new ExpressionDeserializer();
                var serialized   = serializer.Serialize(exp);
                var deserialized = (LambdaExpression)deserializer.Deserialize(serialized);
                var value        = new ExpressionEvaluator().Eval(deserialized.Body,
                                                                  new[] {
                    new Parameter(deserialized.Parameters[0], "a"),
                    new Parameter(deserialized.Parameters[1], "b"),
                });
            }

            sw.Stop();
            Console.WriteLine(sw.Elapsed);
        }
Пример #6
0
        public static string SerializeExpression(linq.Expression expr)
        {
            var typeResolver = new TypeResolver(assemblies: AppDomain.CurrentDomain.GetAssemblies(), knownTypes: null);
            var serializer   = new ExpressionSerializer(typeResolver);
            var retVal       = serializer.Serialize(expr).ToString();

            return(retVal);
        }
Пример #7
0
        private void OnSerializing(StreamingContext context)
        {
            var cleanedExpression = ExpressionUtility.Ensure(_predicate);
            var serializer        = new ExpressionSerializer();
            var xmlElement        = serializer.Serialize(cleanedExpression);

            _serializedPredicate = xmlElement.ToString();
        }
Пример #8
0
        public async void Serialize(Expression <Func <Customer, bool> > lambda, string expectedResult)
        {
            var serializer = new ExpressionSerializer();
            var result     = await serializer.Serialize(lambda);

            //Console.WriteLine(result);
            Assert.Equal(expectedResult, result);
        }
Пример #9
0
        public static XElement SerializeQuery(this Expression expression)
        {
            ExpressionSerializer serializer = new ExpressionSerializer()
            {
                Converters = { new BoxedExpressionXmlConverter() }
            };

            return(serializer.Serialize(expression));
        }
Пример #10
0
        public void Null_Expression()
        {
            var ser = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);

            var arr = ser.Serialize(expression: null);
            var otp = ser.Deserialize(arr);

            Assert.IsNull(otp);
        }
Пример #11
0
        public static XElement SerializeQuery(this IQueryable query)
        {
            DLinqSerializationTypeResolver resolver   = new DLinqSerializationTypeResolver(null);
            ExpressionSerializer           serializer = new ExpressionSerializer(resolver)
            {
                Converters = { new DLinqCustomExpressionXmlConverter(null, resolver) }
            };

            return(serializer.Serialize(query.Expression));
        }
Пример #12
0
        public AdHocSpecification(Expression <Func <T, bool> > specification)
        {
            var cleanedExpression = ExpressionUtility.Ensure(specification);

            //this.specification = specification;
            var serializer           = new ExpressionSerializer();
            var serializedExpression = serializer.Serialize(cleanedExpression);

            serializedExpressionXml = serializedExpression.ToString();
        }
Пример #13
0
        public void Serialize <T>(T dto)
        {
            if (typeof(Expression).IsAssignableFrom(typeof(T)))
            {
                _expressionSerializer.Serialize(_client.GetStream(), (Expression)(object)dto);
            }
            MemoryStream ms = new MemoryStream(2048);

            BsonSerializer.Serialize <T>(new BsonBinaryWriter((_client.GetStream())), dto);
        }
Пример #14
0
        private static void AssertRoundtrip(params Expression[] expressions)
        {
            var equ = new ExpressionEqualityComparer(() => new Comparator());

            foreach (var e in expressions)
            {
                var ser = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);

#if USE_SLIM
                var arr = ser.Serialize(e.ToExpressionSlim());
                var otp = ser.Deserialize(arr).ToExpression();
#else
                var arr = ser.Serialize(e);
                var otp = ser.Deserialize(arr);
#endif

                Assert.IsTrue(equ.Equals(e, otp), e.ToString());
            }
        }
Пример #15
0
        public void PrimitiveTypeTest()
        {
            Expression <Func <int> > addExpr = () => 1 + 1;
            var      serializer = new ExpressionSerializer();
            XElement addXml     = serializer.Serialize(addExpr);
            Expression <Func <int> > addExpResult = serializer.Deserialize <Func <int> >(addXml);
            Func <int> addExpResultFunc           = addExpResult.Compile();

            Assert.AreEqual(2, addExpResultFunc());  // evaluates to 2
        }
Пример #16
0
        public Deserialize()
        {
            _jsonSerializer   = new CustomBonsaiSerializer();
            _binarySerializer = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);

            var expr = (Expression <Func <IEnumerable <int> > >)(() => Enumerable.Range(0, 10).Where(x => x > 0).Select(x => x * x));

            _json   = _jsonSerializer.Serialize(expr.ToExpressionSlim());
            _binary = _binarySerializer.Serialize(expr.ToExpressionSlim());
        }
Пример #17
0
        public void ExternalTypesSerialization()
        {
            var serializer = new ExpressionSerializer();
            var deserializer = new ExpressionDeserializer();
            var list = new List<int>();
            Expression<Func<List<int>, int>> expression = l => l.Count;

            var serialized = serializer.Serialize(expression);

            var deserialized = deserializer.Deserialize(serialized);
        }
Пример #18
0
        public static string ToXml <T>(this Expression <T> exp)
        {
            var s = new ExpressionSerializer(new TypeResolver(
                                                 new Assembly[]
            {
                Assembly.GetExecutingAssembly(),
                Assembly.GetCallingAssembly()
            }));
            var x = s.Serialize(exp);

            return(x.ToString());
        }
Пример #19
0
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            var resolver   = new TypeResolver(App.Plugins, new[] { typeof(Expression) });
            var serializer = new ExpressionSerializer(resolver)
            {
                Converters = { new XmlConverter(null, resolver) }
            };

            var rootEl = serializer.Serialize(_expression);

            info.AddValue("expression", rootEl.ToString());
        }
Пример #20
0
        public void ComplexTypeTest()
        {
            Expression <Func <Customer, bool> > addExpr = (customer) => string.IsNullOrEmpty(customer.CustomerID);
            var      serializer   = new ExpressionSerializer();
            XElement addXml       = serializer.Serialize(addExpr);
            var      addExpResult = serializer.Deserialize <Func <Customer, bool> >(addXml);
            Func <Customer, bool> addExpResultFunc = addExpResult.Compile();

            Assert.AreEqual(true, addExpResultFunc(new Customer()
            {
                CustomerID = "Allen"
            }));                                                                               // evaluates to 2
        }
Пример #21
0
        public void ExpressionSerializer_ArgumentChecking()
        {
            var ser = new ExpressionSerializer(new BinaryObjectSerializer());

            Assert.ThrowsException <ArgumentNullException>(() => _ = new ExpressionSerializer(serializer: null));
            Assert.ThrowsException <ArgumentNullException>(() => _ = new ExpressionSerializer(serializer: null, ExpressionFactory.Instance));
            Assert.ThrowsException <ArgumentNullException>(() => _ = new ExpressionSerializer(new BinaryObjectSerializer(), expressionFactory: null));

#if !USE_SLIM
            Assert.ThrowsException <ArgumentNullException>(() => ser.Serialize(default(Stream), Expression.Constant(1)));
#endif
            Assert.ThrowsException <ArgumentNullException>(() => ser.Deserialize(default(Stream)));
            Assert.ThrowsException <ArgumentNullException>(() => ser.Deserialize(default(byte[])));
        }
Пример #22
0
        public static JsonElement GetSerializedFragment <TSerializer, TExpression>(
            TExpression expression,
            JsonSerializerOptions options = null)
            where TExpression : Expression
            where TSerializer : SerializableExpression
        {
            var state = options == null ?
                        new SerializationState() : options.ToSerializationState();
            var json = JsonSerializer.Serialize(
                ExpressionSerializer.Serialize(expression, state) as TSerializer,
                options);

            return(JsonDocument.Parse(json).RootElement);
        }
 public AdHocSpecification(Expression <Func <T, bool> > specification)
 {
     if (specification == null)
     {
         this.serializedExpressionXml = string.Empty;
     }
     else
     {
         var cleanedExpression    = ExpressionUtility.Ensure(specification);
         var serializer           = new ExpressionSerializer();
         var serializedExpression = serializer.Serialize(cleanedExpression);
         this.serializedExpressionXml = serializedExpression.ToString();
     }
 }
Пример #24
0
        // Very simple serialization example
        public static void BasicExpressionSerialization()
        {
            Console.WriteLine("BASIC SAMPLE - Serialize/Deserialize Simple Expression:");

            Expression <Func <int, int, int> > addExpr = (x, y) => x + y;
            ExpressionSerializer serializer            = new ExpressionSerializer();
            XElement             addXml = serializer.Serialize(addExpr);
            Expression <Func <int, int, int> > addExpResult = serializer.Deserialize <Func <int, int, int> >(addXml);
            Func <int, int, int> addExpResultFunc           = addExpResult.Compile();
            int result = addExpResultFunc(1, 2);  // evaluates to 3

            Console.WriteLine("Deserialized Expression Tree:");
            Console.WriteLine(" " + addExpResult.ToString());
            Console.WriteLine();
        }
Пример #25
0
        public void BasicExpressionSerialization()
        {
            XElement addXml;
            Expression <Func <int, int, int> > addExpr = (x, y) => x + y;
            ExpressionSerializer serializer            = new ExpressionSerializer();
            Expression           simplifiedAddExpr     = Evaluator.PartialEval(addExpr);

            //addXml = serializer.Serialize(simplifiedAddExpr);	//does not seem necessary
            addXml = serializer.Serialize(addExpr);
            Expression <Func <int, int, int> > addExpResult = serializer.Deserialize <Func <int, int, int> >(addXml);
            Func <int, int, int> addExpResultFunc           = addExpResult.Compile();
            int result = addExpResultFunc(1, 2);              // evaluates to 3

            Debug.WriteLine("Deserialized Expression Tree:");
            Debug.WriteLine(" " + addExpResult.ToString());
        }
Пример #26
0
        private static void Old()
        {
            var x = Expression.Parameter(typeof(int));
            var i = typeof(Interlocked).GetMethods().Single(m => m.Name == "Exchange" && m.GetParameters().Last().ParameterType == typeof(int));

            Expression.Block(new[] { x }, Expression.Call(instance: null, i, x, Expression.Constant(1)));

            var ser = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);

            var inp = Expression.Constant(42);
            var arr = ser.Serialize(inp);
            var otp = ser.Deserialize(arr);

            var equ = new ExpressionEqualityComparer();

            Console.WriteLine(equ.Equals(inp, otp));
        }
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            _serializer = Serialization.CreateSerializer();

            //This is essentially mapping types to objects. The IGoodVibesValidator just enforces that you use the interface for some semblance
            //of control. That said, you can quite eaisily break this if you are so inclined
            //var validators = await this.StateManager.GetOrAddAsync<IReliableDictionary<ComparableType, IGoodVibesValidator>>(ValidatorDictionary);
            var validators = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, List <XElement> > >(SerializedValidatorDictionary);

            using (var tx = this.StateManager.CreateTransaction())
            {
                if (await validators.GetCountAsync(tx) == 0)
                {
                    List <XElement> values = new List <XElement>();
                    //Expression<Func<ReportBase, ValidationMessage>> expr1 = ReportValidationRules.RatingRule;
                    //Expression<Func<ReportBase, ValidationMessage>> expr2 = ReportValidationRules.PosterRule;
                    //Expression<Func<ReportBase, ValidationMessage>> expr3 = ReportValidationRules.LocationRule;

                    //values.Add(_serializer.Serialize(expr1));
                    //values.Add(_serializer.Serialize(expr2));
                    //values.Add(_serializer.Serialize(expr3));

                    ReportValidationRules.ReportRules.ForEach(x => values.Add(_serializer.Serialize(x)));
                    await validators.AddAsync(tx, typeof(ReportBase).AssemblyQualifiedName, values);
                }
                await tx.CommitAsync();
            }
            //using (var tx = this.StateManager.CreateTransaction())
            //{
            //    if (await validators.GetCountAsync(tx) != 0)
            //    {
            //        var val = await validators.TryGetValueAsync(tx, typeof(SurfReport).AssemblyQualifiedName);
            //        if (val.HasValue)
            //        {
            //            XElement x = val.Value.FirstOrDefault();
            //            var serializedValidator = _serializer.Deserialize<Func<ReportBase, ValidationMessage>>(x);
            //            var test = new SurfReport(Ratings.None, "ben", "dfs", DateTime.Now, null, 0, 0);
            //            var godIHopeThisJustFuckingWorksForOnce = serializedValidator.Compile()(test);

            //        }

            //    }

            //}
        }
Пример #28
0
        public void BasicExpressionSerialization()
        {
            Type funcT1T2T3 = typeof(Func <>).Assembly.GetType("System.Func`3");

            Debug.WriteLine("BASIC SAMPLE - Serialize/Deserialize Simple Expression:");
            XElement addXml;
            Expression <Func <int, int, int> > addExpr = (x, y) => x + y;
            ExpressionSerializer serializer            = new ExpressionSerializer();
            Expression           simplifiedAddExpr     = Evaluator.PartialEval(addExpr);

            //addXml = serializer.Serialize(simplifiedAddExpr);	//does not seem necessary
            addXml = serializer.Serialize(addExpr);
            Expression <Func <int, int, int> > addExpResult = serializer.Deserialize <Func <int, int, int> >(addXml);
            Func <int, int, int> addExpResultFunc           = addExpResult.Compile();
            int result = addExpResultFunc(1, 2);              // evaluates to 3

            Debug.WriteLine("Deserialized Expression Tree:");
            Debug.WriteLine(" " + addExpResult.ToString());
        }
Пример #29
0
        public void NotSupportedExpressions()
        {
            var binder = Binder.Convert(CSharpBinderFlags.None, typeof(int), typeof(Tests));

            var es = new Expression[]
            {
                Expression.DebugInfo(Expression.SymbolDocument("foo"), 1, 2, 3, 4),
                Expression.Dynamic(binder, typeof(int), Expression.Constant(42)),
                new MyNode(),
            };

            foreach (var e in es)
            {
                Assert.ThrowsException <NotSupportedException>(() =>
                {
                    var ser = new ExpressionSerializer(new BinaryObjectSerializer(), ExpressionFactory.Instance);
                    ser.Serialize(e);
                });
            }
        }
Пример #30
0
        static void Main(string[] args)
        {
            //hubsTest();
            //return;

            //experiments();
            //return;

            var f = new Func <int, int, int>((x, y) => x + y);

            //var invokeMethod = f.Invoke();

            return;

            //var a = 2;
            //var b = 2;
            //var c = 2;
            var prmA = Expression.Parameter(typeof(SomeObject), "obj");
            var prmB = Expression.Parameter(typeof(string), "b");
            var prmC = Expression.Parameter(typeof(long), "c");
            var obj  = new SomeObject();
            Expression <Func <long> > exp = () => 1;

            var body2 = Expression.Block(Expression.Assign(Expression.PropertyOrField(prmA, nameof(SomeObject.Property)), Expression.Constant(1)));

            var serializer   = new ExpressionSerializer();
            var deserializer = new ExpressionDeserializer();
            var serialized   = serializer.Serialize(exp);
            var deserialized = (LambdaExpression)deserializer.Deserialize(serialized);

            var prms = new[] {
                new Parameter(prmA, obj),
            };
            // var value = new ExpressionEvaluator().Eval(deserialized.Body, prms);
            var value = new ExpressionEvaluator().Eval(body2, prms);

            //bench();
        }
Пример #31
0
 public static XElement SerializeQuery(this IQueryable query)
 {
     DLinqSerializationTypeResolver resolver = new DLinqSerializationTypeResolver(null);
     ExpressionSerializer serializer = new ExpressionSerializer(resolver) { Converters = { new DLinqCustomExpressionXmlConverter(null, resolver) } };
     return serializer.Serialize(query.Expression);
 }