public async Task SerializeToStreamAsync_SerializesModuleSourceTypeStreamInvocationRequestsAsync() { // Arrange const ModuleSourceType dummyModuleSourceType = ModuleSourceType.Stream; const string dummyModuleSource = "dummyModuleSource"; var dummyModuleStreamSource = new MemoryStream(Encoding.UTF8.GetBytes(dummyModuleSource)); var dummyInvocationRequest = new InvocationRequest(dummyModuleSourceType, moduleStreamSource: dummyModuleStreamSource); var dummyJsonService = new JsonService(); using (ExposedInvocationContent testSubject = CreateInvocationContent(dummyJsonService, dummyInvocationRequest)) { var resultMemoryStream = new MemoryStream(); // Act await testSubject.ExposedSerializeToStreamAsync(resultMemoryStream, null).ConfigureAwait(false); // Assert resultMemoryStream.Position = 0; using (var resultReader = new StreamReader(resultMemoryStream)) { string result = resultReader.ReadToEnd(); Assert.Equal($"{{\"moduleSourceType\":{(int)dummyModuleSourceType}}}{Encoding.UTF8.GetString(InvocationContent.BOUNDARY_BYTES)}{dummyModuleSource}", result); } } }
protected override void PerformOfflineAction(OfflineDatabase offlineDatabase, IOfflineDefinitionLoader offlineDefinitions) { Response = new FishingCatchResponse(); Reward fishingReward = offlineDefinitions.GetFishingReward(FishingCatchRequest.winningRewardName); offlineDefinitions.AddReward(fishingReward, Response); JsonService jsonService = Service.Get <JsonService>(); Dictionary <string, RewardJsonReader> dictionary = new Dictionary <string, RewardJsonReader>(); dictionary.Add(client.PlayerSessionId.ToString(), jsonService.Deserialize <RewardJsonReader>(jsonService.Serialize(RewardJsonWritter.FromReward(fishingReward)))); Response.rewards = new SignedResponse <RewardedUserCollectionJsonHelper> { Data = new RewardedUserCollectionJsonHelper { rewards = dictionary, source = RewardSource.MINI_GAME, sourceId = "fishing" } }; if (Response.wsEvents == null) { Response.wsEvents = new List <SignedResponse <WebServiceEvent> >(); } Response.wsEvents.Add(new SignedResponse <WebServiceEvent> { Data = new WebServiceEvent { type = 1, details = new JsonData(FishingCatchRequest.winningRewardName) } }); }
public static void ExportData(string userName) { JsonService jsonService = Service.Get <JsonService>(); string token = ((!string.IsNullOrEmpty(userName)) ? RegistrationProfile.Id(userName) : Service.Get <OfflineDatabase>().AccessToken); OfflineDataExport offlineDataExport = default(OfflineDataExport); offlineDataExport.BreadCrumbs = OfflineDatabase.Read <BreadcrumbCollection>(token); offlineDataExport.ClaimableRewards = OfflineDatabase.Read <ClaimableRewardData>(token); offlineDataExport.ConsumableInventory = OfflineDatabase.Read <ConsumableInventory>(token); offlineDataExport.Equipment = OfflineDatabase.Read <CustomEquipmentCollection>(token); offlineDataExport.DailySpinData = OfflineDatabase.Read <DailySpinData>(token); offlineDataExport.IglooData = OfflineDatabase.Read <IglooEntity>(token); offlineDataExport.RoomRewards = OfflineDatabase.Read <InRoomRewards>(token); offlineDataExport.Assets = OfflineDatabase.Read <PlayerAssets>(token); offlineDataExport.Outfit = OfflineDatabase.Read <PlayerOutfitDetails>(token); offlineDataExport.Profile = OfflineDatabase.Read <Profile>(token); offlineDataExport.QuestStates = OfflineDatabase.Read <QuestStates>(token); offlineDataExport.RegistrationProfile = OfflineDatabase.Read <RegistrationProfile>(token); offlineDataExport.IglooLayouts = OfflineDatabase.Read <SceneLayoutEntity>(token); offlineDataExport.Tube = OfflineDatabase.Read <TubeData>(token); offlineDataExport.Tutorials = OfflineDatabase.Read <TutorialData>(token); OfflineDataExport objectToSerialize = offlineDataExport; objectToSerialize.UserName = objectToSerialize.RegistrationProfile.userName; TextEditor textEditor = new TextEditor(); textEditor.text = jsonService.Serialize(objectToSerialize); textEditor.SelectAll(); textEditor.Copy(); }
public void JsonService_ShouldSupport_Escaping_URLs() { var json = JsonService.For("http://marketplace.envato.com/api/v2/") .Get("/new-files-from-user:kayub,codecanyon.json"); // If it didn't work, it'd throw an exception }
public void JsonService_GET_ShouldReturn_Decompressed_GZip_Response() { dynamic x = JsonService.GetFrom("http://api.stackoverflow.com/1.1/users/109458/answers?pagesize=5&sort=creation"); Assert.IsNotNull(x); Assert.IsNotNull(x.total); }
public JsonService InitJsonService() { var service = new JsonService(new IoService()); service.Init(@"../../testdata/config_test.json"); return(service); }
public void CreateDefaultComponents() { Guid tmp = Guid.NewGuid(); JsonService.SaveObjectToFile(new DocumentItem(tmp) { Name = "SourceCode" } , Path.Combine(Constants.PreparedComponentsFolder, $"{tmp}.linaq")); tmp = Guid.NewGuid(); JsonService.SaveObjectToFile(new DocumentItem(tmp) { Name = "Header", hasEndTag = true } , Path.Combine(Constants.PreparedComponentsFolder, $"{tmp}.linaq")); tmp = Guid.NewGuid(); JsonService.SaveObjectToFile(new DocumentItem(tmp) { Name = "Footer", hasEndTag = true } , Path.Combine(Constants.PreparedComponentsFolder, $"{tmp}.linaq")); }
public void returns_users_when_integrated() { // substitute in IoC in real world scenario IJsonService jsonService = new JsonService(new HttpClient()); jsonService.GetUsers().Count().ShouldBeGreaterThan(0); }
private void WriteLog( bool result, string question, string answers, ResultStatus closedQuestionsResultStatus, ResultStatus openQuestionsResultStatus, Dictionary <QuestionTypeEnum, Dictionary <string, AnswerRegister> > answersRegister) { if (AppSettings.Learning.SaveDebugLogs) { JsonSerializerOptions options = JsonService.GetJsonSerializerOptions(true, null); string logData = JsonSerializer.Serialize( new { Result = result, Question = question, Answers = answers, ClosedQuestionsProgress = closedQuestionsResultStatus.ToString(), OpenQuestionsProgress = openQuestionsResultStatus.ToString(), AnswersRegister = answersRegister }, options ); Logger.LogDebug(logData); } }
public static Dictionary <string, ThietBiModel> GetDsThietBi(string nhaMay_name) { Dictionary <string, ThietBiModel> dsThietBiGiamSat = new Dictionary <string, ThietBiModel>(); try { Dictionary <string, NhaMayModel> dicNhaMay = JsonService.GetDicNhaMay(); foreach (var nhaMay_item in dicNhaMay) { if (nhaMay_item.Value.Name == nhaMay_name) { dsThietBiGiamSat = nhaMay_item.Value.dsThietBi; } } /*Dictionary<string, ThietBiTCPIP> deviceIP = jsonObj.ToObject<Dictionary<string, ThietBiTCPIP>>(); * foreach (var deviceIPUnit in deviceIP) * { * if (deviceIPUnit.Value.Protocol == "Modbus TCP/IP" || deviceIPUnit.Value.Protocol == "Siemens S7-1200") * { * dsThietBiGiamSat.Add(deviceIPUnit.Key, deviceIPUnit.Value); * } * } * Dictionary<string, ThietBiCOM> deviceCom = jsonObj.ToObject<Dictionary<string, ThietBiCOM>>(); * foreach (var deviceComUnit in deviceCom) * { * if (deviceComUnit.Value.Protocol == "Serial Port") * { * dsThietBiGiamSat.Add(deviceComUnit.Key, deviceComUnit.Value); * } * }*/ } catch { } return(dsThietBiGiamSat); }
public async Task InvokeAsync( HttpContext context, ISchemaStorage schemaStorage, JsonService jsonService) { ContentSchema schema; if (context.GetRouteValue("id") is string) { Guid id = Guid.Parse((string)context.GetRouteValue("id")); schema = await schemaStorage.GetContentSchemaAsync(id); } else { string name = (string)context.GetRouteValue("name"); schema = await schemaStorage.GetContentSchemaAsync(name); } RestContentSchema restSchema = schema.ToRest(); string json = jsonService.Serialize(restSchema); await context.Response.WriteAsync(json); }
public static SlaveModel GetDsSlave(string nhamay_name, string thietbi_name, string slave_name) { try { Dictionary <string, NhaMayModel> dicNhaMay = JsonService.GetDicNhaMay(); if (dicNhaMay.ContainsKey(nhamay_name)) { NhaMayModel nhaMayModel = dicNhaMay[nhamay_name]; var nhamay_item = nhaMayModel.dsThietBi; foreach (var thietBi_item in nhamay_item) { if (thietBi_item.Value.Name == thietbi_name) { foreach (var slave_item in thietBi_item.Value.dsSlave) { if (slave_item.Value.Name == slave_name) { return(slave_item.Value); } } } } } } catch { return(null); } return(null); }
//public static void Main(string[] args) //{ // BuildWebHost(args).Run(); //} //public static IWebHost BuildWebHost(string[] args) => // WebHost.CreateDefaultBuilder(args) // .UseStartup<Startup>() // .Build(); public static void Main(string[] args) { XmlDocument log4netConfig = new XmlDocument(); log4netConfig.Load(File.OpenRead("log4net.config")); var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]); var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService <ApplicationDbContext>(); //DbInitializer.Initialize( context ); JsonService jsonService = new JsonService(context); jsonService.UpdatePlayerRoster(); jsonService.UpdateDailyStats(); jsonService.LoadCumulativePlayerStats(); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } host.Run(); } }
public void should_stub_provider() { JsonService.Stub(new JsonProviderStub()); JsonService .Serialize(new object()) .ShouldEqual("Test"); }
private async void SaveChanges(object sender, EventArgs args) { try { ValidateSavedModel(); var result = await ApiService.Account.Update(Model); if (result.IsSuccess) { Alert.Send("Dades desades"); string modelString = JsonService.Serialize(Model); Settings.Save("user", modelString); } else { Alert.Send("Error al desar les dades"); } } catch (Exception e) { Debug.WriteLine(e); Alert.Send("Error al desar les dades"); } }
public HttpResponseMessage Get(HttpRequestMessage request) { IEnumerable <KeyValuePair <string, string> > keyValuePairs = GetKeyValuePairs(request); string json = new JsonService(keyValuePairs).Get(); return(CreateHttpResponseMessage(json, request)); }
private Entry MakeConfigEntry(JsonService service) { var config = service.SyncConfig; var configEntry = config.Entries[0]; return(configEntry); }
public SendMessage() { if (File.Exists(Environment.CurrentDirectory + "//credentials.json")) { userData = JsonService.DeserializeJsonFile(Environment.CurrentDirectory + "//credentials.json"); } }
public static async Task <Session> GetSession(long accountServerId) { var db = ConnectionMultiplexerHolder.Instance.Redis.GetDatabase(); var redisValue = await db.StringGetAsync(SessionKey(accountServerId)); return(redisValue.HasValue ? JsonService.DeserializeFromDB <Session>(redisValue) : null); }
public async Task InvokeAsync( HttpContext context, IContentStorage contentStore, ISchemaStorage schemaStorage, JsonService jsonService) { string schema = (string)context.GetRouteValue("schema"); QueryParameters queryParameters = await jsonService.Deserialize <QueryParameters>(context.Request.Body); ContentSchema schemaModel = await schemaStorage.GetContentSchemaAsync(schema); QueryResult <ContentItem> contentItems = await contentStore.Query(schema, queryParameters); foreach (ContentItem contentItem in contentItems.Items) { contentItem.ApplySchema(schemaModel); } QueryResult <RestContentItem> resultQuery = new QueryResult <RestContentItem>() { Offset = contentItems.Offset, Count = contentItems.Count, TotalCount = contentItems.TotalCount, Items = contentItems.Items.Select(x => x.ToRest()).ToList() }; string json = jsonService.Serialize(resultQuery); await context.Response.WriteAsync(json); }
static void Main(string[] args) { //JsonService.WriteToFile(@"d:\files\persons.json", new Person("Andreas","Saarenpää",30,"Lindesberg")); JsonService.WriteToFileCorrect(@"d:\files\persons.json", new Person("Andreas", "Saarenpää", 30, "Lindesberg")); JsonService.ReadFromFile(@"d:\files\persons.json"); }
//service Model == APi MOODEL public void UpdateBlog(Blog blog) //APIMODEL { var str = JsonService.SerializeObject(blog); //APIMODEL -> MODEL RESULT ->APIMODEL UnitOfWork.DbContext.Update(blog); }
public void JsonService_GET_ShouldReturn_Value_ForTwitterArray() { dynamic[] tweets = JsonService.GetFrom("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=kamranayub"); Assert.IsNotNull(tweets); Assert.IsTrue(tweets.Length > 1); }
public ActionResult GitHubBasicList() { // Get Kamran's repos var repositories = JsonService.GetFrom("https://github.com/api/v2/json/repos/show/kamranayub"); return(View(repositories)); }
public static void Main(string[] args) { if (args != null && args.Length != 1) { throw new ArgumentOutOfRangeException("Provide config file name!"); } string configFilename = args[0]; // get configuration... var service = new JsonService(new IoService()); service.Init(configFilename); var config = service.SyncConfig; // git pull... var gitService = new GitService(); foreach (var entry in config.Entries) { var response = gitService.Pull(entry); Console.WriteLine("response was: " + response.Msg); } }
public ActionResult GitHubUpdateProfile(string username, string token) { if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(username)) { ViewBag.Error = "Enter a user and API token in the URL (e.g. ?username=your_username&token=your_api_token) to test."; return(View()); } var gitParams = new Dictionary <string, string>(); gitParams["login"] = username; gitParams["token"] = token; gitParams["values[blog]"] = "http://github.com/" + username; // Get old blog var oldBlog = JsonService.GetFrom("https://github.com/api/v2/json/user/show/" + username).user.blog; // Update to new blog var jsonUpdate = JsonService.PostTo("https://github.com/api/v2/json/user/show/" + username, gitParams); // Revert gitParams["values[blog]"] = oldBlog.ToString(); var jsonReverted = JsonService.PostTo("https://github.com/api/v2/json/user/show/" + username, gitParams); return(View(new[] { jsonUpdate, jsonReverted })); }
public Database(IServiceProvider provider, string file) : base(provider) { _json = provider.GetRequiredService <JsonService>(); _file = file; LoadDatabase(); }
public ActionResult EnvatoBasicList() { // Get Kamran's Code Canyon items var files = JsonService.GetFrom("http://marketplace.envato.com/api/v2/new-files-from-user:kayub,codecanyon.json"); return(View(files)); }
public async Task User_Should_Be_Logged_In() { var auth = JObject.Parse(@"{ 'email': '*****@*****.**', 'password': '******' }"); var httpResponse = await _client.PostAsJsonAsync("Accounts/Login", auth); Console.WriteLine(httpResponse.Content.ReadAsStringAsync()); Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); var user = await httpResponse.Content.ReadAsAsync <ApplicationUser>(); Assert.NotNull(user); Assert.NotNull(user.Email); Assert.NotEmpty(user.Email); Assert.NotNull(user.UserName); Assert.NotEmpty(user.UserName); Assert.NotNull(user.Name); Assert.NotEmpty(user.Name); Console.WriteLine(JsonService.Serialize(user)); Assert.NotNull(user.Token); Assert.NotEmpty(user.Token); }
public void DeserializeMethodShouldReturnRightResultObject() { //Arrange var jsonToDeserialize = "{\"sources\":[{\"id\":\"dcfe1db6-2484-42c2-9d9e-a77a28a5078d\",\"name\":\"BKAL33+KBT T\",\"description\":\"Plato Chemicals Test\",\"sourceBusinessUnits\":[]}],\"operations\":[{\"id\":\"d2760435-9d0b-4b69-adce-09017f2840c6\",\"name\":\"Unload into warehouse\",\"description\":\"Unloading goods into the warehouse\",\"icon\":null,\"tags\":[\"string\"]}]}"; var jsonService = new JsonService(); var flowFilter = new FlowFilter(new List <FlowSource> { new FlowSource("BKAL33+KBT T") }, new List <FlowOperation> { new FlowOperation("Unload into warehouse") }, new List <FlowSite>(), new List <FlowOperationalDepartment>(), new List <FlowTypePlanning>(), new List <FlowCustomer>(), new List <FlowProductionSite>(), new List <FlowTransportType>(), "No"); //Act var result = jsonService.Deserialize <FlowFilter>(jsonToDeserialize); //Assert result.Sources.Should().BeEquivalentTo(flowFilter.Sources); result.Operations.Should().BeEquivalentTo(flowFilter.Operations); }
public void Read_Json_From_ValidFile_Returns_Valid_SyncConfig () { var service = new JsonService (new IoService ()); String fileName = @"../../testdata/config_test.json"; service.Init (fileName); Assert.IsNotNull (service.SyncConfig); Assert.AreEqual ("config_test.json", service.SyncConfig.Name); Assert.AreEqual (DefaultGitAction.Push, service.SyncConfig.Entries [0].DefaultGitAction); }
public void Read_Json_From_ValidFile_Returns_Valid_Entries () { var service = new JsonService (new IoService ()); String fileName = @"../../testdata/config_test.json"; service.Init (fileName); Assert.IsNotNull (service.SyncConfig); Assert.That (service.SyncConfig.Entries.Count > 0); foreach (var entry in service.SyncConfig.Entries) { Assert.That (entry.Id is System.Guid); Assert.IsNotNullOrEmpty (entry.Local); Assert.IsNotNullOrEmpty (entry.Name); Assert.IsNotNullOrEmpty (entry.Remote); } }
public string Invoke(JsonService service, IRequest request) { List<object> parameters = new List<object>(); foreach (var parameter in Action.GetParameters()) { string val = request.Parameters[parameter.Name]; if (parameter.ParameterType == typeof(string)) { parameters.Add(val); } else if (parameter.ParameterType == typeof(Nullable<Guid>)) { Guid? guid = null; try { guid = new Guid(val); } catch { } parameters.Add(guid); } } var obj = Action.Invoke(service, parameters.ToArray()); return Newtonsoft.Json.JsonConvert.SerializeObject(obj); }
private Entry MakeConfigEntry(JsonService service) { var config = service.SyncConfig; var configEntry = config.Entries[0]; return configEntry; }
public JsonResult Logs() { _logsService = new JsonService<ExceptionLog>(Server.MapPath("~/Logs/logs.json")); return Json(_logsService.GetCollection()); }
public void SetUp() { json = new JsonService(); }
public JsonService InitJsonService () { var service = new JsonService (new IoService ()); service.Init (@"../../testdata/config_test.json"); return service; }
public LoggingService(IEmailService emailService, string path = null) { _emailService = emailService; _loggingService = new JsonService<ExceptionLog>(path); }
public void SetUp() { json = new JsonService(); wait = new ManualResetEvent(false); }