public IEnumerable <Book> GetBooks(Rubric rubric = null, Publisher publisher = null, Author author = null, string search = "")
        {
            var books = Ninject.Get <GetBooksQuery>().Execute();

            if (rubric != null)
            {
                var rubrics    = GetRubrics();
                var dictionary = rubrics.ToDictionary(r => r.Id);
                if (dictionary.ContainsKey(rubric.Id))
                {
                    rubric = dictionary[rubric.Id];
                    books  = from b in books
                             where b.Rubric.Id == rubric.Id || dictionary.ContainsKey(b.Rubric.Id) && Rubric.IsChildOf(rubrics, dictionary[b.Rubric.Id], rubric)
                             select b;
                }
            }
            if (author != null)
            {
                var query = Ninject.Get <GetAuthorBooksQuery>();
                query.Author = author;
                var authorBooks = query.Execute();
                books = from b in books
                        join ab in authorBooks on b.Id equals ab.Id
                        select b;
            }
            books                 = publisher.Return(p => books.Where(b => b.Publisher.Id == p.Id), books);
            books                 = string.IsNullOrEmpty(search) ? books : from b in books
                            let s = search.ToLower()
                                    where b.Name.ToLower().Contains(s) || (b.Annotation ?? string.Empty).ToLower().Contains(s)
                                    select b;

            return(books.ToArray());
        }
        protected override void ApplicationStartup(Ninject.IKernel container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Conventions.ViewLocationConventions.Add((viewName, model, context) => string.Concat("../../Views/", context.ModuleName.Replace("Controller", ""), "/", viewName));
            Conventions.ViewLocationConventions.Add((viewName, model, context) => string.Concat("Views/", context.ModuleName.Replace("Controller", ""), "/", viewName));
        }
        public IEnumerable <Author> SetBookAuthors(Book book, IEnumerable <Author> authors)
        {
            var existsAuthors       = GetBookAuthors(book).ToArray();
            var existsDictionary    = existsAuthors.ToDictionary(a => a.Id);
            var insertingDictionary = authors.ToDictionary(a => a.Id);

            var provider = Factory.Get();
            var executor = Ninject.Get <Executor>();

            //сначала удаляем те, что существуют, но больше не нужные
            //затем добавляем те, что не существуют
            executor.ExecuteNonQueries((from a in existsAuthors
                                        where !insertingDictionary.ContainsKey(a.Id)
                                        select(BookAuthorQuery) new DeleteBookAuthorQuery(provider)
            {
                Book = book,
                Author = a
            })
                                       .Union(from a in authors
                                              where !existsDictionary.ContainsKey(a.Id)
                                              select(BookAuthorQuery) new InsertBookAuthorQuery(provider)
            {
                Book   = book,
                Author = a
            }));
            return(authors);
        }
        public IEnumerable <Rubric> GetRubricsHierarchy()
        {
            var rubrics = Rubric.FormTree(Ninject.Get <GetRubricsQuery>().Execute()).ToArray();

            ClearTree(rubrics);
            return(rubrics);
        }
