private void bRestore_Click(object sender, EventArgs e) { var folderBrowserDialog1 = new FolderBrowserDialog(); // Show the FolderBrowserDialog. DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { string folderName = folderBrowserDialog1.SelectedPath; try { DirectoryInfo d = new DirectoryInfo(folderName); //Assuming Test is your Folder FileInfo[] Files = d.GetFiles("*.chum5json"); //Getting Text files foreach (FileInfo file in Files) { try { string sinjson = File.ReadAllText(file.FullName); SINner sin = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson); UploadInfoObject uploadInfoObject = new UploadInfoObject(); uploadInfoObject.Client = PluginHandler.MyUploadClient; uploadInfoObject.UploadDateTime = DateTime.Now; uploadInfoObject.SiNners = new List <SINner> { sin }; var t = StaticUtils.Client.PostWithHttpMessagesAsync(uploadInfoObject); t.ContinueWith((posttask) => { if (posttask.Result.Response.IsSuccessStatusCode) { System.Diagnostics.Trace.TraceInformation("SINner " + sin.Id + " posted!"); } else { string msg = posttask.Result.Response.ReasonPhrase + ": " + Environment.NewLine; var content = posttask.Result.Response.Content.ReadAsStringAsync().Result; msg += content; System.Diagnostics.Trace.TraceWarning("SINner " + sin.Id + " not posted: " + msg); } }); } catch (Exception ex) { System.Diagnostics.Trace.TraceError("Could not read file " + file.FullName + ": " + ex.ToString()); continue; } } } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.ToString()); Invoke(new Action(() => MessageBox.Show(ex.Message))); } } }
private async Task RestoreTask(FolderBrowserDialog folderBrowserDialog1) { string folderName = folderBrowserDialog1.SelectedPath; try { DirectoryInfo d = new DirectoryInfo(folderName); //Assuming Test is your Folder FileInfo[] Files = d.GetFiles("*.chum5json"); //Getting Text files foreach (FileInfo file in Files) { try { using (new CursorWait(true, this)) { string sinjson = File.ReadAllText(file.FullName); SINner sin = Newtonsoft.Json.JsonConvert.DeserializeObject <SINner>(sinjson); UploadInfoObject uploadInfoObject = new UploadInfoObject(); uploadInfoObject.Client = PluginHandler.MyUploadClient; uploadInfoObject.UploadDateTime = DateTime.Now; uploadInfoObject.SiNners = new List <SINner> { sin }; var client = StaticUtils.GetClient(); var posttask = client.PostSINWithHttpMessagesAsync(uploadInfoObject); await posttask; if (posttask.Result.Response.IsSuccessStatusCode) { Log.Info("SINner " + sin.Id + " posted!"); } else { string msg = posttask.Result.Response.ReasonPhrase + ": " + Environment.NewLine; var content = posttask.Result.Response.Content.ReadAsStringAsync().Result; msg += content; Log.Warn("SINner " + sin.Id + " not posted: " + msg); } } } catch (Exception ex) { Log.Error(ex, "Could not read file " + file.FullName + ": "); continue; } } } catch (Exception ex) { Log.Error(ex); Invoke(new Action(() => Program.MainForm.ShowMessageBox(ex.Message))); } }
public static async Task <HttpOperationResponse> PostSINnerAsync(CharacterExtended ce) { HttpOperationResponse res = null; try { UploadInfoObject uploadInfoObject = new UploadInfoObject(); uploadInfoObject.Client = PluginHandler.MyUploadClient; uploadInfoObject.UploadDateTime = DateTime.Now; ce.MySINnerFile.UploadDateTime = DateTime.Now; uploadInfoObject.SiNners = new List <SINner>() { ce.MySINnerFile }; System.Diagnostics.Trace.TraceInformation("Posting " + ce.MySINnerFile.Id + "..."); var client = await StaticUtils.GetClient(); if (!StaticUtils.IsUnitTest) { res = await client.PostSINWithHttpMessagesAsync(uploadInfoObject); if ((res.Response.StatusCode != HttpStatusCode.OK) && (res.Response.StatusCode != HttpStatusCode.Accepted) && (res.Response.StatusCode != HttpStatusCode.Created)) { var msg = "Post of " + ce.MyCharacter.Alias + " completed with StatusCode: " + res?.Response?.StatusCode; msg += Environment.NewLine + "Reason: " + res?.Response?.ReasonPhrase; var content = await res.Response.Content.ReadAsStringAsync(); msg += Environment.NewLine + "Content: " + content; System.Diagnostics.Trace.TraceWarning(msg); PluginHandler.MainForm.DoThreadSafe(() => { MessageBox.Show(msg); }); throw new ArgumentException(msg); } } else { client.PostSINWithHttpMessagesAsync(uploadInfoObject).RunSynchronously(); } System.Diagnostics.Trace.TraceInformation("Post of " + ce.MySINnerFile.Id + " finished."); } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.ToString()); throw; } return(res); }
public UploadInfoObject GetUploadInfoObjectExample() { var sin = new SINnerExample().GetSINnerExample(); var id = Guid.NewGuid(); sin.UploadClientId = id; UploadInfoObject info = new UploadInfoObject() { SINners = new List <SINner>() { sin }, UploadDateTime = DateTime.Now, Client = new UploadClient() { Id = id, ChummerVersion = System.Reflection.Assembly.GetAssembly(typeof(UploadInfoObjectExample)).GetName().Version.ToString(), } }; return(info); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'UploadInfoObjectExample.GetUploadInfoObjectExample()' public UploadInfoObject GetUploadInfoObjectExample() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'UploadInfoObjectExample.GetUploadInfoObjectExample()' { var sin = new SINnerExample().GetSINnerExample(); var id = Guid.NewGuid(); sin.UploadClientId = id; UploadInfoObject info = new UploadInfoObject() { SINners = new List <SINner>() { sin }, UploadDateTime = DateTime.Now, Client = new UploadClient() { Id = id, ChummerVersion = System.Reflection.Assembly.GetAssembly(typeof(UploadInfoObjectExample)).GetName().Version.ToString(), } }; return(info); }
public async Task <IActionResult> PostSIN([FromBody] UploadInfoObject uploadInfo) { return(await PostSINnerInternal(uploadInfo)); }
private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo) { _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + "."); ApplicationUser user = null; SINner sinner = null; try { if (!ModelState.IsValid) { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); string msg = "ModelState is invalid: "; foreach (var err in errors) { foreach (var singleerr in err) { msg += Environment.NewLine + "\t" + singleerr.ToString(); } } return(BadRequest(new HubException(msg))); } if (uploadInfo.UploadDateTime == null) { uploadInfo.UploadDateTime = DateTime.Now; } if (uploadInfo.Client != null) { if (!UploadClientExists(uploadInfo.Client.Id)) { _context.UploadClients.Add(uploadInfo.Client); } else { _context.UploadClients.Attach(uploadInfo.Client); _context.Entry(uploadInfo.Client).State = EntityState.Modified; _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client); } } var returncode = HttpStatusCode.OK; user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name); foreach (var tempsinner in uploadInfo.SINners) { sinner = tempsinner; if (sinner.Id.ToString() == "string") { sinner.Id = Guid.Empty; } if (String.IsNullOrEmpty(sinner.MyExtendedAttributes.JsonSummary)) { return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null")); } if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false) { return(BadRequest("Sinner " + sinner.Id + ": Visibility contains no entries!")); } if (sinner.LastChange == null) { return(BadRequest("Sinner " + sinner.Id + ": LastChange not set!")); } if ((sinner.SINnerMetaData.Visibility.Id == null) || (sinner.SINnerMetaData.Visibility.Id == Guid.Empty)) { sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid(); } var oldsinner = (from a in _context.SINners.Include(a => a.SINnerMetaData.Visibility.UserRights) .Include(b => b.MyGroup) where a.Id == sinner.Id select a).FirstOrDefault(); if (oldsinner != null) { var olduserrights = oldsinner.SINnerMetaData.Visibility.UserRights.ToList(); bool canedit = false; foreach (var oldright in olduserrights) { if ((oldright.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant() && (oldright.CanEdit == true))) { canedit = true; break; } } if (!canedit) { string msg = "SINner " + sinner.Id + " is not editable for user " + user.Email + "."; throw new NoUserRightException(msg); } _context.UserRights.RemoveRange(olduserrights); bool userfound = false; foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights) { if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant()) { ur.CanEdit = true; userfound = true; } ur.Id = Guid.NewGuid(); ur.SINnerId = sinner.Id; _context.UserRights.Add(ur); } if (!userfound) { SINerUserRight ownUser = new SINerUserRight(); ownUser.Id = Guid.NewGuid(); ownUser.SINnerId = sinner.Id; ownUser.CanEdit = true; ownUser.EMail = user.Email; sinner.SINnerMetaData.Visibility.UserRights.Add(ownUser); _context.UserRights.Add(ownUser); } } else { var ownuserfound = false; var list = sinner.SINnerMetaData.Visibility.UserRights.ToList(); foreach (var ur in list) { ur.SINnerId = sinner.Id; if (ur.EMail.ToLowerInvariant() == "*****@*****.**".ToLowerInvariant()) { sinner.SINnerMetaData.Visibility.UserRights.Remove(ur); } if (ur.EMail.ToLowerInvariant() == user.Email.ToLowerInvariant()) { ownuserfound = true; } } if (!ownuserfound) { SINerUserRight ownright = new SINerUserRight(); ownright.CanEdit = true; ownright.EMail = user.Email; ownright.SINnerId = sinner.Id; ownright.Id = Guid.NewGuid(); sinner.SINnerMetaData.Visibility.UserRights.Add(ownright); } } foreach (var tag in sinner.SINnerMetaData.Tags) { tag.SetSinnerIdRecursive(sinner.Id); } sinner.UploadClientId = uploadInfo.Client.Id; SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user); SINnerGroup oldgroup = null; if (dbsinner != null) { oldgroup = dbsinner.MyGroup; _context.SINners.Attach(dbsinner); if (String.IsNullOrEmpty(sinner.GoogleDriveFileId)) { sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId; } if (String.IsNullOrEmpty(sinner.DownloadUrl)) { sinner.DownloadUrl = dbsinner.DownloadUrl; } _context.UserRights.RemoveRange(dbsinner.SINnerMetaData.Visibility.UserRights); _context.SINnerVisibility.Remove(dbsinner.SINnerMetaData.Visibility); var alltags = await dbsinner.GetTagsForSinnerFlat(_context); _context.Tags.RemoveRange(alltags); _context.SINnerMetaData.Remove(dbsinner.SINnerMetaData); _context.SINners.Remove(dbsinner); dbsinner.SINnerMetaData.Visibility.UserRights.Clear(); dbsinner.SINnerMetaData.Visibility = null; dbsinner.SINnerMetaData.Tags = null; dbsinner.SINnerMetaData = null; await _context.SaveChangesAsync(); await _context.SINners.AddAsync(sinner); string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString(); msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange; _logger.LogError(msg); List <Tag> taglist = sinner.SINnerMetaData.Tags; UpdateEntityEntries(taglist); } else { returncode = HttpStatusCode.Created; sinner.MyGroup = null; _context.SINners.Add(sinner); } try { await _context.SaveChangesAsync(); if (oldgroup != null) { var roles = await _userManager.GetRolesAsync(user); await SINnerGroupController.PutSiNerInGroupInternal(oldgroup.Id.Value, sinner.Id.Value, user, _context, _logger, oldgroup.PasswordHash, roles); } } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is SINner) { Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger); } else if (entry.Entity is Tag) { Utils.DbUpdateConcurrencyExceptionHandler(entry, _logger); } else { throw new NotSupportedException( "Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } if (e is HubException) { return(Conflict(e)); } HubException hue = new HubException("Exception in PostSINnerFile: " + e.ToString(), e); //var msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict) { ReasonPhrase = e.Message }; return(Conflict(hue)); } } List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList(); switch (returncode) { case HttpStatusCode.OK: return(Accepted("PostSIN", myids)); case HttpStatusCode.Created: return(CreatedAtAction("PostSIN", myids)); default: break; } return(BadRequest()); } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } if (e is HubException) { return(BadRequest(e)); } HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e); return(BadRequest(hue)); } }
/// <summary> /// Store the MetaData for chummerfiles (to get a Id). /// This Id can be used to store the actual file with PUT afterwards. /// Alternativly, the DownloadUrl can be set directly from the Client. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='uploadInfo'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PostSINAsync(this ISINnersClient operations, UploadInfoObject uploadInfo = default(UploadInfoObject), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PostSINWithHttpMessagesAsync(uploadInfo, null, cancellationToken).ConfigureAwait(false); }
/// <summary> /// Store the MetaData for chummerfiles (to get a Id). /// This Id can be used to store the actual file with PUT afterwards. /// Alternativly, the DownloadUrl can be set directly from the Client. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='uploadInfo'> /// </param> public static void PostSIN(this ISINnersClient operations, UploadInfoObject uploadInfo = default(UploadInfoObject)) { Task.Factory.StartNew(s => ((ISINnersClient)s).PostSINAsync(uploadInfo), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); }
private async Task <IActionResult> PostSINnerInternal(UploadInfoObject uploadInfo) { _logger.LogTrace("Post SINnerInternalt: " + uploadInfo + "."); ApplicationUser user = null; SINner sinner = null; try { if (!ModelState.IsValid) { var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); string msg = "ModelState is invalid: "; foreach (var err in errors) { foreach (var singleerr in err) { msg += Environment.NewLine + "\t" + singleerr.ToString(); } } return(new BadRequestObjectResult(new HubException(msg))); } if (uploadInfo.UploadDateTime == null) { uploadInfo.UploadDateTime = DateTime.Now; } if (uploadInfo.Client != null) { if (!UploadClientExists(uploadInfo.Client.Id)) { _context.UploadClients.Add(uploadInfo.Client); } else { _context.UploadClients.Attach(uploadInfo.Client); _context.Entry(uploadInfo.Client).State = EntityState.Modified; _context.Entry(uploadInfo.Client).CurrentValues.SetValues(uploadInfo.Client); } } var returncode = HttpStatusCode.OK; user = await _signInManager.UserManager.FindByNameAsync(User.Identity.Name); foreach (var tempsinner in uploadInfo.SINners) { sinner = tempsinner; if (sinner.Id.ToString() == "string") { sinner.Id = Guid.Empty; } if (String.IsNullOrEmpty(sinner.JsonSummary)) { return(BadRequest("sinner " + sinner.Id + ": JsonSummary == null")); } if (sinner.SINnerMetaData.Visibility.UserRights.Any() == false) { return(BadRequest("Sinner " + sinner.Id + ": Visibility contains no entries!")); } if (sinner.LastChange == null) { return(BadRequest("Sinner " + sinner.Id + ": LastChange not set!")); } if (sinner.SINnerMetaData.Visibility.Id == null) { sinner.SINnerMetaData.Visibility.Id = Guid.NewGuid(); } var olduserrights = await(from a in _context.UserRights where a.SINnerId == sinner.Id select a).ToListAsync(); _context.UserRights.RemoveRange(olduserrights); foreach (var ur in sinner.SINnerMetaData.Visibility.UserRights) { ur.Id = Guid.NewGuid(); ur.SINnerId = sinner.Id; _context.UserRights.Add(ur); } foreach (var tag in sinner.SINnerMetaData.Tags) { tag.SetSinnerIdRecursive(sinner.Id); } sinner.UploadClientId = uploadInfo.Client.Id; SINner dbsinner = await CheckIfUpdateSINnerFile(sinner.Id.Value, user); if (dbsinner != null) { _context.SINners.Attach(dbsinner); if (String.IsNullOrEmpty(sinner.GoogleDriveFileId)) { sinner.GoogleDriveFileId = dbsinner.GoogleDriveFileId; } if (String.IsNullOrEmpty(sinner.DownloadUrl)) { sinner.DownloadUrl = dbsinner.DownloadUrl; } //_context.Entry(dbsinner.SINnerMetaData.Visibility).State = EntityState.Modified; _context.Entry(dbsinner.SINnerMetaData.Visibility).CurrentValues.SetValues(sinner.SINnerMetaData.Visibility); //_context.Tags.RemoveRange(dbsinner.AllTags); _context.Entry(dbsinner).State = EntityState.Modified; _context.Entry(dbsinner).CurrentValues.SetValues(sinner); string msg = "Sinner " + sinner.Id + " updated: " + _context.Entry(dbsinner).State.ToString(); msg += Environment.NewLine + Environment.NewLine + "LastChange: " + dbsinner.LastChange; _logger.LogError(msg); List <Tag> taglist = sinner.SINnerMetaData.Tags; UpdateEntityEntries(taglist); } else { returncode = HttpStatusCode.Created; _context.SINners.Add(sinner); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { if (entry.Entity is SINner) { DbUpdateConcurrencyExceptionHandler(entry); } else if (entry.Entity is Tag) { DbUpdateConcurrencyExceptionHandler(entry); } else { throw new NotSupportedException( "Don't know how to handle concurrency conflicts for " + entry.Metadata.Name); } } } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e); var msg = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Conflict) { ReasonPhrase = hue.Message }; return(Conflict(msg)); } List <Guid> myids = (from a in uploadInfo.SINners select a.Id.Value).ToList(); switch (returncode) { case HttpStatusCode.OK: return(Accepted("PostSINnerFile", myids)); case HttpStatusCode.Created: return(CreatedAtAction("PostSINnerFile", myids)); default: break; } return(BadRequest()); } catch (Exception e) { try { var tc = new Microsoft.ApplicationInsights.TelemetryClient(); Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry telemetry = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(e); telemetry.Properties.Add("User", user?.Email); telemetry.Properties.Add("SINnerId", sinner?.Id?.ToString()); telemetry.Metrics.Add("TagCount", (double)sinner?.AllTags?.Count); tc.TrackException(telemetry); } catch (Exception ex) { _logger.LogError(ex.ToString()); } HubException hue = new HubException("Exception in PostSINnerFile: " + e.Message, e); return(BadRequest(hue)); } }