Exemple #1
0
 protected override void OnCompleteType(
     ITypeCompletionContext context,
     IDictionary <string, object?> contextData)
 {
     _converter             = context.Services.GetTypeConverter();
     _objectToDictConverter = new ObjectToDictionaryConverter(_converter);
     base.OnCompleteType(context, contextData);
 }
        public void ToDictionary_WithEmptyObject()
        {
            var value = new { };

            var actual = ObjectToDictionaryConverter.ToDictionary(value);

            //Assert
            actual.Should().BeEmpty();
        }
        public void Should_Return_Valid_Dictionary_Parser_For_Anonymous_Object()
        {
            var anonymousObject = new { Int = 1, Str = "str" };

            var converter = ObjectToDictionaryConverter.GetConverter(anonymousObject.GetType());

            var dictionary = converter.ConvertFromObject(anonymousObject);

            Assert.AreEqual(anonymousObject.Int, (int)dictionary[nameof(anonymousObject.Int)]);
            Assert.AreEqual(anonymousObject.Str, (string)dictionary[nameof(anonymousObject.Str)]);
        }
        public void ToDictionary_WithObject()
        {
            var value = new { First = 1, Second = 2, Third = 3 };

            var actual = ObjectToDictionaryConverter.ToDictionary(value);

            //Assert
            actual.Should().Contain("First", 1);
            actual.Should().Contain("Second", 2);
            actual.Should().Contain("Third", 3);
        }
        public void Should_Return_Same_Object_From_Cache_For_Anonymous_Object()
        {
            var firstAnonymousObject = new { Int = 1, Str = "str" };

            var first = ObjectToDictionaryConverter.GetConverter(firstAnonymousObject.GetType());

            var secondAnonymousObject = new { Int = 2, Str = "str2" };

            var second = ObjectToDictionaryConverter.GetConverter(secondAnonymousObject.GetType());

            Assert.AreSame(first, second);
        }
        public void Should_Return_Valid_Dictionary_Parser_For_Plain_Object()
        {
            var plainObject = new FlatObject {
                Int = 1, Str = "str", Time = DateTime.UtcNow
            };

            var parser = ObjectToDictionaryConverter.GetConverter(plainObject.GetType());

            var dictionary = parser.ConvertFromObject(plainObject);

            Assert.AreEqual(plainObject.Int, (int)dictionary[nameof(plainObject.Int)]);
            Assert.AreEqual(plainObject.Str, (string)dictionary[nameof(plainObject.Str)]);
            Assert.AreEqual(plainObject.Time, (DateTime)dictionary[nameof(plainObject.Time)]);
        }
Exemple #7
0
        private static void TransferDataObjectToLogEventProperties(LogEventInfo log, object logProperties)
        {
            if (logProperties == null || logProperties is string)
            {
                return;
            }

            var properties = logProperties as IDictionary ??
                             ObjectToDictionaryConverter.Convert(logProperties);

            foreach (var key in properties.Keys)
            {
                log.Properties.Add(key, properties[key]);
            }
        }
        public void Should_Return_Same_Object_From_Cache_For_Plain_Object()
        {
            var firstAnonymousObject = new FlatObject {
                Int = 1, Str = "str", Time = DateTime.UtcNow
            };

            var first = ObjectToDictionaryConverter.GetConverter(firstAnonymousObject.GetType());

            var secondAnonymousObject = new FlatObject {
                Int = 2, Str = "str2", Time = DateTime.Now
            };

            var second = ObjectToDictionaryConverter.GetConverter(secondAnonymousObject.GetType());

            Assert.AreSame(first, second);
        }
        public void Should_Return_Valid_Dictionary_Parser_For_NonFlat_Object()
        {
            var nonFlatObject = new NonFlatObject
            {
                Int        = 2,
                FlatObject = new FlatObject {
                    Int = 1, Str = "str", Time = DateTime.UtcNow
                }
            };

            var parser = ObjectToDictionaryConverter.GetConverter(nonFlatObject.GetType());

            var dictionary = parser.ConvertFromObject(nonFlatObject);

            Assert.AreEqual(nonFlatObject.Int, (int)dictionary[nameof(nonFlatObject.Int)]);
            Assert.AreSame(nonFlatObject.FlatObject, (FlatObject)dictionary[nameof(nonFlatObject.FlatObject)]);
        }
Exemple #10
0
        /// <summary>
        /// Makes a 'GET' request to the server using a URI
        /// </summary>
        /// <typeparam name="T">The type of object the response should be deserialized ot</typeparam>
        /// <returns>An object with response data</returns>
        private async Task <GitHubResponse <T> > Get <T>(GitHubRequest githubRequest) where T : new()
        {
            var url = new StringBuilder().Append(githubRequest.Url);

            if (githubRequest.Args != null)
            {
                url.Append(ToQueryString(ObjectToDictionaryConverter.Convert(githubRequest.Args).ToArray()));
            }
            var absoluteUrl = url.ToString();

            // If there is no cache, just directly execute and parse. Nothing more
            using (var request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl))
            {
                using (var requestResponse = await ExecuteRequest(request).ConfigureAwait(false))
                {
                    return(await ParseResponse <T>(requestResponse).ConfigureAwait(false));
                }
            }
        }