Exemplo n.º 5
0
        void AddRequest(Book book)
        {
            var quantity = 1;

            using (var form = Ninject.Get <BookQuantityInputDialog>()) {
                if (form.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                quantity = form.BookQuantity;
            }

            if (!Requests.Any(r => r.Book.Id == book.Id))
            {
                Requests.Add(new Request()
                {
                    Id = new RequestHeader()
                    {
                        Id = -1
                    },
                    Book         = book,
                    BookQuantity = quantity
                });
                Requests = Requests.OrderBy(r => r.Book.Name).ToList();
                gcResult.Bind(Requests);
            }
        }
        public IEnumerable <Author> GetBookAuthors(Book book)
        {
            var query = Ninject.Get <GetBookAuthorsQuery>();

            query.Book = book;
            return(query.Execute());
        }
        private static object GetCurrentUser(Ninject.Activation.IContext context, Ninject.Planning.Targets.ITarget target)
        {
            if(HttpContext.Current != null)
                return HttpContext.Current.GetOwinContext().Authentication.User.Identity;

            return null;
        }
 public static void Bind(Ninject.IKernel kernel)
 {
     kernel
         .BindFilter<PermissionAuthorizeFilter>(FilterScope.Controller | FilterScope.Action, null)
         .WhenControllerHas<PermissionAuthorizeAttribute>()
         .WithConstructorArgumentFromControllerAttribute<PermissionAuthorizeAttribute>("Permissions", x => x.Permissions);
 }
Exemplo n.º 9
0
        public Reader AddReader(Reader reader)
        {
            if (GetReaders().Any(r => r.PassportNumber == reader.PassportNumber && r.Card.ExpiryDate.Date > DateTime.Now.Date))
            {
                throw new Exception("Читатель с таким номером паспорта уже существует и его читательский билет не истек! Добавление читателя невозможно");
            }

            var executor = Ninject.Get <Executor>();
            var provider = Factory.Get();

            reader.Card = new Card();
            var insertReader = new InsertReaderQuery(provider)
            {
                Reader = reader
            };
            var insertCard = new InsertCardQuery(provider)
            {
                Reader = reader
            };

            executor.ExecuteNonQueries(new NoValueQuery[] {
                insertReader,
                insertCard
            });
            return(reader);
        }
Exemplo n.º 10
0
        public IEnumerable <Reader> GetBookObligators(Book book)
        {
            var query = Ninject.Get <GetBookObligatorsQuery>();

            query.Book = book;
            return(query.Execute());
        }
Exemplo n.º 11
0
        public RequestApproved CloseRequest(RequestApproved request)
        {
            request = GetRequestApproved(request);

            if (request.IsReturned)
            {
                throw new Exception("Книга уже возвращена");
            }

            var returnBook = Ninject.Get <UpdateBooksQuantityQuery>();

            returnBook.Book         = request.Id.Book;
            returnBook.BookQuantity = request.Id.BookQuantity;

            var closeRequest = Ninject.Get <CloseRequestQuery>();

            closeRequest.RequestApproved = request;

            var executor = Ninject.Get <Executor>();

            try {
                executor.ExecuteNonQueries(new NoValueQuery[] {
                    returnBook,
                    closeRequest
                });
                request.IsReturned = true;
            } catch (Exception exc) {
                throw exc;
            }
            return(request);
        }
Exemplo n.º 12
0
        public IEnumerable <RequestRejected> GetRejectedRequests(Card card)
        {
            var query = Ninject.Get <GetRejectedRequestsQuery>();

            query.Card = card;
            return(query.Execute().OrderByDescending(r => r.Id.Id.CreateDate));
        }
Exemplo n.º 13
0
        public override IInterceptor CreateInterceptor(Ninject.Core.Interception.IRequest request)
        {
            var ti = request.Kernel.Get<TransactionInterceptor>();
            ti.ConnectionName = ConnectionName;

            return ti;
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Ninject.InitKernel(NatsClientTypeEnum.Subscriber);
            var publisher = Ninject.Get <INatsClient>();
            var task      = publisher.Run("foo");

            task.Start();
        }
Exemplo n.º 15
0
        public Book AddBook(Book book)
        {
            var query = Ninject.Get <InsertBookQuery>();

            query.Book = book;
            query.Execute();
            return(book);
        }
Exemplo n.º 16
0
        public Reader DeleteReader(Reader reader)
        {
            var query = Ninject.Get <DeleteReaderQuery>();

            query.Reader = reader;
            query.Execute();
            return(reader);
        }
Exemplo n.º 17
0
        public Book DeleteBook(Book book)
        {
            var query = Ninject.Get <DeleteBookQuery>();

            query.Book = book;
            query.Execute();
            return(book);
        }
Exemplo n.º 18
0
        public Rubric DeleteRubric(Rubric rubric)
        {
            var query = Ninject.Get <DeleteRubricQuery>();

            query.Rubric = rubric;
            query.Execute();
            return(rubric);
        }
Exemplo n.º 19
0
        static void Main()
        {
            Ninject.InitKernel(NatsClientTypeEnum.Publisher);
            var publisher = Ninject.Get <INatsClient>();
            var task      = publisher.Run("foo");

            task.Start();
        }
Exemplo n.º 20
0
        public Publisher DeletePublisher(Publisher publisher)
        {
            var query = Ninject.Get <DeletePublisherQuery>();

            query.Publisher = publisher;
            query.Execute();
            return(publisher);
        }
Exemplo n.º 21
0
        public override void Init(Ninject.IKernel container)
        {
            _lastCheck = DateTime.UtcNow;

            base.Init(container);

            _eventhandlingServiceHost.Init();
        }
Exemplo n.º 22
0
        public Rubric AddRubric(Rubric rubric)
        {
            var query = Ninject.Get <InsertRubricQuery>();

            query.Rubric = rubric;
            query.Execute();
            return(rubric);
        }
Exemplo n.º 23
0
        public Publisher AddPublisher(Publisher publisher)
        {
            var query = Ninject.Get <InsertPublisherQuery>();

            query.Publisher = publisher;
            query.Execute();
            return(publisher);
        }
Exemplo n.º 24
0
        public Author DeleteAuthor(Author author)
        {
            var query = Ninject.Get <DeleteAuthorQuery>();

            query.Author = author;
            query.Execute();
            return(author);
        }
Exemplo n.º 25
0
        public Author AddAuthor(Author author)
        {
            var query = Ninject.Get <InsertAuthorQuery>();

            query.Author = author;
            query.Execute();
            return(author);
        }
Exemplo n.º 26
0
 public override void Activate(Ninject.Activation.IContext context, Ninject.Activation.InstanceReference reference)
 {
     if(reference.Instance is ILogger)
     {
         _logger = (ILogger)reference.Instance;
     }
     _logger.Debug("Ninject Activate: " + reference.Instance.GetType());
     base.Activate(context, reference);
 }
Exemplo n.º 27
0
 void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (!(e.Cancel = !DialogMessages.Question("Вы уверены, что хотите покинуть систему?")))
     {
         try {
             GetAuthenticationProxy().LogOut(Ninject.Get <AuthenticationData>());
         } catch {
         }
     }
 }
