public static string Sync(AppBlocksDbContext sourceDbContext, AppBlocksDbContext destinationDbContext, bool WhatIf = false) { var results = string.Empty; var sourceItems = sourceDbContext.Items.OrderBy(i => i.CreatorId).ToList(); results += $"<tr><td>Items found:{sourceItems.Count} in {sourceDbContext.Database.CurrentTransaction.TransactionId}</td></tr>\r\n"; var newItems = new List <Item>(); var updatedItems = new List <Item>(); var compareItems = true; var dirty = false; if (compareItems) { foreach (var item in sourceItems) { var existingItem = destinationDbContext.Items.FirstOrDefault(i => i.Id == item.Id); if (existingItem != null) { results += $"<tr><td>{item.Id}</td><td>{item.Name}</td><td>Already exists.</td></tr>\r\n"; } else { results += $"<tr><td>{item.Id}</td><td>{item.Name}</td><td>Does not exist.</td></tr>\r\n"; if (!WhatIf) { dirty = true; //shouldnt need to do this as long as creator is an actual item //var creator = destinationDbContext.Items.FirstOrDefault(i => i.Id == item.CreatorId); //if (creator == null) //{ // destinationDbContext.Items.Add(creator); //} //destinationDbContext.BulkInsert(item); newItems.Add(item); } } } } if (dirty) { var recordsUpdated = 0; try { //using EFCore.BulkExtensions; //requires EFCore 3.1.8 and newers //recordsUpdated = destinationDbContext.SaveChanges(); //destinationDbContext.BulkInsert(newItems); recordsUpdated += newItems.Count; results += $"<tr><td>Records Updated:{recordsUpdated}</td></tr>"; } catch (Exception exception) { results += $"<tr><td>Error saving {recordsUpdated} records:{exception}</td></tr>"; } } return(results); }
///// <summary> ///// FromUri ///// </summary> ///// <param name="uri"></param> ///// <returns></returns> //public static T FromUri<T>(Uri uri = null) where T : Item //{ // //if (uri == null) uri = new Uri(typeof(T).FullName != "AppBlocks.Models.User" ? Context.AppBlocksBlocksServiceUrl + Context.GroupId : Context.AppBlocksServiceUrl + "/account/authenticate"); // //_logger?.LogInformation($"{typeof(Item).Name}.FromUri({uri}) started:{DateTime.Now.ToShortTimeString()}"); // var content = string.Empty; // try // { // var request = (HttpWebRequest)WebRequest.Create(uri); // request.ServerCertificateValidationCallback = (message, cert, chain, errors) => { return true; }; // // response.GetResponseStream(); // using (var response = (HttpWebResponse)request.GetResponse()) // { // //_logger?.LogInformation($"HttpStatusCode:{response.StatusCode}"); // var responseValue = string.Empty; // if (response.StatusCode != HttpStatusCode.OK) // { // var message = $"{typeof(Item).FullName} ERROR: Request failedd. Received HTTP {response.StatusCode}"; // throw new ApplicationException(message); // } // // grab the response // using (var responseStream = response.GetResponseStream()) // { // if (responseStream != null) // using (var reader = new StreamReader(responseStream)) // { // responseValue = reader.ReadToEnd(); // } // } // content = responseValue; // } // } // catch (Exception exception) // { // //_logger?.LogInformation($"{nameof(Item)}.FromUri({uri}) ERROR:{exception.Message} {exception}"); // Trace.WriteLine($"{nameof(Item)}.FromUri({uri}) ERROR:{exception.Message} {exception}"); // } // //_logger?.LogInformation($"content:{content}"); // return FromJson<T>(content); //} ///// <summary> ///// FromJson ///// </summary> ///// <param name="json"></param> //public static T FromJson<T>(string json) where T : List<Item> //{ // var typeName = typeof(T).FullName; // //_logger?.LogInformation($"{typeof(Item).Name}.FromJson<{typeName}>({json}) started:{DateTime.Now.ToShortTimeString()}"); // var jsonFile = Common.FromFile(json, typeName); // if (!string.IsNullOrEmpty(jsonFile)) json = jsonFile; // if (typeName == "AppBlocks.Models.User") // { // //json = Context.AppBlocksServiceUrl + "/account/authenticate";// Models.Settings.GroupId // } // if (json.ToLower().StartsWith("http") || string.IsNullOrEmpty(json)) //|| json == Context.GroupId // { // return FromUri<T>(!string.IsNullOrEmpty(json) ? new Uri(json) : null); //&& json != Context.GroupId // } // else // { // if (string.IsNullOrEmpty(json) ) return null; //|| json == Context.GroupId // var jsonTrimmed = json.Trim(); // if (!jsonTrimmed.StartsWith("[") && !jsonTrimmed.StartsWith("{")) return null; // var array = json.StartsWith("[") && json.EndsWith("]"); // if (!array) return JsonSerializer.Deserialize<T>(json); // var items = JsonSerializer.Deserialize<List<T>>(json); // if (items == null) return null; // var item = items.FirstOrDefault(); // item.SetChildren(items); // return item; // } //} public static async Task <string> ItemActionAsync(AppBlocksDbContext db, Item item, string actionName) { var action = db.Items.FirstOrDefault(item => item.TypeId == "Block" && item.Name == actionName); if (action == null) { return(null); } var url = action.Data; if (string.IsNullOrEmpty(url)) { return(null); } if (url.Contains($"{actionName}Id")) { var actionItem = item.Children.FirstOrDefault(item => item.ParentId == item.Id && item.Name == $"{actionName}Id"); if (actionItem == null) { return(null); } url = url.Replace($"{actionName}Id", actionItem.Data); } //_logger?.LogInformation($"{typeof(Item).Name}({actionName})-url:{url} started:{DateTime.Now.ToShortTimeString()}"); if (string.IsNullOrEmpty(url)) { return(null); } var xml = new XmlDocument(); xml.LoadXml(url); //var items = Item.FromJsonAsync<List<Item>>(Newtonsoft.Json.JsonConvert.SerializeXmlNode(xml)); var items = FromXml <List <Item> >(new Uri(url)); //return items.Count; foreach (var itemNew in items) { //mapping, versus updating?? await db.Items.AddAsync(itemNew); } await db.SaveChangesAsync(); return($"Added:{items.Count}"); }