public void Deserialize_ShouldBeAbleToHandle_NullDateTimeValues()
        {
            var response = new RestResponse { Content = "[{\"closed_at\":null}]" };
            var serializer = new CustomJsonSerializer();
            var issues = serializer.Deserialize<List<Issue>>(response);

            Assert.IsNull(issues[0].ClosedAt);
        }
        //[Description("https://bitbucket.org/Readify/neo4jclient/issue/89")]
        public void ShouldSerializeCustomTypeThatHasTypeConverterUsingTypeConverterBasedJsonConverter()
        {
            //Arrange
            var serializer = new CustomJsonSerializer
            {
                JsonConverters = new[] { new TypeConverterBasedJsonConverter() }
            };

            var model = new TestModelB
            {
                CustomValue = new TestValueB
                {
                    A = 'o',
                    B = 'p'
                }
            };

            //Act
            var rawResult = serializer.Serialize(model);

            //Assert
            const string expectedRawOutput =
                "{\r\n  \"CustomValue\": \"op\"\r\n}";

            Assert.Equal(expectedRawOutput, rawResult);
        }
예제 #3
0
        static async Task Main(string[] args)
        {
            const int    MAX_NUMBER_REQUEST      = 800;
            const string BEARER_KEY              = "Bearer {replace with you bearer token from your tweeter dev account}";
            const int    MAX_RESULTS_PER_REQUEST = 99;

            //parameters
            var NewestDate = DateTime.Parse("2021-05-14T07:00:33Z");
            var OldestDate = DateTime.Parse("2020-12-28T07:00:33Z");
            var searchKeys = "doge bitcoin";
            var username   = "******";

            var httpClient    = new CustomHttpClient();
            var serializer    = new CustomJsonSerializer();
            var tweeterSearch = new TweetSearch(MAX_NUMBER_REQUEST, MAX_RESULTS_PER_REQUEST, BEARER_KEY, httpClient, serializer);

            Console.WriteLine("Process started. Please wait..");

            var final_result = await tweeterSearch.GetAllRelevantTweets(username, NewestDate, OldestDate, searchKeys);

            Console.WriteLine("------------------------------------------------------------------------");

            foreach (var tweet in final_result)
            {
                Console.WriteLine(string.Format("{0} ({1})\r\n", tweet.text, tweet.created_At));
            }
        }
        public void ShouldSerializeCustomValueWithCustomJsonConverter()
        {
            //Arrange
            var serializer = new CustomJsonSerializer
            {
                JsonConverters = new [] { new TestValueAConverter() }
            };

            var model = new TestModelA
            {
                CustomValue = new TestValueA
                {
                    A = 'o',
                    B = 'p'
                }
            };

            //Act
            var rawResult = serializer.Serialize(model);

            //Assert
            const string expectedRawOutput =
                "{\r\n  \"CustomValue\": \"op\"\r\n}";

            Assert.AreEqual(expectedRawOutput, rawResult);
        }
        //[Description("https://bitbucket.org/Readify/neo4jclient/issue/89")]
        public void ShouldSerializeCustomValueWithCustomJsonConverter()
        {
            //Arrange
            var serializer = new CustomJsonSerializer
            {
                JsonConverters = new [] { new TestValueAConverter() }
            };

            var model = new TestModelA
            {
                CustomValue = new TestValueA
                {
                    A = 'o',
                    B = 'p'
                }
            };

            //Act
            var rawResult = serializer.Serialize(model);

            //Assert
            string expectedRawOutput =
                $"{{{Environment.NewLine}  \"CustomValue\": \"op\"{Environment.NewLine}}}";

            Assert.Equal(expectedRawOutput, rawResult);
        }
예제 #6
0
        public AppBootstrapper(Action <ConfigurableBootstrapperConfigurator> configuration, bool enableViewSupportWhichMakesTheUnitTestsReallySlow = false) : base(with => {
            if (enableViewSupportWhichMakesTheUnitTestsReallySlow)
            {
                // Do not use view support if it is not needed. Makes the unit tests much slower.
                with.ViewLocationProvider <FileSystemViewLocationProvider>();
                with.ViewFactory <TestingViewFactory>();
            }
            configuration(with);
        }) {
            JsonSerializer = new CustomJsonSerializer();
            InternalConfiguration.Serializers.Clear();
            InternalConfiguration.Serializers.Add(JsonSerializer.GetType());

            BeforeRequest.AddItemToEndOfPipeline(context => {
                if (AuthenticatedUser == null)
                {
                    context.CurrentUser = null;
                }
                else
                {
                    var userIdentity    = new VoterIdentity(AuthenticatedUser);
                    context.CurrentUser = userIdentity;
                }
                return(null);
            });

            OnError = OnError
                      + ErrorPipelines.HandleModelBindingException()
                      + ErrorPipelines.HandleRequestValidationException()
                      + ErrorPipelines.HandleSecurityException();
        }