Exemple #11
0
        public async Task <IActionResult> GetOrders(OrdersPagingParameters orderParams)
        {
            var uri = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(_client.BaseAddress.ToString(),
                                                                                    ObjectToDictionaryConverter.ConvertToDictionary(orderParams));

            var orderResponse = await _client.GetAsync(uri);

            if (orderResponse.IsSuccessStatusCode)
            {
                var ordersStream = await orderResponse.Content.ReadAsStreamAsync();

                var orders = Serializer.Deserialize <OrdersPagedResult>(ordersStream);
                if (orders != null)
                {
                    return(StatusCode((int)orderResponse.StatusCode, orders));
                }
            }
            return(StatusCode((int)orderResponse.StatusCode));
        }
Exemple #12
0
        public void SimplePassTest()
        {
            PdfConverterGlobalSettings settings = new PdfConverterGlobalSettings();

            settings.Collate       = false;
            settings.ColorMode     = ColorMode.Grayscale;
            settings.Copies        = 5;
            settings.DocumentTitle = "Bojangles";
            settings.Margin        = new PdfPageMargin()
            {
                Bottom = "2cm",
                Top    = "4cm",
                Left   = "4cm",
                Right  = "2cm"
            };
            settings.Orientation    = Orientation.Portrait;
            settings.UseCompression = false;

            Dictionary <string, string> strObj = ObjectToDictionaryConverter.Convert(settings);

            var Collate        = strObj["collate"];
            var _ColorMode     = strObj["colorMode"];
            var Copies         = strObj["copies"];
            var DocumentTitle  = strObj["documentTitle"];
            var MarginBottom   = strObj["margin.bottom"];
            var MarginTop      = strObj["margin.top"];
            var MarginLeft     = strObj["margin.left"];
            var MarginRight    = strObj["margin.right"];
            var _Orientation   = strObj["orientation"];
            var UseCompression = strObj["useCompression"];

            Assert.AreEqual("false", Collate);
            Assert.AreEqual("Grayscale", _ColorMode);
            Assert.AreEqual("5", Copies);
            Assert.AreEqual("Bojangles", DocumentTitle);
            Assert.AreEqual("2cm", MarginBottom);
            Assert.AreEqual("4cm", MarginTop);
            Assert.AreEqual("4cm", MarginLeft);
            Assert.AreEqual("2cm", MarginRight);
            Assert.AreEqual("Portrait", _Orientation);
            Assert.AreEqual("false", UseCompression);
        }
Exemple #13
0
        protected byte[] ConvertHtmlToPdf(PdfConverterGlobalSettings globalSettings, PdfConverterObjectSettings objectSettings, byte[] data = null)
        {
            byte[] resultBuffer = null;

            lock (_converterRoot)
            {
                try
                {
                    Dictionary <string, string> sGlobalSettings = ObjectToDictionaryConverter.Convert(globalSettings);
                    Dictionary <string, string> sObjectSettings = ObjectToDictionaryConverter.Convert(objectSettings);

                    IntPtr globalSettingsPtr = WkHtmlToPdfImports.wkhtmltopdf_create_global_settings();
                    GlobalSettingsPtr = globalSettingsPtr;
                    foreach (var globalSetting in sGlobalSettings)
                    {
                        WkHtmlToPdfImports.wkhtmltopdf_set_global_setting(globalSettingsPtr, globalSetting.Key, globalSetting.Value);
                    }

                    IntPtr objectSettingsPtr = WkHtmlToPdfImports.wkhtmltopdf_create_object_settings();
                    ObjectSettingsPtr = objectSettingsPtr;
                    foreach (var objectSetting in sObjectSettings)
                    {
                        WkHtmlToPdfImports.wkhtmltopdf_set_object_setting(objectSettingsPtr, objectSetting.Key, objectSetting.Value);
                    }

                    IntPtr converterPtr = WkHtmlToPdfImports.wkhtmltopdf_create_converter(globalSettingsPtr);
                    ConverterPtr = converterPtr;

                    //Set Callbacks
                    WkHtmlToPdfImports.wkhtmltopdf_set_progress_changed_callback(converterPtr, ProgressChangedCallback);
                    WkHtmlToPdfImports.wkhtmltopdf_set_phase_changed_callback(converterPtr, PhaseChangedCallback);
                    WkHtmlToPdfImports.wkhtmltopdf_set_error_callback(converterPtr, ErrorCallback);
                    WkHtmlToPdfImports.wkhtmltopdf_set_warning_callback(converterPtr, WarningCallback);

                    WkHtmlToPdfImports.wkhtmltopdf_add_object(converterPtr, objectSettingsPtr, data);

                    if (!WkHtmlToPdfImports.wkhtmltopdf_convert(converterPtr))
                    {
                        int errorCode = WkHtmlToPdfImports.wkhtmltopdf_http_error_code(converterPtr);
                        throw new WkHtmlToPdfException(errorCode);
                    }

                    IntPtr dataPtr   = IntPtr.Zero;
                    int    resultLen = WkHtmlToPdfImports.wkhtmltopdf_get_output(converterPtr, out dataPtr);
                    if (resultLen > 0)
                    {
                        resultBuffer = new byte[resultLen];
                        Marshal.Copy(dataPtr, resultBuffer, 0, resultLen);
                    }
                }
                finally
                {
                    if (GlobalSettingsPtr != IntPtr.Zero)
                    {
                        WkHtmlToPdfImports.wkhtmltopdf_destroy_global_settings(GlobalSettingsPtr);
                        GlobalSettingsPtr = IntPtr.Zero;
                    }
                    if (ObjectSettingsPtr != IntPtr.Zero)
                    {
                        WkHtmlToPdfImports.wkhtmltopdf_destroy_object_settings(ObjectSettingsPtr);
                        ObjectSettingsPtr = IntPtr.Zero;
                    }
                    if (ConverterPtr != IntPtr.Zero)
                    {
                        WkHtmlToPdfImports.wkhtmltopdf_destroy_converter(ConverterPtr);
                        ConverterPtr = IntPtr.Zero;
                    }
                }
            }

            return(resultBuffer);
        }
        public void ToDictionary_WithNull()
        {
            Action action = () => ObjectToDictionaryConverter.ToDictionary(null);

            action.ShouldThrowArgumentNullException();
        }
