Exemplo n.º 1
0
        private Customer GetCustomer(ResolveFieldContext <object> context, IServiceProvider serviceProvider)
        {
            var service = serviceProvider.GetService <ICustomerQueryService>();

            var id = context.GetArgument <int?>("id");

            if (id != null)
            {
                var response = service.GetCustomerById((int)id);

                return(new Customer
                {
                    Name = response.Name,
                    Id = response.Id
                });
            }

            var name = context.GetArgument <string>("name");

            if (name != null)
            {
                var response = service.GetCustomerByName(name);

                return(new Customer
                {
                    Name = response.Name,
                    Id = response.Id
                });
            }

            return(null);
        }
Exemplo n.º 2
0
        private async Task <Result> CreateTask(ResolveFieldContext <object> context)
        {
            var task      = context.GetArgument <MTask>("task");
            var companyId = context.GetArgument <int>("companyId");

            await _unitOfWork.BeginTransactionAsync();

            try
            {
                ApplicationUser user = await _userManager.GetUserAsync((ClaimsPrincipal)context.UserContext);

                AttachingFiles(task, user, task.Company.CompanyId);

                await _unitOfWork.Task.Insert(task);

                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();

                return(new Result {
                    Status = true, Value = task.TaskId.ToString()
                });
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                return(new Result {
                    Status = false, Message = ex.Message
                });
            }
        }
Exemplo n.º 3
0
        private async Task <Chat> CreateChat(ResolveFieldContext <object> context)
        {
            var chat      = context.GetArgument <Chat>("chat");
            var companyId = context.GetArgument <int>("companyId");
            var userId    = context.GetArgument <string>("userId");

            await _unitOfWork.BeginTransactionAsync();

            try
            {
                chat.Company = new Company
                {
                    CompanyId = companyId
                };

                chat.Owner = new ApplicationUser
                {
                    Id = userId
                };

                await _unitOfWork.Chat.Insert(chat);

                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();

                return(chat);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                _unitOfWork.Rollback();
                return(null);
            }
        }
Exemplo n.º 4
0
        public static IQueryable <T> ApplyPaginationAndOrderBy <T>(this IQueryable <T> queryable, ResolveFieldContext <object> context)
        {
            var result = queryable;

            if (context.Arguments["orderby"] != null)
            {
                result = result.OrderBy(context.GetArgument <string>("orderby"));
            }
            else
            {
                result = result.OrderBy("Id");
            }

            if (context.Arguments["offset"] != null)
            {
                result = result.Skip(context.GetArgument <int>("offset"));
            }

            if (context.Arguments["first"] != null)
            {
                result = result.Take(context.GetArgument <int>("first"));
            }

            return(result);
        }
        public static IEnumerable <TSource> Page <T, TSource>(this ResolveFieldContext <T> context, IEnumerable <TSource> source)
        {
            var skip  = context.GetArgument <int>("skip");
            var first = context.GetArgument <int>("first");
            var last  = context.GetArgument <int>("last");

            if (last == 0 && first == 0)
            {
                var serviceProvider = ((GraphQLContext)context.UserContext).ServiceProvider;
                first = serviceProvider.GetService <IOptions <GraphQLSettings> >().Value.DefaultNumberOfResults;
            }

            if (last > 0)
            {
                source = source.Skip(Math.Max(0, source.Count() - last));
            }
            else
            {
                if (skip > 0)
                {
                    source = source.Skip(skip);
                }

                if (first > 0)
                {
                    source = source.Take(first);
                }
            }

            return(source);
        }
        private FamilyModel GetFamily(ResolveFieldContext <object> arg)
        {
            var id   = arg.GetArgument <int?>("id");
            var name = arg.GetArgument <string>("name");

            return(_dbSample.DBSample().FirstOrDefault(x => x.Name == name || x.Id == id));
        }
