public void SendNoteJudge(Note.NoteJudge noteJudge) { foreach(IJudgeReceiver judgeReceiver in m_judgeReceiverList) { judgeReceiver.Receive(noteJudge); } }
public void TestSoundLogic2() { var soundLogic = new SoundLogic(); List<Tuple<Note, int>> result = new List<Tuple<Note, int>>(); var rootNote = new Note(new List<string>() { "B" }); var startNote = new Note(new List<string>() { "E" }); soundLogic.getScaleNotes(EInstrument.Guitar, EScale.Major, rootNote, 3, startNote, true, ref result); Assert.AreEqual(new Note(new List<string>() { "E" }), result[0].Item1); Assert.AreEqual(3, result[0].Item2); Assert.AreEqual(new Note(new List<string>() { "F#", "Gb" }), result[1].Item1); Assert.AreEqual(3, result[1].Item2); Assert.AreEqual(new Note(new List<string>() { "G#", "Ab" }), result[2].Item1); Assert.AreEqual(3, result[2].Item2); Assert.AreEqual(new Note(new List<string>() { "A#", "Bb" }), result[3].Item1); Assert.AreEqual(3, result[3].Item2); Assert.AreEqual(new Note(new List<string>() { "B" }), result[4].Item1); Assert.AreEqual(3, result[4].Item2); Assert.AreEqual(new Note(new List<string>() { "C#", "Db" }), result[5].Item1); Assert.AreEqual(4, result[5].Item2); Assert.AreEqual(new Note(new List<string>() { "D#", "Eb" }), result[6].Item1); Assert.AreEqual(4, result[6].Item2); }
//Constructor public NoteViewModel(NoteModel note = null) { if (note == null) { _note = new NoteModel(); } else { _note = note; } _window = new Note(); _window.DataContext = this; #region Events and commands _window.MouseLeftButtonDown += Grid_LeftClick; _window.txt_Title.LostFocus += Title_LostFocus; _window.HeaderBorder.MouseRightButtonUp += HeaderBorder_RightClick; _window.Deactivated += Window_Deactivated; CreateCloseCommand(); CreateNewTaskCommand(); #endregion _window.Show(); //_window.Topmost = true; _window.txt_DataText.Focus(); HiddenWindow.HideNoteFromAltTab(_window); App.Notes.Add(this); }
/// <summary> /// Submit Button Click Event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { NoteAdmin _Noteadmin = new NoteAdmin(); Note _NoteAccess = new Note(); _NoteAccess.CaseID = ItemID; _NoteAccess.AccountID = null; _NoteAccess.CreateDte = System.DateTime.Now; _NoteAccess.CreateUser = HttpContext.Current.User.Identity.Name; _NoteAccess.NoteTitle = txtNoteTitle.Text.Trim(); _NoteAccess.NoteBody = ctrlHtmlText.Html ; bool Check = _Noteadmin.Insert(_NoteAccess); if (Check) { //redirect to main page Response.Redirect(CancelLink); } else { //display error message lblError.Text = "An error occurred while updating. Please try again."; lblError.Visible = true; } }
/// <summary> /// Play an array of Notes /// </summary> /// <param name="notes">An array of Note objects, each defining a frequency and duration</param> public void Play(Note[] notes) { foreach (Note note in notes) { Play(note.Frequency, note.Duration); } }
/// <summary> /// Scans through a notechart and assigns the HOPO tag to notes that are of a /// different type than the previous note, and have a tick difference less than /// the specified HOPO tick threshold. /// </summary> /// <param name="inputNotechart"> /// Any notechart (expected to not have hammeron information already filled out). /// </param> /// <param name="inputChartInfo"> /// All information pertaining to the chart. /// </param> /// <returns> /// The same notechart with proper hammeron note settings. /// </returns> public static Notes AssignHOPOS(Notes inputNotechart, Info inputChartInfo) { Notes notechartToReturn = inputNotechart; int HOPOTickThreshold = (inputChartInfo.resolution * 4) / inputChartInfo.HOPOThreshold; Note currentNote = new Note(); Note nextNote = new Note(); // We stop at (count - 2) due to the currentNote/nextNote/thirdNote setup for (int i = 0; i < inputNotechart.notes.Count - 1; i++) { currentNote = inputNotechart.notes[i]; nextNote = inputNotechart.notes[i + 1]; if (i == 470) { nextNote.ToString(); } // If difference is 0, it is a chord and should not be a hammeron. // We need to check the third note in case the next note is the start // of a chord. if (((nextNote.tickValue - currentNote.tickValue) <= HOPOTickThreshold) && (!nextNote.noteType.isEqual(currentNote.noteType)) && (!nextNote.isChord)) { notechartToReturn.notes[i + 1].isHOPO = true; } } return notechartToReturn; }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); string item = null; _isEditMode = false; if (NavigationContext.QueryString.TryGetValue("item", out item)) { //call get note; if (_manager != null) { _currentNote = _manager.Retrieve(Convert.ToInt32(item)); //set node properties to the UI if (_currentNote == null) { tbContent.Text = string.Empty; tbTitle.Text = string.Empty; } else { tbContent.Text = _currentNote.Content; tbTitle.Text = _currentNote.Title; _isEditMode = true; } } } }
void CreatePlatforms(){ if (Selection.activeGameObject != null) { if(Selection.activeGameObject.GetComponent<PlayOnTouch>() != null){ platformNote = Selection.activeGameObject.GetComponent<PlayOnTouch>().note; platformLength = Mathf.FloorToInt(Selection.activeGameObject.transform.localScale.x / 10); } GameObject holder = new GameObject ("Platform " + platformNote); GameObject replaceable = Selection.activeGameObject; if(Selection.activeGameObject.GetComponent<PlayOnTouch>() != null){ holder.transform.position = replaceable.transform.position; holder.transform.parent = replaceable.transform.parent.transform; } else { holder.transform.position = replaceable.transform.position; holder.transform.parent = replaceable.transform; } bool paired = platformLength % 2 == 0; for (float i = -Mathf.Floor(platformLength / 2); i <= Mathf.Floor(platformLength / 2); i++) { if(!paired || i != Mathf.Floor(platformLength / 2)){ GameObject newPlatform = (GameObject)PrefabUtility.InstantiatePrefab (platform); newPlatform.GetComponent<PlayOnTouch>().SetNote(platformNote); if(paired){ newPlatform.transform.position = holder.transform.position + new Vector3 ((i * 10) + 5, 0, 0); } else { newPlatform.transform.position = holder.transform.position + new Vector3 (i * 10, 0, 0); } newPlatform.transform.parent = holder.transform; } } } }
private void NoteDeletedHandler (object noteMgr, Note deletedNote) { deletedNotes [deletedNote.Id] = deletedNote.Title; fileRevisions.Remove (deletedNote.Id); Write (localManifestFilePath); }
public void TestNote() { Note note = new Note(TITLE, ""); Assert.AreEqual(note.Title, TITLE); note.Content = CONTENT; Assert.AreEqual(note.Content, CONTENT); }
//Button Add click handler private void btnAdd_Click(object sender, EventArgs e) { if (CheckUpCount() == true) { try { //show Editor dialog frmEditor EditorForm = new frmEditor(); EditorForm.ShowDialog(); //add new data to data-collection if (EditorForm.IsCanceled == false) { Note NewNote = new Note(EditorForm.TextName, EditorForm.TextArray); EncryptedData.AddNote(NewNote); } } catch (OutOfMemoryException Exc) { MessageBox.Show(Exc.ToString()); } catch (ArgumentException Exc) { MessageBox.Show(Exc.ToString()); } //add new record to grid UpdateGrid(); } }
public ActionResult AddOrMod(string title, string content, int id = -1) { if (!User.Identity.IsAuthenticated) return Redirect(_client.OAuthCheckUrl()); try { var note = new Note(); if (id != -1) { note = _entities.Notes.SingleOrDefault(m => m.Id == id); if (note == null) { throw new Exception("Note not exists."); } } note.Title = title; note.Content = content; note.User = User.Identity.Name; if(note.EntityState != EntityState.Modified) _entities.AddToNotes(note); _entities.SaveChanges(); _entities.Refresh(RefreshMode.StoreWins, note); return Json(new { code = 0, data = note }, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new { code = 1, data = ex.Message }, JsonRequestBehavior.AllowGet); } }
public void Open(List<Minion> minions, List<Note> notes) { //Transform parent = this.transform.parent; this.minion = null; foreach (Minion m in minions) { if (m.gameObject.name == this.minionName) { this.minion = m; break; } } this.note = null; foreach (Note n in notes) { if (n.gameObject.name == this.noteName) { this.note = n; break; } } if (this.minion != null) { this.minion.EnableClicks(); this.minion.gameObject.GetComponent<SpriteRenderer>().color = Color.white; } if (this.note != null) { this.note.EnableClicks(); this.note.gameObject.GetComponent<SpriteRenderer>().color = Color.white; } }
public IEnumerable<MethodValue> GetValues(ReflectedInstance value, Type type, MethodInfo methodInfo) { if (methodInfo.Name == "Beep") { Note[] melody = new Note[] { new Note(Note.C, 0, 100), new Note(Note.C, 0, 100), new Note(Note.D, 0, 100), new Note(Note.E, 0, 100), new Note(Note.F, 0, 100), new Note(Note.G, 0, 100), new Note(Note.A, 0, 100), new Note(Note.B, 0, 100), new Note(Note.C, 1, 100), new Note(Note.D, 1, 100), new Note(Note.E, 1, 100), new Note(Note.F, 1, 100), new Note(Note.G, 1, 100), new Note(Note.A, 1, 100), new Note(Note.B, 1, 100), new Note(Note.C, 2, 100) }; var parameters = methodInfo.GetParameters(); foreach (var note in melody) { var methodValue = methodInfo.Invoke("Beep", new object[] { note.Frequency, note.Duration }); var parameter = new MethodValueParam(parameters[0].Name, parameters[0], note.Frequency); var parameter1 = new MethodValueParam(parameters[1].Name, parameters[1], note.Duration); yield return new MethodValue(methodValue, parameter, parameter1); } } }
async void CheckForResumedStartup() { if (await FileHelper.ExistsAsync(App.TransientFilename)) { // Read the file. string str = await FileHelper.ReadTextAsync(App.TransientFilename); // Delete the file. await FileHelper.DeleteFileAsync(App.TransientFilename); // Break down the file contents. string[] contents = str.Split('\x1F'); string filename = contents[0]; bool isNoteEdit = Boolean.Parse(contents[1]); string entryText = contents[2]; string editorText = contents[3]; // Create the Note object and initialize it with saved data. Note note = new Note(filename); note.Title = entryText; note.Text = editorText; // Navigate to NotePage. NotePage notePage = new NotePage(note, isNoteEdit); await this.Navigation.PushAsync(notePage); } }
public Note(Note note) { this.position = note.position; this.type = note.type; this.next = note.next; this.prev = note.prev; }
/// <summary> /// Handles the Click event of the lbAddNote control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void lbAddNote_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var service = new NoteService( rockContext ); var note = new Note(); note.IsSystem = false; note.IsAlert = false; note.NoteTypeId = noteType.Id; note.EntityId = contextEntity.Id; note.Text = tbNewNote.Text; if ( noteType.Sources != null ) { var source = noteType.Sources.DefinedValues.FirstOrDefault(); if ( source != null ) { note.SourceTypeValueId = source.Id; } } service.Add( note ); rockContext.SaveChanges(); ShowNotes(); }
private void btn_OK_Click(object sender, EventArgs e) { List<Note> ln = new List<Note>(); foreach (string line in rtb_FastNote.Lines) { if(line.Trim() == "") continue; string[] onnote = line.Split('|'); if (onnote.Length >= 2) { Note note = new Note(); note.word = onnote[0]; note.up = onnote[1]; if (onnote.Length >= 3) note.down = onnote[2]; if (onnote.Length >= 4) note.foot = onnote[3]; ln.Add(note); } } SetNote sn = (SetNote)this.Owner; sn.listNotes = ln; this.DialogResult = DialogResult.OK; Close(); }
/// <summary> /// Method to fill the notes entity with the data entered in the controls /// </summary> public Note FillNoteEntity() { Note objNote = new Note(); objNote.UserId = _userId; objNote.UserTributeId = _tributeId; objNote.Title = txtNoteTitle.Text.Trim(); //objNote.MessageWithoutHtml = StripHtml(ftbNoteMessage.Value); //ftbNoteMessage.HtmlStrippedText; objNote.MessageWithoutHtml = ftbNoteMessage.PlainText.ToString(); //cute editor; //objNote.PostMessage = ftbNoteMessage.Value; // ftbNoteMessage.Text; objNote.PostMessage = ftbNoteMessage.Text.ToString(); // cute editor; objNote.ModuleTypeName = MODULE_TYPE_NAME; objNote.UserName = _userName; objNote.TributeName = _tributeName; objNote.TributeType = _tributeType; objNote.TributeUrl = _tributeUrl; objNote.PathToVisit = "<a href='http://" + Request.ServerVariables["SERVER_NAME"] + Request.ApplicationPath; // if (Equals(mode, "edit")) //if user is editing the note note id is required to update it. { objNote.NotesId = _noteId; objNote.ModifiedBy = _userId; objNote.ModifiedDate = DateTime.Now; } else { objNote.CreatedBy = _userId; objNote.CreatedDate = DateTime.Now; } return objNote; }
private void ReadBeatFromTxt(string fileName) { string noteString = Resources.Load<TextAsset>(fileName).text; string[] lines = noteString.Split('\n'); int bpm = Int32.Parse(lines[1]); int quantize = Int32.Parse(lines[2]); float beatLen = 60.0f / (float)bpm * (4.0f / (float)quantize); uint count = 0; uint notecount = 0; for (int i = 3; i < lines.Length; ++i) { foreach (char c in lines[i]) { switch (c) { case '0': notecount++; Note newNote = new Note(notecount, (int)((count * beatLen + NoteMover.NoteDelay) * 1000000) + BEAT_DELAY_TEMP); NoteList.Enqueue(newNote); count++; break; case '-': count++; break; case ' ': break; case ';': Turnline newTurnline = new Turnline( (int)((count * beatLen + NoteMover.NoteDelay) * 1000000) + BEAT_DELAY_TEMP); FlipList.Enqueue(newTurnline); break; } } } }
public override void GenerateFrequencies(Note[] notes) { for (int i = 0; i < notes.Length - 1; i++) { float duration1 = notes[i].Duration; int j = i+1; for (; j < notes.Length; j++) { if (!notes[j].IsRest()) break; else duration1 += notes[j].Duration; } float duration2 = notes[j].Duration; j++; for(; j < notes.Length; j++) { if (!notes[j].IsRest()) break; else duration2 += notes[j].Duration; } float rel = duration1 / duration2; if (float.IsInfinity(rel) || float.IsNaN(rel)) continue; Add(new Pair(rel)); if (j >= notes.Length - 1) break; } }
public static int getNoteIndex(Note note) { switch (note) { case Note.C1: case Note.Cs: return 0; case Note.D1: case Note.Ds: return 1; case Note.E1: return 2; case Note.F1: case Note.Fs: return 3; case Note.G1: case Note.Gs: return 4; case Note.A1: case Note.As: return 5; case Note.B1: return 6; case Note.C2: return 7; default: return -1; } }
public void AddNotes(string SqlWhereClause = null) { int idFld = m_NotesTable.FindField("Notes_ID"); int ownerFld = m_NotesTable.FindField("OwnerID"); int typeFld = m_NotesTable.FindField("Type"); int notesFld = m_NotesTable.FindField("Notes"); int dsFld = m_NotesTable.FindField("DataSourceID"); ICursor theCursor; if (SqlWhereClause == null) { theCursor = m_NotesTable.Search(null, false); } else { IQueryFilter QF = new QueryFilterClass(); QF.WhereClause = SqlWhereClause; theCursor = m_NotesTable.Search(QF, false); } IRow theRow = theCursor.NextRow(); while (theRow != null) { Note anNote = new Note(); anNote.Notes_ID = theRow.get_Value(idFld).ToString(); anNote.OwnerID = theRow.get_Value(ownerFld).ToString(); anNote.Notes = theRow.get_Value(notesFld).ToString(); anNote.Type = theRow.get_Value(typeFld).ToString(); anNote.DataSourceID = theRow.get_Value(dsFld).ToString(); anNote.RequiresUpdate = true; m_NotesDictionary.Add(anNote.Notes_ID, anNote); theRow = theCursor.NextRow(); } }
public float ComputeFitness(Note[] individual) { float weighted_sum = 0; for (int i = 0; i < metrics.Length; i++) { var x = metrics[i].Generate(individual); var t = target_metrics[i]; float magx = 0; float magt = 0; float dot = 0; foreach(var v in x.Values) magx += v * v; foreach(var v in t.Values) magt += v * v; foreach (var p in x.Keys) { float f1 = x[p]; if (!t.ContainsKey(p)) continue; float f2 = t[p]; dot += f1 * f2; } magx = (float)Math.Sqrt(magx); magt = (float)Math.Sqrt(magt); if (magx == 0 || magt == 0) return 0; weighted_sum += dot / (magx * magt); } return weighted_sum / metrics.Length; }
public List<Note> GetNotes(Roll roll) { string sql = NotesSql(roll); var reader = Data_Context.RunSelectSQLQuery(sql, 30); var notes = new List<Note>(); if (reader.HasRows) { var sReader = new SpecialistsReader(); while (reader.Read()) { string uName = reader["Author"] as string; var spec = sReader.GetSpecialist(uName); string n = reader["Note"] as string; DateTime date = reader.GetDateTime(4); string step = reader["StepTypeID"] as string; var note = new Note(spec, n, date, step); notes.Add(note); } return notes; } else return null; }
public NoteContent(object sender , object sender1) { this.InitializeComponent(); item = (Button)sender; item1 = (Button) sender1; notepadRepository = new NotepadRepository(); ourNotes = notepadRepository.GetNotes(item.Content.ToString().ToLower()); notepad = ourNotes[0].notepad; foreach (Note note in ourNotes) { if (note.title == item1.Content.ToString().ToLower()) CurrNote = note; } if (CurrNote != null) { if (CurrNote.title == "+") CurrNote.title = "New Title"; NoteAct.Text = CurrNote.content; //NoteAct.Document.SetText(new Windows.UI.Text.TextSetOptions(), CurrNote.content); NoteName.Text = CurrNote.title; } AppTitle.Text = notepad; foreach (Note note in ourNotes) { notes.Items.Add(createNoteButton(note.title,note.content)); } }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); if ( action != null && action.Activity != null && action.Activity.Workflow != null && action.Activity.Workflow.Id > 0 ) { var text = GetAttributeValue( action, "Note" ).ResolveMergeFields( GetMergeFields( action ) ); var note = new Note(); note.IsSystem = false; note.IsAlert = GetAttributeValue( action, "IsAlert" ).AsBoolean(); note.EntityId = action.Activity.Workflow.Id; note.Caption = string.Empty; note.Text = text; var noteType = NoteTypeCache.Read( GetAttributeValue( action, "NoteType" ).AsGuid() ); if ( noteType != null ) { note.NoteTypeId = noteType.Id; } new NoteService( rockContext ).Add( note ); return true; } else { errorMessages.Add( "A Note can only be added to a persisted workflow with a valid ID." ); return false; } }
private static void Go(long userId) { var settings = new MongoServerSettings { Server = new MongoServerAddress("127.0.0.1", 27017), SafeMode = SafeMode.False }; var mongoServer = new MongoServer(settings); var database = mongoServer.GetDatabase("Test"); var map = new NoteMap(); var collection = new EntityCollection<Note>(database, map.GetDescriptor(), true); var note = new Note { NoteID = "1", Title = "This is a book.", Content = "Oh yeah", UserID = 123321L }; // collection.InsertOnSubmit(note); // collection.SubmitChanges(); // var data = collection.SelectTo(n => new { n.NoteID, n.UserID }); collection.Log = Console.Out; var a = 4; collection.Update( n => new Note { }, n => true); }
public NewItemWindow(Note source) : this() { Title = "Edit Note"; NoteEditControl.SourceNote = source; }
public static DialogResult showDialog( Form parent, Note note, bool fCanDelete ) { using ( FNote dlg = new FNote() ) { dlg.cmdDelete.Visible = fCanDelete; foreach ( string s in Directory.GetDirectories( Global.Preferences.MainPath ) ) { int i; if ( int.TryParse( s.Substring( s.LastIndexOf('_') + 1 ), out i ) ) if ( i > 400000 ) dlg.cboOrder.Items.Add( i.ToString() ); } if ( note.RegardingDate != DateTime.MinValue ) dlg.dtp.Date = note.RegardingDate; if ( note.OrderNumber != 0 ) dlg.cboOrder.Text = note.OrderNumber.ToString(); dlg.txt.Text = note.Text; DialogResult retVal = dlg.ShowDialog( parent ); if ( retVal == DialogResult.OK ) { note.Text = dlg.txt.Text; note.RegardingDate = dlg.optDatum.Checked ? dlg.dtp.Date : DateTime.MinValue; int.TryParse( dlg.cboOrder.Text, out note.OrderNumber ); } return retVal; } }
private bool ParseNoteBeat(IXmlNode element, Track track, Bar bar, bool chord, bool isFirstBeat) { int voiceIndex = 0; var voiceNodes = element.GetElementsByTagName("voice"); if (voiceNodes.Count > 0) { voiceIndex = Std.ParseInt(Std.GetNodeValue(voiceNodes.Get(0))) - 1; } Beat beat; var voice = GetOrCreateVoice(bar, voiceIndex); if (chord || (isFirstBeat && voice.Beats.Count == 1)) { beat = voice.Beats[voice.Beats.Count - 1]; } else { beat = new Beat(); voice.AddBeat(beat); } var note = new Note(); beat.AddNote(note); beat.IsEmpty = false; element.IterateChildren(c => { if (c.NodeType == XmlNodeType.Element) { switch (c.LocalName) { case "grace": //var slash = e.GetAttribute("slash"); //var makeTime = Std.ParseInt(e.GetAttribute("make-time")); //var stealTimePrevious = Std.ParseInt(e.GetAttribute("steal-time-previous")); //var stealTimeFollowing = Std.ParseInt(e.GetAttribute("steal-time-following")); beat.GraceType = GraceType.BeforeBeat; beat.Duration = Duration.ThirtySecond; break; case "duration": beat.Duration = (Duration)Std.ParseInt(Std.GetNodeValue(c)); break; case "tie": ParseTied(c, note); break; case "cue": // not supported break; case "instrument": // not supported break; case "type": switch (Std.GetNodeValue(c)) { //case "256th": // break; //case "128th": // break; //case "breve": // break; //case "long": // break; case "64th": beat.Duration = Duration.SixtyFourth; break; case "32nd": beat.Duration = Duration.ThirtySecond; break; case "16th": beat.Duration = Duration.Sixteenth; break; case "eighth": beat.Duration = Duration.Eighth; break; case "quarter": beat.Duration = Duration.Quarter; break; case "half": beat.Duration = Duration.Half; break; case "whole": beat.Duration = Duration.Whole; break; } break; case "dot": note.IsStaccato = true; break; case "accidental": ParseAccidental(c, note); break; case "time-modification": ParseTimeModification(c, beat); break; case "stem": // not supported break; case "notehead": if (c.GetAttribute("parentheses") == "yes") { note.IsGhost = true; } break; case "beam": // not supported break; case "notations": ParseNotations(c, beat, note); break; case "lyric": // not supported break; // "full-note" case "chord": chord = true; break; case "pitch": ParsePitch(c, track, beat, note); break; case "unpitched": // TODO: not yet fully supported note.String = 0; note.Fret = 0; break; case "rest": beat.IsEmpty = false; break; } } }); return(chord); }
public static int GetTomMask(Note note) { return(note.GetMaskWithRequiredFlags(Note.Flags.None)); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); Guid? groupGuid = null; Person person = null; Group group = null; string noteValue = string.Empty; string captionValue = string.Empty; bool isAlert = false; // get the group attribute Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid(); if (!groupAttributeGuid.IsEmpty()) { groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull(); if (groupGuid.HasValue) { group = new GroupService(rockContext).Get(groupGuid.Value); if (group == null) { errorMessages.Add("The group provided does not exist."); } } else { errorMessages.Add("Invalid group provided."); } } // get person alias guid Guid personAliasGuid = Guid.Empty; string personAttribute = GetAttributeValue(action, "Person"); Guid guid = personAttribute.AsGuid(); if (!guid.IsEmpty()) { var attribute = AttributeCache.Read(guid, rockContext); if (attribute != null) { string value = action.GetWorklowAttributeValue(guid); personAliasGuid = value.AsGuid(); } if (personAliasGuid != Guid.Empty) { person = new PersonAliasService(rockContext).Queryable() .Where(p => p.Guid.Equals(personAliasGuid)) .Select(p => p.Person) .FirstOrDefault(); } else { errorMessages.Add("The person could not be found!"); } } // get caption captionValue = GetAttributeValue(action, "Caption"); guid = captionValue.AsGuid(); if (guid.IsEmpty()) { captionValue = captionValue.ResolveMergeFields(GetMergeFields(action)); } else { var workflowAttributeValue = action.GetWorklowAttributeValue(guid); if (workflowAttributeValue != null) { captionValue = workflowAttributeValue; } } // get group member note noteValue = GetAttributeValue(action, "Note"); guid = noteValue.AsGuid(); if (guid.IsEmpty()) { noteValue = noteValue.ResolveMergeFields(GetMergeFields(action)); } else { var workflowAttributeValue = action.GetWorklowAttributeValue(guid); if (workflowAttributeValue != null) { noteValue = workflowAttributeValue; } } // get alert type string isAlertString = GetAttributeValue(action, "IsAlert"); guid = isAlertString.AsGuid(); if (guid.IsEmpty()) { isAlert = isAlertString.AsBoolean(); } else { var workflowAttributeValue = action.GetWorklowAttributeValue(guid); if (workflowAttributeValue != null) { isAlert = workflowAttributeValue.AsBoolean(); } } // get note type NoteTypeCache noteType = null; Guid noteTypeGuid = GetAttributeValue(action, "NoteType").AsGuid(); if (!noteTypeGuid.IsEmpty()) { noteType = NoteTypeCache.Read(noteTypeGuid, rockContext); if (noteType == null) { errorMessages.Add("The note type provided does not exist."); } } else { errorMessages.Add("Invalid note type provided."); } // set note if (group != null && person != null && noteType != null) { var groupMembers = new GroupMemberService(rockContext).Queryable() .Where(m => m.Group.Guid == groupGuid && m.PersonId == person.Id).ToList(); if (groupMembers.Count() > 0) { foreach (var groupMember in groupMembers) { NoteService noteservice = new NoteService(rockContext); Note note = new Note(); noteservice.Add(note); note.NoteTypeId = noteType.Id; note.Text = noteValue; note.IsAlert = isAlert; note.Caption = captionValue; note.EntityId = groupMember.Id; rockContext.SaveChanges(); } } else { errorMessages.Add(string.Format("{0} is not a member of the group {1}.", person.FullName, group.Name)); } } errorMessages.ForEach(m => action.AddLogEntry(m, true)); return(true); }
private async Task <Note> FindNoteById(int id) { Note note = await noteWorkflow.FindNoteById(id); return(note); }
private NoteDto MapNoteToDto(Note note) { return(mapper.Map <NoteDto>(note)); }
public async Task <NoteDto> FindNoteDtoById(int id) { Note note = await noteWorkflow.FindNoteById(id); return(MapNoteToDto(note)); }
private void ApplyNoteStringFrets(Track track, Beat beat, Note note, int fullNoteValue) { note.String = FindStringForValue(track, beat, fullNoteValue); note.Fret = fullNoteValue - Note.GetStringTuning(track, note.String); }
public bool IsInViewport(Note note) { return(note.StartBeat <= MaxBeatInViewport && note.EndBeat >= MinBeatInViewport && note.MidiNote <= MaxMidiNoteInViewport && note.MidiNote >= MinMidiNoteInViewport); }
public void Update(Note note) { notes[note.Id] = note; }
public MoveUpEventArgs(Note note) { Note = note; }
public void SaveNote() { note1.Save(); //save data to database note2 = new Note("test1"); //get data from database Assert.True(note1.GetValue("title") == "test1"); //compare data }
public IActionResult NotesEdit(int id) { Note model = id == default ? new Note() : notesRepository.GetNoteById(id); return(View(model)); }
public void ReadArtificialHarmonic(Note note) { var type = Data.ReadByte(); if (_versionNumber >= 500) { switch (type) { case 1: note.HarmonicType = HarmonicType.Natural; note.HarmonicValue = DeltaFretToHarmonicValue(note.Fret); break; case 2: // ReSharper disable UnusedVariable var harmonicTone = Data.ReadByte(); var harmonicKey = Data.ReadByte(); var harmonicOctaveOffset = Data.ReadByte(); note.HarmonicType = HarmonicType.Artificial; // ReSharper restore UnusedVariable break; // TODO: how to calculate the harmonic value? case 3: note.HarmonicType = HarmonicType.Tap; note.HarmonicValue = DeltaFretToHarmonicValue(Data.ReadByte()); break; case 4: note.HarmonicType = HarmonicType.Pinch; note.HarmonicValue = 12; break; case 5: note.HarmonicType = HarmonicType.Semi; note.HarmonicValue = 12; break; } } else if (_versionNumber >= 400) { switch (type) { case 1: note.HarmonicType = HarmonicType.Natural; break; case 3: note.HarmonicType = HarmonicType.Tap; break; case 4: note.HarmonicType = HarmonicType.Pinch; break; case 5: note.HarmonicType = HarmonicType.Semi; break; case 15: note.HarmonicType = HarmonicType.Artificial; break; case 17: note.HarmonicType = HarmonicType.Artificial; break; case 22: note.HarmonicType = HarmonicType.Artificial; break; } } }
public Note Add(Note note) { note.Id = (notes.Keys.Count > 0) ? notes.Keys.Max() + 1 : 1; notes.Add(note.Id, note); return(note); }
public void ReadNoteEffects(Track track, Voice voice, Beat beat, Note note) { var flags = Data.ReadByte(); var flags2 = 0; if (_versionNumber >= 400) { flags2 = Data.ReadByte(); } if ((flags & 0x01) != 0) { ReadBend(note); } if ((flags & 0x10) != 0) { ReadGrace(voice, note); } if ((flags2 & 0x04) != 0) { ReadTremoloPicking(beat); } if ((flags2 & 0x08) != 0) { ReadSlide(note); } else if (_versionNumber < 400) { if ((flags & 0x04) != 0) { note.SlideType = SlideType.Shift; } } if ((flags2 & 0x10) != 0) { ReadArtificialHarmonic(note); } else if (_versionNumber < 400) { if ((flags & 0x04) != 0) { note.HarmonicType = HarmonicType.Natural; note.HarmonicValue = DeltaFretToHarmonicValue(note.Fret); } if ((flags & 0x08) != 0) { note.HarmonicType = HarmonicType.Artificial; } } if ((flags2 & 0x20) != 0) { ReadTrill(note); } note.IsLetRing = (flags & 0x08) != 0; note.IsHammerPullOrigin = (flags & 0x02) != 0; if ((flags2 & 0x40) != 0) { note.Vibrato = VibratoType.Slight; } note.IsPalmMute = (flags2 & 0x02) != 0; note.IsStaccato = (flags2 & 0x01) != 0; }
public void Setup() { note1 = new Note("1", "test1", "02-02-2020", "testing", "testing Environment", true); }
/// <summary> /// Basic Integration test for Notes /// </summary> public async Task TestNotesBasic() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/notes"); // create a new object. Note note = new Note(); note.Text = initialName; string jsonString = note.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); note = JsonConvert.DeserializeObject <Note>(jsonString); // get the id var id = note.Id; // change the name note.Text = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/notes/" + id); request.Content = new StringContent(note.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/notes/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); note = JsonConvert.DeserializeObject <Note>(jsonString); // verify the change went through. Assert.Equal(note.Text, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/notes/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/notes/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); }
public void ReadSlide(Note note) { if (_versionNumber >= 500) { var type = Data.ReadSignedByte(); switch (type) { case 1: note.SlideType = SlideType.Shift; break; case 2: note.SlideType = SlideType.Legato; break; case 4: note.SlideType = SlideType.OutDown; break; case 8: note.SlideType = SlideType.OutUp; break; case 16: note.SlideType = SlideType.IntoFromBelow; break; case 32: note.SlideType = SlideType.IntoFromAbove; break; default: note.SlideType = SlideType.None; break; } } else { var type = Data.ReadSignedByte(); switch (type) { case 1: note.SlideType = SlideType.Shift; break; case 2: note.SlideType = SlideType.Legato; break; case 3: note.SlideType = SlideType.OutDown; break; case 4: note.SlideType = SlideType.OutUp; break; case -1: note.SlideType = SlideType.IntoFromBelow; break; case -2: note.SlideType = SlideType.IntoFromAbove; break; default: note.SlideType = SlideType.None; break; } } }
private void AddSongComponentToSong(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { //Als er nog geen noot op de posisitie is zal er een nieuwe bijgetekend worden if (EditorHelper.ValidateDoubleInput(ListWithSongComponents, MouseX, MouseY)) { ListWithSongComponents.Add(new Note(Note.GetNoteLetterFromY(MouseY), Note.GetOctaveFromY(MouseY), false, ComponentLength.QUARTER, MouseX)); ListWithSongComponents = ListWithSongComponents.OrderBy(x => x.X).ToList(); } } if (e.Button == MouseButtons.Right) { //Open een submenu waar noten verandert kunnen worden LastMouseXForContextMenu = e.X / EditorHelper.NOTE_FULL_WIDTH; LastMouseYForContextMenu = e.Y / EditorHelper.LINE_PADDING_VERTICAL; CreateMyMenu(); } }
public void ReadNote(Track track, Bar bar, Voice voice, Beat beat, int stringIndex) { var newNote = new Note(); newNote.String = bar.Staff.Tuning.Length - stringIndex; var flags = Data.ReadByte(); if ((flags & 0x02) != 0) { newNote.Accentuated = AccentuationType.Heavy; } else if ((flags & 0x40) != 0) { newNote.Accentuated = AccentuationType.Normal; } newNote.IsGhost = ((flags & 0x04) != 0); if ((flags & 0x20) != 0) { var noteType = Data.ReadByte(); if (noteType == 3) { newNote.IsDead = true; } else if (noteType == 2) { newNote.IsTieDestination = true; } } if ((flags & 0x01) != 0 && _versionNumber < 500) { Data.ReadByte(); // duration Data.ReadByte(); // tuplet } if ((flags & 0x10) != 0) { var dynamicNumber = Data.ReadSignedByte(); newNote.Dynamic = ToDynamicValue(dynamicNumber); beat.Dynamic = newNote.Dynamic; } if ((flags & 0x20) != 0) { newNote.Fret = Data.ReadSignedByte(); } if ((flags & 0x80) != 0) { newNote.LeftHandFinger = (Fingers)Data.ReadSignedByte(); newNote.RightHandFinger = (Fingers)Data.ReadSignedByte(); newNote.IsFingering = true; } if (_versionNumber >= 500) { if ((flags & 0x01) != 0) { newNote.DurationPercent = Data.GpReadDouble(); } var flags2 = Data.ReadByte(); newNote.AccidentalMode = (flags2 & 0x02) != 0 ? NoteAccidentalMode.SwapAccidentals : NoteAccidentalMode.Default; } beat.AddNote(newNote); if ((flags & 0x08) != 0) { ReadNoteEffects(track, voice, beat, newNote); } }
private Sequence GetSequenceFromWPFStaffs(List <MusicalSymbol> WPFStaffs, int bpm, int beatNote, int beatsPerBar) { List <string> notesOrderWithCrosses = new List <string>() { "c", "cis", "d", "dis", "e", "f", "fis", "g", "gis", "a", "ais", "b" }; int absoluteTicks = 0; Sequence sequence = new Sequence(); Track metaTrack = new Track(); sequence.Add(metaTrack); // Calculate tempo int speed = 60000000 / bpm; byte[] tempo = new byte[3]; tempo[0] = (byte)((speed >> 16) & 0xff); tempo[1] = (byte)((speed >> 8) & 0xff); tempo[2] = (byte)(speed & 0xff); metaTrack.Insert(0 /* Insert at 0 ticks*/, new MetaMessage(MetaType.Tempo, tempo)); Track notesTrack = new Track(); sequence.Add(notesTrack); for (int i = 0; i < WPFStaffs.Count; i++) { var musicalSymbol = WPFStaffs[i]; switch (musicalSymbol.Type) { case MusicalSymbolType.Note: Note note = musicalSymbol as Note; // Calculate duration double absoluteLength = 1.0 / (double)note.Duration; absoluteLength += (absoluteLength / 2.0) * note.NumberOfDots; double relationToQuartNote = beatNote / 4.0; double percentageOfBeatNote = 1.0 / beatNote / absoluteLength; double deltaTicks = (sequence.Division / relationToQuartNote) / percentageOfBeatNote; // Calculate height int noteHeight = notesOrderWithCrosses.IndexOf(note.Step.ToLower()) + ((note.Octave + 1) * 12); noteHeight += note.Alter; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 90)); // Data2 = volume absoluteTicks += (int)deltaTicks; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 0)); // Data2 = volume break; case MusicalSymbolType.TimeSignature: byte[] timeSignature = new byte[4]; timeSignature[0] = (byte)beatsPerBar; timeSignature[1] = (byte)(Math.Log(beatNote) / Math.Log(2)); metaTrack.Insert(absoluteTicks, new MetaMessage(MetaType.TimeSignature, timeSignature)); break; default: break; } } notesTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); metaTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); return(sequence); }
public static HarpNote From(Note note) { return(Map[$"{note.Key}{note.Octave}"]); }
// Update is called once per frame protected override void Update() { if (editor.currentState != ChartEditor.State.Editor) { return; } if (movingSongObjects.Count > 0) { if (Input.GetMouseButtonUp(0)) { CompleteMoveAction(); } else { UpdateSnappedPos(); //Debug.Log("Group move: " + editor.services.mouseMonitorSystem.world2DPosition); if (editor.services.mouseMonitorSystem.world2DPosition != null) { Vector2 mousePosition = (Vector2)editor.services.mouseMonitorSystem.world2DPosition; int chartPosOffset = (int)(objectSnappedChartPos - initObjectSnappedChartPos); if (anchorArrayPos >= 0) { chartPosOffset = (int)(objectSnappedChartPos - originalSongObjects[anchorArrayPos].tick); } //Debug.Log(anchorArrayPos); bool hitStartOfChart = false; // Guard for chart limit, if the offset was negative, yet the position becomes greater if (movingSongObjects.Count > 0 && chartPosOffset < 0 && (uint)((int)originalSongObjects[0].tick + chartPosOffset) > originalSongObjects[0].tick) { hitStartOfChart = true; } // Update the new positions of all the notes that have been moved for (int i = 0; i < movingSongObjects.Count; ++i) { // Alter X position if ((SongObject.ID)movingSongObjects[i].classID == SongObject.ID.Note) { Note note = movingSongObjects[i] as Note; if (!note.IsOpenNote()) { float position = NoteController.GetXPos(0, originalSongObjects[i] as Note) + (mousePosition.x - initMousePos.x); // Offset note.rawNote = PlaceNote.XPosToNoteNumber(position, editor.laneInfo); } } // Alter chart position if (!hitStartOfChart) { movingSongObjects[i].tick = (uint)((int)originalSongObjects[i].tick + chartPosOffset); } else { movingSongObjects[i].tick = originalSongObjects[i].tick - originalSongObjects[0].tick; } if (movingSongObjects[i].controller) { movingSongObjects[i].controller.SetDirty(); } } } // Enable objects into the pool editor.songObjectPoolManager.EnableNotes(notesToEnable); editor.songObjectPoolManager.EnableSP(starpowerToEnable); editor.songObjectPoolManager.EnableChartEvents(chartEventsToEnable); editor.songObjectPoolManager.EnableBPM(bpmsToEnable); editor.songObjectPoolManager.EnableTS(timeSignaturesToEnable); editor.songObjectPoolManager.EnableSections(sectionsToEnable); editor.songObjectPoolManager.EnableSongEvents(eventsToEnable); } } }
public HomeControllerTest() { // Lets create some sample notebooks // Notebook 1 does not has a current note notebook1 = new NoteBook { NotebookId = 1, Email = "*****@*****.**", CreateDate = DateTime.Now, CurrentNote = null }; // Notebook 2 has a current note that is valid notebook2 = new NoteBook { NotebookId = 2, Email = "*****@*****.**", CreateDate = DateTime.Now, CurrentNote = 22 }; // Notebook 3 has a current note that does not exist on the note list notebook3 = new NoteBook { NotebookId = 3, Email = "*****@*****.**", CreateDate = DateTime.Now, CurrentNote = 333 }; //Notebook 4 has no assoicated notes notebook4 = new NoteBook { NotebookId = 4, Email = "*****@*****.**", CreateDate = DateTime.Now, CurrentNote = null }; //Notebook 5 does not exist on the notebook list and has no assoicated notes notebook5 = new NoteBook { NotebookId = 5, Email = "*****@*****.**", CreateDate = DateTime.Now, CurrentNote = null }; notebookList = new List <NoteBook> { notebook1, notebook2, notebook3, notebook4 }; // Lets create some sample notes and notebooks note1 = new Note { NoteBookId = 1, NoteId = 10, Subject = "10", NoteText = "10", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; note2 = new Note { NoteBookId = 2, NoteId = 22, Subject = "22", NoteText = "22", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; note3 = new Note { NoteBookId = 3, NoteId = 33, Subject = "33", NoteText = "33", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; note4 = new Note { NoteBookId = 1, NoteId = 14, Subject = "14", NoteText = "14", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; note5 = new Note { NoteBookId = 1, NoteId = 13, Subject = "c", NoteText = "d", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }; noteList = new List <Note> { note1, note2, note3, note4, new Note { NoteBookId = 1, NoteId = 15, Subject = "15", NoteText = "15", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 2, NoteId = 21, Subject = "21", NoteText = "21", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 3, NoteId = 16, Subject = "26", NoteText = "16", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 1, NoteId = 17, Subject = "e", NoteText = "f", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 2, NoteId = 28, Subject = "g", NoteText = "h", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 3, NoteId = 30, Subject = "30", NoteText = "30", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 1, NoteId = 19, Subject = "19", NoteText = "19", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 2, NoteId = 24, Subject = "24", NoteText = "24", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, new Note { NoteBookId = 2, NoteId = 25, Subject = "25", NoteText = "25", CreateDate = DateTime.Now, UpdateDate = DateTime.Now }, }; // Lets create our dummy repository notebooksRepo = new DummyNotebooksRepository(notebookList); noteRepo = new DummyNoteRepository(noteList); // Let us now create the Unit of work with our dummy repository dataRepo = new DataRepository(notebooksRepo, noteRepo); // Now lets create the BooksController object to test and pass our unit of work controller = new HomeController(dataRepo); noteRepo.SetNotebook(notebookList); }
public DrumsNoteHitKnowledge(Note note) : base(note) { standardPadTiming = new InputTiming(); cymbalPadTiming = new InputTiming(); }
public INoteCore CreateNote(string id) { return(Note.CreateNote(id, noteRepo)); }
/// <summary> /// Map data /// </summary> /// <param name="dbContext"></param> /// <param name="oldObject"></param> /// <param name="instance"></param> /// <param name="systemId"></param> private static void CopyToInstance(DbAppContext dbContext, Project oldObject, ref Models.Project instance, string systemId) { if (oldObject.Project_Id <= 0) { return; } // add the user specified in oldObject.Modified_By and oldObject.Created_By if not there in the database User modifiedBy = ImportUtility.AddUserFromString(dbContext, "", systemId); User createdBy = ImportUtility.AddUserFromString(dbContext, oldObject.Created_By, systemId); if (instance == null) { instance = new Models.Project { Id = oldObject.Project_Id }; try { try { //4 properties instance.ProvincialProjectNumber = oldObject.Project_Num; ServiceArea serviceArea = dbContext.ServiceAreas.FirstOrDefault(x => x.Id == oldObject.Service_Area_Id); District dis = dbContext.Districts.FirstOrDefault(x => x.Id == serviceArea.DistrictId); if (dis != null) { instance.District = dis; instance.DistrictId = dis.Id; } else { // this means that the District Id is not in the database // (happens when the production data does not include district Other than "Lower Mainland" or all the districts) return; } } catch { // do nothing } try { instance.Name = oldObject.Job_Desc1; } catch { // do nothing } try { instance.Information = oldObject.Job_Desc2; } catch { // do nothing } try { instance.Notes = new List <Note>(); Note note = new Note { Text = new string(oldObject.Job_Desc2.Take(2048).ToArray()), IsNoLongerRelevant = true }; instance.Notes.Add(note); } catch { // do nothing } try { instance.CreateTimestamp = DateTime.ParseExact(oldObject.Created_Dt.Trim().Substring(0, 10), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); } catch { instance.CreateTimestamp = DateTime.UtcNow; } instance.CreateUserid = createdBy.SmUserId; } catch { // do nothing } dbContext.Projects.Add(instance); } else { instance = dbContext.Projects.First(x => x.Id == oldObject.Project_Id); instance.LastUpdateUserid = modifiedBy.SmUserId; instance.LastUpdateTimestamp = DateTime.UtcNow; dbContext.Projects.Update(instance); } }
public void SaveNote(Note note) { _context.Entry(note).State = note.Id == 0 || note.Id == default ? EntityState.Added : EntityState.Modified; _context.SaveChanges(); }
public NoteTag(Note note, Tag tag) { Note = note ?? throw new ArgumentNullException(nameof(note)); Tag = tag ?? throw new ArgumentNullException(nameof(tag)); }
public void Aggregates_should_be_persisted_in_one_transaction() { var factory = new AbsoluteOrderingSqlPersistenceFactory("SqlJoesEventStore", new BinarySerializer(), true); var streamPersister = factory.Build(); streamPersister.Initialize(); var store = new OptimisticEventStore(streamPersister, new NullDispatcher()); var uowFactory = new JoesUnitOfWorkFactory(store); NcqrsEnvironment.SetDefault <IUnitOfWorkFactory>(uowFactory); var note1Id = Guid.NewGuid(); var note2Id = Guid.NewGuid(); //Create using (var uow = uowFactory.CreateUnitOfWork(Guid.NewGuid())) { var note1 = new Note(note1Id, "Text 1"); var note2 = new Note(note2Id, "Text 2"); uow.Accept(); } try { using (var tx = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted })) { using (var uow = uowFactory.CreateUnitOfWork(Guid.NewGuid())) { var note1 = (Note)uow.GetById(typeof(Note), note1Id, null); note1.ChangeText("Text 1 Modified"); var note2 = (Note)uow.GetById(typeof(Note), note2Id, null); note2.ChangeText("Text 2 Modified"); var t = new Thread(() => { using (var nestedUow = uowFactory.CreateUnitOfWork(Guid.NewGuid())) { note2 = (Note)nestedUow.GetById(typeof(Note), note2Id, null); note2.ChangeText("Text 2 Modified from mested UoW"); nestedUow.Accept(); } }); t.Start(); t.Join(); uow.Accept(); //Throws } tx.Complete(); } } catch (Exception) { //Swallow } //Nothing should be modified using (var uow = uowFactory.CreateUnitOfWork(Guid.NewGuid())) { var note1 = (Note)uow.GetById(typeof(Note), note1Id, null); note1.Text.Should().Be("Text 1"); var note2 = (Note)uow.GetById(typeof(Note), note2Id, null); note2.Text.Should().Be("Text 2 Modified from mested UoW"); } }