Exemplo n.º 28
0
        protected override void ApplicationStartup(Ninject.IKernel container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            // Embedded view support
            //ResourceViewLocationProvider.RootNamespaces.Add();
            Conventions.ViewLocationConventions.Add((viewName, model, context) =>
            {
                return string.Concat("Pool/", viewName);
            });
        }
Exemplo n.º 29
0
 public IEnumerable <RequestCreator> GetRequestCreators(string search = "")
 {
     search = (search ?? string.Empty).Trim().ToLower();
     return
         (Ninject.Get <GetRequestCreatorsQuery>()
          .Execute()
          .Where(r =>
                 r.FirstName.ToLower().Contains(search) ||
                 r.LastName.ToLower().Contains(search) ||
                 r.MiddleName.ToLower().Contains(search) ||
                 r.Card.Id.ToString().Contains(search)));
 }
Exemplo n.º 30
0
        public static void Main(string[] args)
        {
            var kernel = new StandardKernel();
            kernel.Load<Protogame2DIoCModule>();
            kernel.Load<ProtogameAssetIoCModule>();
            AssetManagerClient.AcceptArgumentsAndSetup<GameAssetManagerProvider>(kernel, args);

            using (var game = new {PROJECT_SAFE_NAME}Game(kernel))
            {
                game.Run();
            }
        }