Exemplo n.º 7
0
        private Customer OnCreateCustomer(ResolveFieldContext <Customer> context)
        {
            var data = context.UserContext as DataSource;

            if (data == null)
            {
                return(null);
            }

            var firstName = context.GetArgument <string>("firstName");
            var lastName  = context.GetArgument <string>("lastName");
            var city      = context.GetArgument <string>("city");

            var customer = new Customer()
            {
                FirstName = firstName,
                LastName  = lastName,
                City      = city,
                Id        = data.Customers.Max(c => c.Id) + 1
            };

            data.Customers.Add(customer);

            return(customer);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Производит резолвинг данных с текущим контекстом.
        /// </summary>
        /// <param name="context">Контекст.</param>
        /// <returns>Данные.</returns>
        public override async Task <object> Resolve(ResolveFieldContext <object> context)
        {
            var request = new GetUserListsRequest();

            request.UserName           = context.GetArgument <string>("userName");
            request.LastListId         = context.GetArgument <string>("lastListId");
            request.SelectedListNumber = context.GetArgument <string>("selectedListNumber");
            request.ForUserName        = context.UserContext.As <UserContext>().UserName;
            request.ForUserId          = context.UserContext.As <UserContext>().UserId;

            MessageOutputBase outputMessage = null;

            await Execute(flow =>
            {
                flow.StartRegisterFlow()
                .Add <CheckUserExistsStep>()
                .Add <FetchUserListsStep>();

                flow.
                When <UserNotFoundStep, UserNotFoundParams>((notFound) =>
                {
                    outputMessage = notFound.Response;
                })
                .When <FetchUserListsStep, FetchUserListsParams>((fetch) =>
                {
                    outputMessage = fetch.ListsResponse;
                });
            }, request,
                          context);

            ProcessErrors(context, outputMessage);

            return(outputMessage);
        }
Exemplo n.º 9
0
        public static List <T> Paginate(IQueryable <T> result, ResolveFieldContext <object> context)
        {
            int page     = context.GetArgument <int>("page");
            int pageSize = context.GetArgument <int>("pageSize");

            return(result.Skip((page - 1) * pageSize).Take(pageSize).ToList());
        }
            protected override IEnumerable <Highscore> Resolve(ResolveFieldContext context)
            {
                var argumentScore  = context.GetArgument <int> (Templates.Highscore.Score);
                var argumentAmount = context.GetArgument <int>(Templates.Highscore.Amount, 5);

                using (var searchContent = ContentSearchManager.GetIndex(Templates.Highscore.MasterDbName).CreateSearchContext())
                {
                    var searchResults = searchContent.GetQueryable <HighscoreSearchResultItem>()
                                        .Where(i => i.LatestVersion &&
                                               i.Language == Templates.Highscore.DbLanguage &&
                                               i.TemplateId == Templates.Highscore.ID &&
                                               i.Path.StartsWith(Templates.Highscore.ContentPath));
                    var results = searchResults.GetResults();

                    var highscores = (from doc in results.Hits
                                      select new Highscore()
                    {
                        Name = doc.Document.GetField(Templates.Highscore.Name).Value,
                        Created = doc.Document.CreatedDate,
                        Score = int.Parse(doc.Document.GetField(Templates.Highscore.Score).Value)
                    }).ToList();
                    var high = highscores.Where(hs => hs.Score > argumentScore).Take(argumentAmount);
                    var low  = highscores.Where(hs => hs.Score < argumentScore).Take(argumentAmount);

                    return(high.Concat(low));
                }
            }
            protected override Highscore Resolve(ResolveFieldContext context)
            {
                var argumentScore = context.GetArgument <int>(Templates.Highscore.Score, -1);
                var argumentName  = context.GetArgument <string>(Templates.Highscore.NameLowercase);

                var master     = Factory.GetDatabase(Templates.Highscore.Master);
                var parentItem = master.Items[Templates.Highscore.HighscoresPath];
                var template   = master.GetTemplate(Templates.Highscore.ID);

                var highscore = new Highscore()
                {
                    Score   = argumentScore,
                    Name    = argumentName,
                    Created = DateTime.Now
                };

                using (new SecurityDisabler())
                {
                    var item = parentItem.Add(argumentName, template);
                    item.Editing.BeginEdit();
                    item[Templates.Highscore.Score] = argumentScore.ToString();
                    item[Templates.Highscore.Name]  = argumentName;
                    highscore.Added = item.Editing.EndEdit();
                }

                return(highscore);
            }
Exemplo n.º 12
0
        public String CSV(ResolveFieldContext <object> graphqlContext, HttpContext accesor)
        {
            var validation = this.validateToken(accesor);

            if (!validation)
            {
                return(null);
            }


            var results = from timeReports in _context.TimeReports select timeReports;
            var id      = graphqlContext.GetArgument <int>("id");

            results = results.Where((tr => tr.UserId == id));
            if (graphqlContext.HasArgument("inicialDate") && graphqlContext.HasArgument("endDate"))
            {
                var initialDateString = graphqlContext.GetArgument <string>("inicialDate");
                var initialDate       = DateTime.Parse(initialDateString);
                var endDateString     = graphqlContext.GetArgument <string>("endDate");
                var endDate           = DateTime.Parse(endDateString);
                results = results.Where(tr => tr.date > initialDate && tr.date < endDate);
            }
            else
            {
                if (graphqlContext.HasArgument("inicialDate"))
                {
                    var initialDateString = graphqlContext.GetArgument <string>("inicialDate");
                    var initialDate       = DateTime.Parse(initialDateString);
                    results = results.Where(tr => tr.date > initialDate);
                }
                if (graphqlContext.HasArgument("endDate"))
                {
                    var endDateString = graphqlContext.GetArgument <string>("endDate");
                    var endDate       = DateTime.Parse(endDateString);
                    results = results.Where(tr => tr.date < endDate);
                }
            }

            using (var workbook = new XLWorkbook()){
                var worksheet  = workbook.Worksheets.Add("Users");
                var currentRow = 1;
                worksheet.Cell(currentRow, 1).Value = "hours";
                worksheet.Cell(currentRow, 2).Value = "date";
                foreach (var report in results)
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = report.Hours;
                    worksheet.Cell(currentRow, 2).Value = report.date;
                }

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    var content = stream.ToArray();
                    var base64  = Convert.ToBase64String(content);

                    return(base64);
                }
            }
        }