예제 #7
0
        private static void OcrService_BatchComplete(object sender, OcrBatch batch)
        {
            //Console.WriteLine("Batch {0} completed", batch.JobIdentifier);
            // publish result to outgoing queue/exchange
            var messageBatch = new RecogniseBatchCourtesyAmountResponse
            {
                jobIdentifier = batch.JobIdentifier,
                voucher       = batch.Vouchers.Select(v => new RecogniseCourtesyAmountResponse
                {
                    documentReferenceNumber = v.Id,
                    capturedAmount          = v.AmountResult.Result ?? "0",
                    amountConfidenceLevel   = v.AmountResult.Score ?? "0",
                    amountRegionOfInterest  = new RegionOfInterest
                    {
                        height = v.AmountResult.Location.Height,
                        left   = v.AmountResult.Location.Left,
                        top    = v.AmountResult.Location.Top,
                        width  = v.AmountResult.Location.Width
                    }
                }).ToArray()
            };

            //MessageBus.Publish(messageBatch, RoutingKey);
            //Queue.PublishToExchange(OutboundExchangeName, batch.JobIdentifier, RoutingKey, CustomJsonSerializer.MessageToBytes(messageBatch));
            Exchange.SendMessage(CustomJsonSerializer.MessageToBytes(messageBatch), RoutingKey, batch.JobIdentifier);
        }
            public void CamelCaseListTest()
            {
                //setup
                var model = new List <CamelModel>
                {
                    new CamelModel
                    {
                        FirstName   = "first",
                        DateOfBirth = new DateTime(1980, 4, 1),
                        Gender      = Gender.Male
                    },
                    new CamelModel
                    {
                        FirstName   = "second",
                        DateOfBirth = new DateTime(1981, 4, 1),
                        Gender      = Gender.Female
                    }
                };

                var serializer = new CustomJsonSerializer();

                serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver();
                var st = serializer.Serialize(model);

                //act
                var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver);
                var output       = deserializer.Deserialize <List <CamelModel> >(st);

                //assert
                AssertCamelModel(model[0], output[0]);
                AssertCamelModel(model[1], output[1]);
            }
        public void JsonSerializerWithEnumConverterShouldConvertEnumToStringValues()
        {
            // Arrange
            var testClass = new TestFoo
            {
                Gender         = Gender.Female,
                GenderNullable = Gender.Male
            };

            var serializer = new CustomJsonSerializer
            {
                JsonConverters = new JsonConverter[]
                {
                    new EnumValueConverter(),
                    new NullableEnumValueConverter()
                }
            };

            const string expected = "{\r\n  \"Gender\": \"Female\",\r\n  \"GenderNullable\": \"Male\"\r\n}";

            // Act
            var result = serializer.Serialize(testClass);

            // Assert
            Assert.Equal(expected, result);
        }
예제 #10
0
 public virtual void Consumer_ReceiveMessage(IBasicGetResult message)
 {
     ContinueProcessing = false;
     if (message == null)
     {
         return;                  // queue is empty
     }
     Message       = CustomJsonSerializer.BytesToMessage <T>(message.Body);
     CorrelationId = message.BasicProperties.CorrelationId;
     RoutingKey    = message.RoutingKey;
     if (message.Body.Count() == 0)
     {
         Log.Error(
             "SubscriberBase: Consumer_ReceiveMessage(message) - message.Body contains no data for message id {0}",
             message.BasicProperties.MessageId);
     }
     if (Message != null)
     {
         ContinueProcessing = true;
         return;
     }
     if (message.Body.Count() > 0)
     {
         Log.Error("SubscriberBase: Consumer_ReceiveMessage(message) - message.Body contains data which is not compatible with {0} for message id {1}", typeof(T).ToString(), message.BasicProperties.MessageId);
     }
     InvalidExchange.SendMessage(message.Body, InvalidRoutingKey, "");
 }
        public void CamelCaseListTest()
        {
            //setup
            var model =  new List<CamelModel>
            {
                new CamelModel
                {
                    FirstName = "first",
                    DateOfBirth = new DateTime(1980, 4, 1),
                    Gender = Gender.Male
                },
                new CamelModel
                {
                    FirstName = "second",
                    DateOfBirth = new DateTime(1981, 4, 1),
                    Gender = Gender.Female
                }
            };

            var serializer = new CustomJsonSerializer();
            serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver();
            var st = serializer.Serialize(model);

            //act
            var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver);
            var output = deserializer.Deserialize<List<CamelModel>>(st);

            //assert
            AssertCamelModel(model[0], output[0]);
            AssertCamelModel(model[1], output[1]);
        }
예제 #12
0
        public async Task <string> React(PublicId userId, PublicId toId, ReactionType type)
        {
            var reaction = (ActivityObject)Activator.CreateInstance(CustomJsonSerializer.TypeOf(type.ToString()));

            reaction.actor = new List <BaseObject> {
                new Common.Person {
                    PublicId = userId,
                }
            }.ToCollection();

            var target = await _activityContent.Get(toId, userId);

            if (target != null)
            {
                reaction.target = new List <BaseObject> {
                    target
                }.ToCollection();

                var res = await _activityStream.Post("outbox", reaction);

                return(reaction.id);
            }
            else
            {
                return(null);
            }
        }
