private void InsUpdDelBranch(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { DateTime date = ConvertNE.convertNepaliToEnglish(txtoperationstartdate.Text); var objBranch = new Branch(id, txtbranchname.Text, txtbranchcode.Text, txtaddress.Text, txtemailid.Text, txttelno.Text, txtcontactpersonname.Text, date, chkismain.Checked); msg = BL_Branch.InsUpdDelBranch(Event, objBranch, out id); } else { var objBranch = new Branch(id, "", "", "", "", "", "", Convert.ToDateTime("01/01/1753"), true); msg = BL_Branch.InsUpdDelBranch(Event, objBranch, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
private void InsUpdDelStore(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objColor = new Store(id, int.Parse(txtStoreNo.Text), txtStoreName.Text); msg = BL_Store.InsUpdDelStore(Event, objColor, out id); } else { var objColor = new Store(id, 0, ""); msg = BL_Store.InsUpdDelStore(Event, objColor, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
private void InsUpdDelColor(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objColor = new Color(id, Convert.ToInt32((string)ddlCategory.SelectedValue), Convert.ToInt32((string)ddlStyle.SelectedValue), txtColorCode.Text, txtColorName.Text); msg = BL_Color.InsUpdDelColor(Event, objColor, out id); } else { var objColor = new Color(id, 0, 0, "", ""); msg = BL_Color.InsUpdDelColor(Event, objColor, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
/// <summary> /// We need to ask the current primary to quit taking write ops /// so that the left over ops can first be replicated /// before the actual election mechanism begins. /// </summary> /// <returns></returns> private bool RequestPrimaryToStopOperations() { ShardConfiguration sConfg = null; bool endResult = false; if (_clusterConfigMgr != null) { sConfg = _clusterConfigMgr.GetShardConfiguration(_context.LocalShardName); } if (sConfg != null) { MembershipChangeArgs args = new MembershipChangeArgs(); args.ChangeType = MembershipChangeArgs.MembershipChangeType.RestrictPrimary; args.ServerName = _context.LocalAddress; args.ElectionId = _latestMembership.ElectionId; DatabaseMessage msg = new DatabaseMessage(); msg.Payload = args; msg.NeedsResponse = true; msg.OpCode = OpCode.RestrictPrimary; msg.MessageType = MessageType.DBOperation; ShardRequestBase <bool> request = _shard.CreateUnicastRequest <bool>(new Server(new Address(_latestMembership.Primary.Name, sConfg.Port), Status.Running), msg); IAsyncResult result = request.BeginExecute(); endResult = request.EndExecute(result); if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsInfoEnabled) { LoggerManager.Instance.ShardLogger.Info("MembershipMgr.RequestPrimaryToStopOperations()", "Requested primary to stop taking write operations. Primary response: " + endResult.ToString()); } } return(endResult); }
void OnTabsChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (TabViewModel tab in e.NewItems) { Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Add(tab.Model)); Configuration.AvailableTabs.Add(tab.Title); } break; case NotifyCollectionChangedAction.Remove: foreach (TabViewModel tab in e.OldItems) { Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Remove(tab.Model)); Configuration.AvailableTabs.Remove(tab.Title); Messenger.Default.Unregister(tab); // Removing items one-by-one so that the NotifyCollectionChangedAction.Remove // event is fired for each of them in the Applications collection. foreach (var application in tab.Applications.ToList()) { tab.Applications.Remove(application); } } break; case NotifyCollectionChangedAction.Move: // TODO: break; } }
void Edit(TabViewModel toEdit) { if (toEdit == null) { throw new ArgumentNullException("toEdit"); } TabViewModel editTab = new TabViewModel(); editTab.UpdateWith(toEdit); ServiceManager.GetService <IViewService>().OpenDialog(editTab); if (editTab.Result != MessageResult.Okay) { return; // Cancelled edit } if (!editTab.Title.Equals(toEdit.Title, StringComparison.InvariantCultureIgnoreCase)) { // Tab title changed, check if any other tabs have this title. if (Tabs.Any(t => t.Title == editTab.Title)) { ServiceManager.GetService <IMessageBoxService>().Show( "Tab wit that title already exists", "Astounding Dock", MessageIcon.Error); // Re-open dialog. Edit(toEdit); return; } } toEdit.UpdateWith(editTab); Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Update(toEdit.Model)); }
private void InsUpdDelKnittingSubCategory(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objKnitting = new KnittingSubCategory(id, int.Parse(ddlCategory.SelectedValue), "", txtSubCategoryName.Text); msg = BL_Knitting_SubCategory.InsUpdDelKnittingSubCategory(Event, objKnitting, out id); } else { var objKnitting = new KnittingSubCategory(id, int.Parse(ddlCategory.SelectedValue), "", ""); msg = BL_Knitting_SubCategory.InsUpdDelKnittingSubCategory(Event, objKnitting, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
void ReorderTabs(TabViewModel tab, bool moveUp) { if (moveUp && tab.TabOrder == 1) { return; } if (!moveUp && tab.TabOrder == Tabs.Max(x => x.TabOrder)) { return; } int currentPosition = Tabs.IndexOf(tab); int newPosition = moveUp ? currentPosition - 1 : currentPosition + 1; Tabs.Move(currentPosition, newPosition); int tabOrder = 1; foreach (var item in Tabs) { item.TabOrder = tabOrder; tabOrder++; Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Update(item.Model)); } // Refresh the view to reapply the sort TabsView.Refresh(); }
private void InsUpdDelGender(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objGender = new GenderClass(id, txtGender.Text); msg = BL_Gender.InsUpdDelGender(Event, objGender, out id); } else { var objGender = new GenderClass(id, ""); msg = BL_Gender.InsUpdDelGender(Event, objGender, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgBox.ShowSuccess(msg); } else { _msgBox.ShowWarning(msg); } FillGridView(); ClearAll(); }
/// <summary> /// Update a record in the connected Database server /// </summary> /// <param name="record">New contains of Record</param> public void Update(DataRecord record) { byte[] sendbuffer = record.ToBytes(); sendbuffer[0] = (byte)DatabaseMessage.Comm_Update; Client.Send(sendbuffer); // Listen for Response byte[] recvbuffer = new byte[Shared.kMaxNetBuffer]; if (Client.Receive(recvbuffer) > 0) { DatabaseMessage message = (DatabaseMessage)recvbuffer[0]; if (message == DatabaseMessage.Error_InvalidArgs) { throw new ArgumentException(); } else if (message == DatabaseMessage.Error_OutOfMemory) { throw new OutOfMemoryException(); } else if (message == DatabaseMessage.Error_DatabaseError) { throw new DatabaseException(); } } }
void OnApplicationsChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (ApplicationViewModel application in e.NewItems) { Log.DebugFormat("Adding {0}", application.Title); //IsExpanded = true; application.Tab = Title; Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Add(application.Model)); } break; case NotifyCollectionChangedAction.Remove: foreach (ApplicationViewModel application in e.OldItems) { Log.DebugFormat("Removing {0}", application.Title); Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Remove(application.Model)); } break; case NotifyCollectionChangedAction.Move: // TODO: Probably should save application positions? break; } }
private static string GetMessage(Message.Enum en, string languageCode) { languageCode = string.IsNullOrWhiteSpace(languageCode) ? Message.LanguageCode.VI : languageCode; Message message = DatabaseMessage.Get(languageCode, en); return(message != null ? message.message : null); }
private void InsUpdDelKnittingCategory(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objKnittingCategory = new KnittingCategory(id, txtCategoryName.Text); msg = BL_Knitting_Category.InsUpdDelKnittingCategory(Event, objKnittingCategory, out id); } else { var objKnittingCategory = new KnittingCategory(id, ""); msg = BL_Knitting_Category.InsUpdDelKnittingCategory(Event, objKnittingCategory, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
private void InsUpdDelStaffInfo(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { // var session=new BK_Session(int userId,) var objStaff = new Staff(id, Convert.ToInt32(BK_Session.GetSession().UserId), Convert.ToInt32((string)ddl_branch.SelectedValue), txtStaffName.Text, Convert.ToInt32((string)ddlDesignation.SelectedValue), txtAddress.Text, txtContactNo.Text, txtEmail.Text, Convert.ToInt32((string)ddlQualification.SelectedValue), txtRemarks.Text, true, Convert.ToDateTime(BK_Session.GetSession().OpDate), Convert.ToInt32((string)ddlGender.SelectedValue), Convert.ToDateTime(txtJobStartDate.Text), Convert.ToInt32((string)ddlTitle.SelectedValue), Convert.ToDateTime("01/01/1991"), Convert.ToDateTime("01/01/1991"), Convert.ToDateTime(txtDOB.Text), txtCitizenNo.Text, txtPpNo.Text, Convert.ToInt32((string)ddlDepartment.SelectedValue), Convert.ToInt32((string)ddlmaritalstatus.SelectedValue), Convert.ToInt32((string)ddlServiceType.SelectedValue), Convert.ToInt32((string)ddlEthnicGroups.SelectedValue)); msg = BL_Staff.InsUpdDelStaffInfo(Event, objStaff, out id); } else if (Event == 'N') { var objStaff = new Staff(id, 0, 0, "", 0, "", "", "", 0, "", false, Convert.ToDateTime("01/01/1991"), 0, Convert.ToDateTime("01/01/1991"), 0, Convert.ToDateTime("01/01/1991"), Convert.ToDateTime("01/01/1991"), Convert.ToDateTime("01/01/1991"), "", "", 0, 0, 0, 0); msg = BL_Staff.UpdStaffToInactive(Event, objStaff, out id); } else { var objStaff = new Staff(id, 0, 0, "", 0, "", "", "", 0, "", false, Convert.ToDateTime("01/01/1991"), 0, Convert.ToDateTime("01/01/1991"), 0, Convert.ToDateTime("01/01/1991"), Convert.ToDateTime("01/01/1991"), Convert.ToDateTime("01/01/1991"), "", "", 0, 0, 0, 0); msg = BL_Staff.InsUpdDelStaffInfo(Event, objStaff, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
private void InsUpdDelSize(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objSize = new SizeClass(id, txtSize.Text); msg = BL_Size.InsUpdDelSize(Event, objSize, out id); } else { var objSize = new SizeClass(id, ""); msg = BL_Size.InsUpdDelSize(Event, objSize, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
private void InsUpdDelTheme(char Event, int id) { var msg = ""; if (Event == 'I' || Event == 'U') { var objTheme = new ThemeSetup(id, txtCategoryName.Text); msg = BL_Theme.InsUpdDelTheme(Event, objTheme, out id); } else { var objTheme = new ThemeSetup(id, ""); msg = BL_Theme.InsUpdDelTheme(Event, objTheme, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } FillGridview(); ClearAll(); }
void OnDatabaseMessage(DatabaseMessage message) { try { switch (message.Action) { case DatabaseMessage.ActionType.Add: if (message.Application != null) { Add(message.Application); } else if (message.Tab != null) { Add(message.Tab); } break; case DatabaseMessage.ActionType.Remove: if (message.Application != null) { Remove(message.Application); } else if (message.Tab != null) { Remove(message.Tab); } break; case DatabaseMessage.ActionType.Update: if (message.Application != null) { Update(message.Application); } else if (message.Tab != null) { Update(message.Tab); } break; case DatabaseMessage.ActionType.Move: if (message.Tab != null && message.TabB != null) { Move(message.Tab, message.TabB); } break; case DatabaseMessage.ActionType.Save: DoSave(); break; } // Save changes. Save(); } catch (Exception ex) { Log.FatalFormat("Database exception {0}", ex); } }
void OnApplicationExit(object sender, ExitEventArgs e) { Logger.Debug("OnApplicationExit"); // When the application closes, explictly save the database to avoid // any information being lost due to the wait-timer on the save. Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Save()); }
private void ShardConnected() { DatabaseMessage msg = new DatabaseMessage(); msg.MessageType = MessageType.DBOperation; if (_threadPool != null) { _threadPool.ExecuteTask(new ShardEventDeliverTask(msg, _shardListener)); } }
private void RefreshCollection(DatabaseMessage message) { if (message.PositionsSuccessful) { //Reimplement GetValueTotals(); } if (AllocationChartPositions == null && Positions != null) { Messenger.Default.Send(new ChartRequestMessage(Positions.ToList(), true, false, false)); } }
/// <summary> /// Replies to a client with an error message /// </summary> /// <param name="server">Server to send the reply</param> /// <param name="reply">Error Message</param> private void ErrorReply(DatabaseServer server, DatabaseMessage reply) { try { byte[] sendbuffer = { (byte)reply }; server.Send(GetID(), sendbuffer); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.ReadKey(); } }
//添加聊天信息 public void AddMessage(Message msg) { DatabaseMessage newMessage = new DatabaseMessage { Sender = msg.Sender, Receiver = msg.Receiver, Time = msg.SendTime, Type = msg.Type.ToString(), Content = msg.Content }; dataContext.DatabaseMessage.InsertOnSubmit(newMessage); dataContext.SubmitChanges(); }
public List <List <string> > Get(string key, string contextType, string context) { var objectKey = new DatabaseMessageKey(contextType, context, key); DatabaseMessage messageObject = null; bool inCache = false; lock (this.cache) { if (this.cache.ContainsKey(objectKey)) { messageObject = this.cache[objectKey]; inCache = true; } } if (!inCache) { messageObject = this.databaseSession.QueryOver <DatabaseMessage>() .Where(x => x.MessageKey == key) .And(x => x.ContextType == contextType) .And(x => x.Context == context) .And(x => x.Format == 1) .SingleOrDefault(); lock (this.cache) { if (!this.cache.ContainsKey(objectKey)) { this.cache.Add(objectKey, messageObject); } } } if (messageObject == null) { return(null); } try { var data = JsonSerializer.Deserialize <List <List <string> > >(messageObject.Value); return(data); } catch (JsonException ex) { this.logger.ErrorFormat(ex, "Invalid message for {0} / ({1}) {2}.", key, contextType, context); return(null); } }
void Edit(ApplicationViewModel toEdit) { if (toEdit == null) { throw new ArgumentNullException("toEdit"); } ApplicationViewModel editApplication = new ApplicationViewModel(); editApplication.UpdateWith(toEdit); ServiceManager.GetService <IViewService>().OpenDialog(editApplication); if (editApplication.Result != MessageResult.Okay) { return; // Cancelled edit. } if (!editApplication.Title.Equals(toEdit.Title, StringComparison.InvariantCultureIgnoreCase)) { // Application title has changed, check if any other applications have the new title if (Tabs.Any(t => t.Applications.Any(a => a.Title == editApplication.Title))) { ServiceManager.GetService <IMessageBoxService>().Show( "Already exists with the title " + editApplication.Title, "Astounding Dock", MessageIcon.Error); // Re-open dialog. Edit(toEdit); return; } } toEdit.UpdateWith(editApplication); if (toEdit.Tab != toEdit.OldTab) { // Moving to a new tab. var newTab = Tabs.Single(t => t.Title == toEdit.Tab); Move(toEdit, newTab); } else { Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Update(toEdit.Model)); } // Refresh the view to reapply the sort in case the application was renamed. // Needs to be done after 'UpdateWith' is called. Tabs.Single(t => t.Title == editApplication.Tab).ApplicationsView.Refresh(); }
public void Set(string key, string contextType, string context, List <List <string> > value) { var databaseMessageKey = new DatabaseMessageKey(contextType, context, key); lock (this.cache) { if (this.cache.ContainsKey(databaseMessageKey)) { this.cache.Remove(databaseMessageKey); } } var messageObject = this.databaseSession.QueryOver <DatabaseMessage>() .Where(x => x.MessageKey == key) .And(x => contextType == null || x.ContextType == contextType) .And(x => context == null || x.Context == context) .SingleOrDefault(); if (messageObject == null) { messageObject = new DatabaseMessage { Context = context, ContextType = contextType, MessageKey = key }; } messageObject.Value = JsonSerializer.Serialize(value); messageObject.Format = 1; messageObject.LastUpdated = DateTime.UtcNow; this.databaseSession.SaveOrUpdate(messageObject); this.databaseSession.Flush(); lock (this.cache) { if (this.cache.ContainsKey(databaseMessageKey)) { this.cache.Remove(databaseMessageKey); } this.cache.Add(databaseMessageKey, messageObject); } }
/// <summary> /// Find a record in the connected Database server and wait for the return /// </summary> /// <param name="memberid">Memberid of the record to download</param> /// <returns>Retrieved record</returns> public DataRecord Find(int memberid) { while (true) { byte[] sendbuffer = new DataRecord(memberid, "", "", DateTime.Now).ToBytes(); sendbuffer[0] = (byte)DatabaseMessage.Comm_Find_MemberID; Client.Send(sendbuffer); // Listen for Response byte[] recvbuffer = new byte[Shared.kMaxNetBuffer]; if (Client.Receive(recvbuffer) > 0) { DatabaseMessage message = (DatabaseMessage)recvbuffer[0]; if (message == DatabaseMessage.Success) { continue; } if (message == DatabaseMessage.Error_InvalidArgs) { throw new ArgumentException(); } else if (message == DatabaseMessage.Error_OutOfMemory) { throw new OutOfMemoryException(); } else if (message == DatabaseMessage.Client_Found_Record) { DataRecord record = DataRecord.FromBytes(recvbuffer); return(record); } else if (message == DatabaseMessage.Error_ItemNotFound) { throw new KeyNotFoundException(); } else if (message == DatabaseMessage.Error_DatabaseError) { throw new DatabaseException(); } } } throw new FormatException(); }
/// <summary> /// If we mess up the tab ordering just reset the order /// </summary> void FixTabOrdering() { int tabsWithDefaultOrder = Tabs.Count(x => x.TabOrder == 1); int tabsWithMaxOrder = Tabs.Count(x => x.TabOrder == Tabs.Max(m => m.TabOrder)); if (tabsWithDefaultOrder > 1 || tabsWithMaxOrder > 1) { int order = 1; foreach (var tab in Tabs.OrderBy(x => x.Title)) { tab.TabOrder = order; order++; Messenger.Default.Send <DatabaseMessage>(DatabaseMessage.Update(tab.Model)); } // Refresh the view to reapply the sort TabsView.Refresh(); } }
private void InsUpdDelSetup(string value, char Event, int id) { var msg = ""; if ((value == "Dg") && (Event == 'I' || Event == 'U')) { var objDesignation = new Designation(id, txtDesignation.Text); msg = BL_Staff.InsUpdDelDesignation(Event, objDesignation, out id); } else if ((value == "Dp") && (Event == 'I' || Event == 'U')) { var objDepartment = new Department(id, txtDepartment.Text); msg = BL_Staff.InsUpdDelDepartment(Event, objDepartment, out id); } else if ((value == "Aq") && (Event == 'I' || Event == 'U')) { var objQualification = new AcedamicQualification(id, txtAcedamicQualification.Text); msg = BL_Staff.InsUpdDelAcedamicQualification(Event, objQualification, out id); } else if ((value == "St") && (Event == 'I' || Event == 'U')) { var objServiceType = new ServiceType(id, txtServiceType.Text); msg = BL_Staff.InsUpdDelService(Event, objServiceType, out id); } else if ((value == "Eg") && (Event == 'I' || Event == 'U')) { var objEthnicGroup = new EthnicGroup(id, txtEthnicGroup.Text, 1, "XX"); msg = BL_Staff.InsUpdDelEthnicGroup(Event, objEthnicGroup, out id); } if (DatabaseMessage.ContainMessage(msg)) { _msgbox.ShowSuccess(msg); } else { _msgbox.ShowWarning(msg); } // FillGridview(); // ClearAll(); }
/// <summary> /// On the recievement of a message from a client. Does the message handling. /// </summary> /// <param name="Server">The DatabaseServer that initiated the connection</param> /// <param name="buffer">The recieved message buffer</param> public void OnReceive(DatabaseServer Server, byte[] buffer) { // Command message is first byte DatabaseMessage command = (DatabaseMessage)buffer[0]; switch (command) { case DatabaseMessage.Comm_Insert: try { PerformInsert(buffer); } catch (ArgumentException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (KeyNotFoundException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (OutOfMemoryException) { ErrorReply(Server, DatabaseMessage.Error_OutOfMemory); } catch (IndexOutOfRangeException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (FormatException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (XmlException) { ErrorReply(Server, DatabaseMessage.Error_DatabaseError); } SuccessReply(Server); break; case DatabaseMessage.Comm_Update: try { PerformUpdate(buffer); } catch (KeyNotFoundException) { ErrorReply(Server, DatabaseMessage.Error_ItemNotFound); } catch (IndexOutOfRangeException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (FormatException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (XmlException) { ErrorReply(Server, DatabaseMessage.Error_DatabaseError); } SuccessReply(Server); break; case DatabaseMessage.Comm_Find_MemberID: try { DataRecord record = PerformFind(buffer); byte[] sendbuffer = record.ToBytes(); sendbuffer[0] = (byte)DatabaseMessage.Client_Found_Record; Server.Send(GetID(), sendbuffer); } catch (KeyNotFoundException) { ErrorReply(Server, DatabaseMessage.Error_ItemNotFound); } catch (IndexOutOfRangeException) { ErrorReply(Server, DatabaseMessage.Error_InvalidArgs); } catch (XmlException) { ErrorReply(Server, DatabaseMessage.Error_DatabaseError); } SuccessReply(Server); break; } }
/// <summary> /// Compares _myPositions to the _databaseOriginalState from launch /// and creates lists of securities to update, insert, or delete. /// </summary> public void SavePortfolioToDatabase() { BackupDatabase(); var positionsToInsert = new List <Position>(); var positionsToUpdate = new List <Position>(); var positionsToDelete = new List <Position>(); foreach (var pos in _portfolioOriginalState) { if (!_myPositions.Any(s => s.Ticker == pos.Ticker)) { positionsToDelete.Add(pos); } } foreach (var p in _myPositions) { //Current position's ticker is in the original list but the current quantity is different if (_portfolioOriginalState.Any(pos => pos.Ticker == p.Ticker && pos.SharesOwned != p.SharesOwned)) { positionsToUpdate.Add(p); continue; } //Current position's ticker not in original list if (!_portfolioOriginalState.Any(pos => pos.Ticker == p.Ticker)) { positionsToInsert.Add(p); continue; } //Current position share quantity matches original list. //Check if taxlots are different or the same as original. if (_portfolioOriginalState.Any(pos => pos.Ticker == p.Ticker && pos.SharesOwned == p.SharesOwned)) { var originalPosition = _portfolioOriginalState.Find(s => s.Ticker == p.Ticker); if (originalPosition != null && !TaxLotsAreEqual(originalPosition, p)) { positionsToUpdate.Add(p); } } } //If no inserts, updates, or deletes, exit method. if (positionsToInsert.Count == 0 && positionsToUpdate.Count == 0 && positionsToDelete.Count == 0) { return; } try { if (positionsToUpdate.Any()) { UpdatePositions(positionsToUpdate); } if (positionsToInsert.Any()) { InsertPositions(positionsToInsert); } if (positionsToDelete.Any()) { DeletePositions(positionsToDelete); } } catch (SqlException ex) { var msg = new DatabaseMessage(ex.Message, false); Messenger.Default.Send(msg); } catch (InvalidOperationException ex) { var msg = new DatabaseMessage(ex.Message, false); Messenger.Default.Send(msg); } }