Exemplo n.º 31
0
 void OnEndLoadAuthors(Book book, IEnumerable <Author> bookAuthors, IEnumerable <Author> authors)
 {
     Ninject.Rebind <BookAuthorEditForm>().ToMethod(method => {
         return(new BookAuthorEditForm(book, authors)
         {
             Data = bookAuthors,
             Operation = EditFormOperation.Insert
         });
     });
     using (var form = Ninject.Get <BookAuthorEditForm>()) {
         form.ShowDialog();
     }
 }
Exemplo n.º 32
0
        public Rubric UpdateRubric(Rubric rubric)
        {
            var rubrics = GetRubrics();

            if (Rubric.IsChildOf(rubrics, rubric, rubric))
            {
                throw new Exception("Обнаружена циклическая зависимость рубрик. Обновление рубрики невозможно");
            }

            var query = Ninject.Get <UpdateRubricQuery>();

            query.Rubric = rubric;
            query.Execute();
            return(rubric);
        }
        public void Register(Ninject.IKernel container)
        {
            //database initializer
            //container.Bind<IDatabaseInitializer<ThipperContext>>().To<ThipperSampleDataInitializer>();
            //container.Bind<ThipperContext>().To<ThipperContext>().InRequestScope();

            //repositories
            //container.Bind<IUserProfileRepository>().To<UserProfileRepository>();
            //container.Bind<IObjectDetailRepository>().To<ObjectDetailRepository>();
            //container.Bind<IItemRepository>().To<ItemRepository>();
            //container.Bind<ILocationRepository>().To<LocationRepository>();
            //container.Bind<IContactRepository>().To<ContactRepository>();
            //container.Bind<IGroupRepository>().To<GroupRepository>();
            //container.Bind<ITrackRepository>().To<TrackRepository>();
        }
Exemplo n.º 34
0
        /*
         * Ninject scoping function; traverse the activation context hierarchy to the root, or a type
         * that has a GameObjectBoundary attribute.
         */
        public static object GameObjectBoundaryScoper(Ninject.Activation.IContext context)
        {
            if (context.Request.Target != null) {

                if (context.Request.Target.Type.IsDefined(typeof(GameObjectBoundary), true)) {
                    return context;
                }
            }

            if (context.Request.ParentContext != null) {
                return GameObjectBoundaryScoper (context.Request.ParentContext);
            }

            return context;
        }
Exemplo n.º 35
0
        public AuthenticationData Authenticate(string name, string hash)
        {
            var employee = Ninject.Get <GetEmployeesQuery>().Execute().FirstOrDefault(e => e.Name == name && e.Password == hash);

            if (employee != null)
            {
                var result = new AuthenticationData()
                {
                    Id       = Guid.NewGuid(),
                    Employee = employee
                };
                Authorized[result.Id] = result;
                return(result);
            }
            return(null);
        }
 public void Intercept(Ninject.Extensions.Interception.IInvocation invocation)
 {
     try
     {
         invocation.Proceed();
     }
     catch (InvalidOperationException e)
     {
         if (e.InnerException is ArgumentNullException)
         {
             var x = 1;
             //DO SOMETHING WITH THE ORIGIONAL ERROR!
         }
         
         //DO SOMETHING WITH THE ORIGIONAL ERROR!
     }
 }
Exemplo n.º 37
0
        public RequestCreator CreateRequest(Reader reader, IEnumerable <Request> requests)
        {
            if (requests == null || !requests.Any())
            {
                throw new Exception("Для создания запроса необходимо выбрать хотя бы одну книгу");
            }

            var card = GetReaders().Select(r => r.Card).FirstOrDefault(c => c.Id == reader.Card.Id);

            if (card == null)
            {
                throw new Exception("Не удалось обнаружить читательский билет. Возможно, билет не создан");
            }
            if (card.ExpiryDate.Date < DateTime.Now.Date)
            {
                throw new Exception("Срок действия читательского билета истек. Перед созданием запроса продлите читательский билет");
            }

            var executor = Ninject.Get <Executor>();
            var id       = Ninject.Get <GenerateRequestIdQuery>().Execute();
            var provider = Factory.Get();

            foreach (var r in requests)
            {
                r.Id = new RequestHeader()
                {
                    Id     = id,
                    Reader = reader
                };
            }

            executor.ExecuteNonQueries(from r in requests
                                       select new InsertRequestQuery(provider)
            {
                Request = r
            });

            return(GetRequestCreators().FirstOrDefault(c => c.Card.Id == reader.Card.Id));
        }