예제 #13
0
        /// <summary>
        /// Executes a specified action proxy from an addon.
        /// </summary>
        /// <param name="actionProxy">The <see cref="ActionProxy"/> to execute.</param>
        /// <param name="timeout">The action execution timeout (in milliseconds).</param>
        /// <returns>The response from the Agent upon executing the action proxy.</returns>
        public ActionExecutionResponse ExecuteProxy(ActionProxy actionProxy, int timeout)
        {
            RestRequest sendActionProxyRequest = new RestRequest(Endpoints.EXECUTE_ACTION_PROXY, Method.POST);

            sendActionProxyRequest.RequestFormat = DataFormat.Json;

            string json = CustomJsonSerializer.ToJson(actionProxy.ProxyDescriptor, this.serializerSettings);

            sendActionProxyRequest.AddJsonBody(json);

            if (timeout > 0)
            {
                // Since action proxy execution can take a while, you can override the default timeout.
                this.client.Timeout = timeout;
            }

            IRestResponse sendActionProxyResponse = this.client.Execute(sendActionProxyRequest);

            if (sendActionProxyResponse.StatusCode.Equals(HttpStatusCode.NotFound))
            {
                string errorMessage = $"Action {actionProxy.ProxyDescriptor.ClassName} in addon {actionProxy.ProxyDescriptor.Guid} is not installed for your account.";

                Logger.Error(errorMessage);
                throw new AddonNotInstalledException(errorMessage);
            }

            // Reset the client timeout to the RestSharp default.
            this.client.Timeout = this.defaultRestClientTimeoutInMilliseconds;

            return(CustomJsonSerializer.FromJson <ActionExecutionResponse>(sendActionProxyResponse.Content, this.serializerSettings));
        }
예제 #14
0
        /// <summary>
        /// Retrieves the version of the Agent currently in use.
        /// </summary>
        /// <returns>An instance of the <see cref="Version"/> class containing the Agent version.</returns>
        private Version GetAgentVersion()
        {
            RestRequest getAgentStatusRequest = new RestRequest(Endpoints.STATUS, Method.GET);

            IRestResponse getAgentStatusResponse = this.client.Execute(getAgentStatusRequest);

            if (getAgentStatusResponse.ErrorException != null)
            {
                string errorMessage = $"An error occurred connecting to the Agent. Is your Agent running at {this.remoteAddress}?";

                Logger.Error(errorMessage);
                throw new AgentConnectException(errorMessage);
            }

            if ((int)getAgentStatusResponse.StatusCode >= 400)
            {
                throw new AgentConnectException($"Failed to get Agent status: {getAgentStatusResponse.ErrorMessage}");
            }

            AgentStatusResponse agentStatusResponse = CustomJsonSerializer.FromJson <AgentStatusResponse>(getAgentStatusResponse.Content, this.serializerSettings);

            Logger.Info($"Current Agent version is {agentStatusResponse.Tag}");

            return(new Version(agentStatusResponse.Tag));
        }
예제 #15
0
        /// <summary>
        /// Starts a new session with the Agent.
        /// </summary>
        /// <param name="reportSettings">Settings (project name, job name) to be included in the report.</param>
        /// <param name="capabilities">Additional options to be applied to the driver instance.</param>
        private void StartSession(ReportSettings reportSettings, DriverOptions capabilities)
        {
            RestRequest startSessionRequest = new RestRequest(Endpoints.DEVELOPMENT_SESSION, Method.POST);

            startSessionRequest.RequestFormat = DataFormat.Json;

            string json = CustomJsonSerializer.ToJson(new SessionRequest(reportSettings, capabilities), this.serializerSettings);

            startSessionRequest.AddJsonBody(json);

            IRestResponse startSessionResponse = this.client.Execute(startSessionRequest);

            if (startSessionResponse.ErrorException != null)
            {
                string errorMessage = $"An error occurred connecting to the Agent. Is your Agent running at {this.remoteAddress}?";

                Logger.Error(errorMessage);
                throw new AgentConnectException(errorMessage);
            }

            if ((int)startSessionResponse.StatusCode >= 400)
            {
                this.HandleSessionStartFailure(startSessionResponse);
                return;
            }

            this.StartSdkSession(startSessionResponse, capabilities);

            // Only retrieve the Agent version when it has not yet been set
            if (this.agentVersion == null)
            {
                this.agentVersion = this.GetAgentVersion();
            }
        }
예제 #16
0
        private void LogIn()
        {
            List <Person> persons;

            if (!File.Exists(usersFile))
            {
                MessageBox.Show("Oooops...Something was wrong!");
                return;
            }

            using (CustomJsonSerializer <List <Person> > serializer = new CustomJsonSerializer <List <Person> >())
            {
                persons = serializer.DeserializeFromFile(usersFile);
            }

            if (!persons.Any(p => p.AccountNumber == loginBox.Text && p.Password == passwordBox.Text))
            {
                MessageBox.Show("Incorrect login or password!");
                return;
            }


            currentPerson       = persons.Find(p => p.AccountNumber == loginBox.Text);
            loginBox.Enabled    = false;
            passwordBox.Enabled = false;

            signInButton.Enabled = false;
            signUpButton.Enabled = false;

            InitializeChainFromStore();
        }