Exemplo n.º 13
0
        public IEnumerable <Book> All(ResolveFieldContext <object> context, bool order)
        {
            var results = from books in _context.Books select books;

            if (context.HasArgument("name"))
            {
                var value = context.GetArgument <string>("name");
                results = results.Where(a => a.Name.Contains(value));
            }
            if (context.HasArgument("description"))
            {
                var value = context.GetArgument <string>("description");
                results = results.Where(a => a.Description.Contains(value));
            }
            if (context.HasArgument("price"))
            {
                var value = context.GetArgument <double>("price");
                results = results.Where(a => a.Price == value);
            }
            if (context.HasArgument("authorId"))
            {
                var value = context.GetArgument <long>("authorId");
                results = results.Where(a => a.AuthorId == value);
            }
            results = order?results.OrderBy(x => x.Name): results;
            return(PaginatedList <Book> .Paginate(results, context));
        }
Exemplo n.º 14
0
        private Account GetAccount(ResolveFieldContext <object> context, IServiceProvider serviceProvider)
        {
            var id = context.GetArgument <int?>("id");

            if (id != null)
            {
                return(new Account
                {
                    Currency = "USD",
                    Balance = 1000.0,
                    Id = id
                });
            }

            var currency = context.GetArgument <string>("currency");

            if (currency != null)
            {
                return(new Account
                {
                    Currency = "Sek",
                    Balance = 1000.0,
                    Id = 1
                });
            }

            return(null);
        }
Exemplo n.º 15
0
        private async Task <IList <DTO.PersonOutput> > LoadPeople(ResolveFieldContext <object> context)
        {
            var userName           = context.GetArgument <string>("userName");
            var normalizedUserName = context.GetArgument <string>("normalizedUserName");

            return(await PersonManager.GetEntitiesAsync(userName, normalizedUserName));
        }
Exemplo n.º 16
0
        private Employee OnSetActive(ResolveFieldContext <Employee> resolveFieldContext)
        {
            if (_employeeRepository == null)
            {
                return(null);
            }

            var idValue = resolveFieldContext.
                          GetArgument <int?>("id");

            if (idValue == null)
            {
                throw new ArgumentException($"\"id\" argument is missing");
            }

            var isActiveValue = resolveFieldContext.
                                GetArgument <bool?>("isActive");

            if (isActiveValue == null)
            {
                throw new ArgumentException($"\"isActive\" argument is missing");
            }

            var employee = _employeeRepository.Employees.FirstOrDefault(e => e.Id == idValue.Value);

            // push mutation to domain
            employee?.SetActive(isActiveValue.Value);

            return(employee);
        }
Exemplo n.º 17
0
        private async Task <IList <DTO.UnitOutput> > LoadUnits(ResolveFieldContext <object> context)
        {
            var id   = context.GetArgument <long?>("id");
            var name = context.GetArgument <string>("name");

            return(await UnitManager.GetEntitiesAsync(id, name));
        }