Exemplo n.º 38
0
        public Reader RenewCard(Reader reader)
        {
            reader = GetReaders().FirstOrDefault(r => r.Id == reader.Id);
            if (reader == null)
            {
                throw new Exception("Читатель не найден");
            }
            if (reader.Card.ExpiryDate.Date > DateTime.Now.Date)
            {
                throw new Exception("Срок действия читательского билета еще не истек. Продление невозможно");
            }
            if (reader.Card.ExpiryDate.AddMonths(1).Date < DateTime.Now.Date)
            {
                throw new Exception("Продление читательского билета возможно только в течении месяца после его срока истечения");
            }

            var query = Ninject.Get <RenewCardQuery>();

            query.Reader = reader;
            query.Execute();
            return(reader);
        }
Exemplo n.º 39
0
        async void LogIn()
        {
            if (_blocked)
            {
                return;
            }
            _blocked = true;
            try {
                var result = await LogIn(Login, Password);

                if (result != null)
                {
                    Ninject.Bind <AuthenticationData>().ToConstant(result);
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    throw new Exception("Неудалось подключиться к серверу. Неверное имя пользователя или пароль");
                }
            } catch (Exception exc) {
                DialogMessages.Error(exc.Message);
            }
            _blocked = false;
        }
Exemplo n.º 40
0
        //public IEnumerable<RequestApproved> GetApprovedRequests(RequestHeader request) {
        //    var query = Ninject.Get<GetApprovedRequestsQuery>();
        //    query.Request = request;
        //    return query.Execute();
        //}

        //public IEnumerable<RequestRejected> GetRejectedRequests(RequestHeader request) {
        //    var query = Ninject.Get<GetRejectedRequestsQuery>();
        //    query.Request = request;
        //    return query.Execute();
        //}

        public RequestApproved RenewRequest(RequestApproved request)
        {
            request = GetRequestApproved(request);

            if (request.IsReturned)
            {
                throw new Exception("Книга уже возвращена. Продление невозможно");
            }

            if (DateTime.Now.Date <= request.ReturnDate.Date)
            {
                throw new Exception("Срок возврата еще не истек. Продление невозможно");
            }

            var command = Ninject.Get <RenewRequestQuery>();

            command.RequestApproved = request;
            try {
                command.Execute();
            } catch (DbException exc) {
                throw new Exception("Достигнут предел числа продлений. Дальнейшее продление невозможно");
            }
            return(request);
        }
Exemplo n.º 41
0
        public IEnumerable <Notification> SendNotifications()
        {
            var query = Ninject.Get <SendNotificationsQuery>();

            query.Execute();
            var sended = query.Notifications.ToList();
            var result = new List <Notification>();

            if (sended.Count > 0)
            {
                result.AddRange(
                    from s in sended
                    join n in Ninject.Get <GetNotificationsQuery>().Execute() on new {
                    RequestId = s.RequestId,
                    BookId    = s.BookId
                } equals new {
                    RequestId = n.Id.Id.Id,
                    BookId    = n.Id.Book.Id
                }
                    select n
                    );
            }
            return(result);
        }
Exemplo n.º 42
0
 private object getScope(Ninject.Activation.IContext context)
 {
     return sceneScope;
 }