예제 #17
0
        /// <summary>
        ///  Overriding the base method to handle reports at batches.
        ///  While there are reports in the queue - collect up to 10 reports and send them at batch.
        /// </summary>
        /// <exception>FailedReportException if cannot send report to the agent more than <see cref="MaxReportFailureAttempts"/> attempts.</exception>
        protected override void HandleReport()
        {
            // LinkedList to store the reports batch before sending them.
            LinkedList <Report> batchReports = new LinkedList <Report>();

            // Extract and remove up to 10 items or till queue is empty from queue - without blocking it.
            while (this.ReportItems.Count > 0 && batchReports.Count < this.maxBatchSize)
            {
                QueueItem item;

                // Get the first item in the queue without blocking it.
                bool taken = this.ReportItems.TryTake(out item);

                if (taken && item != null && item.Report != null)
                {
                    batchReports.AddLast(item.Report);
                }
            }

            if (batchReports.Count == 0)
            {
                return;
            }

            // Build REST request.
            RestRequest sendReportsBatchRequest = new RestRequest(Endpoints.REPORT_BATCH, Method.POST);

            sendReportsBatchRequest.RequestFormat = DataFormat.Json;
            string json = CustomJsonSerializer.ToJson(batchReports, this.serializerSettings);

            sendReportsBatchRequest.AddJsonBody(json);

            this.SendReport(sendReportsBatchRequest);
        }
예제 #18
0
        /// <summary>
        /// Invoke a synchronous service with the specified payload. The method call block until the method return.
        /// </summary>
        /// <typeparam name="TI">The payload type.</typeparam>
        /// <typeparam name="TO">The return type.</typeparam>
        /// <param name="serviceName">The name of the service, as configured in Argilla.Node.ServiceName.</param>
        /// <param name="payload">The payload used for invoke the service.</param>
        /// <returns></returns>
        public static TO Invoke <TI, TO>(string serviceName, TI payload)
        {
            TO outputValue = default;

            PayloadSync payloadSync = new PayloadSync()
            {
                Payload = payload
            };

            string json = CustomJsonSerializer.Serialize(payloadSync);

            Exception lastException = null;

            try
            {
                Endpoint endpoint = GetFreeEndpoint(serviceName);

                string jsonResult = HttpHelper.Post(endpoint.EndpointSync, json);

                outputValue = CustomJsonSerializer.Deserialize <TO>(jsonResult);

                lastException = null;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);

                ResolveResponse resolveResponse = Resolve(serviceName);

                foreach (Endpoint endpoint in resolveResponse.Endpoints)
                {
                    try
                    {
                        string jsonResult = HttpHelper.Post(endpoint.EndpointSync, json);

                        outputValue = CustomJsonSerializer.Deserialize <TO>(jsonResult);

                        lastException = null;

                        break;
                    }
                    catch (Exception e)
                    {
                        lastException = e;
                    }
                }
            }

            if (lastException != null)
            {
                logger.Error(lastException, lastException.Message);

                throw lastException;
            }

            logger.Debug(String.Format("Output value: {0}", outputValue));

            return(outputValue);
        }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AgentClient"/> class.
        /// </summary>
        /// <param name="remoteAddress">The remote address where the Agent is running.</param>
        /// <param name="token">The development token used to authenticate with the Agent.</param>
        /// <param name="capabilities">Requested driver options for the browser session.</param>
        /// <param name="reportSettings">Contains the project and job name to report to TestProject.</param>
        /// <param name="disableReports">Set to true to disable all reporting to TestProject, false otherwise.</param>
        /// <param name="compatibleVersion">Minimum Agent version that supports the requested feature. Can be used to check Agent compatibility.</param>
        private AgentClient(Uri remoteAddress, string token, DriverOptions capabilities, ReportSettings reportSettings, bool disableReports, Version compatibleVersion = null)
        {
            this.remoteAddress = this.InferRemoteAddress(remoteAddress);

            ReportSettings sessionReportSettings = disableReports ? null : this.InferReportSettings(reportSettings);

            this.reportSettings = sessionReportSettings;

            if (token != null)
            {
                this.token = token;
            }
            else if (Environment.GetEnvironmentVariable(this.tpDevToken) != null)
            {
                this.token = Environment.GetEnvironmentVariable(this.tpDevToken);
            }
            else
            {
                throw new InvalidTokenException("No token has been provided.");
            }

            this.client = new RestClient(this.remoteAddress);
            this.client.AddDefaultHeader("Authorization", this.token);

            this.serializerSettings = CustomJsonSerializer.Populate(new JsonSerializerSettings());

            // Check that Agent version supports the requested feature.
            if (compatibleVersion != null)
            {
                Logger.Trace($"Checking if the Agent version is {compatibleVersion} at minimum");

                agentVersion = this.GetAgentVersion();

                if (agentVersion.CompareTo(compatibleVersion) < 0)
                {
                    throw new AgentConnectException($"Current Agent version {agentVersion} does not support the requested feature," +
                                                    $" should be at least {compatibleVersion}");
                }
            }

            this.reportsQueue = new ReportsQueue(this.client);

            this.StartSession(sessionReportSettings, capabilities);

            // Verify the agent version supports local report generation
            this.VerifyIfLocalReportsIsSupported(reportSettings.ReportType);

            // Show local report path only when executing on local agents.
            if (this.client.BaseUrl.IsLocal())
            {
                Logger.Info($"Execution Report: {this.sessionResponse.LocalReport}");
            }

            if (!string.IsNullOrWhiteSpace(this.sessionResponse.LocalReportUrl))
            {
                Logger.Info($"Execution Report Link: {this.sessionResponse.LocalReportUrl}");
            }
        }
