public DataImportWindow(Instrument instrument) { InitializeComponent(); //reload the instrument first to make sure we have up-to-date data using (var context = new MyDBContext()) { context.Instruments.Attach(instrument); context.Entry(instrument).Reload(); _instrument = instrument; } Title += " - " + _instrument.Symbol; //fill frequency combo box var values = MyUtils.GetEnumValues<BarSize>(); foreach (BarSize s in values) { FrequencyComboBox.Items.Add(s); } FrequencyComboBox.SelectedItem = BarSize.OneDay; MinDT.Value = new DateTime(1950, 1, 1); MaxDT.Value = DateTime.Now; }
/// <summary> /// Add a new instrument or update an existing instrument in the database. /// </summary> /// <param name="instrument"></param> /// <param name="updateIfExists"></param> /// <param name="saveChanges">Set to true if saving to db should be done.</param> /// <returns>True if the insertion or update succeeded. False if it did not.</returns> public static bool AddInstrument(Instrument instrument, bool updateIfExists = false, bool saveChanges = true) { if (instrument.IsContinuousFuture) { throw new Exception("Cannot add continuous futures using this method"); } using (var context = new MyDBContext()) { var existingInstrument = context.Instruments.SingleOrDefault(x => (x.ID == instrument.ID) || (x.Symbol == instrument.Symbol && x.DatasourceID == instrument.DatasourceID && x.ExchangeID == instrument.ExchangeID)); if (existingInstrument == null) //object doesn't exist, so we add it { //if necessary, load sessions from teplate or exchange if (instrument.SessionsSource == SessionsSource.Exchange) { instrument.Sessions = new List<InstrumentSession>(); var exchange = context.Exchanges.Include("Sessions").First(x => x.ID == instrument.ExchangeID); foreach (ExchangeSession s in exchange.Sessions) { instrument.Sessions.Add(MyUtils.SessionConverter(s)); } } else if (instrument.SessionsSource == SessionsSource.Template) { instrument.Sessions = new List<InstrumentSession>(); var template = context.SessionTemplates.Include("Sessions").First(x => x.ID == instrument.SessionTemplateID); foreach (TemplateSession s in template.Sessions) { instrument.Sessions.Add(MyUtils.SessionConverter(s)); } } context.Instruments.Add(instrument); context.Database.Connection.Open(); if (saveChanges) context.SaveChanges(); return true; } else if (updateIfExists) //object exist, but we want to update it { context.Entry(existingInstrument).CurrentValues.SetValues(instrument); if (saveChanges) context.SaveChanges(); return true; } } return false; //object exists and we don't update it }
public DataEditWindow(Instrument instrument) { InitializeComponent(); DataContext = this; Data = new ObservableCollection<OHLCBar>(); //grab and update the instrument using (var context = new MyDBContext()) { context.Instruments.Attach(instrument); context.Entry(instrument).Reload(); TheInstrument = instrument; } string timezone = TheInstrument.Exchange == null ? "UTC" : TheInstrument.Exchange.Timezone; _tzInfo = TimeZoneInfo.FindSystemTimeZoneById(timezone); StartTime = new DateTime(1950, 1, 1, 0, 0, 0, 0); EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0); if (!TheInstrument.ID.HasValue) return; //grab the data info using (var localStorage = DataStorageFactory.Get()) { var storageInfo = localStorage.GetStorageInfo(TheInstrument.ID.Value); if (storageInfo.Count == 0) //if it doesn't have any data, we just exit { MessageBox.Show("This instrument has no data."); Hide(); } else { foreach (StoredDataInfo s in storageInfo) //fill the resolution box { ResolutionComboBox.Items.Add(s.Frequency); } } } }
private void ExecuteSave() { using (var context = new MyDBContext()) { if (Job.UseTag) { Job.Instrument = null; Job.InstrumentID = null; Job.TagID = Job.Tag.ID; } else //Job is for a specific instrument, not a tag { Job.InstrumentID = Job.Instrument.ID; Job.Tag = null; Job.TagID = null; } context.DataUpdateJobs.Attach(Job); context.Entry(Job).State = EntityState.Modified; context.SaveChanges(); } }
private void ModifyBtn_Click(object sender, RoutedEventArgs e) { using (var entityContext = new MyDBContext()) { bool nameExists = entityContext.Exchanges.Any(x => x.Name == TheExchange.Name); if (nameExists && (_addingNew || _originalExchange.Name != TheExchange.Name)) { MessageBox.Show("Name already exists, please change it."); return; } if (_addingNew) { entityContext.Exchanges.Add(TheExchange); } else { entityContext.Exchanges.Attach(_originalExchange); entityContext.Entry(_originalExchange).CurrentValues.SetValues(TheExchange); } entityContext.SaveChanges(); //find removed sessions and mark them as deleted var removedSessions = _originalExchange.Sessions.Where(x => !TheExchange.Sessions.Any(y => y.ID == x.ID)).ToList(); for (int i = 0; i < removedSessions.Count; i++) { entityContext.Entry(removedSessions[i]).State = System.Data.Entity.EntityState.Deleted; } //find the ones that overlap and modify them, if not add them foreach (ExchangeSession s in TheExchange.Sessions) { if (s.ID != 0) //this means it's not newly added { var session = _originalExchange.Sessions.First(x => x.ID == s.ID); entityContext.ExchangeSessions.Attach(session); entityContext.Entry(session).CurrentValues.SetValues(s); } else //completely new { _originalExchange.Sessions.Add(s); } } entityContext.SaveChanges(); //find instruments using this exchange as session source, and update their sessions if (TheExchange.ID != -1) { var instruments = entityContext.Instruments.Where(x => x.SessionsSource == SessionsSource.Exchange && x.ExchangeID == TheExchange.ID).ToList(); foreach (Instrument i in instruments) { entityContext.InstrumentSessions.RemoveRange(i.Sessions); i.Sessions.Clear(); foreach (ExchangeSession s in TheExchange.Sessions) { i.Sessions.Add(MyUtils.SessionConverter(s)); } } } entityContext.SaveChanges(); } ExchangeAdded = true; Hide(); }
/// <summary> /// Updates the instrument with new values. Instrument must have an ID. /// </summary> public static void UpdateInstrument(Instrument instrument) { if(!instrument.ID.HasValue) return; using (var context = new MyDBContext()) { try { //find it Instrument instrumentFromDB = context.Instruments.First(x => x.ID == instrument.ID); //update it context.Entry(instrumentFromDB).CurrentValues.SetValues(instrument); //perhaps update all the underlying collections as well? //save it context.SaveChanges(); } catch (Exception ex) { MessageBox.Show("Update instrument error: " + ex.Message); } } }
/// <summary> /// Add a new instrument or update an existing instrument in the database. /// </summary> /// <param name="instrument"></param> /// <param name="updateIfExists"></param> /// <param name="saveChanges">Set to true if saving to db should be done.</param> /// <returns>True if the insertion or update succeeded. False if it did not.</returns> public Instrument AddInstrument(Instrument instrument, bool updateIfExists = false, bool saveChanges = true) { if (instrument.IsContinuousFuture) { throw new Exception("Cannot add continuous futures using this method."); } using (var context = new MyDBContext()) { //make sure data source is set and exists if(instrument.Datasource == null || !context.Datasources.Any(x => x.Name == instrument.Datasource.Name)) { throw new Exception("Failed to add instrument: invalid datasource."); } //make sure exchange exists, if it is set if(instrument.Exchange != null && !context.Exchanges.Any(x => x.Name == instrument.Exchange.Name)) { throw new Exception("Failed to add instrument: exchange does not exist."); } if (instrument.PrimaryExchange != null && !context.Exchanges.Any(x => x.Name == instrument.PrimaryExchange.Name)) { throw new Exception("Failed to add instrument: primary exchange does not exist."); } //check if the instrument already exists in the database or not var existingInstrument = context.Instruments.SingleOrDefault(x => (x.ID == instrument.ID) || (x.Symbol == instrument.Symbol && x.DatasourceID == instrument.DatasourceID && x.ExchangeID == instrument.ExchangeID && x.Expiration == instrument.Expiration)); if (existingInstrument == null) //object doesn't exist, so we add it { //attach the datasource, exchanges, etc. so it doesn't try to add them //also load sessions at the same time context.Datasources.Attach(instrument.Datasource); if (instrument.PrimaryExchange != null) { context.Exchanges.Attach(instrument.PrimaryExchange); context.Entry(instrument.PrimaryExchange).Collection(x => x.Sessions).Load(); } if (instrument.PrimaryExchangeID != instrument.ExchangeID && instrument.Exchange != null) { context.Exchanges.Attach(instrument.Exchange); context.Entry(instrument.Exchange).Collection(x => x.Sessions).Load(); } //if necessary, load sessions from teplate or exchange if (instrument.SessionsSource == SessionsSource.Exchange && instrument.Exchange != null) { instrument.Sessions = instrument.Exchange.Sessions.Select(x => x.ToInstrumentSession()).ToList(); } else if (instrument.SessionsSource == SessionsSource.Exchange && instrument.Exchange == null) { instrument.SessionsSource = SessionsSource.Custom; instrument.Sessions = new List<InstrumentSession>(); } else if (instrument.SessionsSource == SessionsSource.Template) { instrument.Sessions = new List<InstrumentSession>(); var template = context.SessionTemplates.Include("Sessions").FirstOrDefault(x => x.ID == instrument.SessionTemplateID); if (template != null) { foreach (TemplateSession s in template.Sessions) { instrument.Sessions.Add(s.ToInstrumentSession()); } } } context.Instruments.Add(instrument); context.Database.Connection.Open(); if (saveChanges) context.SaveChanges(); Log(LogLevel.Info, string.Format("Instrument Manager: successfully added instrument {0}", instrument)); return instrument; } else if (updateIfExists) //object exist, but we want to update it { Log(LogLevel.Info, string.Format("Instrument Manager: updating existing instrument ID {0} with the following details: {1}", existingInstrument.ID, instrument)); context.Entry(existingInstrument).CurrentValues.SetValues(instrument); if (saveChanges) context.SaveChanges(); return existingInstrument; } } return null; //object exists and we don't update it }
/// <summary> /// /// </summary> /// <param name="instrument">If we're updating or cloning an instrument, pass it here.</param> /// <param name="addingNew">True if adding a new instrument. False if we're updating an instrument.</param> /// <param name="addingContFut">True if adding a continuous futures instrument.</param> public AddInstrumentManuallyWindow(Instrument instrument = null, bool addingNew = true, bool addingContFut = false) { InitializeComponent(); //If it's a continuous future, make the continuous future tab visible if ((instrument != null && instrument.IsContinuousFuture) || addingContFut) { ContFutTabItem.Visibility = Visibility.Visible; TypeComboBox.IsEnabled = false; } else { ContFutTabItem.Visibility = Visibility.Hidden; } DataContext = this; _addingNew = addingNew; _context = new MyDBContext(); if (instrument != null) { _context.Instruments.Attach(instrument); _context.Entry(instrument).Reload(); if (instrument.Exchange != null) _context.Entry(instrument.Exchange).Reload(); if (instrument.ContinuousFuture != null) { _context.ContinuousFutures.Attach(instrument.ContinuousFuture); _context.Entry(instrument.ContinuousFuture).Reload(); } if (!addingNew) { if (instrument.Tags != null) { foreach (Tag tag in instrument.Tags) { _context.Tags.Attach(tag); } } if (instrument.Sessions != null) { foreach (InstrumentSession session in instrument.Sessions) { _context.InstrumentSessions.Attach(session); } } } TheInstrument = addingNew ? (Instrument)instrument.Clone() : instrument; if (TheInstrument.Tags == null) TheInstrument.Tags = new List<Tag>(); if (TheInstrument.Sessions == null) TheInstrument.Sessions = new List<InstrumentSession>(); TheInstrument.Sessions = TheInstrument.Sessions.OrderBy(x => x.OpeningDay).ThenBy(x => x.OpeningTime).ToList(); _originalSessions = new List<InstrumentSession>(TheInstrument.Sessions); } else { TheInstrument = new Instrument { Tags = new List<Tag>(), Sessions = new List<InstrumentSession>() }; //need to do some extra stuff if it's a continuous future if (addingContFut) { TheInstrument.ContinuousFuture = new ContinuousFuture(); TheInstrument.Type = InstrumentType.Future; TheInstrument.IsContinuousFuture = true; } CustomRadioBtn.IsChecked = true; } //Tags Tags = new ObservableCollection<CheckBoxTag>(); foreach (Tag t in _context.Tags) { Tags.Add(new CheckBoxTag(t, TheInstrument.Tags.Contains(t))); } //Sessions SelectedSessions = new ObservableCollection<InstrumentSession>(TheInstrument.Sessions); //Window title if (addingNew) { Title = "Add New Instrument"; AddBtn.Content = "Add"; } else { Title = "Modify Instrument"; AddBtn.Content = "Modify"; } Exchanges = new ObservableCollection<Exchange>(); var exchangeList = _context.Exchanges.AsEnumerable().OrderBy(x => x.Name); foreach (Exchange e in exchangeList) { Exchanges.Add(e); } //fill template box var templates = _context.SessionTemplates.Include("Sessions").ToList(); foreach (SessionTemplate t in templates) { TemplateComboBox.Items.Add(t); } if (TheInstrument.SessionsSource == SessionsSource.Template) { TemplateComboBox.SelectedItem = templates.First(x => x.ID == TheInstrument.SessionTemplateID); } //set the right radio button... CustomRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Custom; TemplateRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Template; ExchangeRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Exchange; //populate instrument type combobox with enum values var instrumentTypeValues = MyUtils.GetEnumValues<InstrumentType>(); foreach (InstrumentType t in instrumentTypeValues) { TypeComboBox.Items.Add(t); } //populate option type combobox with enum values var optionTypeValues = MyUtils.GetEnumValues<OptionType>(); foreach (OptionType t in optionTypeValues) { OptionTypeComboBox.Items.Add(t); } var dataSources = _context.Datasources.AsEnumerable(); foreach (Datasource d in dataSources) { DatasourceComboBox.Items.Add(d); } //sort the sessions so they're ordered properly... SessionsGrid.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("OpeningDay", System.ComponentModel.ListSortDirection.Ascending)); //fill the RolloverRuleType combobox var rolloverTypes = MyUtils.GetEnumValues<ContinuousFuturesRolloverType>(); foreach (ContinuousFuturesRolloverType t in rolloverTypes) { if (t != ContinuousFuturesRolloverType.Time) RolloverRuleType.Items.Add(t); } //fill the RootSymbolComboBox foreach (UnderlyingSymbol s in _context.UnderlyingSymbols) { RootSymbolComboBox.Items.Add(s); } ContractMonths = new ObservableCollection<KeyValuePair<int, string>>(); //fill the continuous futures contrat month combobox for (int i = 1; i < 10; i++) { ContractMonths.Add(new KeyValuePair<int, string>(i, MyUtils.Ordinal(i) + " Contract")); } //time or rule-based rollover, set the radio button check if (TheInstrument.ContinuousFuture != null) { if (TheInstrument.ContinuousFuture.RolloverType == ContinuousFuturesRolloverType.Time) { RolloverTime.IsChecked = true; } else { RolloverRule.IsChecked = true; } } }
/// <summary> /// /// </summary> /// <param name="instrument">If we're updating or cloning an instrument, pass it here.</param> /// <param name="addingNew">True if adding a new instrument. False if we're updating an instrument.</param> public AddInstrumentManuallyWindow(Instrument instrument = null, bool addingNew = true) { InitializeComponent(); DataContext = this; _addingNew = addingNew; var context = new MyDBContext(); if (instrument != null) { context.Instruments.Attach(instrument); context.Entry(instrument).Reload(); context.Entry(instrument.Exchange).Reload(); TheInstrument = (Instrument)instrument.Clone(); if (TheInstrument.Tags == null) TheInstrument.Tags = new List<Tag>(); if (TheInstrument.Sessions == null) TheInstrument.Sessions = new List<InstrumentSession>(); TheInstrument.Sessions = TheInstrument.Sessions.OrderBy(x => x.OpeningDay).ThenBy(x => x.OpeningTime).ToList(); } else { TheInstrument = new Instrument { Tags = new List<Tag>(), Sessions = new List<InstrumentSession>() }; } Tags = new ObservableCollection<CheckBoxTag>(); foreach (Tag t in context.Tags) { Tags.Add(new CheckBoxTag(t, TheInstrument.Tags.Contains(t))); } if (addingNew) { Title = "Add New Instrument"; AddBtn.Content = "Add"; } else { Title = "Modify Instrument"; AddBtn.Content = "Modify"; _originalInstrument = instrument; } Exchanges = new ObservableCollection<Exchange>(); var exchangeList = context.Exchanges.AsEnumerable().OrderBy(x => x.Name); foreach (Exchange e in exchangeList) { Exchanges.Add(e); } //fill template box var templates = context.SessionTemplates.Include("Sessions").ToList(); foreach (SessionTemplate t in templates) { TemplateComboBox.Items.Add(t); } if (TheInstrument.SessionsSource == SessionsSource.Template) { TemplateComboBox.SelectedItem = templates.First(x => x.ID == TheInstrument.SessionTemplateID); } //set the right radio button... CustomRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Custom; TemplateRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Template; ExchangeRadioBtn.IsChecked = TheInstrument.SessionsSource == SessionsSource.Exchange; //populate instrument type combobox with enum values var instrumentTypeValues = MyUtils.GetEnumValues<InstrumentType>(); foreach (InstrumentType t in instrumentTypeValues) { TypeComboBox.Items.Add(t); } //populate option type combobox with enum values var optionTypeValues = MyUtils.GetEnumValues<OptionType>(); foreach (OptionType t in optionTypeValues) { OptionTypeComboBox.Items.Add(t); } var dataSources = context.Datasources.AsEnumerable(); foreach (Datasource d in dataSources) { DatasourceComboBox.Items.Add(d); } //sort the sessions so they're ordered properly... SessionsGrid.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("OpeningDay", System.ComponentModel.ListSortDirection.Ascending)); context.Dispose(); }
private void AddBtn_Click(object sender, RoutedEventArgs e) { using (var context = new MyDBContext()) { if (_addingNew && context.Instruments.Any( x => x.DatasourceID == TheInstrument.DatasourceID && x.ExchangeID == TheInstrument.ExchangeID && x.Symbol == TheInstrument.Symbol && x.Expiration == TheInstrument.Expiration) ) { //there's already an instrument with this key MessageBox.Show("Instrument already exists. Change datasource, exchange, or symbol."); return; } //check that if the user picked a template-based session set, he actually selected one of the templates if (TheInstrument.SessionsSource == SessionsSource.Template && TheInstrument.SessionTemplateID == -1) { MessageBox.Show("You must pick a session template."); return; } TheInstrument.Tags.Clear(); foreach (Tag t in Tags.Where(x=> x.IsChecked).Select(x => x.Item)) { context.Tags.Attach(t); TheInstrument.Tags.Add(t); } if (_addingNew) { if (TheInstrument.Exchange != null) context.Exchanges.Attach(TheInstrument.Exchange); if (TheInstrument.PrimaryExchange != null) context.Exchanges.Attach(TheInstrument.PrimaryExchange); context.Datasources.Attach(TheInstrument.Datasource); context.Instruments.Add(TheInstrument); } else //simply manipulating an existing instrument { context.Exchanges.Attach(TheInstrument.Exchange); context.Exchanges.Attach(TheInstrument.PrimaryExchange); context.Datasources.Attach(TheInstrument.Datasource); context.Instruments.Attach(_originalInstrument); context.Entry(_originalInstrument).CurrentValues.SetValues(TheInstrument); _originalInstrument.Tags.Clear(); foreach (Tag t in TheInstrument.Tags) { _originalInstrument.Tags.Add(t); } var sessions = _originalInstrument.Sessions.ToList(); foreach (InstrumentSession i in sessions) { context.Entry(i).State = System.Data.Entity.EntityState.Deleted; } _originalInstrument.Sessions.Clear(); foreach (InstrumentSession s in TheInstrument.Sessions) { _originalInstrument.Sessions.Add(s); } } context.Database.Connection.Open(); context.SaveChanges(); } InstrumentAdded = true; Hide(); }
private void ModifyBtn_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(TheSymbol.Symbol)) { MessageBox.Show("Must have a symbol."); return; } using (var entityContext = new MyDBContext()) { //check that the symbol doesn't already exist bool symbolExists = entityContext.UnderlyingSymbols.Count(x => x.Symbol == TheSymbol.Symbol) > 0; bool addingNew = TheSymbol.ID == -1; if (symbolExists && addingNew) { MessageBox.Show("Must have a symbol."); return; } if (addingNew) { entityContext.UnderlyingSymbols.Add(TheSymbol); } else { entityContext.UnderlyingSymbols.Attach(_originalSymbol); entityContext.Entry(_originalSymbol).CurrentValues.SetValues(TheSymbol); } entityContext.SaveChanges(); } SymbolAdded = true; Hide(); }
private void ModifyBtn_Click(object sender, RoutedEventArgs e) { //ensure sessions don't overlap try { MyUtils.ValidateSessions(TheTemplate.Sessions.ToList<ISession>()); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } //save to db using (var entityContext = new MyDBContext()) { bool nameExists = entityContext.SessionTemplates.Any(x => x.Name == TheTemplate.Name); bool addingNew = TheTemplate.ID == -1; if (nameExists && (addingNew || _originalTemplate.Name != TheTemplate.Name)) { MessageBox.Show("Name already exists, please change it."); return; } if (addingNew) { entityContext.SessionTemplates.Add(TheTemplate); } else { entityContext.SessionTemplates.Attach(_originalTemplate); entityContext.Entry(_originalTemplate).CurrentValues.SetValues(TheTemplate); } entityContext.SaveChanges(); //find removed sessions and mark them as deleted if (_originalTemplate != null) { var removedSessions = _originalTemplate.Sessions.Where(x => !TheTemplate.Sessions.Any(y => y.ID == x.ID)).ToList(); foreach (TemplateSession t in removedSessions) { entityContext.Entry(t).State = System.Data.Entity.EntityState.Deleted; } //find the ones that overlap and modify them, if not add them foreach (TemplateSession s in TheTemplate.Sessions) { if (s.ID != 0) //this means it's not newly added { var session = _originalTemplate.Sessions.First(x => x.ID == s.ID); entityContext.TemplateSessions.Attach(session); entityContext.Entry(session).CurrentValues.SetValues(s); } } } entityContext.SaveChanges(); //find instruments using this exchange as session source, and update their sessions if (TheTemplate.ID != -1) { var instruments = entityContext.Instruments.Where(x => x.SessionsSource == SessionsSource.Template && x.ExchangeID == TheTemplate.ID).ToList(); foreach (Instrument i in instruments) { entityContext.InstrumentSessions.RemoveRange(i.Sessions); i.Sessions.Clear(); foreach (TemplateSession s in TheTemplate.Sessions) { i.Sessions.Add(s.ToInstrumentSession()); } } } entityContext.SaveChanges(); } TemplateAdded = true; Hide(); }
private void SaveBtn_OnClick(object sender, RoutedEventArgs e) { if (JobsGrid.SelectedItems.Count != 1) return; if (FrequencyComboBox.SelectedItem == null) { MessageBox.Show("You must select a frequency."); return; } using (var context = new MyDBContext()) { var job = (DataUpdateJobDetails)JobsGrid.SelectedItem; if (job.UseTag) { if (TagsComboBox.SelectedItem == null) { MessageBox.Show("You must select a tag."); return; } job.Instrument = null; job.InstrumentID = null; job.Tag = (Tag)TagsComboBox.SelectedItem; job.TagID = job.Tag.ID; } else //job is for a specific instrument, not a tag { if (InstrumentsComboBox.SelectedItem == null) { MessageBox.Show("You must select an instrument."); return; } job.Instrument = (Instrument)InstrumentsComboBox.SelectedItem; job.InstrumentID = job.Instrument.ID; job.Tag = null; job.TagID = null; } context.DataUpdateJobs.Attach(job); context.Entry(job).State = EntityState.Modified; context.SaveChanges(); } }
private void AddBtn_Click(object sender, RoutedEventArgs e) { using (var context = new MyDBContext()) { if (_addingNew && context.Instruments.Any( x => x.DatasourceID == TheInstrument.DatasourceID && x.ExchangeID == TheInstrument.ExchangeID && x.Symbol == TheInstrument.Symbol && x.Expiration == TheInstrument.Expiration) ) { //there's already an instrument with this key MessageBox.Show("Instrument already exists. Change datasource, exchange, or symbol."); return; } //check that if the user picked a template-based session set, he actually selected one of the templates if (TheInstrument.SessionsSource == SessionsSource.Template && TheInstrument.SessionTemplateID == -1) { MessageBox.Show("You must pick a session template."); return; } if (TheInstrument.IsContinuousFuture && TheInstrument.Type != InstrumentType.Future) { MessageBox.Show("Continuous futures type must be Future."); return; } if (TheInstrument.Datasource == null) { MessageBox.Show("You must select a data source."); return; } if (TheInstrument.Multiplier == null) { MessageBox.Show("Must have a multiplier value."); return; } TheInstrument.Tags.Clear(); foreach (Tag t in Tags.Where(x=> x.IsChecked).Select(x => x.Item)) { context.Tags.Attach(t); TheInstrument.Tags.Add(t); } ContinuousFuture tmpCF = null; if (_addingNew) { if (TheInstrument.Exchange != null) context.Exchanges.Attach(TheInstrument.Exchange); if (TheInstrument.PrimaryExchange != null) context.Exchanges.Attach(TheInstrument.PrimaryExchange); context.Datasources.Attach(TheInstrument.Datasource); if (TheInstrument.IsContinuousFuture) { tmpCF = TheInstrument.ContinuousFuture; //EF can't handle circular references, so we hack around it TheInstrument.ContinuousFuture = null; TheInstrument.ContinuousFutureID = null; } context.Instruments.Add(TheInstrument); } else //simply manipulating an existing instrument { if (TheInstrument.Exchange != null) context.Exchanges.Attach(TheInstrument.Exchange); if(TheInstrument.PrimaryExchange != null) context.Exchanges.Attach(TheInstrument.PrimaryExchange); context.Datasources.Attach(TheInstrument.Datasource); context.Instruments.Attach(_originalInstrument); context.Entry(_originalInstrument).CurrentValues.SetValues(TheInstrument); if (TheInstrument.IsContinuousFuture) { //TheInstrument.ContinuousFuture.InstrumentID context.ContinuousFutures.Attach(TheInstrument.ContinuousFuture); } _originalInstrument.Tags.Clear(); foreach (Tag t in TheInstrument.Tags) { _originalInstrument.Tags.Add(t); } var sessions = _originalInstrument.Sessions.ToList(); foreach (InstrumentSession i in sessions) { context.Entry(i).State = System.Data.Entity.EntityState.Deleted; } _originalInstrument.Sessions.Clear(); foreach (InstrumentSession s in TheInstrument.Sessions) { _originalInstrument.Sessions.Add(s); } } context.Database.Connection.Open(); context.SaveChanges(); if (tmpCF != null) { context.UnderlyingSymbols.Attach(tmpCF.UnderlyingSymbol); TheInstrument.ContinuousFuture = tmpCF; TheInstrument.ContinuousFuture.Instrument = TheInstrument; TheInstrument.ContinuousFuture.InstrumentID = TheInstrument.ID.Value; context.SaveChanges(); } } InstrumentAdded = true; Hide(); }