Exemplo n.º 43
0
 private static object scoper(Ninject.Activation.IContext context)
 {
     return levelScope;
 }
Exemplo n.º 44
0
 protected override void OnError(Ninject.Core.Interception.IInvocation invocation, Exception exception)
 {
     ConfigurationHelper.RollbackTransaction(ConnectionName);
 }
Exemplo n.º 45
0
 public override object Create(Ninject.Core.Activation.IContext context)
 {
     return _service.GetImplementation();
 }
Exemplo n.º 46
0
 protected override Type DoGetImplementationType(Ninject.Core.Activation.IContext context)
 {
     return _service.ImplementationType;
 }
 public override Ninject.Extensions.Interception.IInterceptor CreateInterceptor(Ninject.Extensions.Interception.Request.IProxyRequest request)
 {
     return new LoggingInterceptor();
 }
 public void ParseWithCompressFlagAndInputFileNameShouldReturnCompressCommand()
 {
     var arguments = new[] {"-c", "input"};
     ICommand actual = target.Parse(arguments);
     Assert.IsInstanceOf<CompressCommand>(actual);
 }
 public void ParseWithDecompressFlagWithoutInputFileNameShouldReturnHelpCommand()
 {
     var arguments = new[] {"-d"};
     ICommand actual = target.Parse(arguments);
     Assert.IsInstanceOf<HelpCommand>(actual);
 }
 public NinjectDependencyScope(Ninject.Syntax.IResolutionRoot resolver)
 {
     this.resolver = resolver;
 }
Exemplo n.º 51
0
 protected override void AfterInvoke(Ninject.Core.Interception.IInvocation invocation)
 {
     ConfigurationHelper.CommitTransaction(ConnectionName);
 }
 public void ParseWithInvalidFlagShouldReturnHelpCommand()
 {
     var arguments = new[] {"-f", "Forr"};
     ICommand actual = target.Parse(arguments);
     Assert.IsInstanceOf<HelpCommand>(actual);
 }
Exemplo n.º 53
0
			public ControllerFactoryStub(Ninject.Syntax.IResolutionRoot resolutionRoot) : base(resolutionRoot) { }
 public void ParseWithMoreThanTwoArgumentsShouldReturnHelpCommand()
 {
     var arguments = new[] {"-c", "Foo", "Bar"};
     ICommand actual = target.Parse(arguments);
     Assert.IsInstanceOf<HelpCommand>(actual);
 }
 public override void OnClick(Ninject.IKernel kernel)
 {
     throw new System.NotImplementedException();
 }
 /// <summary>Obtains the BatchedEntityDataContext.</summary>
 /// <param name="context">The ninject context.</param>
 /// <returns></returns>
 protected virtual IObjectContextOrchestrator ObtainObjectContextOrchestrator(Ninject.Activation.IContext context)
 {
     return new ObjectContextOrchestrator(this.EntityConnectionContainers);
 }
Exemplo n.º 57
0
 protected override void SetupDependencies(Ninject.IKernel kernel)
 {
     kernel.Load<Configuration.IoC.AppServicesModule>();
     kernel.Load<Configuration.IoC.DomainServicesModule>();
 }
 /*protected override IEnumerable<Type> ViewEngines
 {
     get
     {
         return new Type[] { typeof(RazorViewEngine) };
     }
 }*/
 protected override void ConfigureApplicationContainer(Ninject.IKernel existingContainer)
 {
     base.ConfigureApplicationContainer(existingContainer);
     existingContainer.Load(new INinjectModule[]{ new MyApplicationModule() });
 }
 protected override void ConfigureRequestContainer(Ninject.IKernel container)
 {
     base.ConfigureRequestContainer(container);
     //container.Bind<MyModule>();
 }
Exemplo n.º 60
0
 protected override void ConfigureApplicationContainer(Ninject.IKernel container)
 {
     container.Bind<IDocumentSession>().ToMethod(c => DocumentSession.Invoke());
 }