예제 #20
0
        public async Task <BaseObject> Get(PublicId id, PublicId viewerId)
        {
            var target = (BaseObject)Activator.CreateInstance(CustomJsonSerializer.TypeOf(id.Type));

            target.PublicId = id;
            await BindSqlContent(target);

            return(target);
        }
예제 #21
0
        /// <summary>
        /// Converts action parameters to a format understood by the Agent.
        /// </summary>
        /// <param name="actionProxy">The <see cref="ActionProxy"/> for which the parameters should be formatted.</param>
        /// <returns>A formatted set of action parameters.</returns>
        private Dictionary <string, object> FormatParameters(ActionProxy actionProxy)
        {
            string actionProxyAsJson = CustomJsonSerializer.ToJson(actionProxy, CustomJsonSerializer.Populate(new JsonSerializerSettings()));

            Dictionary <string, object> actionParameters = JsonConvert.DeserializeObject <Dictionary <string, object> >(actionProxyAsJson);

            actionParameters.Remove("proxyDescriptor");

            return(actionParameters);
        }
예제 #22
0
        public RegisterResponse Unregister(RegisterRequest registerRequest)
        {
            string resolverBaseAddress = ArgillaSettings.Current.Resolver.BaseAddress.EndsWith("/") ? ArgillaSettings.Current.Resolver.BaseAddress : ArgillaSettings.Current.Resolver.BaseAddress + "/";
            string resolverAddress     = resolverBaseAddress + "unregister";
            string json = CustomJsonSerializer.Serialize(registerRequest);

            logger.Debug(String.Format("Registration request: {0}", json));

            string result = HttpHelper.Post(resolverAddress, json);

            return(CustomJsonSerializer.Deserialize <RegisterResponse>(result));
        }
예제 #23
0
        /// <summary>
        /// Sends a <see cref="StepReport"/> to the Agent.
        /// </summary>
        /// <param name="stepReport">The payload object containing the step details to be reported.</param>
        public void ReportStep(StepReport stepReport)
        {
            RestRequest sendStepReportRequest = new RestRequest(Endpoints.REPORT_STEP, Method.POST);

            sendStepReportRequest.RequestFormat = DataFormat.Json;

            string json = CustomJsonSerializer.ToJson(stepReport, this.serializerSettings);

            sendStepReportRequest.AddJsonBody(json);

            this.reportsQueue.Submit(sendStepReportRequest, stepReport);
        }
예제 #24
0
        private void UpdateChainInfo()
        {
            var files = Directory.GetFiles(folderUsersData);

            foreach (var file in files)
            {
                using (CustomJsonSerializer <Chain> serializer = new CustomJsonSerializer <Chain>())
                {
                    serializer.SerializeToFile(Chain, file);
                }
            }
        }
예제 #25
0
        static JiraRestClient()
        {
            JsConfig.DateHandler = JsonDateHandler.ISO8601;

#if DEBUG
            Debug = true;
#endif

            CustomJsonSerializer.RegisterAllClasses();
            ServiceClientBase.HttpWebRequestFilter  = HttpWebRequestFilter;
            ServiceClientBase.HttpWebResponseFilter = HttpWebResponseFilter;
        }
 public BusBootstrapper(
     IWindsorContainer container,
     string connectionString,
     string prefix,
     IMessagesTracker messagesTracker)
 {
     this._container        = container;
     this._connectionString = connectionString;
     CustomSerializer       = new CustomJsonSerializer();
     Prefix          = prefix;
     MessagesTracker = messagesTracker;
 }
예제 #27
0
        /// <summary>
        /// Reports a WebDriver command to TestProject.
        /// </summary>
        /// <param name="driverCommandReport">Payload object containing command information and execution result.</param>
        public void ReportDriverCommand(DriverCommandReport driverCommandReport)
        {
            RestRequest sendDriverCommandRequest = new RestRequest(Endpoints.REPORT_COMMAND, Method.POST);

            sendDriverCommandRequest.RequestFormat = DataFormat.Json;

            string json = CustomJsonSerializer.ToJson(driverCommandReport, this.serializerSettings);

            sendDriverCommandRequest.AddJsonBody(json);

            this.reportsQueue.Submit(sendDriverCommandRequest, driverCommandReport);
        }
예제 #28
0
        private void InitializeChainFromStore()
        {
            var path = Path.Combine(folderUsersData, ChainFilePattern());

            using (CustomJsonSerializer <Chain> serializer = new CustomJsonSerializer <Chain>())
            {
                Chain = serializer.DeserializeFromFile(path) ?? new Chain();
                while (Chain.Blocks.Count(b => b.Index == 0) > 1)
                {
                    Chain.Blocks.Remove(Chain.Blocks.First(b => b.Index == 0));
                }
            }
        }
