public static HttpResponseMessage CallSendApiMethod(string apiUrl, string methodName, Dictionary <string, string> queryString, object model) { HttpResponseMessage result; var resourceDocument = JsonConvert.SerializeObject(model); var content = new StringContent(resourceDocument, Encoding.UTF8, "application/json"); var uriBuilder = new UriBuilder(webApiBaseAddress + apiUrl + methodName) { }; var query = HttpUtility.ParseQueryString(uriBuilder.Query); foreach (var item in queryString) { query[item.Key] = item.Value; } uriBuilder.Query = query.ToString(); using (var client = CreateClient()) { Upsert upsert = client.PostAsync; var response = upsert(uriBuilder.Uri.ToString(), content).Result; result = response; } return(result); }
/**********************************************************************************/ public async void SaveTransaction(Transaction transaction) { if (transaction.User == 0) { transaction.User = User.Id; } transaction.Changed = DateTime.Now.ToTimeStamp(); if (transaction.Created == 0) { transaction.Created = transaction.Changed; } #if DEBUG Logger.Trace("Saving transaction: \n\n" + JsonConvert.SerializeObject(transaction)); #endif if (transaction.IncomeAccount == Guid.Empty || transaction.OutcomeAccount == Guid.Empty || (Math.Abs(transaction.Outcome) < 0.01 && Math.Abs(transaction.Income) < 0.01)) { Logger.Log("Transaction is not valid!"); return; } var upsert = new Upsert() { Id = transaction.Id, Type = UpsertType.Transaction }; Upserts.Add(upsert); _db.Table <Transaction>().Save(transaction); _db.Table <Upsert>().Save(upsert); await Syncronize(); }
///<summary> /// Builds a SubSonic upsert query from the passed-in object. ///</summary> public static ISqlQuery ToUpsertQuery <T>(this T item, IDataProvider provider) where T : class, new() { // TODO.ZJG: This is not really implemented. Type type = typeof(T); ITable tbl = provider.FindOrCreateTable <T>(); Upsert query = null; if (tbl != null) { var hashed = item.ToDictionary(); query = new Upsert(provider).Into <T>(tbl); foreach (string key in hashed.Keys) { IColumn col = tbl.GetColumnByPropertyName(key); if (col != null) { if (!col.AutoIncrement && !col.IsReadOnly && !(col.DefaultSetting != null && hashed[key] == null)) { query.Value(col.QualifiedName, hashed[key], col.DataType); } } } } return(query); }
private string GenerateUpsertQuery(Upsert upsertQuery) { var statementParts = new List <string> { GenerateDocument(upsertQuery.Poco), $@"""doc_as_upsert"": true" }; return($"{{ {string.Join(",", statementParts)} }}"); }
public void WritePermissions(DdlRules rules, StringWriter writer) { var template = _mapping.DdlTemplate.IsNotEmpty() ? rules.Templates[_mapping.DdlTemplate.ToLower()] : rules.Templates["default"]; Table.WriteTemplate(template, writer); Upsert.WriteTemplate(rules, template, writer); Update.WriteTemplate(rules, template, writer); Insert.WriteTemplate(rules, template, writer); Overwrite?.WriteTemplate(rules, template, writer); }
static async Task <ExitResult> WinEvt(WinEvtOptions o) { var path = Environment.ExpandEnvironmentVariables(SysMonEvtLogPath); if (!File.Exists(path)) { Error("The SysMon event log file at {0} was not found. Ensure you have installed SysMon on this system.", path); return(ExitResult.NOT_FOUND); } else { EventData = new Upsert(); var winevt = new WinEvtLogReader(EventData); Info("Using SysMon event log file at {0}.", path); Info("Reading SysMon event log. Press any key to exit."); winevt.ReadSysMonLog(); return(ExitResult.SUCCESS); } }
public void UpsertQuery_Generation_UpdatePoco() { // Arrange InitPoco(); var query = Upsert.Document(poco); var queryObject = new { doc = new { TestInteger = 12345, TestText = "ABCDEFG", TestBool = true, TestDateTime = new DateTime(2017, 9, 10), TestDouble = 1.337 }, doc_as_upsert = true }; // Act and Assert TestQuery(queryObject, query); TestQuery(queryObject, query, true); }
public async Task <UpsertResult> Upsert(string graphName, Upsert data, bool?ack, bool?new_vertex_only, bool?vertex_must_exist) { if (data.vertices == null) { data.vertices = new VerticesUpsert(); } if (data.edges == null) { data.edges = new EdgesUpsert(); } int vc = data.vertices.Count; int ec = data.edges.Count; using (var op = Begin("Upsert {0} vertices and {1} edges into graph {2} on server {3}", vc, ec, graphName, RestServerUrl)) { var query = "graph/" + graphName; var response = await RestHttpPostAsync <Upsert, UpsertResult>(query, data); op.Complete(); return(response); } }
public async Task <IActionResult> Edit([FromForm] EmployeeModel model) { if (!ModelState.IsValid) { PartialView(); } // Map model to resource var resource = mapper.Map <EmployeeResource>(model); // save resource to Json var resourceDocument = JsonConvert.SerializeObject(resource); using (var content = new StringContent(resourceDocument, Encoding.UTF8, "application/json")) { using (var client = restClient.CreateClient(User)) { // determen call update or insert Upsert upsert = client.PutAsync; // no RowVersion indicates insert if (model.RowVersion.IsNullOrEmpty()) { upsert = client.PostAsync; } using (var response = await upsert(apiUrl, content)) { // init result var result = new ResourceResult <EmployeeResource>(resource); // read result from RESTful service var responseDocument = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) { // Fetch created or updated resource from response result.Resource = JsonConvert.DeserializeObject <EmployeeResource>(responseDocument);; } else { // fetch errors and or exceptions result = JsonConvert.DeserializeObject <ResourceResult <EmployeeResource> >(responseDocument); } // Set error message for concurrency error if (response.StatusCode == HttpStatusCode.Conflict) { result.Errors.Clear(); result.Errors.Add(new ValidationError("This record is modified by another user")); result.Errors.Add(new ValidationError("Your work is not saved and replaced with new content")); result.Errors.Add(new ValidationError("Please review the new content and if required edit and save again")); } if (response.StatusCode.IsInSet(HttpStatusCode.OK, HttpStatusCode.Created, HttpStatusCode.Conflict)) { return(StatusCode(response.StatusCode.ToInt32(), result)); } // copy errors so they will be rendered in edit form foreach (var error in result.Errors) { ModelState.AddModelError(error.MemberName ?? "", error.Message); } // Update model with Beautify effect(s) and make it visible in the partial view IEnumerable <PropertyInfo> properties = model.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { var rawValue = property.GetValue(model); var attemptedValue = rawValue == null ? "" : Convert.ToString(rawValue, CultureInfo.InvariantCulture); ModelState.SetModelValue(property.Name, rawValue, attemptedValue); } // No need to specify model here, it has no effect on the render process :-( return(PartialView()); } } } }
public void Merge(TodoChangeMessage message) { Upsert = Upsert.Concat(message.Upsert).ToArray(); Delete = Delete.Concat(message.Delete).ToArray(); }
public async Task <IActionResult> Edit([FromForm] UploadedFileModel model) { if (!ModelState.IsValid) { PartialView(); } if (model.FileToUpload != null) { //var uploads = Path.Combine(env.WebRootPath, "uploads"); var uploads = Path.Combine("C:/", "uploads"); bool exists = Directory.Exists(uploads); if (!exists) { Directory.CreateDirectory(uploads); } var fileName = Path.GetFileName(model.FileToUpload.FileName); var fileStream = new FileStream(Path.Combine(uploads, model.FileToUpload.FileName), FileMode.Create); string mimeType = model.FileToUpload.ContentType; byte[] fileData = new byte[model.FileToUpload.Length]; BlobStorageService objBlobService = new BlobStorageService(); model.ImageFilePath = objBlobService.UploadFileToBlob(model.ImageFilename, model.FileToUpload.FileName, fileData, mimeType); } // Map model to resource var resource = mapper.Map <UploadedFileResource>(model); // save resource to Json var resourceDocument = JsonConvert.SerializeObject(resource); using (var content = new StringContent(resourceDocument, Encoding.UTF8, "application/json")) { // determen call update or insert Upsert upsert = apiClient.PutAsync; // no RowVersion indicates insert if (model.RowVersion.IsNullOrEmpty()) { upsert = apiClient.PostAsync; } using (var response = await upsert(apiUrl, content)) { // init result var result = new ResourceResult <UploadedFileResource>(resource); // read result from RESTful service var responseDocument = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) { // Fetch created or updated resource from response result.Resource = JsonConvert.DeserializeObject <UploadedFileResource>(responseDocument);; } else { // fetch errors and or exceptions result = JsonConvert.DeserializeObject <ResourceResult <UploadedFileResource> >(responseDocument); } // Set error message for concurrency error if (response.StatusCode == HttpStatusCode.Conflict) { result.Errors.Clear(); result.Errors.Add(new ValidationError("This record is modified by another user")); result.Errors.Add(new ValidationError("Your work is not saved and replaced with new content")); result.Errors.Add(new ValidationError("Please review the new content and if required edit and save again")); } if (response.StatusCode.IsInSet(HttpStatusCode.OK, HttpStatusCode.Created, HttpStatusCode.Conflict)) { return(StatusCode(response.StatusCode.ToInt32(), result)); } // copy errors so they will be rendered in edit form foreach (var error in result.Errors) { ModelState.AddModelError(error.MemberName ?? "", error.Message); } // Update model with Beautify effect(s) and make it visible in the partial view IEnumerable <PropertyInfo> properties = model.GetType().GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { var rawValue = property.GetValue(model); var attemptedValue = rawValue == null ? "" : Convert.ToString(rawValue, CultureInfo.InvariantCulture); ModelState.SetModelValue(property.Name, rawValue, attemptedValue); } // No need to specify model here, it has no effect on the render process :-( return(PartialView()); } } }
public void UpsertQuery_ExceptionTest_PocoId() { InitPoco(); poco.Id = null; TestExceptions(typeof(ArgumentNullException), () => Upsert.Document(poco), "Poco Id is null"); }
public void UpsertQuery_ExceptionTest_Poco() { TestExceptions(typeof(ArgumentNullException), () => Upsert.Document(A.Fake <Poco>()), "Poco is null"); }