Example #1
0
        private void btnBaslat_Click(object sender, EventArgs e)
        {
            lbSinyaller.Items.Clear();
            lbHatalar.Items.Clear();
            label_BinanceListelenenCoinAdet.Yazdir(string.Empty);
            lbIslenenCoinAdet.Yazdir(string.Empty);
            Task.Run(() =>
            {
                using (var binanceClient = new BinanceClient())
                {
                    var data       = binanceClient.GetAllPrices().Data;
                    var enumerable = data.Where(x => x.Symbol.EndsWith("BTC"))
                                     .Select(x => x.Symbol = x.Symbol.Replace("BTC", "")).ToList();
                    label_BinanceListelenenCoinAdet.Yazdir(enumerable.Count().ToString());
                    enumerable
                    .AsParallel()
                    .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                    .ForAll(_analizEt);
                }
            }).ContinueWith(t =>
            {
                if (File.Exists(_dosyaAdi))
                {
                    File.Delete(_dosyaAdi);
                }
                if (!_kayitlar.Any())
                {
                    MessageBox.Show("Kayit Yok!");
                }
                File.WriteAllBytes(_dosyaAdi, _kayitlar.Serialize());
                MessageBox.Show("Kaydedildi");
            });

            lbSinyalAdet.Yazdir(_kayitlar.Count().ToString());
        }
    static void Main(string[] args)
    {
        var personsWithKnownTypes = new Dictionary <string, Address>();

        personsWithKnownTypes.Add("John Smith", new Address {
            Country = "US", City = "New York"
        });
        personsWithKnownTypes.Add("Jean Martin", new Address {
            Country = "France", City = "Paris"
        });
        // no need to provide known types to the serializer
        var serializedPersons1       = personsWithKnownTypes.Serialize(null);
        var deserializedPersons1     = serializedPersons1.Deserialize <Dictionary <string, Address> >(null);
        var personsWithoutKnownTypes = new Dictionary <string, object>();

        personsWithoutKnownTypes.Add("John Smith", new Address {
            Country = "US", City = "New York"
        });
        personsWithoutKnownTypes.Add("Jean Martin", new CodedAddress {
            CountryCode = 33, CityCode = 75
        });
        // must provide known types to the serializer
        var knownTypes = new List <Type> {
            typeof(Address), typeof(CodedAddress)
        };
        var serializedPersons2   = personsWithoutKnownTypes.Serialize(knownTypes);
        var deserializedPersons2 = serializedPersons2.Deserialize <Dictionary <string, object> >(knownTypes);
    }
        public async Task It_should_update_null_field()
        {
            Dictionary <string, object> testEntityV1 = new Dictionary <string, object> {
                { "nullProp", null }, { "EntityName", "checkNull" }
            };

            using TestServer server = TestServer(UserRole.Administrator);
            using HttpClient client = server.CreateHttpClient();

            HttpResponseMessage result = await client.PostAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/nullField",
                testEntityV1.Serialize());

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Dictionary <string, object> testEntityV2 = new Dictionary <string, object> {
                { "nullProp", "notnull" }, { "EntityName", "checkNull" }
            };

            HttpResponseMessage ver1Json = await client.PatchAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/nullField",
                testEntityV2.Serialize());

            Assert.Equal(HttpStatusCode.OK, ver1Json.StatusCode);

            HttpResponseMessage configFound =
                await client.GetAsync(
                    $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/nullField/json");

            Assert.Equal(HttpStatusCode.OK, configFound.StatusCode);

            dynamic ver1Data = configFound.Deserialize <dynamic>();

            Assert.Equal(ver1Data.nullProp, testEntityV2["nullProp"]);
            Assert.Equal(ver1Data.EntityName, testEntityV2["EntityName"]);
        }
Example #4
0
            public override IValue Serialize() =>
#pragma warning disable LAA1002
            new Dictionary(new Dictionary <IKey, IValue>
            {
                [(Text)"id"]   = id.Serialize(),
                [(Text)"cost"] = cost.Serialize(),
            }.Union((Dictionary)base.Serialize()));