Exemplo n.º 18
0
        private Employee OnCreateEmployee(ResolveFieldContext <Employee> resolveFieldContext)
        {
            if (_employeeRepository == null)
            {
                return(null);
            }

            var isActiveValue = resolveFieldContext.
                                GetArgument <bool>("isActive");
            var ageValue = resolveFieldContext.
                           GetArgument <int>("age");
            var firstNameValue = resolveFieldContext.
                                 GetArgument <string>("firstName");
            var lastNameValue = resolveFieldContext.
                                GetArgument <string>("lastName");
            var genderValue = resolveFieldContext.
                              GetArgument <string>("gender");

            int newId = _employeeRepository.Employees.Max(e => e.Id) + 1;

            Employee employee = Employee.Create(newId, isActiveValue, ageValue, firstNameValue, lastNameValue, genderValue);

            _employeeRepository.Employees.Add(employee);

            return(employee);
        }
Exemplo n.º 19
0
        public IEnumerable <Project> filter(ResolveFieldContext <object> graphqlContext, HttpContext accesor)
        {
            var validation = this.validateToken(accesor);

            if (!validation)
            {
                return(null);
            }

            var results = from projects in _context.Projects select projects;

            if (graphqlContext.HasArgument("id"))
            {
                var id = graphqlContext.GetArgument <int>("id");
                results = results.Where(p => p.id == id);
            }
            if (graphqlContext.HasArgument("name"))
            {
                var name = graphqlContext.GetArgument <string>("name");
                results = results.Where(p => p.Name.Contains(name));
            }
            if (graphqlContext.HasArgument("description"))
            {
                var name = graphqlContext.GetArgument <string>("description");
                results = results.Where(p => p.Description.Contains(name));
            }
            return(results);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Get all available arguments as an object
        /// </summary>
        /// <param name="context"></param>
        /// <typeparam name="ContextType"></typeparam>
        /// <typeparam name="ArgumentsType"></typeparam>
        /// <returns></returns>
        public static ArgumentsType GetArguments <ContextType, ArgumentsType>(this ResolveFieldContext <ContextType> context, ArgumentsType result) where ArgumentsType : new()
        {
            var argumentsProperties = typeof(ArgumentsType).GetProperties();

            var argumentNameLookup = context.Arguments.Keys.ToDictionary(x => x.ToLower(), x => x);

            foreach (var argumentsProperty in argumentsProperties)
            {
                var lowerPropertyName = argumentsProperty.Name.ToLower();

                //get the actual argument name in its proper case
                var argumentName = argumentNameLookup.ContainsKey(lowerPropertyName) ?
                                   argumentNameLookup[lowerPropertyName] :
                                   null;

                //if the context has this argument defined and available, get it
                if (argumentName != null && context.Arguments.ContainsKey(argumentName) && context.Arguments[argumentName] != null)
                {
                    //IEnumerable objects need some explicit typing
                    if (argumentsProperty.PropertyType == typeof(IEnumerable <int>))
                    {
                        var value = context.GetArgument <List <int> >(argumentName);
                        argumentsProperty.SetValue(result, value);
                    }
                    else
                    {
                        var value = context.GetArgument(argumentName, argumentsProperty.PropertyType);
                        argumentsProperty.SetValue(result, value);
                    }
                }
            }
            return(result);
        }
        public async Task <TSource> AddOrUpdateAsync <TSource>(ResolveFieldContext <object> context, string sourceName) where TSource : class
        {
            AssertWithClaimsPrincipal(AssertAction.Create, context);
            var item = context.GetArgument <TSource>(sourceName);
            var ctx  = context.UserContext as IGraphRequestContext;

            try
            {
                var edges = _connectionEdgeResolver.HandleConnectionEdges(item, async(model) =>
                {
                    await _graphQlRepositoryProvider.GetRepository(model.GetType())
                    .AddOrUpdateAsync(model.GetType(), model, ctx);
                });

                if (edges.Count > 0)
                {
                    await _graphQlRepositoryProvider.GetRepository(typeof(ConnectionEdge))
                    .BatchAddOrUpdateAsync(edges, ctx);
                }

                if (_searchMappedModels.TryGetMappedSearchType <TSource>(out var mappedSearchType))
                {
                    var mappedInstance = _searchMappedModels.CreateInstanceFromMap(item);
                    await _graphQlRepositoryProvider.GetRepository(mappedSearchType)
                    .AddAsync(mappedSearchType, mappedInstance, ctx);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An error has occured while performing an add operation.");
                throw;
            }
            return(context.GetArgument <TSource>(sourceName));
        }
Exemplo n.º 22
0
        public object Resolve(ResolveFieldContext context)
        {
            var queryable = _dbContext.Query(_tableMetadata.AssemblyFullName);

            if (context.FieldName.Contains("_list"))
            {
                var first = context.Arguments["first"] != null?
                            context.GetArgument("first", int.MaxValue) :
                                int.MaxValue;

                var offset = context.Arguments["offset"] != null?
                             context.GetArgument("offset", 0) :
                                 0;

                return(queryable
                       .Skip(offset)
                       .Take(first)
                       .ToDynamicList <object>());
            }
            else
            {
                var id = context.GetArgument <Guid>("id");
                return(queryable.FirstOrDefault($"Id == @0", id));
            }
        }
        public IEnumerable <Book> All(ResolveFieldContext <object> context)
        {
            var result = from b in _context.Books select b;

            if (context.HasArgument("name"))
            {
                var value = context.GetArgument <string>("name");
                result = result.Where(a => a.Name.Contains(value));
            }
            if (context.HasArgument("description"))
            {
                var value = context.GetArgument <string>("description");
                result = result.Where(a => a.Description.Contains(value));
            }
            if (context.HasArgument("price"))
            {
                var value = context.GetArgument <double>("price");
                result = result.Where(a => a.Price == value);
            }
            if (context.HasArgument("authorId"))
            {
                var value = context.GetArgument <long>("authorId");
                result = result.Where(a => a.AuthorId == value);
            }
            return(result);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Update user using GraphQL mutation
        /// </summary>
        /// <param name="_userService">Generic user repository</param>
        /// <param name="context">GraphQL context</param>
        /// <returns>User updated</returns>
        public static async Task <User> UpdateUserGQL(
            this IEntityService <User> _userService,
            ResolveFieldContext <object> context)
        {
            User   user   = context.GetArgument <User>("user");
            string userBy = context.GetArgument <string>("userBy");

            if (user == null || user.Id.Equals(Guid.Empty))
            {
                context.Errors.Add(new ExecutionError("User to update or id field empty."));
                return(null);
            }

            User dbUser = await _userService.GetByIdAsync(user.Id);

            if (dbUser == null)
            {
                context.Errors.Add(new ExecutionError($"Couldn't find user with id {user.Id}."));
                return(null);
            }

            dbUser.Name             = user.Name;
            dbUser.Email            = user.Email;
            dbUser.Password         = user.Password;
            dbUser.ModificationDate = DateTime.UtcNow;
            dbUser.LastMdifiedBy    = userBy;

            return(await _userService.UpdateAsync(dbUser));
        }
Exemplo n.º 25
0
        public static IEnumerable <TSource> Page <T, TSource>(this ResolveFieldContext <T> context, IEnumerable <TSource> source)
        {
            var skip  = context.GetArgument <int>("skip");
            var first = context.GetArgument <int>("first");
            var last  = context.GetArgument <int>("last");

            if (last > 0)
            {
                source = source.Skip(Math.Max(0, source.Count() - last));
            }
            else
            {
                if (skip > 0)
                {
                    source = source.Skip(skip);
                }

                if (first > 0)
                {
                    source = source.Take(first);
                }
            }

            return(source);
        }
Exemplo n.º 26
0
        public IEnumerable<T> Resolve(ResolveFieldContext context)
        {
            var zzz3 = context.ParentType.Fields.Single(f => f.Name == context.Document.Operations.Single().SelectionSet.Selections.OfType<Field>().Single().Name);
            var zzz = context.Schema.FindType("order");
            var zzz2 = context.Schema.Query.Fields.Single(f => f.Name == context.FieldAst.Name);

            var barcode = context.GetArgument<string>("barcode");
            var title = context.GetArgument<string>("title");
            var sellingPrice = context.GetArgument<decimal>("sellingPrice");

            var results = new List<T>();

            var odataParser = new ODataUriParser(_edmModel, new Uri("http://dummy"), new Uri("http://dummy/Orders?$expand=Customer&$select=Name"));
            odataParser.Resolver.EnableCaseInsensitive = true;
            //ODataUri odataUri = odataParser.ParseUri();

            var translator = new OeGraphQLAstToODataUri(_edmModel, context.Schema);
            ODataUri odataUri = translator.Translate(context.Document.OriginalQuery);
            var odataQuery = odataUri.BuildUri(ODataUrlKeyDelimiter.Parentheses);

            var parser = new OeGetParser(_dataAdapter, _edmModel);
            Parsers.OeQueryContext queryContext = parser.CreateQueryContext(odataUri, 0, false, OeMetadataLevel.Minimal);
            Db.OeAsyncEnumerator asyncEnumerator = _dataAdapter.ExecuteEnumerator(context.UserContext, queryContext, CancellationToken.None);
            using (var entityAsyncEnumerator = new OeEntityAsyncEnumerator<T>(queryContext.EntryFactory, asyncEnumerator, queryContext))
            {
                while (entityAsyncEnumerator.MoveNext().GetAwaiter().GetResult())
                    results.Add((T)entityAsyncEnumerator.Current);
            }
            return results;
        }
Exemplo n.º 27
0
        private async Task <ExecutionResult> CheckExecution(ResolveFieldContext <object> context)
        {
            var taskId = context.GetArgument <int>("taskId");
            var status = context.GetArgument <bool>("status");

            await _unitOfWork.BeginTransactionAsync();

            try
            {
                ApplicationUser user = await _userManager.GetUserAsync((ClaimsPrincipal)context.UserContext);

                var result = await _unitOfWork.Task.MarkExecution(taskId, status, user);

                _unitOfWork.Commit();
                result.Status = true;

                return(result);
            }
            catch (Exception)
            {
                _unitOfWork.Rollback();
                return(new ExecutionResult {
                    Status = false
                });
            }
        }
Exemplo n.º 28
0
        protected override Event Resolve(ResolveFieldContext context)
        {
            string name        = context.GetArgument <string>("name");
            string description = context.GetArgument <string>("description");
            string date        = context.GetArgument <string>("date");
            string location    = context.GetArgument <string>("location");
            Guid   group_id    = context.GetArgument <Guid>("group_id");

            name = ItemUtil.ProposeValidItemName(name);

            var variables = new
            {
                date,
                description,
                location,
                name,
                group_id
            };

            var graphQLClient = new GraphQLClient();

            DataObject <InsertEventData> responseObject = graphQLClient.Execute <DataObject <InsertEventData> >("CreateEvent.graphql", variables);

            Event eventResult = responseObject.data.insert_event.returning.FirstOrDefault();

            return(eventResult);
        }
Exemplo n.º 29
0
        private async Task <bool> ChangeDateTimeCalendarEvent(ResolveFieldContext <object> context)
        {
            int      calendarEventId = context.GetArgument <int>("calendarEventId");
            DateTime start           = context.GetArgument <DateTime>("startDateTime");
            DateTime end             = context.GetArgument <DateTime>("endDateTime");

            await _unitOfWork.BeginTransactionAsync();

            try
            {
                var calendarEvent = await _unitOfWork.CalendarEvent.FindById(calendarEventId);

                calendarEvent.Start = start;
                calendarEvent.End   = end;

                await _unitOfWork.SaveChangesAsync();

                _unitOfWork.Commit();

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                _unitOfWork.Rollback();
                return(false);
            }
        }
Exemplo n.º 30
0
        private object GetTradeEntries(DatabaseContext storeProvider, ResolveFieldContext <object> context)
        {
            if (context == null)
            {
                throw new ArgumentNullException();
            }

            var mongoFilterBuilder = Builders <FellowLibrary.Models.TradeEntry> .Filter;

            var finalFilter = mongoFilterBuilder.Where(x => true);

            var marketProvider = context.GetArgument <int?>("marketProvider");

            if (marketProvider.HasValue)
            {
                finalFilter = finalFilter & mongoFilterBuilder.Eq(x => x.Provider, marketProvider.Value);
            }

            var tradingPair = context.GetArgument <String>("tradingPair");

            if (tradingPair != null)
            {
                finalFilter = finalFilter & mongoFilterBuilder.Eq(x => x.TradingPair, tradingPair);
            }


            return(new FellowLibrary.Models.TradeEntry[] { });

            //return storeProvider.Trades.FindAsync(finalFilter);
        }