Ejemplo n.º 1
0
        private void RunTest(object value, int times, bool useGZip)
        {
            var vType          = value?.GetType() ?? typeof(object);
            var compressor     = useGZip ? CompressorManager.GetByEncodingType("gzip") : null;
            var memStream      = new RecycleMemoryStream();
            var jsonSerializer = new JsonTextSerializer {
                Compressor = compressor
            };
            var xmlSerializer = new XmlTextSerializer {
                Compressor = compressor
            };
            var binarySerializer = new BinaryFormatterSerializer {
                Compressor = compressor
            };
            var ut8JsonSerializer = new Utf8JsonTextSerializer {
                Compressor = compressor
            };
            var msgPackSerializer = new MsgPackSerializer {
                Compressor = compressor
            };
            var nBinarySerializer = new NBinarySerializer {
                Compressor = compressor
            };
            var rawBinarySerializer = new RawBinarySerializer {
                Compressor = compressor
            };
            var wBinarySerializer = new WBinarySerializer {
                Compressor = compressor
            };
            var pwBinarySerializer = new PWBinarySerializer {
                Compressor = compressor
            };

            Core.Log.Warning("Running Serializer Test. Use GZIP = {0}", useGZip);
            Core.Log.WriteEmptyLine();
            Core.Log.InfoBasic("By size:");
            Core.Log.InfoBasic("\tJson Bytes Count: {0}", SerializerSizeProcess(value, vType, jsonSerializer));
            Core.Log.InfoBasic("\tXml Bytes Count: {0}", SerializerSizeProcess(value, vType, xmlSerializer));
            Core.Log.InfoBasic("\tBinaryFormatter Bytes Count: {0}", SerializerSizeProcess(value, vType, binarySerializer));
            Core.Log.InfoBasic("\tUtf8Json Bytes Count: {0}", SerializerSizeProcess(value, vType, ut8JsonSerializer));
            Core.Log.InfoBasic("\tMessagePack Bytes Count: {0}", SerializerSizeProcess(value, vType, msgPackSerializer));
            Core.Log.InfoBasic("\tNBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, nBinarySerializer));
            Core.Log.InfoBasic("\tRawBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, rawBinarySerializer));
            Core.Log.InfoBasic("\tWBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, wBinarySerializer));
            Core.Log.InfoBasic("\tPortable WBinary Bytes Count: {0}", SerializerSizeProcess(value, vType, pwBinarySerializer));
            Core.Log.WriteEmptyLine();
            Core.Log.InfoBasic("By Times: {0}", times);
            SerializerProcess("Json", value, vType, times, jsonSerializer, memStream);
            SerializerProcess("Utf8Json", value, vType, times, ut8JsonSerializer, memStream);
            SerializerProcess("NBinary", value, vType, times, nBinarySerializer, memStream);
            SerializerProcess("RawBinary", value, vType, times, rawBinarySerializer, memStream);
            SerializerProcess("WBinary", value, vType, times, wBinarySerializer, memStream);
            SerializerProcess("PWBinary", value, vType, times, pwBinarySerializer, memStream);
            Console.ReadLine();
        }
Ejemplo n.º 2
0
        public HttpStatusTransport(int port = 80)
        {
            var htmlPage       = this.GetAssembly().GetResourceString("Status.htm");
            var xmlSerializer  = new XmlTextSerializer();
            var jsonSerializer = new JsonTextSerializer()
            {
                UseCamelCase = true
            };

            _httpServer = new SimpleHttpServer();
            _httpServer.AddGetHandler("/", ctx =>
            {
                ctx.Response.Write(htmlPage);
            });
            _httpServer.AddGetHandler("/xml", ctx =>
            {
                if (OnFetchStatus == null)
                {
                    return;
                }
                var statuses             = OnFetchStatus.Invoke();
                ctx.Response.ContentType = SerializerMimeTypes.Xml;
                xmlSerializer.Serialize(statuses, ctx.Response.OutputStream);
            });
            _httpServer.AddGetHandler("/json", ctx =>
            {
                if (OnFetchStatus == null)
                {
                    return;
                }
                var statuses             = OnFetchStatus.Invoke();
                ctx.Response.ContentType = SerializerMimeTypes.Json;
                jsonSerializer.Serialize(statuses, ctx.Response.OutputStream);
            });
            _httpServer.AddGetHandler("/gccollect", ctx =>
            {
                GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                ctx.Response.ContentType = SerializerMimeTypes.Json;
                ctx.Response.Write("true");
            });
            _httpServer.AddGetHandler("/discovery", ctx =>
            {
                var services       = DiscoveryService.GetRegisteredServices();
                var statusServices = services.Where(s => s.Category == DiscoveryService.FrameworkCategory && s.Name == "STATUS.HTTP").ToArray();
                ctx.Response.WriteLine("<html><head><title>Discovered Status Services</title></head><body style='padding:30px;'><h1 style='text-align:center;'>Discovered status services</h1>");
                foreach (var g in statusServices.GroupBy(s => new { s.EnvironmentName, s.MachineName }).OrderBy(s => s.Key.EnvironmentName))
                {
                    ctx.Response.WriteLine($"<h3>Environment: {g.Key.EnvironmentName} - Machine: {g.Key.MachineName}</h3>");
                    ctx.Response.WriteLine("<ul>");
                    foreach (var ss in g)
                    {
                        var dct = (Dictionary <string, object>)ss.Data.GetValue();
                        ctx.Response.WriteLine("<li style='list-style-type: none;'>");
                        foreach (var ssAddress in ss.Addresses)
                        {
                            ctx.Response.WriteLine($"<a href='http://{ssAddress.ToString()}:{dct["Port"]}/' target='_blank' style='text-decoration: none;color: blue;'>{ssAddress.ToString()}</a> /");
                        }
                        ctx.Response.WriteLine($" {ss.ApplicationName}</li>");
                    }
                    ctx.Response.WriteLine("</ul>");
                }
                ctx.Response.WriteLine("</body></html>");
            });
            StartListening(port).WaitAsync();
            Core.Status.DeAttachObject(_httpServer);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Connects the Connector and authorizes the credentials of the user.
        /// </summary>
        /// <param name="properties">Collection of information required by this Connector to connect to the REST service.</param>
        public void Connect(IDictionary <string, string> properties)
        {
            /* LogMethodExecution will write time stamps at the start and
             * end of the using statement. Use this to keep track of when
             * methods are executing
             */

            using (new LogMethodExecution("Rest CDK Example", "RestConnector.Connect()"))
            {
                /* For the initial authorization, we need to connect and get the access token
                 * Pull the oAuth information out of the properties dictionary and verify its format:
                 */
                try
                {
                    if (Uri.IsWellFormedUriString(properties[OAuthResponse], UriKind.RelativeOrAbsolute))
                    {
                        var queryString = HttpUtility.ParseQueryString(properties[OAuthResponse]);
                        var goToWebinar = new GoToWebinarClient();

                        string oAuthCode = queryString["code"];

                        //get the properties from the REST service:
                        _connectionInfo = goToWebinar.Authenticate(oAuthCode, OAuthApiKey);

                        //loop through and add them to our dictionary:
                        foreach (var item in _connectionInfo)
                        {
                            properties.Add(item.Key, item.Value);
                        }

                        //Use Scribe's CDK to encrypt the access token in the dictionary:
                        //Scribe OnLine uses the properties parameter further up, byref, to store these values.
                        properties["AccessToken"] = Encryptor.Encrypt_AesManaged(properties["AccessToken"], CryptoKey);
                    }
                    else
                    {
                        /* We've connected before and already have the token in our dictionary:
                         *  We're using the connection data that's serialized in memory
                         */


                        using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(properties[OAuthResponse])))
                        {
                            //Use the CDK to deserialize the properties dictionary
                            _connectionInfo = XmlTextSerializer.DeserializeFromStream <Dictionary <string, string> >(memoryStream);

                            /*Check the properties for the access token, if it doesn't exist, dig into it for the
                             * oauth_response and look there for the access token
                             */
                            if (_connectionInfo.ContainsKey("AccessToken"))
                            {
                                _connectionInfo["AccessToken"] = Decryptor.Decrypt_AesManaged(_connectionInfo["AccessToken"], CryptoKey);
                            }
                            else
                            {
                                if (_connectionInfo.ContainsKey(OAuthResponse))
                                {
                                    using (var innerStream = new MemoryStream(Encoding.UTF8.GetBytes(_connectionInfo[OAuthResponse])))
                                    {
                                        _connectionInfo = XmlTextSerializer.DeserializeFromStream <Dictionary <string, string> >(innerStream);
                                        _connectionInfo["AccessToken"] = Decryptor.Decrypt_AesManaged(_connectionInfo["AccessToken"], CryptoKey);
                                    }
                                }
                            }
                        }
                    }

                    //Check to see how the connection went and set some additional members on this class:
                    if (_connectionInfo.Count > 0)
                    {
                        IsConnected             = true;
                        this.QueryProcessor     = new QueryProcessor(_connectionInfo, _webinarClient);
                        this.OperationProcessor = new OperationProcessor(this._webinarClient, this._connectionInfo);
                    }
                }
                catch (System.Net.WebException exception)
                {
                    //Use the CDK to create a message from the exception
                    string message = ExceptionFormatter.BuildActionableException(
                        "Unable to connect to the service due to a Web exception",
                        "The following error occured in the REST Connector",
                        exception);

                    //log the exception
                    Logger.Write(Logger.Severity.Error, "REST Connector", message);

                    //Throw an exception that the CDK will recognize:
                    throw new InvalidConnectionException(message);
                }
                catch (Exception exception)
                {
                    string message = ExceptionFormatter.BuildActionableException(
                        "Unable to connect to the service.",
                        "The following error occured while trying to connect to the REST service.",
                        exception);

                    Logger.Write(Logger.Severity.Error, "REST Connector", message);

                    throw new InvalidConnectionException(message);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sets the default TWCoreValues
        /// </summary>
        public static void SetDefaultTWCoreValues(this IServiceCollection services, CompatibilityVersion compatibilityVersion = CompatibilityVersion.Version_2_2, CoreWebSettings settings = null)
        {
            settings = settings ?? new CoreWebSettings();
            services.AddMvc(options =>
            {
                try
                {
                    if (settings.UseCustomXmlSerializer)
                    {
                        var xmlSerializer = new XmlTextSerializer();
                        options.AddISerializerInputFormatter(xmlSerializer);
                        options.AddISerializerOutputFormatter(xmlSerializer);
                    }
                    else
                    {
                        options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
                        options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                    }

                    if (settings.EnableFormatMapping)
                    {
                        options.FormatterMappings.SetMediaTypeMappingForFormat
                            ("xml", MediaTypeHeaderValue.Parse("application/xml"));
                        options.FormatterMappings.SetMediaTypeMappingForFormat
                            ("js", MediaTypeHeaderValue.Parse("application/json"));
                    }

                    if (settings.EnableTWCoreSerializers)
                    {
                        var serializers = SerializerManager.GetBinarySerializers();
                        foreach (var serializer in serializers)
                        {
                            options.AddISerializerInputFormatter(serializer);
                            options.AddISerializerOutputFormatter(serializer);
                            if (settings.EnableFormatMapping)
                            {
                                options.FormatterMappings.SetMediaTypeMappingForFormat(serializer.Extensions[0].Substring(1),
                                                                                       MediaTypeHeaderValue.Parse(serializer.MimeTypes[0]));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Core.Log.Write(ex);
                }
            }).SetCompatibilityVersion(compatibilityVersion)
            .AddJsonOptions(options =>
            {
                if (settings.EnableJsonStringEnum)
                {
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                }
            });
            services.AddLogging(cfg =>
            {
                if (settings.EnableTWCoreLogger)
                {
                    cfg.AddTWCoreLogger();
                }
            });
            if (settings.EnableGZipCompressor)
            {
                services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Fastest);
                services.AddResponseCompression();
                if (settings.EnableTWCoreSerializers)
                {
                    var serializers = SerializerManager.GetBinarySerializers();

                    services.Configure <ResponseCompressionOptions>(options =>
                    {
                        options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(serializers.SelectMany(i => i.MimeTypes));
                    });
                }
            }
        }
Ejemplo n.º 5
0
        public void Setup()
        {
            Core.InitDefaults();

            var sTest = new STest
            {
                FirstName = "Daniel",
                LastName  = "Redondo",
                Age       = 35,
                value     = 166
            };

            _data = new List <STest>
            {
                sTest, sTest, sTest, sTest, sTest, sTest,
                sTest, sTest, sTest, sTest, sTest, sTest,
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 0, Age = 1, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 1, Age = 2, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 2, Age = 3, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 3, Age = 4, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 4, Age = 5, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 5, Age = 6, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 6, Age = 7, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 7, Age = 8, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 8, Age = 9, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 9, Age = 10, Brother = sTest
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 10, Age = 11
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 11, Age = 12
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 12, Age = 13
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 13, Age = 14
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 14, Age = 15
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 15, Age = 16
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 16, Age = 17
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 17, Age = 18
                },
                new STest {
                    FirstName = "Person", LastName = "Person" + "." + 18, Age = 19
                },
            };

            _jsonSerializer       = new JsonTextSerializer();
            _binData              = _jsonSerializer.Serialize(_data);
            _jsonSerializerStream = new MemoryStream();
            _jsonSerializer.Serialize(_data, _jsonSerializerStream);

            _xmlSerializer       = new XmlTextSerializer();
            _binData             = _xmlSerializer.Serialize(_data);
            _xmlSerializerStream = new MemoryStream();
            _xmlSerializer.Serialize(_data, _xmlSerializerStream);

            _binSerializer       = new BinaryFormatterSerializer();
            _binData             = _binSerializer.Serialize(_data);
            _binSerializerStream = new MemoryStream();
            _binSerializer.Serialize(_data, _binSerializerStream);

            _utf8jsonSerializer       = new Utf8JsonTextSerializer();
            _binData                  = _utf8jsonSerializer.Serialize(_data);
            _utf8jsonSerializerStream = new MemoryStream();
            _utf8jsonSerializer.Serialize(_data, _utf8jsonSerializerStream);

            _msgPackSerializer       = new MsgPackSerializer();
            _binData                 = _msgPackSerializer.Serialize(_data);
            _msgPackSerializerStream = new MemoryStream();
            _msgPackSerializer.Serialize(_data, _msgPackSerializerStream);

            _nBinary       = new NBinarySerializer();
            _binData       = _nBinary.Serialize(_data);
            _nBinaryStream = new MemoryStream();
            _nBinary.Serialize(_data, _nBinaryStream);

            _rawBinary       = new RawBinarySerializer();
            _binData         = _rawBinary.Serialize(_data);
            _rawBinaryStream = new MemoryStream();
            _rawBinary.Serialize(_data, _rawBinaryStream);
        }