Example #5
0
            public override IValue Serialize() =>
#pragma warning disable LAA1002
            new Bencodex.Types.Dictionary(new Dictionary <IKey, IValue>
            {
                [(Text)"materials"] = materials.Serialize(),
                [(Text)"id"]        = id.Serialize(),
            }.Union((Bencodex.Types.Dictionary)base.Serialize()));
        public ActionResult ProcessSelectShop(FormCollection collection)
        {
            var name    = collection["name"];
            var shopid  = collection["shopid"].TryTo(0);
            var ischeck = collection["ischeck"].TryTo(false);
            var all     = collection["all"];

            var r = new Dictionary <int, string>();

            if (!all.IsEmpty())
            {
                r = all.Deserialize <Dictionary <int, string> >();
            }

            if (ischeck && !r.ContainsKey(shopid))
            {
                r.Add(shopid, name);
            }

            if (!ischeck)
            {
                r.Remove(shopid);
            }
            return(Content(r.Serialize()));
        }
        public async Task PingBackAsync(PingBackRequest request)
        {
            var queryString = new Dictionary <string, string>
            {
                { "item_id", request.ItemId.ToString() },
                { "location_id", request.LocationId },
                { "play_datetime", request.PlayDateTime.ToString("O") },
                { "duration", request.Duration.TotalSeconds.ToString("F") },
            };

            var uriBuilder = new UriBuilder
            {
                Path  = Routes.PingBack,
                Query = queryString.Serialize()
            };


            var response = await HttpClient.GetAsync <JToken>(uriBuilder.Uri.PathAndQuery)
                           .ConfigureAwait(false);

            if (response.IsSuccess)
            {
                return;
            }

            throw response.Exception;
        }
        /// <summary>
        /// Pull Creative to be shown
        /// </summary>
        /// <param name="exportId">The export id in string lch-id format</param>
        /// <param name="locationId">The digital display id that you are fetching for</param>
        /// <returns>List of lucit locations or empty list if something went wrong</returns>
        public async Task <List <LucitLocation> > GetCreativeAsync(string exportId, string locationId = null)
        {
            var queryString = new Dictionary <string, string>
            {
                { "location_id", locationId }
            };

            var uriBuilder = new UriBuilder
            {
                Path  = Routes.Creatives(exportId),
                Query = queryString.Serialize()
            };


            var response = await HttpClient.GetAsync <JObject>(uriBuilder.Uri.PathAndQuery)
                           .ConfigureAwait(false);

            var responseObject = response.Data;

            if (!response.IsSuccess)
            {
                throw response.Exception;
            }

            return(responseObject?["lucit_layout_drive"]?["item_sets"]?.ToObject <List <LucitLocation> >() ?? new List <LucitLocation>());
        }
        public async Task SubmitPlayAsync(SubmitPlayRequest request)
        {
            var queryString = new Dictionary <string, string>
            {
                { "creative_id", request.CreativeId },
                { "lucit_layout_digital_board_id", request.DigitalBoardId.ToString() },
                { "play_datetime", request.PlayDateTime.ToString("O") },
                { "duration", request.Duration.TotalSeconds.ToString("F") },
            };

            var uriBuilder = new UriBuilder
            {
                Path  = Routes.Play,
                Query = queryString.Serialize()
            };


            var response = await HttpClient.GetAsync <JToken>(uriBuilder.Uri.PathAndQuery)
                           .ConfigureAwait(false);

            if (response.IsSuccess)
            {
                return;
            }

            throw response.Exception;
        }
        public async Task It_should_update_type_field()
        {
            Dictionary <string, object> testEntityV1 = new Dictionary <string, object> {
                { "var", 123 }, { "EntityName", "DateTimeOffset" }
            };

            using TestServer server = TestServer(UserRole.Administrator);
            using HttpClient client = server.CreateHttpClient();

            HttpResponseMessage result = await client.PostAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/typeUpdate",
                testEntityV1.Serialize());

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Dictionary <string, object> testEntityV2 = new Dictionary <string, object> {
                { "var", DateTime.Now }, { "EntityName", "DateTime" }
            };

            HttpResponseMessage ver1Json = await client.PatchAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/typeUpdate",
                testEntityV2.Serialize());

            Assert.Equal(HttpStatusCode.OK, ver1Json.StatusCode);

            HttpResponseMessage configFound =
                await client.GetAsync(
                    $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/typeUpdate/JsonRefresh");

            Assert.Equal(HttpStatusCode.OK, configFound.StatusCode);

            dynamic ver1Data = configFound.Deserialize <dynamic>();

            Assert.Equal(ver1Data.var, testEntityV2["var"]);
            Assert.Equal(ver1Data.EntityName, testEntityV2["EntityName"]);
        }