예제 #29
0
        private static IRestClient GetClient()
        {
            var client = new RestClient
            {
                BaseUrl = new Uri("https://min-api.cryptocompare.com/data/")
            };
            var settings = new JsonSerializerSettings();

            settings.Converters.Add(new NAConverter());
            var serializer = new CustomJsonSerializer(settings);

            client.AddHandler(serializer.ContentType, serializer);
            return(client);
        }
예제 #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportsQueueBatch"/> class.
        /// </summary>
        /// <param name="client">The <see cref="RestClient"/> HTTP client to send reports to the Agent.</param>
        public ReportsQueueBatch(RestClient client)
            : base(client)
        {
            this.serializerSettings = CustomJsonSerializer.Populate(new JsonSerializerSettings());

            // Override default converter of enum to string since agent is case sensitive.
            this.serializerSettings.Converters.Clear();
            this.serializerSettings.Converters.Add(new StringEnumConverter());

            // Try to get maximum report batch size from env variable.
            string tpMaxBatchSizeEnvVal = Environment.GetEnvironmentVariable(TpMaxBatchSizeVariableName);

            this.maxBatchSize = (tpMaxBatchSizeEnvVal != null) ? int.Parse(tpMaxBatchSizeEnvVal) : MaxReportsBatchSize;
        }
예제 #31
0
 /// <summary>
 /// Deserializes from JSON converting all JARRAYS to associative
 /// arrays...
 /// </summary>
 /// <typeparam name="TType"></typeparam>
 /// <param name="value"></param>
 /// <returns></returns>
 public static object DeserializeObject(string value, Type targetType)
 {
     using (var strReader = new StringReader(value))
     {
         using (var jsonReader = new CustomJsonTextReader(strReader))
         {
             var resolver   = new CustomContractResolver();
             var serializer = new CustomJsonSerializer {
                 ContractResolver = resolver, ObjectCreationHandling = ObjectCreationHandling.Replace
             };
             object unserialized = serializer.Deserialize(jsonReader, targetType);
             return(unserialized);
         }
     }
 }
