// GET (one) public Attachment GetAttachmentFor <TModel>(TModel model) where TModel : ModelBase, IAttachmentParent { // List the attachments against this model. var modelItemId = ModelTypeHelper.GetModelItemId(model); var allAttachmentsXml = _integrationProxy.FindAttachments(typeof(TModel).Name, modelItemId); var allAttachments = ModelSerializer.DeserializeTo <Response>(allAttachmentsXml).Attachments; if (allAttachments == null || allAttachments.Count == 0) { return(null); } var theFirstAttachment = allAttachments.First(); // Get the attachment content var content = _integrationProxy.FindOneAttachment( typeof(TModel).Name, modelItemId, theFirstAttachment.AttachmentID.ToString()); return(theFirstAttachment.WithContent(content)); }
public void TestSerializeModelObject() { var s = new ModelSerializer(StringSerializer.Create(), new LoadedTypeSerializer()); object1.Object = null; // Remove unresolvable dependency var strm = new MemoryStream(); streamWriter = new StreamWriter(strm); var writer = new SectionedStreamWriter(streamWriter); s.SerializeAttributes(object1, writer); streamWriter.Flush(); strm.Position = 0; // For testing string serialized = getStringFromStream(strm); var deserialized = new TestObject(); s.DeserializeAttributes(deserialized, new SectionedStreamReader(new StreamReader(strm))); Assert.AreEqual(object1.ToString(), deserialized.ToString()); }
public async Task <LogItemCreatedResponse> CreateAsync(CreateLogItemRequest request) { var uri = $"{ProjectName}/log"; if (request.Attach == null) { return(await PostAsJsonAsync <LogItemCreatedResponse, CreateLogItemRequest>(uri, request)); } else { var body = ModelSerializer.Serialize <List <CreateLogItemRequest> >(new List <CreateLogItemRequest> { request }); var multipartContent = new MultipartFormDataContent(); var jsonContent = new StringContent(body, Encoding.UTF8, "application/json"); multipartContent.Add(jsonContent, "json_request_part"); var byteArrayContent = new ByteArrayContent(request.Attach.Data, 0, request.Attach.Data.Length); byteArrayContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(request.Attach.MimeType); multipartContent.Add(byteArrayContent, "file", request.Attach.Name); var response = await HttpClient.PostAsync(uri, multipartContent).ConfigureAwait(false); response.VerifySuccessStatusCode(); var c = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(ModelSerializer.Deserialize <Responses>(c).LogItems[0]); } }
public static async Task Run( [QueueTrigger(AzureStorageNames.EmailInputDataQueue, Connection = "AzureWebJobsStorage")] string myQueueItem, [Queue(AzureStorageNames.EmailOutputDataQueue), StorageAccount("AzureWebJobsStorage")] ICollector <EmailInfo> storage, ILogger log) { ModelSerializer modelMappers = new ModelSerializer(); log.LogInformation($"C# Queue trigger function processed: "); try { var modelMapper = new ModelMapper(); if (!string.IsNullOrEmpty(myQueueItem)) { var handler = new NotifyPartiesQueueHandler(new EmailBuilderService(new TemplateDataService())); var email = await handler.Handle(myQueueItem, false); if (email != null) { var output = JsonConvert.SerializeObject(email); storage.Add(email); } } } catch (Exception ex) { log.LogError(ex, $"Something went wrong with the EmailQueueTrigger {myQueueItem}"); throw; } }
private async Task <TResponse> SendAsJsonAsync <TResponse, TRequest>(HttpMethod httpMethod, string uri, TRequest request) { HttpContent httpContent = null; if (request != null) { var memoryStream = new MemoryStream(); ModelSerializer.Serialize <TRequest>(request, memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); httpContent = new StreamContent(memoryStream); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } using (var httpRequest = new HttpRequestMessage(httpMethod, uri)) { using (httpContent) { httpRequest.Content = httpContent; using (var response = await HttpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)) { using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { CheckSuccessStatusCode(response, stream); return(ModelSerializer.Deserialize <TResponse>(stream)); } } } } }
public void ShouldDeserializeWithEscapedNewLine() { var json = "{\"P1\": \"abc\\nabc\"}"; var a = ModelSerializer.Deserialize <A>(json); Assert.Equal("abc\nabc", a.P1); }
protected override async Task <bool> ProcessInternal() { string[] files = await ListInputs(); if (files.Length != 1) { throw new Exception($"Generator received incorrect number of inputs: {files.Length} : {string.Join(",", files)}"); } string modelAsJson = (await ReadFile(files[0])).EnsureYamlIsJson(); CodeModel codeModelT = new ModelSerializer <CodeModel>().Load(modelAsJson); await InitializeCustomSettings(codeModelT); IAnyPlugin plugin = await CreatePlugin(); using (plugin.Activate()) { await InitializeNamespace(); CodeModel codeModel = plugin.Serializer.Load(modelAsJson); GeneratorSettingsTS settings = Singleton <GeneratorSettingsTS> .Instance; settings.UpdatePackageVersion(); ((CodeModelTS)codeModel).Settings = settings; codeModel = plugin.Transformer.TransformCodeModel(codeModel); plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult(); } WriteGeneratedFilesToDisk(); return(true); }
public void ObjectSerialization() { var obj = new TypeB(a: new ScalarA(""), new Uri("https://example.com/lol"), 3); var obj2 = ModelSerializer.DeserializeObject <TypeB>(ModelSerializer.SerializeObject(obj)); Assert.Equal(obj, obj2); }
protected override async Task <bool> ProcessInternal() { new Settings { Namespace = await GetValue("namespace") }; var files = await ListInputs(); if (files.Length != 1) { return(false); } var content = await ReadFile(files[0]); var fs = new MemoryFileSystem(); fs.WriteAllText(files[0], content); var serviceDefinition = SwaggerParser.Load(files[0], fs); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(serviceDefinition); var genericSerializer = new ModelSerializer <CodeModel>(); var modelAsJson = genericSerializer.ToJson(codeModel); WriteFile("codeMode.yaml", modelAsJson, null); return(true); }
public async Task Test(string dataset, string filename) { ModelSerializer modelSerializer = new ModelSerializer(); model = modelSerializer.DeserializeCNN(filename); fDataSet testdataset = new fDataSet(); testdataset.Deserializer(dataset); int index = random.Next(0, testdataset.fData.Count); AI.Core.fDataSet dataSet = new AI.Core.fDataSet(); dataSet.fData = testdataset.fData; pixel = testdataset.fData[index].Pixel; label = testdataset.fData[index].DecodeLabel; //model.predict probs = model.Predict(dataSet.fData[index]); AI.ML.CNN.Trainers.ADAM adam = new AI.ML.CNN.Trainers.ADAM(); softmaxOutput = adam.Softmax(probs); double maxValue = softmaxOutput.Max(); predict = softmaxOutput.ToList().IndexOf(maxValue); //int lindex = random.Next(0, 5); //predict = lindex == 2 ? random.Next(0, 9) : label; result[0] = label; result[1] = predict; await Clients.All.SendAsync("ReceiveMessage", pixel); await Clients.All.SendAsync("ReceiveLabel", result); }
/// <summary> /// Creates a new log item. /// </summary> /// <param name="model">Information about representation of log item.</param> /// <returns>Representation of just created log item.</returns> public async Task <LogItem> AddLogItemAsync(AddLogItemRequest model) { var uri = BaseUri.Append($"{Project}/log"); if (model.Attach == null) { var body = ModelSerializer.Serialize <AddLogItemRequest>(model); var response = await _httpClient.PostAsync(uri, new StringContent(body, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <LogItem>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); } else { var body = ModelSerializer.Serialize <List <AddLogItemRequest> >(new List <AddLogItemRequest> { model }); var multipartContent = new MultipartFormDataContent(); multipartContent.Add(new StringContent(body, Encoding.UTF8, "application/json"), "json_request_part"); multipartContent.Add(new ByteArrayContent(model.Attach.Data, 0, model.Attach.Data.Length), "file", model.Attach.Name); var response = await _httpClient.PostAsync(uri, multipartContent).ConfigureAwait(false); response.VerifySuccessStatusCode(); var c = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(ModelSerializer.Deserialize <Responses>(c).LogItems[0]); } }
private void LoadModel(string file) { viewer.Clear(); curPath = file; BlockData.Model model = ModelSerializer.LoadModel(file); VecInt3 offset = new VecInt3(viewer.GetPivot().x - model.pivotX, viewer.GetPivot().y - model.pivotY, viewer.GetPivot().z - model.pivotZ); int index = 0; for (int i = 0; i < model.blocks.Count; i++) { short blockType = (short)model.blocks[i].type; for (int j = 0; j < model.blocks[i].lenght; j++) { int y = index % model.sizeY; int x = (index / model.sizeY) % model.sizeX; int z = index / (model.sizeX * model.sizeY); viewer.blockManager.setBlock(x + offset.x, y + offset.y, z + offset.z, blockType); index++; } } viewer.SetDirty(); commandManager.Clear(); }
public void TestPersistAttributeTypeScope() { var s = new ModelSerializer(StringSerializer.Create(), new LoadedTypeSerializer()); // Add a new entity to the original model, it should not be serialized! new Engine.WorldRendering.Entity(); var strm = new MemoryStream(); var writer = new StreamWriter(strm); s.Serialize(model, writer); var deserialized = new Data.ModelContainer(); writer.Flush(); strm.Position = 0; // For testing string serialized = getStringFromStream(strm); SimpleModelObject.CurrentModelContainer = deserialized; s.Deserialize(new StreamReader(strm)); Assert.AreNotEqual(model.Objects.Count, deserialized.Objects.Count); Assert.AreEqual(model.Objects[0].ToString(), deserialized.Objects[0].ToString()); Assert.AreEqual(model.Objects[1].ToString(), deserialized.Objects[1].ToString()); }
static void Main(string[] args) { #if !NET461 Thread.CurrentThread.TrySetApartmentState(ApartmentState.STA); #endif try { var vm = new MainWindowViewModel(); var factory = new DemoDockFactory(); IDock layout = null; string path = ModelSerializer.GetBasePath("Layout.json"); if (ModelSerializer.Exists(path)) { layout = ModelSerializer.Load <RootDock>(path); } BuildAvaloniaApp().Start <MainWindow>(() => { // NOTE: Initialize layout after main window was created so child windows can be created. vm.Factory = factory; vm.Layout = layout ?? vm.Factory.CreateLayout(); vm.Factory.InitLayout(vm.Layout, vm); return(vm); }); vm.Factory.CloseLayout(vm.Layout); ModelSerializer.Save(path, vm.Layout); } catch (Exception ex) { Print(ex); } }
private IConsumerResponse CallApi(string method, string body, Uri baseUrl, string endpointName, string itemId, DateTime?lastModifiedDate, NameValueCollection additionalQueryParams, string acceptMimeType) { method = string.IsNullOrEmpty(method) ? "GET" : method.ToUpper(); NameValueCollection allQueryParams = additionalQueryParams ?? new NameValueCollection(); Uri uri = ConstructUri(baseUrl, endpointName, itemId, allQueryParams); IConsumerRequest request = _oauthSession.Request() .ForMethod(method) .ForUri(uri) .WithAcceptHeader(acceptMimeType ?? "text/xml") .WithIfModifiedSince(lastModifiedDate) .SignWithToken(); if ((method == "PUT" || method == "POST")) { request = request.WithBody(body); } IConsumerResponse consumerResponse = request.ToConsumerResponse(); // Check for <ApiException> response message if (consumerResponse.Content.StartsWith("<ApiException")) { ApiExceptionDetails details = ModelSerializer.DeserializeTo <ApiExceptionDetails>(consumerResponse.Content); throw new ApiException(details); } return(consumerResponse); }
public void TestSerializeCustomStringSerializerAttribute() { var model = new ModelContainer(); SimpleModelObject.CurrentModelContainer = model; var obj = new TestCustomObject(); obj.Text = "Hello "; var strm = new MemoryStream(); var writer = new StreamWriter(strm); var serializer = new ModelSerializer(StringSerializer.Create(), new LoadedTypeSerializer()); serializer.QueueForSerialization(obj); serializer.Serialize(writer); writer.Flush(); strm.Position = 0; var str = getStringFromStream(strm); var objects = serializer.Deserialize(new StreamReader(strm)); Assert.AreEqual(obj, objects[0]); }
/// <summary> /// Deletes specified test item. /// </summary> /// <param name="id">ID of the test item to delete.</param> /// <returns>A message from service.</returns> public virtual async Task <Message> DeleteTestItemAsync(string id) { var uri = BaseUri.Append($"{Project}/item/{id}"); var response = await _httpClient.DeleteAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <Message>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Returns specified launch by ID. /// </summary> /// <param name="id">ID of the launch to retrieve.</param> /// <returns>A representation of launch.</returns> public virtual async Task <LaunchResponse> GetAsync(long id) { var uri = BaseUri.Append($"{ProjectName}/launch/{id}"); var response = await HttpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <LaunchResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
public void ShouldThrowExceptionIfIncorrectJson() { var json = "<abc />"; var exp = Assert.ThrowsAny <Exception>(() => ModelSerializer.Deserialize <Message>(json)); Assert.Contains(json, exp.Message); Assert.NotNull(exp.InnerException); }
/// <summary> /// Merge several launches. /// </summary> /// <param name="id">Request for merging.</param> /// <param name="strategy">Known strategy is 'history'.</param> /// <returns>A message from service.</returns> public async Task <Message> AnalyzeLaunchAsync(string id, string strategy) { var uri = BaseUri.Append($"{Project}/launch/{id}/analyze/{strategy}"); var response = await _httpClient.PostAsync(uri, new StringContent(string.Empty, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <Message>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Returns specified log item by ID. /// </summary> /// <param name="id">ID of the log item to retrieve.</param> /// <returns>A representation of log item/</returns> public async Task <LogItem> GetLogItemAsync(string id) { var uri = BaseUri.Append($"{Project}/log/{id}"); var response = await _httpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <LogItem>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// TODO: these constructor arguments should maybe be in the model?? /// </summary> /// <param name="file"></param> /// <param name="interval"></param> /// <param name="?"></param> public AutoSaveSimulator(string file, TimeSpan interval, ModelSerializer serializer) { this.file = file; this.interval = interval; this.serializer = serializer; lastSave = DateTime.Now; }
public virtual async Task <UserResponse> GetAsync() { var uri = BaseUri.Append($"user"); var response = await HttpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <UserResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Returns the list of tests tags for specified launch. /// </summary> /// <param name="launchId">ID of launch.</param> /// <param name="tagContains">Tags should contain specified text.</param> /// <returns></returns> public virtual async Task <List <string> > GetUniqueTagsAsync(string launchId, string tagContains) { var uri = BaseUri.Append($"{Project}/item/tags?launch={launchId}&filter.cnt.tags={tagContains}"); var response = await _httpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <List <string> >(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Get the history of test item executions. /// </summary> /// <param name="testItemId">ID of test item.</param> /// <param name="depth">How many executions to return.</param> /// <param name="full"></param> /// <returns>The list of execution history.</returns> public virtual async Task <List <TestItemHistory> > GetTestItemHistoryAsync(string testItemId, int depth, bool full) { var uri = BaseUri.Append($"{Project}/item/history?ids={testItemId}&history_depth={depth}&is_full={full}"); var response = await _httpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <List <TestItemHistory> >(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
public object Create(IContext context) { var serializer = new ModelSerializer(); serializer.AddTypeSerializer(new DatabaseTypeSerializer()); serializer.AddTypeSerializer(new DataServiceModelTypeSerializer(Content.DataDefinition)); serializer.AddTypeSerializer(new DataServiceModelVectorTypeSerializer(Content.DataDefinition)); return(serializer); }
/// <summary> /// Update specified launch. /// </summary> /// <param name="id">ID of launch to update.</param> /// <param name="request">Information about launch.</param> /// <returns>A message from service.</returns> public virtual async Task <MessageResponse> UpdateAsync(long id, UpdateLaunchRequest request) { var uri = BaseUri.Append($"{ProjectName}/launch/{id}/update"); var body = ModelSerializer.Serialize <UpdateLaunchRequest>(request); var response = await HttpClient.PutAsync(uri, new StringContent(body, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <MessageResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Creates a new launch. /// </summary> /// <param name="request">Information about representation of launch.</param> /// <returns>Representation of just created launch.</returns> public virtual async Task <LaunchCreatedResponse> StartAsync(StartLaunchRequest request) { var uri = BaseUri.Append($"{ProjectName}/launch"); var body = ModelSerializer.Serialize <StartLaunchRequest>(request); var response = await HttpClient.PostAsync(uri, new StringContent(body, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <LaunchCreatedResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// gets all user preferences /// </summary> /// <param name="userName"></param> /// <returns></returns> public virtual async Task <Preference> GetAllPreferences(string userName) { var uri = BaseUri.Append($"project/{Project}/preference/{userName}"); var response = await _httpClient.GetAsync(uri).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <Preference>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Creates a new test item. /// </summary> /// <param name="id">ID of parent item.</param> /// <param name="model">Information about representation of test item.</param> /// <returns>Representation of created test item.</returns> public virtual async Task <TestItem> StartTestItemAsync(string id, StartTestItemRequest model) { var uri = BaseUri.Append($"{Project}/item/{id}"); var body = ModelSerializer.Serialize <StartTestItemRequest>(model); var response = await _httpClient.PostAsync(uri, new StringContent(body, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.VerifySuccessStatusCode(); return(ModelSerializer.Deserialize <TestItem>(await response.Content.ReadAsStringAsync().ConfigureAwait(false))); }
/// <summary> /// Generates client using provided settings. /// </summary> public static void Generate() { if (Settings.Instance == null) { throw new ArgumentNullException("settings"); } Logger.Entries.Clear(); Logger.LogInfo(Resources.AutoRestCore, Version); CodeModel codeModel = null; var modeler = ExtensionsLoader.GetModeler(); try { IEnumerable<ValidationMessage> messages = new List<ValidationMessage>(); // generate model from swagger codeModel = modeler.Build(out messages); // After swagger Parser codeModel = RunExtensions(Trigger.AfterModelCreation, codeModel); // After swagger Parser codeModel = RunExtensions(Trigger.BeforeLoadingLanguageSpecificModel, codeModel); foreach (var message in messages) { Logger.Entries.Add(new LogEntry(message.Severity, message.ToString())); } if (messages.Any(entry => entry.Severity >= Settings.Instance.ValidationLevel)) { throw ErrorManager.CreateError(null, Resources.ErrorGeneratingClientModel, "Errors found during Swagger validation"); } } catch (Exception exception) { throw ErrorManager.CreateError(exception, Resources.ErrorGeneratingClientModel, exception.Message); } var plugin = ExtensionsLoader.GetPlugin(); Logger.WriteOutput(plugin.CodeGenerator.UsageInstructions); Settings.Instance.Validate(); try { var genericSerializer = new ModelSerializer<CodeModel>(); var modelAsJson = genericSerializer.ToJson(codeModel); // ensure once we're doing language-specific work, that we're working // in context provided by the language-specific transformer. using (plugin.Activate()) { // load model into language-specific code model codeModel = plugin.Serializer.Load(modelAsJson); // we've loaded the model, run the extensions for after it's loaded codeModel = RunExtensions(Trigger.AfterLoadingLanguageSpecificModel, codeModel); // apply language-specific tranformation (more than just language-specific types) // used to be called "NormalizeClientModel" . codeModel = plugin.Transformer.TransformCodeModel(codeModel); // next set of extensions codeModel = RunExtensions(Trigger.AfterLanguageSpecificTransform, codeModel); // next set of extensions codeModel = RunExtensions(Trigger.BeforeGeneratingCode, codeModel); // Generate code from CodeModel. plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult(); } } catch (Exception exception) { throw ErrorManager.CreateError(exception, Resources.ErrorSavingGeneratedCode, exception.Message); } }