Example #11
0
        public static void SaveEnvironmentConfigs(Dictionary <string, string> configs)
        {
            string       fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Constants.EnvironmentVariablesFileName);
            StreamWriter sw       = new StreamWriter(fileName);

            sw.Write(configs.Serialize());
            sw.Close();
        }
Example #12
0
        private byte[] generateRequestInFlightCacaheDataSerialized(ActionExecutingContext context)
        {
            Dictionary <string, object> cacheData = new Dictionary <string, object>();

            cacheData.Add("Request.Inflight", new RequestinFlightPlaceHolder());

            return(cacheData.Serialize());
        }
Example #13
0
 public override IValue Serialize() =>
 new Dictionary(new Dictionary <IKey, IValue>
 {
     [(Text)"materials"]   = materials.Serialize(),
     [(Text)"id"]          = id.Serialize(),
     [(Text)"gold"]        = gold.Serialize(),
     [(Text)"actionPoint"] = actionPoint.Serialize(),
     [(Text)"recipeId"]    = recipeId.Serialize(),
     [(Text)"subRecipeId"] = subRecipeId.Serialize(),
 }.Union((Dictionary)base.Serialize()));
Example #14
0
        static void Main(string[] args)
        {
            List <string> level1 = new List <string> {
                "Hey",
                "I am",
                "Level One",
            };
            var lstSeri = level1.Serialize();
            var lvl1de  = lstSeri.DeSerialize <string>();

            lvl1de.DoSerializion();


            //Let's create a dummy dictionary with some entities
            Dictionary <string, string> myDictionary = new Dictionary <string, string>();

            myDictionary["HalloWelt"]  = "lola";
            myDictionary["HalloWelt1"] = "lola2";

            //Serialize the dictionary to a byte array
            var serialized = myDictionary.Serialize();
            //Deserialize that byte array to a dictionary<string,string>
            var deseri = serialized.DeSerialize <string, string>();

            Console.WriteLine(deseri["HalloWelt"]);

            //Same, but not as pretty as the previous example
            serialized = DictionarySerializer <string, string> .Serialize(myDictionary);

            deseri = DictionarySerializer <string, string> .Deserialize(serialized);

            var myDictionary1 = new Dictionary <string, Dictionary <string, string> >
            {
                ["HalloWelt"] = new Dictionary <string, string>
                {
                    ["a"] = "b",
                    ["c"] = "ba",
                    ["d"] = "bs",
                    ["e"] = "bfa",
                },
                ["HalloWelt1"] = new Dictionary <string, string>
                {
                    ["xa"] = "xb",
                    ["xc"] = "xba",
                    ["xd"] = "xbs",
                    ["xe"] = "xbfa",
                },
            };

            serialized = myDictionary1.Serialize();
            var deserialized = serialized.DeSerialize <string, Dictionary <string, Dictionary <string, int> > >();

            Console.ReadLine();
        }
        public void SetOverrides(Dictionary <string, bool> overrides)
        {
            var context = GetCurrentContext();

            var cookie = new HttpCookie(CookieName, overrides.Serialize().Encrypt())
            {
                HttpOnly = true
            };

            context.Response.Cookies.Add(cookie);
        }
