/// <summary> /// Commits the changes to file /// </summary> public void Commit() { string jsonToSave; try { jsonToSave = JsonSerialiser.Serialise(_items); } catch (Exception e) { throw new QuickSaveException("Json serialisation failed", e); } string encryptedJson; try { encryptedJson = Cryptography.Encrypt(jsonToSave, _settings.SecurityMode, _settings.Password); } catch (Exception e) { throw new QuickSaveException("Encryption failed", e); } if (!FileAccess.SaveString(_root, false, encryptedJson)) { throw new QuickSaveException("Failed to write to file"); } }
private void Open() { string fileJson = FileAccess.LoadString(_root, false); if (string.IsNullOrEmpty(fileJson)) { _items = new Dictionary <string, object>(); return; } string decryptedJson; try { decryptedJson = Cryptography.Decrypt(fileJson, _settings.SecurityMode, _settings.Password); } catch (Exception e) { throw new QuickSaveException("Decryption failed", e); } try { _items = JsonSerialiser.Deserialise <Dictionary <string, object> >(decryptedJson) ?? new Dictionary <string, object>(); } catch (Exception e) { throw new QuickSaveException("Failed to deserialise json", e); } }
/// <summary> /// Attempts to load an object from a root under the specified key using the specified settings /// </summary> /// <typeparam name="T">The type of object to load</typeparam> /// <param name="root">The root this object was saved under</param> /// <param name="key">The key this object was saved under</param> /// <param name="settings">Settings</param> /// <param name="result">The object that was loaded</param> /// <returns>Was the load successful</returns> public static bool TryLoad <T>(string root, string key, QuickSaveSettings settings, out T result) { result = default(T); try { string fileJson = FileAccess.LoadString(root, false); if (string.IsNullOrEmpty(fileJson)) { return(false); } string decryptedJson = Cryptography.Decrypt(fileJson, settings.SecurityMode, settings.Password); Dictionary <string, object> items = JsonSerialiser.Deserialise <Dictionary <string, object> >(decryptedJson) ?? new Dictionary <string, object>(); if (!items.ContainsKey(key)) { return(false); } string propertyJson = JsonSerialiser.Serialise(items[key]); result = JsonSerialiser.Deserialise <T>(propertyJson); return(true); } catch { return(false); } }
public async Task Setup() { base.SharedSetup(); _input = new GetTransactionsRequestV1 { Filter = new FileStoreFilterV1 { TimestampRangeStart = DateTimeOffset.MinValue, TimestampRangeEnd = DateTimeOffset.MaxValue } }; Share1.Setup(s => s.ListAsync(It.IsAny <IPathFilter>(), It.IsAny <CancellationToken>())) .Returns(_paths1 = GetSomePaths(1)); Share2.Setup(s => s.ListAsync(It.IsAny <IPathFilter>(), It.IsAny <CancellationToken>())) .Returns(GetNoPaths()); var fileId = Guid.NewGuid(); JsonSerialiser.Setup(s => s.Deserialize <TransactionAdapationEventMetadataFile>(It.IsAny <MemoryStream>(), It.IsAny <Encoding>())) .ReturnsAsync(_expectedMetadata = new TransactionAdapationEventMetadataFile { Events = new [] { TransactionAdaptionEventModel.NewDocumentEvent(fileId) } }); _output = await ClassInTest.GetTransactionsAsync(_input, CancellationToken.None); }
public async Task Bad_FileId_Is_FilteredOut_Filter() { var badEvent = TransactionAdaptionEventModel.NewDocumentEvent(); badEvent.Properties["FileId"] = "Rgsjrjgkisjghr"; JsonSerialiser.Setup(s => s.Deserialize <TransactionAdapationEventMetadataFile>(It.IsAny <MemoryStream>(), It.IsAny <Encoding>())) .ReturnsAsync(_expectedMetadata = new TransactionAdapationEventMetadataFile { Events = new[] { TransactionAdaptionEventModel.AnalysisCompletedEvent(_fileId), TransactionAdaptionEventModel.FileTypeDetectedEvent(FileType.Bmp, _fileId), TransactionAdaptionEventModel.NcfsCompletedEvent(NcfsOutcome.Blocked, _fileId), TransactionAdaptionEventModel.NcfsStartedEvent(_fileId), badEvent, TransactionAdaptionEventModel.RebuildCompletedEvent(GwOutcome.Failed, _fileId), TransactionAdaptionEventModel.RebuildEventStarting(_fileId), } }); _input.Filter.FileIds = new List <Guid> { { Guid.NewGuid() } }; _output = await ClassInTest.GetTransactionsAsync(_input, CancellationToken.None); Assert.That(_output.Count, Is.EqualTo(0)); }
private void WhenTrySetAttendance(ApiBookingSetAttendanceCommand command, SetupData setup) { var json = JsonSerialiser.Serialise(command); var relativePath = string.Format("{0}/{1}", RelativePath, setup.FredOnAaronOrakeiMiniRed14To15.Id); WhenTrySetAttendance(json, relativePath, setup); }
/// <summary> /// POST请求与获取结果 /// </summary> public static string HttpPostWebhook(string Url, string accessToken) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // 加入这一句,否则会报错:未能创建SSL/TLS安全通道 JsonSerialiser jsonSerialiser = new JsonSerialiser(); WebhookData postData = new WebhookData(); string postJson = jsonSerialiser.Serialise(postData); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json;"; request.Headers.Add("Authorization", "Token " + accessToken); request.UserAgent = "2426837192"; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postJson); writer.Flush(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding))) { string retString = reader.ReadToEnd(); return(retString); } }
private string GivenWantToUpdateExistingService(SetupData setup) { var command = new ApiServiceSaveCommand { id = setup.MiniRed.Id, name = "Mini Yellow", description = "Mini Yellow Service", timing = new ApiServiceTiming { duration = 60 }, booking = new ApiServiceBooking { studentCapacity = 12, isOnlineBookable = true }, presentation = new ApiPresentation { colour = "Yellow" }, repetition = new ApiServiceRepetition { sessionCount = 9, repeatFrequency = "d" }, pricing = new ApiPricing { sessionPrice = 10, coursePrice = 80 } }; return(JsonSerialiser.Serialise(command)); }
/// <summary> /// Saves an object to a root using the specified settings, overwriting if it exists /// </summary> /// <typeparam name="T">The type of object to save</typeparam> /// <param name="root">The root this object will be saved under</param> /// <param name="value">The object to save</param> /// <param name="settings">Settings</param> public static void Save <T>(string root, T value, QuickSaveSettings settings) { string jsonToSave; try { jsonToSave = JsonSerialiser.Serialise(TypeHelper.ReplaceIfUnityType(value)); } catch (Exception e) { throw new QuickSaveException("Json serialisation failed", e); } string encryptedJson; try { encryptedJson = Cryptography.Encrypt(jsonToSave, settings.SecurityMode, settings.Password); } catch (Exception e) { throw new QuickSaveException("Encryption failed", e); } if (!FileAccess.SaveString(root, false, encryptedJson)) { throw new QuickSaveException("Failed to write to file"); } }
public WebhookResponse CreateWebhook(string access_token, string owner, string repo) { // 不是自己的仓库,不做任何处理 if (!repo.StartsWith(owner)) { return(null); } url = string.Format("https://api.github.com/repos/{0}/hooks", repo); string token = string.Format("access_token={0}", access_token); string response = HttpService.HttpPostWebhook(url, access_token); // 使用Header传递token //string response = HttpService.HttpPostWebhook(url + "?" + token); // 使用路径传递token try { JsonSerialiser jsonSerialiser = new JsonSerialiser(); var webhook = jsonSerialiser.Deserialise <WebhookResponse>(response); if (webhook.Id == null) { return(null); } return(webhook); } catch (Exception e) { throw e; } }
/// <summary> /// Loads the contents of the root into the specified object using the specified settings /// </summary> /// <typeparam name="T">The type of object to load</typeparam> /// <param name="root">The root this object was saved under</param> /// <param name="settings">Settings</param> /// <returns>The object that was loaded</returns> public static T Load <T>(string root, QuickSaveSettings settings) { string fileJson = FileAccess.LoadString(root, false); if (string.IsNullOrEmpty(fileJson)) { throw new QuickSaveException("File either does not exist or is empty"); } string decryptedJson; try { decryptedJson = Cryptography.Decrypt(fileJson, settings.SecurityMode, settings.Password); } catch (Exception e) { throw new QuickSaveException("Decryption failed", e); } try { return(JsonSerialiser.Deserialise <T>(decryptedJson)); } catch (Exception e) { throw new QuickSaveException("Failed to deserialise json", e); } }
private ApiResponse WhenTryPost(string templateType, SetupData setup) { var command = GivenValidEmailTemplateSaveCommand(); var json = JsonSerialiser.Serialise(command); return(WhenTryPost(json, templateType, setup)); }
private ApiResponse WhenTryPostAnonymously(ApiEmailTemplateSaveCommand command, string templateType, SetupData setup) { var json = JsonSerialiser.Serialise(command); var relativePath = string.Format("{0}/{1}", RelativePath, templateType); return(BusinessAnonymousPost <LocationData>(json, relativePath, setup)); }
private static string CreateNewServiceSaveCommand(ExpectedService expectedService) { var command = new ApiServiceSaveCommand { name = expectedService.Name, description = expectedService.Description, repetition = expectedService.Repetition, presentation = expectedService.Presentation }; if (expectedService.Timing != null) { command.timing = expectedService.Timing; } if (expectedService.Pricing != null) { command.pricing = expectedService.Pricing; } if (expectedService.Booking != null) { command.booking = expectedService.Booking; } return(JsonSerialiser.Serialise(command)); }
public void Handle(string target, HttpRequest baseRequest, HttpResponse response) { response.SetContentType("application/json;charset=utf-8"); response.SetStatus(HttpStatusCode.OK); baseRequest.SetHandled(true); try { if (IsApplication(baseRequest)) { LoanApplication application = new LoanApplication(); application.SetAmount(AmountFrom(baseRequest)); application.SetContact(ContactFrom(baseRequest)); Ticket ticket = _loanRepository.Store(application); response.Write(JsonSerialiser.ToJson(ticket)); } else if (IsStatusRequest(baseRequest) && IdSpecified(baseRequest)) { response.Write(FetchLoanInfo(baseRequest.GetParameter(TICKET_ID))); } else if (IsApproval(baseRequest) && IdSpecified(baseRequest)) { response.Write(ApproveLoan(baseRequest.GetParameter(TICKET_ID))); } else { response.Write("Incorrect parameters provided"); } } catch (ApplicationException ex) { response.Write("Uh oh! Problem occured: " + ex); } }
private string GivenNewLocationWithAnAlreadyExistingLocationName(string duplicateLocationName) { var command = new ApiLocationSaveCommand { name = duplicateLocationName }; return(JsonSerialiser.Serialise(command)); }
private ApiResponse WhenTryUpdateAuthorisedUntil(ApiBusinessSetAuthorisedUntilCommand command, SetupData setup) { var url = string.Format("Businesses/{0}", setup.Business.Id); var json = JsonSerialiser.Serialise(command); var response = AdminPost(json, url); setup.Business.AuthorisedUntil = command.authorisedUntil; return(response); }
private string GivenNewUniqueLocation() { var command = new ApiLocationSaveCommand { name = "Mt Eden Squash Club" }; return(JsonSerialiser.Serialise(command)); }
private object WhenTrySetPaymentStatusForCourseBooking(ApiBookingSetPaymentStatusCommand command, SetupData setup) { RegisterFredOnTwoCourseSessionsInAaronOrakeiHolidayCamp9To15For3Days(setup); var json = JsonSerialiser.Serialise(command); var relativePath = string.Format("{0}/{1}", RelativePath, setup.FredOnAaronOrakeiHolidayCamp9To15For3Days.Id); return(WhenTrySetPaymentStatus(json, relativePath, setup)); }
private static string CreateNewCoachSaveCommand(ExpectedLocation expectedLocation) { var command = new ApiLocationSaveCommand { name = expectedLocation.Name }; return(JsonSerialiser.Serialise(command)); }
private string GivenValidLocationSaveCommand() { var command = new ApiLocationSaveCommand { name = "Mt Eden Soccer Club" }; return(JsonSerialiser.Serialise(command)); }
private object WhenTrySetPaymentStatusForSessionBooking(ApiBookingSetPaymentStatusCommand command, SetupData setup) { RegisterFredOnStandaloneAaronOrakeiMiniRed14To15(setup); var json = JsonSerialiser.Serialise(command); var relativePath = string.Format("{0}/{1}", RelativePath, setup.FredOnAaronOrakeiMiniRed14To15.Id); return(WhenTrySetPaymentStatus(json, relativePath, setup)); }
private void SetBusinessAsExpired(SetupData setup) { var command = new ApiBusinessSetAuthorisedUntilCommand { authorisedUntil = DateTime.UtcNow.AddMonths(-1) }; var url = string.Format("Businesses/{0}", setup.Business.Id); var json = JsonSerialiser.Serialise(command); AdminPost(json, url); }
private string GivenExistingLocationAndChangeToAnAlreadyExistingLocationName(SetupData setup) { var command = new ApiLocationSaveCommand { id = setup.Remuera.Id, name = setup.Orakei.Name }; return(JsonSerialiser.Serialise(command)); }
private string GivenExistingLocationAndKeepLocationNameSame(SetupData setup) { var command = new ApiLocationSaveCommand { id = setup.Orakei.Id, name = setup.Orakei.Name }; return(JsonSerialiser.Serialise(command)); }
private string GivenMissingProperties() { var registration = new ApiBusinessRegistrationCommand { business = new ApiBusiness(), admin = new ApiBusinessAdmin() }; return(JsonSerialiser.Serialise(registration)); }
private string GivenExistingLocationAndChangeToUniqueLocationName(SetupData setup, string newLocationName) { var command = new ApiLocationSaveCommand { id = setup.Orakei.Id, name = newLocationName }; return(JsonSerialiser.Serialise(command)); }
private void UpdateSessionPriceOfLastSessionOfAaronOrakeiHolidayCamp9To15For3Days(SetupData setup) { var command = new ApiSessionSaveCommand(setup.AaronOrakeiHolidayCamp9To15For3Days.Sessions[2]) { id = setup.AaronOrakeiHolidayCamp9To15For3Days.Sessions[2].Id, pricing = { sessionPrice = 75 } }; PostSession(JsonSerialiser.Serialise(command), setup); }
public void Deserialise_EmptyEpisodeAirDate_SetsToNone() { var serialiser = new JsonSerialiser(); var value = serialiser.Deserialise <TvDbEpisodeData>(@"{ firstAired: """" }") .FirstAired; value.IsNone.Should().BeTrue(); }
/// <summary> /// Writes an object to the specified key - you must called commit to write the data to file /// </summary> /// <typeparam name="T">The type of object to write</typeparam> /// <param name="key">The key this object will be saved under</param> /// <param name="value">The object to save</param> /// <returns>The QuickSaveWriter</returns> public QuickSaveWriter Write <T>(string key, T value) { if (Exists(key)) { _items.Remove(key); } _items.Add(key, JsonSerialiser.SerialiseKey(value)); return(this); }
public async Task ExportSyncMethod_CreatesRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.ExportSyncMethod(1, x => x * 12, "func1"); var url = new Uri(api.BaseEndpoint, "/func1/10"); var result = await api.TestRoute<int>(url); Assert.That(result, Is.EqualTo(120)); } }
public async Task Bind_To_PrimativeArgFunc_TestRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.Bind("/funcy/{i}").ToSyncronousMethod<int, int>(i => i * 5); var url = new Uri(api.BaseEndpoint, "/funcy/10"); var result = await api.TestRoute<int>(url); Assert.That(result, Is.EqualTo(50)); } }
public async Task ExportDefinedSyncMethod_CreatesRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.ExportSyncMethod(50, Functions.Random); var url = new Uri(api.BaseEndpoint, "/random/10"); var result = await api.TestRoute<int>(url); Assert.That(result, Is.AtLeast(0)); Assert.That(result, Is.AtMost(10)); } }
public async Task TestRoute_UndefinedRoute_Returns404() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { var url = new Uri(api.BaseEndpoint, "/nothing/10"); try { var result = await api.TestRoute<int>(url); } catch (HttpException ex) { Assert.That(ex.Status, Is.EqualTo(HttpStatusCode.NotFound)); } } }
public async Task Bind_To_TestRouteWithInvalidReturnType() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.Bind("/factorial/{x}").To(new { x = 1 }, a => Task.FromResult(Functions.Factorial(a.x))); var url = new Uri(api.BaseEndpoint, "/factorial/10"); try { await api.TestRoute<double>(url); } catch (Exception ex) { Assert.That(ex, Is.InstanceOf<HttpException>()); } } }
public async Task Bind_To_AnonymousMethodTwoParams_AndTestRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.Bind("/abc/{paramA}").To(new { paramA = 123, paramB = 16 }, a => Task.FromResult(new { x = a.paramA * 5, y = a.paramB * 4 })); var url = new Uri(api.BaseEndpoint, "/abc/44"); var result = await api.TestRoute(url, new { x = 0, y = 0 }); Assert.That(result.x, Is.EqualTo(220)); Assert.That(result.y, Is.EqualTo(16 * 4)); } }
public async Task Bind_To_AnonymousMethod_AndTestRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.Bind("/abc/{param}").To(new { param = 123 }, a => Task.FromResult(new { x = a.param * 5 })); var url = new Uri(api.BaseEndpoint, "/abc/44"); var result = await api.TestRoute(url, new { x = 123 }); Assert.That(result.x, Is.EqualTo(220)); } }
public void JsonSerialiserTestsSetup() { jsonSerialiser = new JsonSerialiser(); }
public async Task Bind_To_DefinedFunc_TestRoute() { var sz = new JsonSerialiser(); using (var api = new HttpApi(sz, 9211)) { api.Bind("/factorial/{x}").ToSyncronousMethod<int, long>(Functions.Factorial); var url = new Uri(api.BaseEndpoint, "/factorial/10"); var expected = Functions.Factorial(10); Console.WriteLine("Expecting {0}", expected); var result = await api.TestRoute<long>(url); Assert.That(result, Is.EqualTo(expected)); } }