Exemplo n.º 1
0
        private List <DataUpdateJobSettings> DeserializeDataUpdateJobSettings(IEnumerable <IJobDetail> jobDetails)
        {
            var result = new List <DataUpdateJobSettings>();

            foreach (var job in jobDetails)
            {
                try
                {
                    var jd = JsonConvert.DeserializeObject <DataUpdateJobSettings>((string)job.JobDataMap["settings"]);
                    if (jd.InstrumentID.HasValue)
                    {
                        jd.Instrument = _context.Set <Instrument>().FirstOrDefault(x => x.ID == jd.InstrumentID.Value);
                    }
                    if (jd.TagID.HasValue)
                    {
                        jd.Tag = _context.Set <Tag>().FirstOrDefault(x => x.ID == jd.TagID.Value);
                    }

                    result.Add(jd);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Failed to deserialize data update job");
                }
            }

            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets an attached entity from the ID of a detached entity
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static T GetAttachedEntity <T>(this IMyDbContext context, T entity) where T : class, IEntity
        {
            if (entity == null)
            {
                return(null);
            }

            return(context.GetLocal(entity) ?? context.Set <T>().FirstOrDefault(x => x.ID == entity.ID));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Updates a collection, adding/removing values.
        /// All newValues must already exist in the database.
        /// Does not update the fields of each element.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <param name="newValues"></param>
        /// <param name="context"></param>
        public static void UpdateCollection <T>(this ICollection <T> collection, IEnumerable <T> newValues, IMyDbContext context) where T : class, IEntity
        {
            var comparer = new LambdaEqualityComparer <T>((x, y) => x.ID == y.ID, x => x.ID);
            var toAdd    = newValues.Except(collection, comparer).ToList();
            var toRemove = collection.Except(newValues, comparer).ToList();
            //grab everything so we don't need an individual query for every item
            var allItems = context.Set <T>().ToList().ToDictionary(x => x.ID, x => x);

            foreach (var element in toAdd)
            {
                var entry = allItems[element.ID];
                collection.Add(entry);
            }
            foreach (var element in toRemove)
            {
                var entry = allItems[element.ID];
                collection.Remove(entry);
            }
        }
Exemplo n.º 4
0
 public IDbSet <T> GetEntity <T>() where T : class
 {
     return(_context.Set <T>());
 }
Exemplo n.º 5
0
        public ExchangeModule(IMyDbContext context) : base("/exchanges")
        {
            this.RequiresAuthentication();

            var dbSet = context.Set <Exchange>();

            Get("/", async(_, token) => await dbSet.Include(x => x.Sessions).ToListAsync(token).ConfigureAwait(false));

            Get("/{Id:int}", parameters =>
            {
                var id       = (int)parameters.Id;
                var exchange = dbSet.Include(x => x.Sessions).FirstOrDefault(x => x.ID == id);

                if (exchange == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                return(exchange);
            });

            Post("/", _ =>
            {
                Exchange exchange = this.BindAndValidate <Exchange>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                dbSet.Add(exchange);
                context.SaveChanges();

                //return the object with the id after inserting
                return(exchange);
            });

            Put("/", _ =>
            {
                Exchange newValues = this.BindAndValidate <Exchange>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                //make sure the exchange we want to update exists
                var exchange = dbSet.Include(x => x.Sessions).FirstOrDefault(x => x.ID == newValues.ID);
                if (exchange == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                //update values on the exchange
                context.UpdateEntryValues(exchange, newValues);

                //add/remove/update the Sessions collection
                exchange.Sessions.UpdateCollectionAndElements(newValues.Sessions, context);

                //some instruments may have their sessions based on this exchange, we need to update them
                var instruments = context.Set <Instrument>()
                                  .Where(x => x.SessionsSource == SessionsSource.Exchange && x.ExchangeID == exchange.ID).ToList();

                foreach (Instrument i in instruments)
                {
                    context.Set <InstrumentSession>().RemoveRange(i.Sessions);
                    i.Sessions.Clear();

                    foreach (ExchangeSession s in exchange.Sessions)
                    {
                        i.Sessions.Add(s.ToInstrumentSession());
                    }
                }

                context.SaveChanges();

                return(exchange);
            });

            Delete("/{Id:int}", parameters =>
            {
                int id       = parameters.Id;
                var exchange = dbSet.FirstOrDefault(x => x.ID == id);

                if (exchange == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                var exchangeReferenced = context.Set <Instrument>().Any(x => x.ExchangeID == id || x.PrimaryExchangeID == id);
                if (exchangeReferenced)
                {
                    return(Negotiate
                           .WithModel(new ErrorResponse(
                                          HttpStatusCode.Conflict,
                                          "Can't delete this exchange because it has instruments assigned to it.", ""))
                           .WithStatusCode(HttpStatusCode.Conflict));
                }

                dbSet.Remove(exchange);
                context.SaveChanges();
                return(exchange);
            });
        }
Exemplo n.º 6
0
 //add Entity
 public void Add(T entity)
 {
     dbContext.Set <T>().Add(entity);
 }
Exemplo n.º 7
0
        public UnderlyingSymbolModule(IMyDbContext context) : base("/underlyingsymbols")
        {
            this.RequiresAuthentication();
            var dbSet = context.Set <UnderlyingSymbol>();

            Get("/", _ => dbSet.ToList());

            Get("/{Id:int}", parameters =>
            {
                var id       = (int)parameters.Id;
                var exchange = dbSet.FirstOrDefault(x => x.ID == id);

                if (exchange == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                return(exchange);
            });

            Put("/", _ =>
            {
                UnderlyingSymbol newValues = this.BindAndValidate <UnderlyingSymbol>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                //make sure the exchange we want to update exists
                var symbol = dbSet.FirstOrDefault(x => x.ID == newValues.ID);
                if (symbol == null)
                {
                    return(HttpStatusCode.NotFound);
                }


                //update values on the exchange
                context.UpdateEntryValues(symbol, newValues);

                context.SaveChanges();

                return(symbol);
            });

            Post("/", _ =>
            {
                UnderlyingSymbol symbol = this.BindAndValidate <UnderlyingSymbol>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                dbSet.Add(symbol);
                context.SaveChanges();

                //return the object with the id after inserting
                return(symbol);
            });

            Delete("/{Id:int}", parameters =>
            {
                int id     = parameters.Id;
                var symbol = dbSet.FirstOrDefault(x => x.ID == id);

                if (symbol == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                var symbolReferenced = context.Set <ContinuousFuture>().Any(x => x.UnderlyingSymbolID == id);
                if (symbolReferenced)
                {
                    return(Negotiate
                           .WithModel(new ErrorResponse(
                                          HttpStatusCode.Conflict,
                                          "Can't delete this underlying symbol because it has continuous futures assigned to it.", ""))
                           .WithStatusCode(HttpStatusCode.Conflict));
                }

                dbSet.Remove(symbol);
                context.SaveChanges();
                return(symbol);
            });
        }
Exemplo n.º 8
0
 public virtual ReadModel Get(int Id)
 {
     return(_context.Set <TEntity>().Find(Id));
 }
Exemplo n.º 9
0
 public async Task <int> AddAsync(TEntity entity)
 {
     Context.Set <TEntity>().Add(entity);
     return(await Context.SaveChangesAsync());
 }
Exemplo n.º 10
0
        public SessionTemplateModule(IMyDbContext context) : base("/sessiontemplates")
        {
            this.RequiresAuthentication();

            var dbSet = context.Set <SessionTemplate>();

            Get["/", runAsync : true] = async(_, token) => await dbSet.Include(x => x.Sessions).ToListAsync(token).ConfigureAwait(false);

            Post["/"] = _ =>
            {
                SessionTemplate template = this.BindAndValidate <SessionTemplate>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                dbSet.Add(template);
                context.SaveChanges();

                //return the object with the id after inserting
                return(template);
            };

            Put["/"] = _ =>
            {
                SessionTemplate newValues = this.BindAndValidate <SessionTemplate>();
                if (ModelValidationResult.IsValid == false)
                {
                    return(this.ValidationFailure());
                }

                //make sure the template we want to update exists
                var template = dbSet.Include(x => x.Sessions).FirstOrDefault(x => x.ID == newValues.ID);
                if (template == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                //update values on the template
                context.UpdateEntryValues(template, newValues);

                //add/remove/update the Sessions collection
                template.Sessions.UpdateCollectionAndElements(newValues.Sessions, context);

                //some instruments may have their sessions based on this template, we need to update them
                var instruments = context.Set <Instrument>()
                                  .Where(x => x.SessionsSource == SessionsSource.Template && x.SessionTemplateID == template.ID).ToList();
                foreach (Instrument i in instruments)
                {
                    context.Set <InstrumentSession>().RemoveRange(i.Sessions);
                    i.Sessions.Clear();

                    foreach (TemplateSession s in template.Sessions)
                    {
                        i.Sessions.Add(s.ToInstrumentSession());
                    }
                }

                context.SaveChanges();

                return(template);
            };

            Delete["/{Id:int}"] = parameters =>
            {
                //It's possible to delete
                int id       = parameters.Id;
                var template = dbSet.FirstOrDefault(x => x.ID == id);

                if (template == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                //make sure there are no references to it
                var templateReferenced = context.Set <Instrument>().Any(x => x.SessionTemplateID == id && x.SessionsSource == SessionsSource.Template);
                if (templateReferenced)
                {
                    return(Negotiate
                           .WithModel(new ErrorResponse(
                                          HttpStatusCode.Conflict,
                                          "Can't delete this template because it has instruments assigned to it.", ""))
                           .WithStatusCode(HttpStatusCode.Conflict));
                }

                dbSet.Remove(template);
                context.SaveChanges();
                return(template);
            };
        }