Example #16
0
        public void SerializeTest()
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();

            dict["asd"] = "dsa";
            string str        = dict.Serialize();
            string str_inline = dict.SerializeInline();

            byte[] bytes = dict.SerializeAsBytes();
            str.Deserialize <Dictionary <string, string> >();
            bytes.Deserialize <Dictionary <string, string> >();
        }
        public void CanSerialize_AndDeserialize_Dictionary()
        {
            var dict = new Dictionary <string, bool>
            {
                { "key1", true },
                { "key2", false },
                { "key3", true }
            };

            var output = dict.Serialize().Deserialize <IDictionary <string, bool> >();

            Assert.AreEqual(3, output.Count);
        }
        private void Save()
        {
            lock (_preferences)
            {
                if (File.Exists(_path))
                {
                    File.Delete(_path);
                }

                string serialized = _preferences.Serialize();
                File.WriteAllText(_path, serialized);
            }
        }
        public void GetOverrides_GivenGoodCookie_ReturnsOverrides()
        {
            var request = Substitute.For <HttpRequestBase>();

            request.Cookies.Returns(new HttpCookieCollection
            {
                new HttpCookie(CookieOverrideProvider.CookieName, _validOverrides.Serialize().Encrypt())
            });
            _context.Request.Returns(request);

            var overrides = _provider.GetOverrides();

            ValidateOverrides(overrides);
        }
Example #20
0
        public static void SaveMessages(Dictionary <Address, Message> d)
        {
            Dictionary <string, Message> s = new Dictionary <string, Message>();

            foreach (KeyValuePair <Address, Message> kvp in d)
            {
                s.Add(kvp.Key.FormattedAddress, kvp.Value);
            }

            if (!File.Exists("SavedMessages.hm"))
            {
                File.Create("SavedMessages.hm");
            }
            File.WriteAllBytes("SavedMessages.hm", s.Serialize());
        }
Example #21
0
        private void button_Kaydet_Click(object sender, EventArgs e)
        {
            var dosyaAdi = "kayitlar.binary";

            if (File.Exists(dosyaAdi))
            {
                File.Delete(dosyaAdi);
            }
            if (!kayitlar.Any())
            {
                MessageBox.Show("Kayit Yok!");
            }
            File.WriteAllBytes(dosyaAdi, kayitlar.Serialize());
            MessageBox.Show("Kaydedildi");
        }
Example #22
0
            /// <summary>
            ///
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                if (!string.IsNullOrWhiteSpace(Raw))
                {
                    return(Raw);
                }

                var dict = new Dictionary <string, object>();

                if (Type == MessageType.Notification)
                {
                    dict.Add(alert, AlertStr);
                    if (Badge != 0)
                    {
                        dict.Add(badge, Badge);
                    }
                    if (Sound.Length != 0)
                    {
                        dict.Add(sound, Sound);
                    }
                    if (Category.Length != 0)
                    {
                        dict.Add(category, Category);
                    }
                }
                else if (Type == MessageType.Message)
                {
                    dict.Add("content-available", 1);
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(Type));
                }

                dict = new Dictionary <string, object>
                {
                    { accept_time, AcceptTimes },
                    { aps, dict },
                    { "custom", Custom }
                };

                return(dict.Serialize());
            }
        public void SerializeCache(string fileName)
        {
            lock (_cacheLock)
                lock (_ratingsToSend)
                {
                    File.Delete(fileName);
                    _cashe.WriteXml(fileName);

                    var sendCasheName = fileName + ".out";
                    File.Delete(sendCasheName);
                    if (_ratingsToSend.Any())
                    {
                        using (var writer = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            _ratingsToSend.Serialize(writer);
                            File.WriteAllText(sendCasheName, writer.GetStringBuilder().ToString(), Encoding.Unicode);
                        }
                    }
                }
        }
        public async Task It_should_update_array_field()
        {
            Dictionary <string, object> testEntityV1 =
                new Dictionary <string, object> {
                { "Array", new[] { "str1", "str2" } }, { "EntityName", "array" }
            };

            using TestServer server = TestServer(UserRole.Administrator);
            using HttpClient client = server.CreateHttpClient();

            HttpResponseMessage result = await client.PostAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/arrayUpdate",
                testEntityV1.Serialize());

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            Dictionary <string, object> testEntityV2 =
                new Dictionary <string, object> {
                { "Array", new[] { "stru1", "stru2" } }, { "EntityName", "array2" }
            };

            HttpResponseMessage ver1Json = await client.PatchAsync(
                $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/arrayUpdate",
                testEntityV2.Serialize());

            Assert.Equal(HttpStatusCode.OK, ver1Json.StatusCode);

            HttpResponseMessage configFound =
                await client.GetAsync(
                    $"features/application/{_env2.Application.Code}/environment/{_env2.Code}/config/arrayUpdate/json");

            Assert.Equal(HttpStatusCode.OK, configFound.StatusCode);

            dynamic ver1Data = configFound.Deserialize <dynamic>();

            Assert.Equal(ver1Data.Array, testEntityV2["Array"]);
            Assert.Equal(ver1Data.EntityName, testEntityV2["EntityName"]);
        }