예제 #32
0
        public ActionResult Resolve([FromBody] ResolveRequest resolveRequest)
        {
            securityManager.Verify(new SecurityAssertion()
            {
                Payload = resolveRequest
            });

            logger.Info("Resolve: " + CustomJsonSerializer.Serialize(resolveRequest));

            ResolveResponse resolveResponse = new ResolveResponse();

            resolveResponse.Endpoints = storageManager.Resolve(resolveRequest);

            return(new JsonResult(resolveResponse));
        }
        public void SerializeTimeSpan()
        {
            // Arrange
            var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters };
            var value = new TimeSpan(400, 13, 3, 2,10);
            var model = new TimeSpanModel
                {
                    Foo = value
                };

            // Act
            var result = serializer.Serialize(model.Foo);

            // Assert
            Assert.AreEqual("400.13:03:02.0100000", result.Replace("\"", ""));
        }
        public void DeserializeGuidWithDefaultJsonConverters()
        {
            //Arrage
            var myGuid = Guid.NewGuid();
            var foo = new EnumerableModel { Guids = new List<Guid> { myGuid } };

            // Act
            var customSerializer = new CustomJsonSerializer{JsonConverters = GraphClient.DefaultJsonConverters};
            var testStr = customSerializer.Serialize(foo);

            var customDeserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters);
            var result = customDeserializer.Deserialize<EnumerableModel>(testStr);

            // Assert
            Assert.AreEqual(myGuid, result.Guids.First());
        }
        public void JsonSerializerShouldSerializeTimeZoneInfo()
        {
            // Arrange
            var serializer = new CustomJsonSerializer
                {
                    JsonConverters = GraphClient.DefaultJsonConverters
                };

            const string ausEasternStandardTime = "AUS Eastern Standard Time";
            var timeZoneData = TimeZoneInfo.FindSystemTimeZoneById(ausEasternStandardTime);

            // Act
            var result = serializer.Serialize(timeZoneData);

            // Assert
            Assert.AreEqual(ausEasternStandardTime, result.Replace("\"",""));
        }
        public void JsonSerializerShouldSerializeAllProperties()
        {
            // Arrange
            var testNode = new TestNode { Foo = "foo", Bar = "bar" };
            var serializer = new CustomJsonSerializer
                {
                    NullHandling = NullValueHandling.Ignore,
                    JsonConverters = GraphClient.DefaultJsonConverters
                };

            // Act
            var result = serializer.Serialize(testNode);
            const string expectedValue = "{\r\n  \"Foo\": \"foo\",\r\n  \"Bar\": \"bar\"\r\n}";

            // Assert
            Assert.AreEqual(expectedValue, result);
        }
        public void ShouldSerializeDateTimeOffsetInCorrectStringFormat()
        {
            //Arrange
            var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters };
            var model = new DateOffsetModel
                {
                    DateTime = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00"),
                    DateTimeNullable = DateTimeOffset.Parse("2012-08-31T00:11:00.3642578+10:00")
                };

            //Act
            var actual = serializer.Serialize(model);

            //Assert
            const string expected =
                "{\r\n  \"DateTime\": \"2012-08-31T00:11:00.3642578+10:00\",\r\n  \"DateTimeNullable\": \"2012-08-31T00:11:00.3642578+10:00\"\r\n}";
            Assert.AreEqual(expected, actual);
        }
        public void ShouldSerializeDateTimeInCorrectStringFormat(string dateTimeStr)
        {
            //Arrange
            var serializer = new CustomJsonSerializer { JsonConverters = GraphClient.DefaultJsonConverters };
            var model = new DateModel
            {
                DateTime = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal),
                DateTimeNullable = DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal)
            };

            //Act
            var actual = serializer.Serialize(model);

            //Assert
            var expected =
                "{\r\n  \"DateTime\": \"" + dateTimeStr + "\",\r\n  \"DateTimeNullable\": \"" + dateTimeStr + "\"\r\n}";
            Assert.AreEqual(expected, actual);
        }
        public void JsonSerializerShouldSerializeEnumToString()
        {
            // Arrange
            var testNode = new TestNodeWithEnum { Status = TestEnum.Value1 };
            var serializer = new CustomJsonSerializer
                {
                    NullHandling = NullValueHandling.Ignore,
                    JsonConverters = new []{new EnumValueConverter()}
                };

            // Act
            var result = serializer.Serialize(testNode);

            const string expectedValue = "{\r\n  \"Status\": \"Value1\"\r\n}";

            // Assert
            Assert.AreEqual(expectedValue, result);
        }
        public void CamelCaseTest()
        {
            //setup
            var model = new CamelModel
            {
                FirstName = "first",
                DateOfBirth = new DateTime(1980, 4, 1),
                Gender = Gender.Male,
                S = "short property"
            };
            var serializer = new CustomJsonSerializer();
            serializer.JsonContractResolver = new CamelCasePropertyNamesContractResolver();
            var st = serializer.Serialize(model);

            //act
            var deserializer = new CustomJsonDeserializer(GraphClient.DefaultJsonConverters, resolver: (DefaultContractResolver)serializer.JsonContractResolver);
            var output = deserializer.Deserialize<CamelModel>(st);

            //assert
            AssertCamelModel(model, output);
        }
        public void ShouldSerializeBuiltInTypeThatHasTypeConverterUsingTypeConverterBasedJsonConverter()
        {
            //Arrange
            var serializer = new CustomJsonSerializer
            {
                JsonConverters = new[] { new TypeConverterBasedJsonConverter() }
            };

            var model = new TestModelC
            {
                MyPoint = new System.Drawing.Point(100, 200)
            };

            //Act
            var rawResult = serializer.Serialize(model);

            //Assert
            const string expectedRawOutput =
            "{\r\n  \"MyPoint\": \"100, 200\"\r\n}";

            Assert.AreEqual(expectedRawOutput, rawResult);
        }
        public void ShouldSerializeNullableInt32ToJsonNumberUsingDefaultJsonConverters()
        {
            // Arrange
            var testNode = new NodeWithBuiltInTypes { Foo = 123 };
            var serializer = new CustomJsonSerializer
            {
                NullHandling = NullValueHandling.Ignore,
                JsonConverters = GraphClient.DefaultJsonConverters
            };

            // Act
            var result = serializer.Serialize(testNode);
            const string expectedValue = "{\r\n  \"Foo\": 123\r\n}";

            // Assert
            Assert.AreEqual(expectedValue, result);
        }
        /// <summary>
        /// Most of the work happens here for generating the hook up script code
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            // MS AJAX aware script management
            ClientScriptProxy scriptProxy = ClientScriptProxy.Current;

            // Register resources
            RegisterResources(scriptProxy);

            string dateFormat = DateFormat;

            if (string.IsNullOrEmpty(dateFormat) || dateFormat == "Auto")
            {
                // Try to create a data format string from culture settings
                // this code will fail if culture can't be mapped on server hence the empty try/catch
                try
                {
                    dateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
                }
                catch { }
            }

            dateFormat = dateFormat.ToLower().Replace("yyyy", "yy");

            // Capture and map the various option parameters
            StringBuilder sbOptions = new StringBuilder(512);
            sbOptions.Append("{");

            string onSelect = OnClientSelect;

            if (DisplayMode == DatePickerDisplayModes.Button)
                sbOptions.Append("showOn: 'button',");
            else if (DisplayMode == DatePickerDisplayModes.ImageButton)
            {
                string img = ButtonImage;
                if (img == "WebResource")
                    img = scriptProxy.GetWebResourceUrl(this, typeof(ControlResources), ControlResources.CALENDAR_ICON_RESOURCE);
                else
                    img = ResolveUrl(ButtonImage);

                sbOptions.Append("showOn: 'button', buttonImageOnly: true, buttonImage: '" + img + "',buttonText: 'Select date',");
            }
            else if (DisplayMode == DatePickerDisplayModes.Inline)
            {
                // need to store selection in the page somehow for inline since it's
                // not tied to a textbox
                scriptProxy.RegisterHiddenField(this, ClientID, Text);
                onSelect = ClientID + "OnSelect";
            }

            if (!string.IsNullOrEmpty(onSelect))
                sbOptions.Append("onSelect: " + onSelect + ",");

            if (DisplayMode != DatePickerDisplayModes.Inline)
            {
                if (!string.IsNullOrEmpty(OnClientBeforeShow))
                    sbOptions.Append("beforeShow: function(y,z) { $('#ui-datepicker-div').maxZIndex(); " +
                                     OnClientBeforeShow + "(y,z); },");
                else
                    sbOptions.Append("beforeShow: function() { $('#ui-datepicker-div').maxZIndex(); },");

            }

            if (MaxDate.HasValue)
                sbOptions.Append("maxDate: " + UrlUtils.EncodeJsDate(MaxDate.Value) + ",");

            if (MinDate.HasValue)
                sbOptions.Append("minDate: " + UrlUtils.EncodeJsDate(MinDate.Value) + ",");

            if (ShowButtonPanel)
                sbOptions.Append("showButtonPanel: true,");

            sbOptions.Append("dateFormat: '" + dateFormat + "'}");


            // Write out initilization code for calendar
            StringBuilder sbStartupScript = new StringBuilder(400);
            sbStartupScript.AppendLine("$( function() {");


            if (DisplayMode != DatePickerDisplayModes.Inline)
            {
                scriptProxy.RegisterClientScriptBlock(Page,
                                                      typeof(ControlResources),
                                                      "__attachDatePickerInputKeys",
                                                      AttachDatePickerKeysScript, true);

                sbStartupScript.AppendFormat("var cal = jQuery('#{0}').datepicker({1}).attachDatepickerInputKeys();\r\n",
                                             ClientID, sbOptions);
            }
            else
            {
                sbStartupScript.AppendLine("var cal = jQuery('#" + ClientID + "Div').datepicker(" + sbOptions.ToString() + ")");

                if (SelectedDate.HasValue && SelectedDate.Value > new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                {
                    CustomJsonSerializer ser = new CustomJsonSerializer();
                    ser.DateSerializationMode = JsonDateEncodingModes.NewDateExpression;
                    string jsDate = ser.Serialize(SelectedDate);

                    sbStartupScript.AppendLine("cal.datepicker('setDate'," + jsDate + ");");
                }
                else
                    sbStartupScript.AppendLine("cal.datepicker('setDate',new Date());");

                // Assign value to hidden form var on selection
                scriptProxy.RegisterStartupScript(this, typeof(ControlResources), UniqueID + "OnSelect",
                    "function  " + ClientID + "OnSelect(dateStr) {\r\n" +
                    ((!string.IsNullOrEmpty(OnClientSelect)) ? OnClientSelect + "(dateStr);\r\n" : "") +
                    "jQuery('#" + ClientID + "')[0].value = dateStr;\r\n}\r\n", true);
            }

            sbStartupScript.AppendLine("} );");
            scriptProxy.RegisterStartupScript(Page, typeof(ControlResources), "_cal" + UniqueID,
                 sbStartupScript.ToString(), true);
        }
        public void ShouldSerializeCustomValueWithCustomJsonConverter()
        {
            //Arrange
            var serializer = new CustomJsonSerializer
                {
                    JsonConverters = new []{new TestValueAConverter()}
                };

            var model = new TestModelA
                {
                    CustomValue = new TestValueA
                        {
                            A = 'o',
                            B = 'p'
                        }
                };

            //Act
            var rawResult = serializer.Serialize(model);

            //Assert
            const string expectedRawOutput =
            "{\r\n  \"CustomValue\": \"op\"\r\n}";

            Assert.AreEqual(expectedRawOutput, rawResult);
        }
 public void SetUp()
 {
     _sut = new CustomJsonSerializer();
 }
        public void JsonSerializerWithEnumConverterShouldConvertEnumToStringValues()
        {
            // Arrange
            var testClass = new TestFoo
                {
                    Gender = Gender.Female,
                    GenderNullable = Gender.Male
                };

            var serializer = new CustomJsonSerializer
                {
                    JsonConverters = new JsonConverter[]
                    {
                        new EnumValueConverter(),
                        new NullableEnumValueConverter()
                    }
                };

            const string expected = "{\r\n  \"Gender\": \"Female\",\r\n  \"GenderNullable\": \"Male\"\r\n}";

            // Act
            var result = serializer.Serialize(testClass);

            // Assert
            Assert.AreEqual(expected, result);
        }
        public void ShouldSerializeNullableBoolToJsonBooleanUsingDefaultJsonConverters()
        {
            // Arrange
            var testNode = new NodeWithBuiltInTypes { Bar = true };
            var serializer = new CustomJsonSerializer
            {
                NullHandling = NullValueHandling.Ignore,
                JsonConverters = GraphClient.DefaultJsonConverters
            };

            // Act
            var result = serializer.Serialize(testNode);
            const string expectedValue = "{\r\n  \"Bar\": true\r\n}";

            // Assert
            Assert.AreEqual(expectedValue, result);
        }