Exemple #15
0
 /// <summary>
 /// Updates a comment
 /// </summary>
 /// <param name="comment">The issue model</param>
 /// <returns></returns>
 public CommentModel Update(CommentModel comment)
 {
     return(Update(ObjectToDictionaryConverter.Convert(comment)));
 }
Exemple #16
0
        public static IScope BeginScope(this ILogger logger, string scopeName, object logProps = null)
        {
            var properties = ObjectToDictionaryConverter.Convert(logProps);

            return(new Scope(logger, scopeName, properties));
        }
Exemple #17
0
        /// <summary>
        /// Makes a 'GET' request to the server using a URI
        /// </summary>
        /// <typeparam name="T">The type of object the response should be deserialized ot</typeparam>
        /// <returns>An object with response data</returns>
        private async Task <GitHubResponse <T> > Get <T>(GitHubRequest githubRequest) where T : new()
        {
            var url = new StringBuilder().Append(githubRequest.Url);

            if (githubRequest.Args != null)
            {
                url.Append(ToQueryString(ObjectToDictionaryConverter.Convert(githubRequest.Args).ToArray()));
            }
            var absoluteUrl = url.ToString();

            // If there is no cache, just directly execute and parse. Nothing more
            if (Cache == null)
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl))
                {
                    using (var requestResponse = await ExecuteRequest(request).ConfigureAwait(false))
                    {
                        return(await ParseResponse <T>(requestResponse).ConfigureAwait(false));
                    }
                }
            }

            // Attempt to get the cached response
            GitHubResponse <T> cachedResponse = null;

            if (githubRequest.RequestFromCache || githubRequest.CheckIfModified)
            {
                try
                {
                    cachedResponse = Cache.Get <GitHubResponse <T> >(absoluteUrl);
                    if (githubRequest.RequestFromCache && cachedResponse != null)
                    {
                        cachedResponse.WasCached = true;
                        return(cachedResponse);
                    }
                }
                catch
                {
                }
            }

            using (var request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl))
            {
                var etag = (githubRequest.CheckIfModified && cachedResponse != null) ? cachedResponse.ETag : null;
                if (etag != null)
                {
                    request.Headers.Add("If-None-Match", string.Format("\"{0}\"", etag));
                }

                using (var response = await ExecuteRequest(request).ConfigureAwait(false))
                {
                    var parsedResponse = await ParseResponse <T>(response).ConfigureAwait(false);

                    if (githubRequest.CacheResponse)
                    {
                        Cache.Set(absoluteUrl, parsedResponse);
                    }

                    return(parsedResponse);
                }
            }
        }
Exemple #18
0
 /// <summary>
 /// Updates an issue
 /// </summary>
 /// <param name="issue">The issue model</param>
 /// <returns></returns>
 public IssueModel Update(CreateIssueModel issue)
 {
     return(Update(ObjectToDictionaryConverter.Convert(issue)));
 }