Example #25
0
            /// <summary>
            ///
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                if (!string.IsNullOrWhiteSpace(Raw))
                {
                    return(Raw);
                }

                var dict = new Dictionary <string, object>
                {
                    { title, Title },
                    { content, Content },
                    { accept_time, AcceptTimes },
                    { custom_content, Custom }
                };

                if (Type == MessageType.Notification)
                {
                    if (Style != null)
                    {
                        dict.Add(builder_id, Style.BuilderId);
                        dict.Add(ring, Style.Ring);
                        dict.Add(vibrate, Style.Vibrate);
                        dict.Add(clearable, Style.Clearable);
                        dict.Add(n_id, Style.NId);
                        dict.Add(ring_raw, Style.RingRaw);
                        dict.Add(lights, Style.Lights);
                        dict.Add(icon_type, Style.IconType);
                        dict.Add(icon_res, Style.IconRes);
                        dict.Add(style_id, Style.StyleId);
                        dict.Add(small_icon, Style.SmallIcon);
                    }

                    dict.Add(action, Action.toJson());
                }

                return(dict.Serialize());
            }
        public ActionResult ProcessSelectShop(FormCollection collection)
        {
            var name = collection["name"];
            var shopid = collection["shopid"].TryTo(0);
            var ischeck = collection["ischeck"].TryTo(false);
            var all = collection["all"];

            var r = new Dictionary<int, string>();
            if (!all.IsEmpty())
            {
                r = all.Deserialize<Dictionary<int, string>>();
            }

            if (ischeck && !r.ContainsKey(shopid))
            {
                r.Add(shopid, name);
            }

            if (!ischeck)
            {
                r.Remove(shopid);
            }
            return Content(r.Serialize());
        }
