public override IEnumerable <DiffInstance> Translate(IEnumerable <DiffInstance> aDiffs) { foreach (DiffInstance aDiff in Snapshotter.TranslateSettings(Section, aDiffs, TranslateKey)) { yield return(aDiff); } }
/// <summary> /// Updates a user. /// </summary> /// <param name="user">The <see cref="User"/> to update.</param> public void UpdateUser(User user) { var original = Current.DB.Users.Get(user.Id); // track which fields change on the object var s = Snapshotter.Start(original); original.Username = user.Username; original.EmailAddress = user.EmailAddress; original.FullName = user.FullName; original.Messages = user.Messages; original.Roles = user.Roles; original.EmailAllowed = user.EmailAllowed; original.PasswordResetToken = user.PasswordResetToken; original.PasswordResetTokenExpirationDate = user.PasswordResetTokenExpirationDate; original.Credentials = user.Credentials; original.IsAdmin = user.IsAdmin; var diff = s.Diff(); if (diff.ParameterNames.Any()) { Current.DB.Users.Update(user.Id, diff); } }
public static void Main() { string connectionString = ConfigurationManager.ConnectionStrings["database-connection-2"].ConnectionString; using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var db = NorthwindDatabase.Init(sqlConnection, commandTimeout: 3); var supplier = db.Suppliers.Get(9); // snapshotter tracks which fields change on the object var s = Snapshotter.Start(supplier); supplier.CompanyName += "_" + Guid.NewGuid().ToString().Substring(1, 4); db.Suppliers.Update(9, s.Diff()); // reload it from database supplier = db.Suppliers.Get(9); ObjectDumper.Write(supplier); } }
public static void SetSnapshotter(this Context context, Action take, Action restore) { var snapshotter = new Snapshotter { Take = take, Restore = restore }; context.Set(snapshotter); }
static void Main(string[] args) { var cnn = new SqlConnection("Data Source=.;Initial Catalog=tempdb;Integrated Security=True"); cnn.Open(); var db = MyDatabase.Init(cnn, commandTimeout: 2); try { db.Execute("waitfor delay '00:00:03'"); } catch (Exception) { Console.WriteLine("yeah ... it timed out"); } db.Execute("if object_id('Products') is not null drop table Products"); db.Execute(@"create table Products ( Id int identity(1,1) primary key, Name varchar(20), Description varchar(max), LastPurchase datetime)"); int?productId = db.Products.Insert(new { Name = "Hello", Description = "Nothing" }); var product = db.Products.Get((int)productId); product.Description = "untracked change"; // snapshotter tracks which fields change on the object var s = Snapshotter.Start(product); product.LastPurchase = DateTime.UtcNow; product.Name += " World"; // run: update Products set LastPurchase = @utcNow, Name = @name where Id = @id // note, this does not touch untracked columns db.Products.Update(product.Id, s.Diff()); // reload product = db.Products.Get(product.Id); Console.WriteLine("id: {0} name: {1} desc: {2} last {3}", product.Id, product.Name, product.Description, product.LastPurchase); // id: 1 name: Hello World desc: Nothing last 12/01/2012 5:49:34 AM Console.WriteLine("deleted: {0}", db.Products.Delete(product.Id)); // deleted: True Console.ReadKey(); }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public ReturnValue ResetPassword(string email, string password) { string hash; string salt; AuthEncryption.GenerateHashAndSalt(password, out salt, out hash); ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.ExtraInformation2 = salt; userToSet.PasswordHash = hash; userToSet.PasswordResetToken = null; userToSet.AccessFailedCount = 0; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "There was nothing to update!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ActionResult Edit(int id, User updatedUser) { User user = Current.DB.Users.Get(id); if (updatedUser.DOB < DateTime.UtcNow.AddYears(-100) || updatedUser.DOB > DateTime.UtcNow.AddYears(-6)) { updatedUser.DOB = null; } if (user.Id == updatedUser.Id && (updatedUser.Id == CurrentUser.Id || CurrentUser.IsAdmin)) { var violations = updatedUser.GetBusinessRuleViolations(ChangeAction.Update); if (violations.Count == 0) { var snapshot = Snapshotter.Start(user); user.Login = HtmlUtilities.Safe(updatedUser.Login); user.AboutMe = updatedUser.AboutMe; user.DOB = updatedUser.DOB; user.Email = HtmlUtilities.Safe(updatedUser.Email); user.Website = HtmlUtilities.Safe(updatedUser.Website); user.Location = HtmlUtilities.Safe(updatedUser.Location); // Preferences are updated separately, so we should likely do this elsewhere instead... // Can likely move it out if we have introduce a fancier OpenID management panel like // the network has. user.EnforceSecureOpenId = updatedUser.EnforceSecureOpenId; var diff = snapshot.Diff(); if (diff.ParameterNames.Any()) { Current.DB.Users.Update(user.Id, snapshot.Diff()); } return(Redirect("/users/" + user.Id)); } else { foreach (var violation in violations) { ModelState.AddModelError(violation.PropertyName, violation.ErrorMessage); } return(Edit(user.Id)); } } else { return(Redirect("/")); } }
private static void InitSnapshotDates(BeatmapSet aBeatmapSet) { snapshotDates = aBeatmapSet.beatmaps.SelectMany(aBeatmap => Snapshotter.GetSnapshots(aBeatmap) .Select(aSnapshot => aSnapshot.creationTime)) .ToList(); snapshotDates.AddRange(Snapshotter.GetSnapshots( aBeatmapSet.beatmaps.First().metadataSettings.beatmapSetId.ToString(), "files") .Select(aSnapshot => aSnapshot.creationTime)); snapshotDates = snapshotDates.Distinct().OrderBy(aDate => aDate).ToList(); }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <param name="loginTime"></param> /// <param name="loginAddress"></param> /// <returns></returns> public ReturnValue UpdateLastLoginInfo(string email, DateTime loginTime, string loginAddress) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.PreviousLoginAddress = userToSet.LastLoginAddress; userToSet.PreviousLoginTime = userToSet.LastLoggedIn; userToSet.LastLoggedIn = loginTime; userToSet.LastLoginAddress = loginAddress; userToSet.AccessFailedCount = 0; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "The failed count was not reset!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue RenameSession(string email, int sessionId, string newName) { var returnValue = new ReturnValue(); try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); // Get the existing session var existingSession = dapperDb.SessionTable.Get(sessionId); if (existingSession == null) { // Something went drastically wrong, this shouldn't happen string msg = string.Format("Couldn't update the session with ID {0} because it didn't exist when we went to update it!", sessionId); _logger.Error(msg); returnValue.Message = msg; return(returnValue); } // Snapshot the current record to track changes var snapshot = Snapshotter.Start(existingSession); existingSession.Name = newName; // Check if we have any changes to make DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { const string msg = "Session name has not changed - nothing to save!"; _logger.Info(msg); returnValue.Message = msg; return(returnValue); } dapperDb.SessionTable.Update(sessionId, snapshot.Diff()); _logger.Debug(string.Format("Updated session {0} with the new name {1}", sessionId, newName)); returnValue.Success = true; return(returnValue); } catch (Exception ex) { string msg = string.Format("An error occurred while trying to update the session name! {0}", ex.Message); _logger.Error(msg); returnValue.Message = msg; return(returnValue); } }
/// <summary> /// Updated for MySQL /// </summary> /// <param name="email"></param> /// <returns></returns> public ReturnValue LockAccount(string email) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.AccessFailedCount = 0; userToSet.LockoutEndDate = DateTime.UtcNow.AddMinutes(5); DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "There was nothing to update!"; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
public ReturnValue UpdateMenuFormat(string email, bool isShortMenuFormat) { ReturnValue returnValue = new ReturnValue(); try { var sw = new Stopwatch(); sw.Start(); DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3, false); var userId = GetIdByEmail(email); if (userId == 0) { returnValue.Message = string.Format("No user was found with the email address {0}", email); return(returnValue); } var userToSet = dapperDb.AuthUserTable.Get(userId); var snapshot = Snapshotter.Start(userToSet); userToSet.ShortMenuFormat = isShortMenuFormat; DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { sw.Stop(); returnValue.Message = "The menu format was not changed."; return(returnValue); } dapperDb.AuthUserTable.Update(userId, snapshot.Diff()); sw.Stop(); returnValue.Success = true; returnValue.TimeTaken = sw.Elapsed; } catch (Exception ex) { returnValue.Message = ex.Message; } return(returnValue); }
private CardModel BuildCardModel ( string identity, string identityType, Dictionary <string, string> customFields, CardScope scope, VirgilKey ownerKey ) { var cardSnapshotModel = new PublishCardSnapshotModel { Identity = identity, IdentityType = identityType, Info = new CardInfoModel { DeviceName = this.context.DeviceManager.GetDeviceName(), Device = this.context.DeviceManager.GetSystemName() }, PublicKeyData = ownerKey.ExportPublicKey().GetBytes(), Scope = scope, Data = customFields }; var snapshot = new Snapshotter().Capture(cardSnapshotModel); var snapshotFingerprint = this.context.Crypto.CalculateFingerprint(snapshot); var cardId = snapshotFingerprint.ToHEX(); var selfSignature = ownerKey.Sign(VirgilBuffer.From(snapshotFingerprint.GetValue())); var signatures = new Dictionary <string, byte[]> { [cardId] = selfSignature.GetBytes() }; var cardModel = new CardModel(cardSnapshotModel) { Id = cardId, Snapshot = snapshot, Meta = new CardMetaModel { Signatures = signatures } }; return(cardModel); }
//public bool CheckChangeChanges(TModel oldData, DynamicParameters newData) //{ // HasChanges = false; // //start observer // Diff = new DynamicParameters(); // //merge new data into old data // ModelService srvc = new ModelService(); // TModel oldDataClone = new TModel(); // srvc.CopyProperty(oldData, oldDataClone); // List<string> ignoreFields = GetIgnoreFields(ActivityType); // //bool status = srvc.Merge<TModel>(newData, oldData, GetIgnoreFields(ActivityType)); // //changes // //Diff = s.Diff(); // List<Dictionary<string, object>> changed_values = new List<Dictionary<string, object>>(); // try // { // foreach (PropertyInfo prop in oldData.GetType().GetProperties()) // { // if (ignoreFields.Contains<string>(prop.Name)) // { // continue; // } // string newValue = prop.GetValue(newData) == null ? string.Empty : prop.GetValue(newData).ToString(); // string oldValue = prop.GetValue(oldData) == null ? string.Empty : prop.GetValue(oldData).ToString(); // if (newValue != oldValue) // { // //setting the changed value in property for saving // Diff.Add(prop.Name, prop.GetValue(newData)); // //storing data for saving in change history. // HasChanges = true; // Dictionary<string, object> row = new Dictionary<string, object>(); // row.Add("field_name", prop.Name); // row.Add("old_value", oldDataClone.GetType().GetProperty(prop.Name).GetValue(oldDataClone)); // row.Add("new_value", newData.GetType().GetProperty(prop.Name).GetValue(newData)); // changed_values.Add(row); // } // } // } // catch(Exception ex) // { // Bango.Base.Log.LogTrace.WriteErrorLog(ex.ToString()); // } // if (HasChanges) // { // Changes.table_name = ModelService.GetTableName(oldData); // Changes.changed_values = JsonConvert.SerializeObject(changed_values); // Changes.activity_datetime = DateTime.Now; // Changes.user_id = Bango.GetCurrentUserId(); // Changes.pkey_name = Changes.GetKeyPropertyInfo().Name; // } // return HasChanges; //} public bool CheckChangeChanges_old(TModel oldData, TModel newData) { HasChanges = false; //start observer var s = Snapshotter.Start(oldData); //merge new data into old data ModelService srvc = new ModelService(); TModel oldDataClone = new TModel(); srvc.CopyProperty(oldData, oldDataClone); bool status = srvc.Merge <TModel>(newData, oldData, GetIgnoreFields(ActivityType)); //changes Diff = s.Diff(); List <Dictionary <string, object> > changed_values = new List <Dictionary <string, object> >(); if (Diff.ParameterNames.AsList <string>().Count > 0) { foreach (string name in Diff.ParameterNames.AsList <string>()) { Dictionary <string, object> row = new Dictionary <string, object>(); row.Add("field_name", name); row.Add("old_value", oldDataClone.GetType().GetProperty(name).GetValue(oldDataClone)); row.Add("new_value", newData.GetType().GetProperty(name).GetValue(newData)); //row.Add("new_value", Diff.Get<string>(name)); changed_values.Add(row); } Changes.table_name = ModelService.GetTableName(oldData); Changes.changed_values = JsonConvert.SerializeObject(changed_values); Changes.activity_datetime = DateTime.Now; Changes.user_id = SessionData.user_id; // Changes.pkey_name = Changes.GetKeyPropertyInfo().Name; Changes.os_computer_name = HttpRequestHelper.GetClientHostName(); Changes.os_ipaddress = HttpRequestHelper.GetClientIpAddress(); Changes.os_useragent = HttpRequestHelper.GetClientBrowser(); // Changes.mac_address = HttpRequestHelper.GetMacAddress(); HasChanges = true; } //if(changes.ParameterNames.le) return(HasChanges); }
public void UpdateSessionLogTotalPlayedTime(Dictionary <int, long> totalPlayedTimes) { try { DapperDb dapperDb = DapperDb.Init(OpenConnection(), 3); foreach (var kvp in totalPlayedTimes) { // Get the existing session var sessionLog = dapperDb.SessionLogTable.Get(kvp.Key); if (sessionLog == null) { // Something went drastically wrong, this shouldn't happen _logger.Error(string.Format("Couldn't update the sessionLog with ID {0} because it didn't exist when we went to update it!", kvp.Key)); continue; } // Snapshot the current record to track changes var snapshot = Snapshotter.Start(sessionLog); sessionLog.TotalPlayedTime = kvp.Value; // Check if we have any changes to make DynamicParameters dynamicParameters = snapshot.Diff(); if (!dynamicParameters.ParameterNames.Any()) { continue; } dapperDb.SessionLogTable.Update(kvp.Key, snapshot.Diff()); TimeSpan timeSpan = new TimeSpan(kvp.Value); _logger.Debug(string.Format("Updated sessionLog {0} with TotalPlayedTime {1} ({2})", kvp.Key, kvp.Value, timeSpan)); } } catch (Exception ex) { _logger.Error(string.Format("An error occurred while trying to update the sessionLog TotalPlayedTimes! {0}", ex.Message)); } }
private static async Task RequestSnapshots(string aBeatmapSetPath) { try { // Beatmapset null (-1) would become ambigious with any other unsubmitted map. if (State.LoadedBeatmapSet.beatmaps.FirstOrDefault()?.metadataSettings.beatmapSetId != null) { Snapshotter.SnapshotBeatmapSet(State.LoadedBeatmapSet); } if (State.LoadedBeatmapSetPath != aBeatmapSetPath) { return; } string html = SnapshotsRenderer.Render(State.LoadedBeatmapSet); await SendMessage("UpdateSnapshots", html); } catch (Exception exception) { string html = ExceptionRenderer.Render(exception); await SendMessage("UpdateException", "Snapshots:" + html); } }
private InitializeDirectoryFlags InitializeLocalIndexAndDirectory(Directory baseLuceneDirectory, Analyzer analyzer, string configuredPath) { lock (_locker) { if (System.IO.Directory.Exists(TempPath) == false) { System.IO.Directory.CreateDirectory(TempPath); } //copy index if it exists, don't do anything if it's not there if (IndexReader.IndexExists(baseLuceneDirectory) == false) { return(InitializeDirectoryFlags.SuccessNoIndexExists); } var writerAttempt = TryCreateWriterWithRetry(baseLuceneDirectory, analyzer); if (writerAttempt.Success == false) { LogHelper.Error <LocalTempStorageIndexer>("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); return(InitializeDirectoryFlags.FailedLocked); } //Try to open the reader from the source, this will fail if the index is corrupt and we'll need to handle that try { //NOTE: To date I've not seen this error occur using (writerAttempt.Result.GetReader()) { } } catch (Exception ex) { writerAttempt.Result.Dispose(); LogHelper.Error <LocalTempStorageIndexer>( string.Format("Could not open an index reader, {0} is empty or corrupt... attempting to clear index files in master folder", configuredPath), ex); if (ClearLuceneDirFiles(baseLuceneDirectory) == false) { //hrm, not much we can do in this situation, but this shouldn't happen LogHelper.Error <LocalTempStorageIndexer>("Could not open an index reader, index is corrupt.", ex); return(InitializeDirectoryFlags.FailedCorrupt); } //the main index is now blank, we'll proceed as normal with a new empty index... writerAttempt = TryCreateWriter(baseLuceneDirectory, analyzer); if (writerAttempt.Success == false) { //ultra fail... LogHelper.Error <LocalTempStorageIndexer>("Could not create index writer with snapshot policy for copying, the index cannot be used", writerAttempt.Exception); return(InitializeDirectoryFlags.FailedLocked); } } using (writerAttempt.Result) { try { var basePath = IOHelper.MapPath(configuredPath); var commit = Snapshotter.Snapshot(); var allSnapshotFiles = commit.GetFileNames() .Concat(new[] { commit.GetSegmentsFileName(), //we need to manually include the segments.gen file "segments.gen" }) .Distinct() .ToArray(); var tempDir = new DirectoryInfo(TempPath); //Get all files in the temp storage that don't exist in the snapshot collection, we want to remove these var toRemove = tempDir.GetFiles() .Select(x => x.Name) .Except(allSnapshotFiles); using (var tempDirectory = new SimpleFSDirectory(tempDir)) { if (TryWaitForDirectoryUnlock(tempDirectory)) { foreach (var file in toRemove) { try { File.Delete(Path.Combine(TempPath, file)); } catch (IOException ex) { if (file.InvariantEquals("write.lock")) { //This might happen if the writer is open LogHelper.Warn <LocalTempStorageIndexer>("The lock file could not be deleted but should be removed when the writer is disposed"); } LogHelper.Debug <LocalTempStorageIndexer>("Could not delete non synced index file file, index sync will continue but old index files will remain - this shouldn't affect indexing/searching operations. {0}", () => ex.ToString()); } } } else { //quit here, this shouldn't happen with all the checks above. LogHelper.Warn <LocalTempStorageIndexer>("Cannot sync index files from main storage, the temp file index is currently locked"); return(InitializeDirectoryFlags.FailedLocked); } foreach (var fileName in allSnapshotFiles.Where(f => f.IsNullOrWhiteSpace() == false)) { var destination = Path.Combine(TempPath, Path.GetFileName(fileName)); //don't copy if it's already there, lucene is 'write once' so this file is meant to be there already if (File.Exists(destination)) { continue; } try { File.Copy( Path.Combine(basePath, "Index", fileName), destination); } catch (IOException ex) { LogHelper.Error <LocalTempStorageIndexer>("Could not copy index file, could not sync from main storage", ex); //quit here return(InitializeDirectoryFlags.FailedFileSync); } } } } finally { Snapshotter.Release(); } } LogHelper.Info <LocalTempStorageIndexer>("Successfully sync'd main index to local temp storage for index: {0}", () => configuredPath); return(InitializeDirectoryFlags.Success); } }
private void ZipButton_Click(object sender, RoutedEventArgs e) { CreateErrorFile(); Snapshotter.ZipConfiguration(); Close(); }
public bool CheckChangeChanges(TModel oldData, DynamicDictionary newData) { HasChanges = false; var s = Snapshotter.Start(oldData); //start observer Diff = new DynamicParameters(); ChangedValues = new ExpandoObject(); //merge new data into old data ModelService srvc = new ModelService(); TModel oldDataClone = new TModel(); srvc.CopyProperty(oldData, oldDataClone); List <string> ignoreFields = GetIgnoreFields(ActivityType); //bool status = srvc.Merge<TModel>(newData, oldData, GetIgnoreFields(ActivityType)); //changes //Diff = s.Diff(); List <Dictionary <string, object> > changed_values = new List <Dictionary <string, object> >(); try { foreach (PropertyInfo prop in oldData.GetType().GetProperties()) { if (ignoreFields.Contains <string>(prop.Name)) { continue; } if (!newData.ContainsKey(prop.Name)) { continue; } string newValue = newData.GetValue(prop.Name) == null ? string.Empty : newData.GetValue(prop.Name).ToString(); string oldValue = prop.GetValue(oldData) == null ? string.Empty : prop.GetValue(oldData).ToString(); if (newValue != oldValue) { //setting the changed value in property for saving //storing data for saving in change history. HasChanges = true; Dictionary <string, object> row = new Dictionary <string, object>(); row.Add("field_name", prop.Name); row.Add("old_value", oldDataClone.GetType().GetProperty(prop.Name).GetValue(oldDataClone)); //row.Add("new_value", newData.GetType().GetProperty(prop.Name).GetValue(newData)); row.Add("new_value", newData.GetValue(prop.Name)); changed_values.Add(row); prop.SetValue(oldData, ModelService.ChangeType(newData.GetValue(prop.Name), prop.PropertyType)); } } } catch (Exception ex) { Bango.Base.Log.LogTrace.WriteErrorLog(ex.ToString()); throw new Exception("Error while tracking changes."); } if (HasChanges) { Changes.table_name = ModelService.GetTableName(oldData); Changes.changed_values = JsonConvert.SerializeObject(changed_values); Changes.activity_datetime = DateTime.Now; Changes.user_id = SessionData.user_id; Changes.activity_type = ActivityType.ToString(); Changes.os_computer_name = HttpRequestHelper.GetClientHostName(); Changes.os_ipaddress = HttpRequestHelper.GetClientIpAddress(); Changes.os_useragent = HttpRequestHelper.GetClientBrowser(); // Changes.pkey_name = Changes.GetKeyPropertyInfo().Name; } Diff = s.Diff(); return(HasChanges); }
private static string RenderBeatmapSnapshots(BeatmapSet aBeatmapSet) { Beatmap refBeatmap = aBeatmapSet.beatmaps[0]; if (refBeatmap.metadataSettings.beatmapSetId == null) { return (Div("paste-separator") + Div("unsubmitted-snapshot-error", "Beatmapset ID is -1. This makes the map ambigious with any other " + "unsubmitted map. Submit the map before using this feature.")); } // Just need the beatmapset id to know in which snapshot folder to look for the files. IEnumerable <Snapshotter.Snapshot> refSnapshots = Snapshotter.GetSnapshots( refBeatmap.metadataSettings.beatmapSetId.ToString(), "files"); Snapshotter.Snapshot lastSnapshot = refSnapshots.First(aSnapshot => aSnapshot.creationTime == refSnapshots.Max(anOtherSnapshot => anOtherSnapshot.creationTime)); List <DiffInstance> refDiffs = new List <DiffInstance>(); foreach (Snapshotter.Snapshot refSnapshot in refSnapshots) { IEnumerable <DiffInstance> refDiffsCompare = Snapshotter.Compare(refSnapshot, lastSnapshot.code).ToList(); refDiffs.AddRange(Snapshotter.TranslateComparison(refDiffsCompare)); } return (Div("paste-separator") + Div("card-container-unselected", DivAttr("card-difficulty", DataAttr("difficulty", "Files"), RenderSnapshotSections(refDiffs, refSnapshots, "Files", true) ) + String.Concat( aBeatmapSet.beatmaps.Select(aBeatmap => { // Comparing current to all previous snapshots for this beatmap so the user // can pick interpretation without loading in-between. IEnumerable <Snapshotter.Snapshot> snapshots = Snapshotter.GetSnapshots(aBeatmap).ToList(); List <DiffInstance> diffs = new List <DiffInstance>(); foreach (Snapshotter.Snapshot snapshot in snapshots) { IEnumerable <DiffInstance> diffsCompare = Snapshotter.Compare(snapshot, aBeatmap.code).ToList(); diffs.AddRange(Snapshotter.TranslateComparison(diffsCompare)); } string version = Encode(aBeatmap.metadataSettings.version); return DivAttr("card-difficulty", DataAttr("difficulty", version), RenderSnapshotSections(diffs, snapshots, version) ); })) ) + Div("paste-separator select-separator") + Div("card-container-selected")); }