Example #27
0
        private static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("To run this program you need a copy of the PASCAL VOC2012 dataset.");
                Console.WriteLine();
                Console.WriteLine("You call this program like this: ");
                Console.WriteLine("./dnn_instance_segmentation_train_ex /path/to/VOC2012 [det-minibatch-size] [seg-minibatch-size] [class-1] [class-2] [class-3] ...");
                return(1);
            }

            try
            {
                Console.WriteLine("\nSCANNING PASCAL VOC2012 DATASET");
                Console.WriteLine();

                var listing = PascalVOC2012.GetPascalVoc2012TrainListing(args[0]).ToArray();
                Console.WriteLine($"images in entire dataset: {listing.Length}");
                if (listing.Length == 0)
                {
                    Console.WriteLine("Didn't find the VOC2012 dataset. ");
                    return(1);
                }

                // mini-batches smaller than the default can be used with GPUs having less memory
                var argc             = args.Length;
                var detMiniBatchSize = argc >= 2 ? int.Parse(args[1]) : 35;
                var segMiniBatchSize = argc >= 3 ? int.Parse(args[2]) : 100;
                Console.WriteLine($"det mini-batch size: {detMiniBatchSize}");
                Console.WriteLine($"seg mini-batch size: {segMiniBatchSize}");

                var desiredClassLabels = new List <string>();
                for (var arg = 3; arg < argc; ++arg)
                {
                    desiredClassLabels.Add(args[arg]);
                }

                if (!desiredClassLabels.Any())
                {
                    desiredClassLabels.Add("bicycle");
                    desiredClassLabels.Add("car");
                    desiredClassLabels.Add("cat");
                }

                Console.Write("desired classlabels:");
                foreach (var desiredClassLabel in desiredClassLabels)
                {
                    Console.Write($" {desiredClassLabel}");
                }
                Console.WriteLine();

                // extract the MMOD rects
                Console.Write("\nExtracting all truth instances...");
                var truthInstances = LoadAllTruthInstances(listing);
                Console.WriteLine(" Done!");
                Console.WriteLine();


                if (listing.Length != truthInstances.Count)
                {
                    throw new ApplicationException();
                }

                var originalTruthImages = new List <TruthImage>();
                for (int i = 0, end = listing.Length; i < end; ++i)
                {
                    originalTruthImages.Add(new TruthImage
                    {
                        Info           = listing[i],
                        TruthInstances = truthInstances[i]
                    });
                }


                var truthImagesFilteredByClass = FilterBasedOnClassLabel(originalTruthImages, desiredClassLabels);

                Console.WriteLine($"images in dataset filtered by class: {truthImagesFilteredByClass.Count}");

                IgnoreSomeTruthBoxes(truthImagesFilteredByClass);
                var truthImages = FilterImagesWithNoTruth(truthImagesFilteredByClass);

                Console.WriteLine($"images in dataset after ignoring some truth boxes: {truthImages.Count}");

                // First train an object detector network (loss_mmod).
                Console.WriteLine("\nTraining detector network:");
                var detNet = TrainDetectionNetwork(truthImages, (uint)detMiniBatchSize);

                // Then train mask predictors (segmentation).
                var segNetsByClass = new Dictionary <string, LossMulticlassLogPerPixel>();

                // This flag controls if a separate mask predictor is trained for each class.
                // Note that it would also be possible to train a separate mask predictor for
                // class groups, each containing somehow similar classes -- for example, one
                // mask predictor for cars and buses, another for cats and dogs, and so on.
                const bool separateSegNetForEachClass = true;


                if (separateSegNetForEachClass)
                {
                    foreach (var classLabel in desiredClassLabels)
                    {
                        // Consider only the truth images belonging to this class.
                        var classImages = FilterBasedOnClassLabel(truthImages, new[] { classLabel });

                        Console.WriteLine($"\nTraining segmentation network for class {classLabel}:");
                        segNetsByClass[classLabel] = TrainSegmentationNetwork(classImages, (uint)segMiniBatchSize, classLabel);
                    }
                }
                else
                {
                    Console.WriteLine("Training a single segmentation network:");
                    segNetsByClass[""] = TrainSegmentationNetwork(truthImages, (uint)segMiniBatchSize, "");
                }

                Console.WriteLine("Saving networks");
                using (var proxy = new ProxySerialize(InstanceSegmentationNetFilename))
                {
                    LossMmod.Serialize(proxy, detNet);
                    segNetsByClass.Serialize(proxy, 4);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(0);
        }
        private byte[] generateCacheData(ResultExecutedContext context)
        {
            Dictionary <string, object> cacheData = new Dictionary <string, object>();

            // Cache Request params:
            cacheData.Add("Request.Method", context.HttpContext.Request.Method);
            cacheData.Add("Request.Path", context.HttpContext.Request.Path.HasValue ? context.HttpContext.Request.Path.Value : string.Empty);
            cacheData.Add("Request.QueryString", context.HttpContext.Request.QueryString.ToUriComponent());
            cacheData.Add("Request.DataHash", getRequestsDataHash(context.HttpContext.Request));

            //Cache Response params:
            cacheData.Add("Response.StatusCode", context.HttpContext.Response.StatusCode);
            cacheData.Add("Response.ContentType", context.HttpContext.Response.ContentType);

            Dictionary <string, List <string> > Headers = context.HttpContext.Response.Headers.ToDictionary(h => h.Key, h => h.Value.ToList());

            cacheData.Add("Response.Headers", Headers);


            // 2019-07-05: Response.Body cannot be accessed because its not yet created.
            // We are saving the Context.Result, because based on this the Response.Body is created.
            Dictionary <string, object> resultObjects = new Dictionary <string, object>();
            var contextResult = context.Result;

            resultObjects.Add("ResultType", contextResult.GetType().AssemblyQualifiedName);

            if (contextResult is CreatedAtRouteResult route)
            {
                //CreatedAtRouteResult.CreatedAtRouteResult(string routeName, object routeValues, object value)
                resultObjects.Add("ResultValue", route.Value);
                resultObjects.Add("ResultRouteName", route.RouteName);

                Dictionary <string, string> RouteValues = route.RouteValues.ToDictionary(r => r.Key, r => r.Value.ToString());
                resultObjects.Add("ResultRouteValues", RouteValues);
            }
            else if (contextResult is ObjectResult objectResult)
            {
                if (objectResult.Value.isAnonymousType())
                {
                    resultObjects.Add("ResultValue", Utils.AnonymousObjectToDictionary(objectResult.Value, Convert.ToString));
                }
                else
                {
                    resultObjects.Add("ResultValue", objectResult.Value);
                }
            }
            else if (contextResult is StatusCodeResult || contextResult is ActionResult)
            {
                // Known types that do not need additional data
            }
            else
            {
                throw new NotImplementedException($"ApplyPostIdempotency.generateCacheData is not implement for IActionResult type {contextResult.GetType().ToString()}");
            }

            cacheData.Add("Context.Result", resultObjects);


            // Serialize & Compress data:
            return(cacheData.Serialize());
        }
 private TestProcess StartProcess(string executable, Dictionary<string, string> args, Action<int, string, Action<string>, Action> onMessage)
 {
     var process = new Process
     {
         StartInfo = new ProcessStartInfo(string.Format(@"{0}\{1}.{0}.exe", executable, TestGroup))
         {
             UseShellExecute = false,
             RedirectStandardOutput = true,
             CreateNoWindow = true,
             RedirectStandardInput = true,
             Arguments = args != null ? args.Serialize() : ""
         }
     };
     ManualResetEventSlim doneEvent = new ManualResetEventSlim(false);
     process.OutputDataReceived += (sender, eventArgs) =>
     {
         Trace.WriteLine(executable + ": " + eventArgs.Data);
         onMessage(process.Id, eventArgs.Data,
             response =>
             {
                 process.StandardInput.WriteLine(response);
                 process.StandardInput.Flush();
             },
             () => doneEvent.Set()
             );
     };
     process.Start();
     process.BeginOutputReadLine();
     return new TestProcess(process, doneEvent);
 }
Example #30
0
 public void SerializeTest()
 {
     Dictionary<string, string> dict = new Dictionary<string, string>();
     dict["asd"] = "dsa";
     string str = dict.Serialize();
     string str_inline = dict.SerializeInline();
     byte[] bytes = dict.SerializeAsBytes();
     str.Deserialize<Dictionary<string, string>>();
     bytes.Deserialize<Dictionary<string, string>>();
 }
Example #31
0
 public static JSONNode ToJSON(this Dictionary <string, object> source)
 {
     return(JSON.Parse(source.Serialize()));
 }
Example #32
0
 private void Pack()
 {
     _bytes          = _headers.Serialize();
     _needsPackaging = false;
 }
Example #33
0
 public virtual string Save <Key, Value>(string name, Dictionary <Key, Value> value)
 {
     return(this.Format(name, value.Serialize(this.SeparatorItem(), this.ChangesOnly())));
 }