Example #1
0
        /// <summary>
        /// Creates all resources
        /// </summary>
        public static void Init()
        {
            var resourceRepository = new Repository<Resource>();
         
            if (resourceRepository.Get().Count == 0)
            {

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Metal",
                        Description = "Basic resource used to build",
                        InitialValue = 200.0
                    }
                    );

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Carbon",
                        Description = "Resource used as basic organic building block",
                        InitialValue = 300.0
                    }
                    );

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Fule",
                        Description = "Used to power other buildings",
                        InitialValue = 100.0
                    }
                    );
            }
        }
        public void ShouldDisplayOnlyDraftNewsCreatedByCurrentUserWhenListingDraftNews()
        {
            string userName = "******";

            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var post = new Post { Id = 1, Title = "Post 1", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = userName };
                repository.Create(post);
                post = new Post { Id = 2, Title = "Post 2", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = userName };
                repository.Create(post);
                post = new Post { Id = 3, Title = "Post 3", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = "anotherUser" };
                repository.Create(post);
                var controller = new PostsController(repository);
            });

            UsingSession((session) =>
            {
                WaitForTheLastWrite<Post>(session);

                var httpContextStub = new Mock<HttpContextBase>
                {
                    DefaultValue = DefaultValue.Mock
                };
                var user = Mock.Get(httpContextStub.Object.User);
                user.Setup(u => u.Identity.Name).Returns(userName);

                var controller = new PostsController(new Repository(session));
                controller.ControllerContext = new ControllerContext(httpContextStub.Object, new RouteData(), controller);
                var result = (ViewResult)controller.News(excludeDraft: false);
                var pages = (PagedList.IPagedList<IBasePostInformation>)result.Model;

                Assert.AreEqual(2, pages.Count);
            });
        }
        public void ShouldFilterByLanguage()
        {
            using (var session = _documentStore.OpenSession())
            {
                var repository = new Repository(session);
                Enumerable.Range(1, 8).ToList().ForEach(i => repository.Create(new Book { Title = "Book " + i, Language = "Venda" }));
                var book1 = new Book { Title = "Book 9", Language = "Zulu" };
                repository.Create(book1);
                var book2 = new Book { Title = "Book 10", Language = "Xhosa" };
                repository.Create(book2);
                session.SaveChanges();

                Assert.AreEqual(10, repository.Count<Book>());

                var expectedBooks = new List<Book> { book1, book2 };
                var booksController = new BooksController(repository);

                var view = (ViewResult)booksController.Filter(new List<string>() { "Zulu", "Xhosa" }, new List<string>(), new List<string>());

                var filterInformation = (FilterInformation)view.Model;
                var actualBooks = filterInformation.BookInformations.Select(bookInformation => bookInformation.Model).ToList();
                Assert.AreEqual(2, actualBooks.Count());
                Assert.AreEqual(expectedBooks.First().Language, actualBooks.First().Language);
                Assert.AreEqual(expectedBooks.Last().Language, actualBooks.Last().Language);
                Assert.AreEqual(2, filterInformation.Languages.Count());
                Assert.AreEqual("Zulu", filterInformation.Languages.First());
                Assert.AreEqual("Xhosa", filterInformation.Languages.Last());
            }
        }
        public void DetailsShouldAuthorsBooks()
        {
            var author1 = new Author()
            {
                Name = "Author1",
                Biography = "Biography1",
                PictureUrl = "myPicture1.jpg",
                CreatedAt = DateTime.UtcNow
            };

            var book1 = new Book
            {
                Title = "Oliver Orphan",
                Author = author1.Name,
                AgeRange = "0~2",
                CreatedAt = DateTime.UtcNow
            };

            var book2 = new Book
            {
                Title = "Oliver Orphan2",
                Author = author1.Name,
                AgeRange = "0~2",
                CreatedAt = DateTime.UtcNow.AddDays(-1)
            };

            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var controller = new AuthorsController(repository);
                controller.Create(author1);

                repository.Create(book1);
                repository.Create(book2);
            });

            using (var session = _documentStore.OpenSession())
            {
                var author = WaitForTheLastWrite<Author>(session);
                var controller = new AuthorsController(new Repository(session));
                var result = (ViewResult) controller.Details(author.Id);
                var authorViewModel = (AuthorViewModel) result.Model;

                AuthorsContollerTestHelper.AssertEqual(authorViewModel.Author, author1);
                var books = authorViewModel.Books;
                Assert.AreEqual(2, books.Count());
                Assert.IsFalse(authorViewModel.HasMoreBooks);

                Assert.AreEqual(book1.Title, books.First().Title);
                Assert.AreEqual(book2.Title, books.Last().Title);
            }
        }
Example #5
0
        public override void Run(string[] args)
        {
            if (args.Length == 0) return;

            URIish source = new URIish(args[0]);

            // guess a name
            string p = source.Path;
            while (p.EndsWith("/"))
                p = p.Substring(0, p.Length - 1);
            int s = p.LastIndexOf('/');
            if (s < 0)
                throw die("Cannot guess local name from " + source);
            string localName = p.Substring(s + 1);
            if (localName.EndsWith(".git"))
                localName = localName.Substring(0, localName.Length - 4);

            if (gitdir == null)
                gitdir = Path.Combine(localName, ".git");

            db = new Repository(new DirectoryInfo(gitdir));
            db.Create();
            db.Config.setBoolean("core", null, "bare", false);
            db.Config.save();

            streamOut.WriteLine("Initialized empty Git repository in " + (new DirectoryInfo(gitdir)).FullName);
            streamOut.Flush();

            saveRemote(source);
            FetchResult r = runFetch();
            Ref branch = guessHEAD(r);
            doCheckout(branch);
        }
Example #6
0
        private static void InsertData()
        {
            var repo = new Repository<Status>();

                repo.Create(new Status { Id = 0, Name = "Lost" });
                repo.Create(new Status { Id = 1, Name = "Found" });

            var repog = new Repository<Gender>();

                repog.Create(new Gender { Id = 0, Name = "Male" });
                repog.Create(new Gender { Id = 1, Name = "Female" });

            var repoa = new Repository<Animal>();

                repoa.Create(new Animal { Id = 0, Name = "Dog",Breeds = getDogBreeds()});
                repoa.Create(new Animal { Id = 1, Name = "Cat", Breeds = getCatBreeds()});
        }
Example #7
0
 private void create()
 {
     if (gitdir == null)
         gitdir = bare ? Environment.CurrentDirectory : Path.Combine(Environment.CurrentDirectory, ".git");
     db = new Repository(new DirectoryInfo(gitdir));
     db.Create(bare);
     Console.WriteLine("Initialized empty Git repository in " + (new DirectoryInfo(gitdir)).FullName);
 }
Example #8
0
        public void TestCreateWorks()
        {
            Repository repository = new Repository(new SqlConnectionDev());
            Club club = new Club();
            club.Name = "Stirling Kyokushin";
            bool result = repository.Create(club);

            Assert.That(result);
        }
Example #9
0
        public static void AssingTicket(User user, Issue issue, Message message, string assignee, TelegramBot bot, Jira jiraConn)
        {
            int state = user.State - 1; //безумный костыль для того, чтобы вычислять статус, который нужно перевсети пользоваетля. Так получилось, что это 3 для 4 статуса, и 5 для 6 статуса.
            string keyboard = null;
            if (state == 3)
            {
                keyboard =
                    "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}";
            }
            try
            {
                issue.Refresh();
                if (issue.Assignee == null & issue.Key.Value.Equals(user.TicketNumber))
                {
                    if (issue.Status.ToString() == "10050")
                    {
                        issue.WorkflowTransition("Распределить");
                    }

                    issue.Assignee = assignee;
                    issue.SaveChanges();

                    user.State = state;
                    user.TicketNumber = "";
                    bot.SendMessage(message.chat.id, "Готово.", keyboard);
                }
                else
                {
                    user.State = state;
                    user.TicketNumber = "";
                    bot.SendMessage(message.chat.id, "Тикет уже распределён", keyboard);
                }
            }
            catch (Exception ex)
            {
                using (var repository = new Repository<DutyBotDbContext>())
                {
                    var logReccord = new Log
                    {
                        Date = DateTime.Now,
                        MessageTipe = "error",
                        UserId = message.chat.id,
                        Operation = "AssingTicket",
                        Exception = ex.GetType() + ": " + ex.Message,
                        AddInfo = issue.Key.Value
                    };
                    repository.Create(logReccord);
                }

                user.State = 3;
                user.TicketNumber = "";
                bot.SendMessage(message.chat.id, "Что-то пошло не так.", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");

            }
        }
Example #10
0
        public void Handle(UserEventData userEvent)
        {
            try
            {
                _logger.Info(userEvent.UserEventActionId == UserEventData.UserEventType.Open ? OpenEventReceivedMsg : ClickEventReceivedMsg, userEvent.batch_id, userEvent.subscriber_id, userEvent.list_id);

                //
                // Notes:
                // - We want to count even missing / invalid UserAgent requests
                //
                if (string.IsNullOrEmpty(userEvent.UserAgent))
                {
                    userEvent.UserAgent = InvalidOrMissingUserAgentMsg;
                    userEvent.IsMobile = false;
                    userEvent.IsTablet = false;
                    userEvent.IsiOS = false;
                    userEvent.IsAndroid = false;
                    
                    _logger.Info(InvalidOrMissingUserAgentMsg);
                }
                else
                {
                    //
                    // Notes:
                    //  DO NOT stop the process / message processing because of incorrect User Agent Strings !
                    try
                    {
                        var parser = new UserAgentParser(string.Format("{0}&requestedCapabilities={1}", _settings.ParsingServiceUrl, _settings.ParsingRequestedCapabilities));
                        parser.Parse(userEvent);
                        userEvent.ValidateUserAgent();
                    }
                    catch (Exception e)
                    {
                        _logger.Error(ErrorParsingUserAgentMsg, userEvent.UserAgent, e.Message);
                    }
                }

                using (var context = new UserEventContext())
                {
                    var repository = new Repository<UserEventContext>(context);
                    repository.Create(userEvent);

                    using (var uow = new UnitOfWork<UserEventContext>(context))
                    {
                        uow.Commit();
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("Error(s) found during a user event processing: {0}", e.Dump());
                throw;
            }
        }
Example #11
0
        public static void Init()
        {
            var buildingRepository = new Repository<Building>();

            if (buildingRepository.Get().Count == 0)
            {
                buildingRepository.Create(
                    MockData()
                );
            }
        }
Example #12
0
 public static async Task LogAsync(Credentials user, LogActivityType activity, string message)
 {
     using (var repo = new Repository())
     {
         var log = repo.Create<activity_log>();
         log.action_id = (int) activity;
         log.credentials_id = Authentication.Credentials.CredId;
         log.message = message;
         log.created = await repo.GetNowAsync();
         repo.Add(log);
         await repo.SaveChangesAsync();
     }
 }
        public void ShouldExcludeDraftPostsWhenListingAllPosts()
        {
            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var post = new Post { Id = 1, Title = "Post 1", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1) } ;
                repository.Create(post);
                post = new Post { Id = 2, Title = "Post 2", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1) } ;
                repository.Create(post);
                post = new Post { Id = 3, Title = "Post 3", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true} ;
                repository.Create(post);
                var controller = new PostsController(repository);
            });

            UsingSession((session) =>
            {
                WaitForTheLastWrite<Post>(session);
                var controller = new PostsController(new Repository(session));
                var result = (ViewResult)controller.News();
                var pages = (PagedList.IPagedList<IBasePostInformation>)result.Model;

                Assert.AreEqual(2, pages.Count);
            });
        }
Example #14
0
        /// <summary>
        /// Registers user if email is unique
        /// </summary>
        /// <param name="userViewModel">Entered data</param>
        /// <returns>User if registerd, null otherwise</returns>
        public User Register(UserViewModel userViewModel)
        {
            var usrRepo = new Repository<User>();

            var user = usrRepo.Get(new Dictionary<string, string>() { { "Email", userViewModel.Email } }).FirstOrDefault();

            if (user != null)
            {
                return null;
            }

            var newUser = CreateUser(userViewModel);

            usrRepo.Create(newUser);

            return newUser;
        }
Example #15
0
        public static void Init() {

            var planetRepositorie = new Repository<Planet>();

            if (planetRepositorie.Get().Count == 0)
            {

                for (int i = 0; i < 10; i++)
                {

                    planetRepositorie.Create(
                            Create()
                        );

                }

            }
        }
Example #16
0
        public void Add_adds_an_entity_to_the_db()
        {
            IRepository repo = new Repository(_sessionFactory);

            var post = new Post
                           {
                               Author = "Khaja Minhajuddin",
                               Title = "Mongo Blog",
                               Body = "Sample post here",
                               CreatedOn = DateTime.Now
                           };

            repo.Create(post);

            var savedPost = repo.Get<Post>(post.Id);

            Assert.NotNull(savedPost);
        }
Example #17
0
        public static void Init()
        {

            var researchRepositorie = new Repository<Research>();
           

            if (researchRepositorie.Get().Count == 0)
            {
                var energy = CreateEnergyResearch();

                researchRepositorie.Create(
                    new List<Research>()
                    {
                        energy,
                        CreateCombustionEngineResearch(),
                        CreateLaserResearch(energy)
                    }
                );
            }

        }
        public ActionResult Create(FormCollection petmodel)
        {
            try
            {
                var repo = new Repository<Pet>();
                var pet = new Pet
                                  {
                                      Id = Guid.NewGuid(),
                                      Age = Convert.ToInt32(petmodel["Age"]),
                                      Breed = new Breed { Name = petmodel["Breed"] },
                                      Name = petmodel["Name"],
                                      Status = new Status() { Name = petmodel["Status"] }
                                  };
                repo.Create(pet);

                return RedirectToAction("Index");
            }
            catch
            {
                return View(petmodel);
            }
        }
Example #19
0
 public virtual void Create(T entity)
 {
     _repository.Create(entity);
 }
Example #20
0
 public BrashActionResult <LGFeature> Create(LGFeature model)
 {
     return(Repository.Create(model));
 }
Example #21
0
        public ServerManager()
        {
            /*       if (Properties.Settings.Default.CallUpgrade)
             *     {
             *         Properties.Settings.Default.Upgrade();
             *         Properties.Settings.Default.CallUpgrade = false;
             *         Properties.Settings.Default.Save();
             *     }*/

            InitializeComponent();
            mainPropertyGrid.PropertySort = PropertySort.Categorized;
            mainPropertyGrid.LineColor    = SystemColors.ControlLight;
            sourceHelper = new TreeViewEditorHelper()
            {
                sortColumnAlphaOrderToolStripMenuItem = sortColumnAlphaOrderToolStripMenuItem, sortColumnSQLOrderToolStripMenuItem = sortColumnSQLOrderToolStripMenuItem, addFromToolStripMenuItem = addFromToolStripMenuItem, addToolStripMenuItem = addToolStripMenuItem, removeToolStripMenuItem = removeToolStripMenuItem, copyToolStripMenuItem = copyToolStripMenuItem, removeRootToolStripMenuItem = removeRootToolStripMenuItem, treeContextMenuStrip = treeContextMenuStrip, mainTreeView = mainTreeView
            };
            toolStripHelper = new ToolStripEditorHelper()
            {
                MainToolStrip = mainToolStrip, MainPropertyGrid = mainPropertyGrid, EntityHandler = this, MainTreeView = mainTreeView
            };
            toolsHelper = new ToolsHelper()
            {
                EntityHandler = this
            };
            toolsHelper.InitHelpers(toolsToolStripMenuItem, false);
            HelperEditor.HandlerInterface = this;

            configureMenuItem.Click += configureClick;
            configurationToolStripMenuItem.DropDownItems.Add(configureMenuItem);

            configurationToolStripMenuItem.DropDownItems.Add(new ToolStripSeparator());
            publishWebMenuItem.Click += configureClick;
            configurationToolStripMenuItem.DropDownItems.Add(publishWebMenuItem);

            configurationToolStripMenuItem.DropDownItems.Add(new ToolStripSeparator());
            securityMenuItem.Click += securityClick;
            configurationToolStripMenuItem.DropDownItems.Add(securityMenuItem);

            ShowIcon = true;
            Icon     = Properties.Resources.serverManager;

            //Repository management, should be part of the installation
            _repository = Repository.Create();
            if (_repository == null)
            {
                _repository = new Repository();
                MessageBox.Show("No repository has been defined or found for this installation. Reports will not be rendered. Please modify the .configuration file to set a RepositoryPath containing at least a Views subfolder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //handle program args
            string[] args       = Environment.GetCommandLineArgs();
            bool     open       = (args.Length >= 2 && args[1].ToLower() == "/o");
            string   fileToOpen = null;

            if (args.Length >= 3 && File.Exists(args[2]))
            {
                fileToOpen = args[2];
            }
            //and last used file
            if (!open && File.Exists(Properties.Settings.Default.LastUsedFile))
            {
                open       = true;
                fileToOpen = Properties.Settings.Default.LastUsedFile;
            }
            if (open && HasValidRepositoryDirectory(fileToOpen))
            {
                openFile(fileToOpen);
            }
            else
            {
                IsModified = false;
                init();
            }
        }
Example #22
0
        async Task Checkjira() // метод вычитывает тикеты из фильтра в jira
        {
            _jiraConn = Jira.CreateRestClient(_jiraParam.Value, _userLoginParam.Value, _userPasswordParam.Value);
            while (_checkjiraflag)
            {
                try  
                {
                    using (var repository = new Repository<DutyBotDbContext>()) //если дежурство закончилось сбрасываю статус пользователя на 3
                    {
                        var users = repository.GetList<User>(u => u.DutyEnd < DateTime.Now & u.State == 5);
                        foreach (var usr in users)
                        {
                            usr.State = 3;
                        }
                        repository.Update();
                    }
                    using (var repository = new Repository<DutyBotDbContext>()) //если статус 6 (обработка тикета), а дежурство закончилось, меняю на 4
                    {
                        var users = repository.GetList<User>(u => u.DutyEnd < DateTime.Now & u.State == 6);
                        foreach (var usr in users)
                        {
                            usr.State = 4;
                        }
                        repository.Update();
                    }

                }
                catch (Exception ex)
                {
                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        var logReccord = new Log
                        {
                            Date = DateTime.Now,
                            MessageTipe = "error",
                            UserId = 0,
                            Operation = "FinishDuty",
                            Exception = ex.GetType() + ": " + ex.Message,
                            AddInfo = ""
                        };
                        repository.Create(logReccord);
                    }
                }
                //вычитываю тикеты из заданного фильтра
                try
                {
                    var issues = _jiraConn.GetIssuesFromJql(_filterParam.Value).ToList();
                    if (issues.Any())
                    {
                        lastIssue = issues.Last();
                        using (var repository = new Repository<DutyBotDbContext>())
                        {
                            var respUsers =
                                repository.GetList<User>(
                                    u => u.DutyStart < DateTime.Now & u.DutyEnd > DateTime.Now & u.State == 5).ToList();
                            //пользователи кто дежурит
                            if (respUsers.Any())
                            {
                                foreach (var usr in respUsers)
                                {
                                    _jiraConn = Jira.CreateRestClient(_jiraParam.Value, usr.Login, usr.Password);
                                    var user = repository.Get<User>(u => u.Id == usr.Id);
                                    user.TicketNumber = lastIssue.Key.ToString();
                                    user.State = 6;
                                    _bot.SendMessage(user.TlgNumber, lastIssue);
                                    repository.Update();
                                }
                            }
                            var inProgressUsers = 
                                repository.GetList<User>(
                                    u => u.DutyStart < DateTime.Now & u.DutyEnd > DateTime.Now & u.State == 6 & u.TicketNumber != lastIssue.Key.Value).ToList();
                            //кто обрабатывает  неактуальный тикет
                            if (inProgressUsers == null || inProgressUsers.Any())
                            {
                                foreach (var usr in inProgressUsers)
                                {
                                    _jiraConn = Jira.CreateRestClient(_jiraParam.Value, usr.Login, usr.Password);
                                    var user = repository.Get<User>(u => u.Id == usr.Id);
                                    user.State = 5;
                                    _bot.SendMessage(user.TlgNumber, "Тикет был распределён, продолжаю мониторинг", "{\"keyboard\": [[\"Ок\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                    repository.Update();
                                }
                            }
                        }
                    }
                    else //если все тикеты распределены, говорю об этом всем, кто обрабатывает тикет
                    {
                        using (var repository = new Repository<DutyBotDbContext>())
                        {
                            var inProgressUsers = repository.GetList<User>(u =>
                                u.DutyStart < DateTime.Now & u.DutyEnd > DateTime.Now & u.State == 6).ToList();
                            //кто обрабатывает тикет неактуальный тикет
                            if (inProgressUsers.Any())
                            {
                                foreach (var usr in inProgressUsers)
                                {
                                    _jiraConn = Jira.CreateRestClient(_jiraParam.Value, usr.Login, usr.Password);
                                    var user = repository.Get<User>(u => u.Id == usr.Id);
                                    user.State = 5;
                                    _bot.SendMessage(user.TlgNumber, "Тикет был распределён, продолжаю мониторинг","{\"keyboard\": [[\"Ок\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                    repository.Update();
                                    }
                            }
                        }
                    }
                    await Task.Delay(10000);
                }
                catch (Exception ex)
                {
                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        var users =
                            repository.GetList<User>(
                                u => u.DutyStart > DateTime.Now & u.DutyEnd < DateTime.Now & u.State == 5);
                        if (users.Any())
                        {
                            foreach (var user in users)
                            {
                                _bot.SendMessage(user.TlgNumber,
                                    "Похоже, что jira не доступна. Мониторинг остановлен. Что будем делать?",
                                    "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                user.State = 3;
                                repository.Update();
                            }
                        }
                        var logReccord = new Log
                        {
                            Date = DateTime.Now,
                            MessageTipe = "error",
                            UserId = 0,
                            Operation = "ReadTicketsFromJira",
                            Exception = ex.GetType() + ": " + ex.Message,
                            AddInfo = ""
                        };
                        repository.Create(logReccord);

                        await Task.Delay(30000);
                    }
                }
            }
        }
Example #23
0
 public virtual object Create(CreateOperation value)
 {
     ResolveTypeAndInstance(value, out Type type, out object instance);
     return(Repository.Create(type, instance));
 }
Example #24
0
        private void SaveTo(Account account)
        {
            var repository = Repository.Create <IAccountRepository>();

            repository.Update(account);
        }
Example #25
0
        async Task ProcessMessages(ISourceBlock<Message> queue) //обрабатываю сообщения в буфере
        {
            Message message;
            while (await queue.OutputAvailableAsync())
            {
                message = (await queue.ReceiveAsync());

                User user;

                try
                {

                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        user = repository.Get<User>(u => u.TlgNumber == message.chat.id);
                        if (user == null)
                        {
                            user = new User
                            {
                                Name = message.chat.first_name,
                                TlgNumber = message.chat.id,
                                State = -1,
                                Login = "",
                                Password = "",
                                TicketNumber = ""
                            };
                            repository.Create(user);
                        }
                    }
                }
                catch (Exception)
                {
                    _bot.SendMessage(message.chat.id,
                        "Что-то пошло не так при обращении к базе данных. Дальнейшая работа не возможна.");
                    Thread.Sleep(5000);
                    return;
                }
                try
                {
                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        user = repository.Get<User>(u => u.Id == user.Id);
                        switch (user.State) //смотрю, в каком статусе пользователь 
                            //- 1 его нет, 0 ззнакомство с DUtyBot, 1 Ввод пароля, 2, проверка доступа в jira, 
                            //3 основной статус, ожидаем команды, 4 пользователь решает что делать с тикетом, который получил от бота по кнопке Проверь тикеты
                            //5 идёт мониторинг тикетов, пользователь получает уведомления, 6 пользователь решает что делать с тикетом, который получил при мониторинге
                        {
                            case -1:
                                _bot.SendMessage(message.chat.id,
                                    "Привет, " + message.chat.first_name +
                                    @"! Меня зовут DutyBot, я создан, чтобы помогать дежурить. Давай знакомиться!
 ",
                                    "{\"keyboard\": [[\"Рассказать DutyBot'у о себе\"], [\"Не хочу знакомиться, ты мне не нравишься\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                user.State = 0;
                                break;
                            case 0:
                                if ((message.text) == "Рассказать DutyBot'у о себе" |
                                    (message.text) == "Ввести учётку еще раз")
                                {
                                    _bot.SendMessage(message.chat.id,
                                        @"Чтобы мы могли работать в Jira, мне нужны твои учётные данные. Напиши мне свой логин в формате d.bot и нажми отправить.
Твои данные будут относительно безопасно храниться на сервере");
                                    user.Name = message.chat.first_name;
                                    user.TlgNumber = message.chat.id;
                                    user.State = 1;
                                    break;
                                }

                                if ((message.text) == "Не хочу знакомиться, ты мне не нравишься")
                                {
                                    _bot.SendMessage(message.chat.id,
                                        @"Очень жаль, но если надумешь, пиши. Я забуду об этом неприятном разговоре");
                                    repository.Delete(user);
                                }

                                break;
                            case 1:
                                _bot.SendMessage(message.chat.id, @"Теперь напиши пароль");

                                user.Login = message.text;
                                user.State = 2;
                                break;
                            case 2:

                                user.Password = message.text;

                                _bot.SendMessage(message.chat.id,
                                    @"Отлично, сейчас я проверю, есть ли у тебя доступ в Jira");
                                if (JiraAddFuncions.CheckConnection(_jiraConn, user.Login,
                                    user.Password))
                                {
                                    _bot.SendMessage(message.chat.id, @"Всё хорошо, можно начинать работу",
                                        "{\"keyboard\": [[\"Начнём\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");

                                    user.Password = message.text;
                                    user.State = 3;
                                    break;
                                }
                                _bot.SendMessage(message.chat.id,
                                    @"Доступа к JIra нет. Возможно учётные данные не верны. Давай попробуем ввести их еще раз. ",
                                    "{\"keyboard\": [[\"Ввести учётку еще раз\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");

                                user.State = 0;
                                break;
                            case 3:
                                switch (message.text)
                                {
                                    case "Начнём":
                                        _bot.SendMessage(message.chat.id,
                                            "Просто напиши мне сообщение, когда я тебе понадоблюсь. В ответ я пришлю меню с вариантами моих действий. Вот такое ↓",
                                            "{\"keyboard\": [[\"Кто сейчас дежурит?\"], [\"Проверь тикеты\"], [\"Помоги с дежурством\"], [\"Пока ничем\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                    case "Кто сейчас дежурит?":
                                        _bot.SendMessage(message.chat.id, DbReader.Readrespersone(),
                                            "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                    case "Проверь тикеты":
                                        _jiraConn = Jira.CreateRestClient(_jiraParam.Value,
                                            user.Login, user.Password);

                                        try
                                        {
                                            var issues =
                                                _jiraConn.GetIssuesFromJql(_filterParam.Value);
                                            IList<Issue> enumerable = issues as IList<Issue> ?? issues.ToList();
                                            if (enumerable.Any())
                                            {
                                                _ticket = enumerable.Last();

                                                user.TicketNumber = _ticket.Key.ToString();
                                                user.State = 4;
                                                _bot.SendMessage(message.chat.id, _ticket);
                                            }
                                            else
                                            {
                                                _bot.SendMessage(message.chat.id, "Тикетов нет",
                                                    "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            _bot.SendMessage(message.chat.id, "Jira не доступна",
                                                "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            var logReccord = new Log
                                            {
                                                Date = DateTime.Now,
                                                MessageTipe = "error",
                                                UserId = 0,
                                                Operation = "SendThatJiraDoesNotWork",
                                                Exception = ex.GetType() + ": " + ex.Message,
                                                AddInfo = ""
                                            };
                                            repository.Create(logReccord);
                                        }

                                        break;
                                    case "Помоги с дежурством":
                                        _bot.SendMessage(message.chat.id, "Как будем дежурить?",
                                            "{\"keyboard\": [[\"Начать мониторить тикеты\"], [\"Мониторить тикеты в моё дежурство\"], [\"Отмена\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                    case "Пока ничего":
                                        _bot.SendMessage(message.chat.id, "Ок, если что, пиши.");
                                        break;
                                    case "Начать мониторить тикеты":
                                        _bot.SendMessage(message.chat.id, @"Начинаю мониторинг.
Я буду мониторить тикеты в течение ближайших 12 часов, после чего мониторинг будет автоматически остановлен.");
                                        user.State = 5;
                                        user.DutyStart = DateTime.Now;
                                        user.DutyEnd = DateTime.Now.AddHours(12);
                                        break;
                                    case "Мониторить тикеты в моё дежурство":

                                        if (DbReader.Readuserdutystart(message.chat.id) ==
                                            Convert.ToDateTime("01.01.1900 0:00:00 ") |
                                            DbReader.Readuserdutystart(message.chat.id) ==
                                            Convert.ToDateTime("01.01.1900 0:00:00 "))
                                        {
                                            _bot.SendMessage(message.chat.id, "У тебя нет дежурств в ближайшее время",
                                                "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            break;
                                        }
                                        _bot.SendMessage(message.chat.id,
                                            "Я буду мониторить тикеты с " +
                                            DbReader.Readuserdutystart(message.chat.id).ToShortDateString() + " " +
                                            DbReader.Readuserdutystart(message.chat.id).ToShortTimeString() + " по " +
                                            DbReader.Readuserdutyend(message.chat.id).ToShortDateString() + " " +
                                            DbReader.Readuserdutyend(message.chat.id).ToShortTimeString());

                                        user.State = 5;
                                        user.DutyStart = DbReader.Readuserdutystart(message.chat.id);
                                        user.DutyEnd = DbReader.Readuserdutyend(message.chat.id);
                                        break;
                                    default:
                                        _bot.SendMessage(message.chat.id, "Чем я могу помочь?",
                                            "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                }

                                break;
                            case 4:
                                if (_ticket.Assignee == null & _ticket.Key.ToString().Equals(user.TicketNumber))
                                {
                                    switch ((message.text))
                                    {
                                        case "Распределить":
                                            _bot.SendMessage(message.chat.id, "Кому назначим?",
                                                "{\"keyboard\": [[\"Технологи\", \"Коммерция\"], [\"Админы\", \"Связисты\"], [\"Олеся\", \"Женя\"], [\"Алексей\", \"Максим\"], [\"Паша\", \"Марина\"], [\"Андрей\", \"Гриша\"], [\"Оля\", \"Настя\"], [\"Маркетинг\", \"Даша\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            break;
                                        case "Решить":
                                            JiraAddFuncions.ResolveTicket(user, _ticket, message, user.Login, _bot,
                                                _jiraConn);
                                            break;
                                        case "Назначить себе":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, user.Login, _bot,
                                                _jiraConn);
                                            break;
                                        case "Технологи":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "technologsupport",
                                                _bot,
                                                _jiraConn);
                                            break;
                                        case "Коммерция":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "crm_otdel", _bot,
                                                _jiraConn);
                                            break;
                                        case "Админы":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "Uk.Jira.TechSupport",
                                                _bot,
                                                _jiraConn);
                                            break;
                                        case "Связисты":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "uk.jira.noc", _bot,
                                                _jiraConn);
                                            break;
                                        case "Олеся":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "o.likhacheva", _bot,
                                                _jiraConn);
                                            break;
                                        case "Женя":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "ev.safonov", _bot,
                                                _jiraConn);
                                            break;
                                        case "Алексей":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "a.sapotko", _bot,
                                                _jiraConn);
                                            break;
                                        case "Максим":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "m.shemetov", _bot,
                                                _jiraConn);
                                            break;
                                        case "Андрей":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "an.zarubin", _bot,
                                                _jiraConn);
                                            break;
                                        case "Гриша":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "g.dementiev", _bot,
                                                _jiraConn);
                                            break;
                                        case "Оля":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "o.tkachenko", _bot,
                                                _jiraConn);
                                            break;
                                        case "Настя":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "a.zakharova", _bot,
                                                _jiraConn);
                                            break;
                                        case "Марина":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "m.vinnikova", _bot,
                                                _jiraConn);
                                            break;
                                        case "Паша":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "p.denisov", _bot,
                                                _jiraConn);
                                            break;
                                        case "Даша":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "d.kormushina", _bot,
                                                _jiraConn);
                                            break;
                                        case "Маркетинг":
                                            JiraAddFuncions.AssingTicket(user, _ticket, message, "Uk.Jira.TradeMarketing", _bot,
                                                _jiraConn);
                                            break;
                                        default:
                                            _bot.SendMessage(message.chat.id, "",
                                        "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            user.State = 3;
                                            break;
                                    }
                                }
                                else
                                {
                                    _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён.",
                                        "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                    user.State = 3;
                                }
                                break;
                            case 5:
                                switch (message.text)
                                {
                                    case ("Ок"):
                                        break;
                                    case ("Остановить мониторинг"):
                                        _bot.SendMessage(message.chat.id, "Готово");
                                        user.State = 3;
                                        break;
                                    case ("Продолжить мониторинг"):
                                        _bot.SendMessage(message.chat.id, "Хорошо, продолжим");
                                        break;
                                    default:
                                        _bot.SendMessage(message.chat.id, "да?",
                                            "{\"keyboard\": [[\"Остановить мониторинг\"], [\"Продолжить мониторинг\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                }
                                break;

                            case 6:
                                switch (message.text)
                                {
                                    case "Распределить":
                                        if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber))
                                        {
                                            _bot.SendMessage(message.chat.id, "Кому назначим?",
                                                "{\"keyboard\": [[\"Технологи\", \"Коммерция\"], [\"Админы\", \"Связисты\"], [\"Олеся\", \"Женя\"], [\"Алексей\", \"Максим\"], [\"Паша\", \"Марина\"], [\"Андрей\", \"Гриша\"], [\"Оля\", \"Настя\"], [\"Маркетинг\", \"Даша\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                            break;
                                        }
                                        _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён.");
                                        user.State = 5;
                                        break;
                                    case "Решить":
                                        if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber))
                                        {
                                            JiraAddFuncions.ResolveTicket(user, lastIssue, message, user.Login, _bot,
                                                _jiraConn);
                                            break;
                                        }
                                        _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён.");
                                        user.State = 5;
                                        break;
                                    case "Назначить себе":
                                        if (lastIssue.Assignee == null & lastIssue.Key.ToString().Equals(user.TicketNumber))
                                        {
                                            JiraAddFuncions.AssingTicket(user, lastIssue, message, user.Login, _bot,
                                                _jiraConn);
                                            break;
                                        }
                                        _bot.SendMessage(message.chat.id, "Похоже, тикет уже распределён.");
                                        user.State = 5;
                                        break;
                                    case "Технологи":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "technologsupport", _bot,
                                            _jiraConn);
                                        break;
                                    case "Коммерция":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "crm_otdel", _bot, _jiraConn);
                                        break;
                                    case "Админы":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "Uk.Jira.TechSupport", _bot,
                                            _jiraConn);
                                        break;
                                    case "Связисты":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "uk.jira.noc", _bot,
                                            _jiraConn);
                                        break;
                                    case "Олеся":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "o.likhacheva", _bot,
                                            _jiraConn);
                                        break;
                                    case "Женя":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "ev.safonov", _bot,
                                            _jiraConn);
                                        break;
                                    case "Алексей":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "a.sapotko", _bot, _jiraConn);
                                        break;
                                    case "Максим":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "m.shemetov", _bot,
                                            _jiraConn);
                                        break;
                                    case "Андрей":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "an.zarubin", _bot,
                                            _jiraConn);
                                        break;
                                    case "Гриша":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "g.dementiev", _bot,
                                            _jiraConn);
                                        break;
                                    case "Оля":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "o.tkachenko", _bot,
                                            _jiraConn);
                                        break;
                                    case "Настя":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "a.zakharova", _bot,
                                            _jiraConn);
                                        break;
                                    case "Марина":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "m.vinnikova", _bot,
                                            _jiraConn);
                                        break;
                                    case "Паша":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "p.denisov", _bot, _jiraConn);
                                        break;
                                    case "Маркетинг":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "Uk.Jira.TradeMarketing", _bot, _jiraConn);
                                        break;
                                    case "Даша":
                                        JiraAddFuncions.AssingTicket(user, lastIssue, message, "d.kormushina", _bot, _jiraConn);
                                        break;
                                    case "Остановить мониторинг":
                                    {
                                        user.State = 3;
                                        _bot.SendMessage(message.chat.id, "Готово");
                                        break;
                                    }

                                    case "Продолжить мониторинг":
                                    {
                                        user.State = 5;
                                        _bot.SendMessage(message.chat.id, "Хорошо, продолжим");
                                        break;
                                    }

                                    default:
                                        _bot.SendMessage(message.chat.id, "да?",
                                            "{\"keyboard\": [[\"Остановить мониторинг\"], [\"Продолжить мониторинг\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                                        break;
                                }
                                break;
                        }
                        repository.Update();
                    }
                }
                catch
                    (Exception ex)
                {
                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        var RepUser = repository.Get<User>(usr => usr.Id == user.Id);
                        if (RepUser.State > 3) RepUser.State = 3;
                        _bot.SendMessage(message.chat.id, "Что-то пошло не так при обработке сообщения. Что будем делать?", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");
                        repository.Update();

                        var logReccord = new Log
                        {
                            Date = DateTime.Now,
                            MessageTipe = "info",
                            UserId = message.chat.id,
                            Operation = "ProcessMessage",
                            Exception = ex.Message,
                            AddInfo = ""
                        };
                        repository.Create(logReccord);
                    }
                    Thread.Sleep(5000);
                }
            }
        }
Example #26
0
 public BrashActionResult <ToolsRequired> Create(ToolsRequired model)
 {
     return(Repository.Create(model));
 }
Example #27
0
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                setContext(context);
                if (_emailDevice != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperTestEmail")
                    {
                        _emailDevice.SendTestEmail();
                    }
                }
                else if (_fileServerDevice != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperTestConnection")
                    {
                        _fileServerDevice.TestConnection();
                    }
                }
                else if (_metaConnection != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperCheckConnection")
                    {
                        _metaConnection.CheckConnection();
                    }
                    if (context.PropertyDescriptor.Name == "HelperCreateFromExcelAccess")
                    {
                        string accessDriver = "Microsoft Access Driver (*.mdb)";
                        string excelDriver  = "Microsoft Excel Driver (*.xls)";
                        try
                        {
                            List <string> drivers       = Helper.GetSystemDriverList();
                            string        accessDriver2 = "Microsoft Access Driver (*.mdb, *.accdb)";
                            if (drivers.Contains(accessDriver2))
                            {
                                accessDriver = accessDriver2;
                            }
                            string excelDriver2 = "Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)";
                            if (drivers.Contains(excelDriver2))
                            {
                                excelDriver = excelDriver2;
                            }
                        }
                        catch { }

                        OpenFileDialog dlg = new OpenFileDialog();
                        dlg.Title            = "Open an Excel or an MS Access File";
                        dlg.CheckFileExists  = true;
                        dlg.CheckPathExists  = true;
                        dlg.InitialDirectory = _metaConnection.Source.Repository.RepositoryPath;
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            string ext    = Path.GetExtension(dlg.FileName);
                            string driver = "";
                            if (ext == ".xls" || ext == ".xlsx" || ext == ".xlsm" || ext == ".xlsb")
                            {
                                _metaConnection.DatabaseType = DatabaseType.MSExcel;
                                driver = excelDriver;
                            }
                            else if (ext == ".mdb" || ext == ".accdb")
                            {
                                _metaConnection.DatabaseType = DatabaseType.MSAccess;
                                driver = accessDriver;
                            }
                            else
                            {
                                throw new Exception("Please select an Excel or MS Access file");
                            }

                            string path = dlg.FileName.Replace(_metaConnection.Source.Repository.RepositoryPath, Repository.SealRepositoryKeyword);
                            _metaConnection.ConnectionString = string.Format(@"Provider=MSDASQL.1;Extended Properties=""DBQ={0};Driver={{{1}}};""", path, driver);
                            setModified();
                            MessageBox.Show("The connection has been created successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else if (_metaTable != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperRefreshColumns")
                    {
                        _metaTable.Refresh();
                        setModified();
                        initEntity(_metaTable);
                    }
                    if (context.PropertyDescriptor.Name == "HelperCheckTable")
                    {
                        _metaTable.CheckTable(null);
                    }
                }
                else if (_metaEnum != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperRefreshEnum")
                    {
                        _metaEnum.RefreshEnum();
                        setModified();
                    }
                }
                else if (_metaColumn != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperCheckColumn")
                    {
                        _metaColumn.MetaTable.CheckTable(_metaColumn);
                    }
                    else if (context.PropertyDescriptor.Name == "HelperCreateEnum")
                    {
                        MetaEnum result = _metaColumn.Source.CreateEnumFromColumn(_metaColumn);
                        _metaColumn.EnumGUID = result.GUID;
                        initEntity(result);
                        setModified();
                    }
                    else if (context.PropertyDescriptor.Name == "HelperShowValues")
                    {
                        try
                        {
                            Cursor.Current = Cursors.WaitCursor;
                            string        result = _metaColumn.MetaTable.ShowValues(_metaColumn);
                            ExecutionForm frm    = new ExecutionForm(null);
                            frm.Text = "Show values";
                            frm.cancelToolStripButton.Visible = false;
                            frm.pauseToolStripButton.Visible  = false;
                            frm.logTextBox.Text            = result;
                            frm.logTextBox.SelectionStart  = 0;
                            frm.logTextBox.SelectionLength = 0;
                            frm.ShowDialog();
                        }
                        finally
                        {
                            Cursor.Current = Cursors.Default;
                        }
                    }
                    else if (context.PropertyDescriptor.Name == "HelperCreateDrillDates")
                    {
                        var year = _metaColumn.MetaTable.Source.AddColumn(_metaColumn.MetaTable);
                        year.DisplayName            = _metaColumn.DisplayName + " Year";
                        year.Type                   = ColumnType.DateTime;
                        year.DateTimeStandardFormat = DateTimeStandardFormat.Custom;
                        year.Format                 = "yyyy";
                        var month = _metaColumn.MetaTable.Source.AddColumn(_metaColumn.MetaTable);
                        month.DisplayName            = _metaColumn.DisplayName + " Month";
                        month.Type                   = ColumnType.DateTime;
                        month.DateTimeStandardFormat = DateTimeStandardFormat.Custom;
                        month.Format                 = "MM/yyyy";
                        if (_metaColumn.MetaTable.Source.Connection.DatabaseType == DatabaseType.Oracle)
                        {
                            year.Name  = string.Format("trunc({0},'year')", _metaColumn.Name);
                            month.Name = string.Format("trunc({0},'month')", _metaColumn.Name);
                        }
                        else if (_metaColumn.MetaTable.Source.Connection.DatabaseType == DatabaseType.MSSQLServer)
                        {
                            year.Name  = string.Format("DATETIME2FROMPARTS(year({0}),1,1,0,0,0,0,0)", _metaColumn.Name);
                            month.Name = string.Format("DATETIME2FROMPARTS(year({0}),month({0}),1,0,0,0,0,0)", _metaColumn.Name);
                        }
                        else if (_metaColumn.MetaTable.Source.Connection.DatabaseType == DatabaseType.MSAccess)
                        {
                            year.Name  = string.Format("DateSerial(DatePart('yyyy',{0}), 1, 1)", _metaColumn.Name);
                            month.Name = string.Format("DateSerial(DatePart('yyyy',{0}), DatePart('m',{0}), 1)", _metaColumn.Name);
                        }
                        year.DrillChildren.Add(month.GUID);
                        month.DrillChildren.Add(_metaColumn.GUID);
                        initEntity(_metaColumn.MetaTable);
                        setModified();
                        MessageBox.Show("A 'Year' column and a 'Month' column have been added to the table with a drill hierarchy.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (context.PropertyDescriptor.Name == "HelperCreateSubReport")
                    {
                        Report report = Report.Create(Repository.Create());
                        //Only on detail view
                        report.Views.Clear();
                        report.AddView(ReportViewTemplate.ModelDetailName);
                        report.Views[0].InitParameters(true);
                        report.Views[0].Parameters.First(i => i.Name == "restriction_button").BoolValue = false;

                        report.Sources.RemoveAll(i => i.MetaSourceGUID != _metaColumn.Source.GUID);

                        if (report.Sources.Count == 0)
                        {
                            throw new Exception("Unable to create the detail report. Please save the Data Source first...");
                        }

                        //And one model
                        ReportModel model = report.Models[0];
                        model.SourceGUID = _metaColumn.Source.GUID;
                        //Add all the element of the table
                        foreach (var el in _metaColumn.MetaTable.Columns.OrderBy(i => i.DisplayOrder))
                        {
                            ReportElement element = ReportElement.Create();
                            element.MetaColumnGUID = el.GUID;
                            element.Name           = el.Name;
                            element.PivotPosition  = (el == _metaColumn ? PivotPosition.Page : PivotPosition.Row);
                            model.Elements.Add(element);
                        }

                        string entityName = _metaColumn.MetaTable.Name;
                        if (entityName.EndsWith("s"))
                        {
                            entityName = entityName.Substring(0, entityName.Length - 1);
                        }
                        string path = Path.Combine(_metaColumn.MetaTable.Source.Repository.SubReportsFolder, Helper.CleanFileName(entityName + " Detail.") + Repository.SealReportFileExtension);
                        path = FileHelper.GetUniqueFileName(path);

                        var sr = new SubReport()
                        {
                            Path = path.Replace(_metaColumn.Source.Repository.RepositoryPath, Repository.SealRepositoryKeyword), Name = entityName + " Detail"
                        };
                        //And the restriction, try to find out the table primary keys
                        if (_metaColumn.Source.IsSQL)
                        {
                            try
                            {
                                DataTable schemaTables = ((OleDbConnection)_metaColumn.Source.GetOpenConnection()).GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, null);
                                Helper.DisplayDataTable(schemaTables);
                                foreach (DataRow row in schemaTables.Rows)
                                {
                                    string schema = "";
                                    if (schemaTables.Columns.Contains("TABLE_SCHEMA"))
                                    {
                                        schema = row["TABLE_SCHEMA"].ToString();
                                    }
                                    else if (schemaTables.Columns.Contains("TABLE_SCHEM"))
                                    {
                                        schema = row["TABLE_SCHEM"].ToString();
                                    }
                                    string fullName = (!string.IsNullOrEmpty(schema) ? _metaColumn.Source.GetTableName(schema) + "." : "") + _metaColumn.Source.GetTableName(row["TABLE_NAME"].ToString());
                                    if (row["TABLE_NAME"].ToString() == _metaColumn.MetaTable.Name || fullName == _metaColumn.MetaTable.Name)
                                    {
                                        var col = _metaColumn.MetaTable.Columns.FirstOrDefault(i => i.Name.ToLower() == row["COLUMN_NAME"].ToString().ToLower() || i.Name.ToLower().EndsWith("." + row["COLUMN_NAME"].ToString().ToLower()));
                                        if (col != null)
                                        {
                                            sr.Restrictions.Add(col.GUID);
                                        }
                                        else
                                        {
                                            //not all pk available....
                                            sr.Restrictions.Clear();
                                            break;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }
                        string message = "";
                        if (sr.Restrictions.Count == 0)
                        {
                            //no PK found, we add the value itself...
                            sr.Restrictions.Add(_metaColumn.GUID);
                            message = "The Sub-Report restriction is based on the Column.";
                        }
                        else
                        {
                            message = "The Sub-Report restrictions are based on the table Primary Keys.";
                        }

                        foreach (var guid in sr.Restrictions)
                        {
                            ReportRestriction restriction = ReportRestriction.CreateReportRestriction();
                            restriction.MetaColumnGUID = guid;
                            restriction.PivotPosition  = PivotPosition.Row;
                            restriction.Prompt         = PromptType.Prompt;
                            restriction.Operator       = Operator.Equal;
                            model.Restrictions.Add(restriction);
                            if (!string.IsNullOrEmpty(model.Restriction))
                            {
                                model.Restriction += "\r\nAND ";
                            }
                            model.Restriction += ReportRestriction.kStartRestrictionChar + restriction.GUID + ReportRestriction.kStopRestrictionChar;
                        }
                        model.InitReferences();

                        report.SaveToFile(path);
                        _metaColumn.SubReports.Add(sr);

                        if (MessageBox.Show(string.Format("A Sub-Report named '{0}' has been created in the dedicated Repository folder.\r\n{1}\r\nDo you want to edit it using a new Report Designer ?", Path.GetFileName(path), message), "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            var p = new Process();
                            p.StartInfo = new ProcessStartInfo(path)
                            {
                                UseShellExecute = true
                            };
                            p.Start();
                        }
                        ;

                        _metaColumn.UpdateEditor();
                        setModified();
                    }
                    else if (context.PropertyDescriptor.Name == "HelperAddSubReport")
                    {
                        OpenFileDialog dlg = new OpenFileDialog();
                        dlg.Filter          = string.Format(Repository.SealRootProductName + " Reports files (*.{0})|*.{0}|All files (*.*)|*.*", Repository.SealReportFileExtension);
                        dlg.Title           = "Select a Sub-Report having prompted restrictions";
                        dlg.CheckFileExists = true;
                        dlg.CheckPathExists = true;
                        var repository = Repository.Create();
                        dlg.InitialDirectory = repository.SubReportsFolder;
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            Report report = Report.LoadFromFile(dlg.FileName, repository, false);
                            var    sr     = new SubReport()
                            {
                                Path = report.FilePath.Replace(repository.RepositoryPath, Repository.SealRepositoryKeyword), Name = Path.GetFileNameWithoutExtension(dlg.FileName)
                            };

                            bool tableOk   = false;
                            var  restrList = new List <ReportRestriction>();
                            foreach (var model in report.Models.Where(i => i.Source.MetaSourceGUID == _metaColumn.Source.GUID))
                            {
                                foreach (var restriction in model.Restrictions)
                                {
                                    foreach (var table in _metaColumn.MetaTable.Source.MetaData.Tables)
                                    {
                                        var col = table.Columns.FirstOrDefault(i => i.GUID == restriction.MetaColumnGUID);
                                        if (col != null)
                                        {
                                            tableOk = true;
                                            if (!restrList.Exists(i => i.MetaColumnGUID == restriction.MetaColumnGUID))
                                            {
                                                restrList.Add(restriction);
                                            }
                                        }
                                    }
                                }
                            }

                            if (!tableOk)
                            {
                                throw new Exception("Unable to add this Sub-Report:\r\nThe report does not contain any restriction...");
                            }

                            var frm = new MultipleSelectForm("Select the restrictions to include", restrList, "DisplayNameEl");
                            //select all by default
                            for (int i = 0; i < frm.checkedListBox.Items.Count; i++)
                            {
                                frm.checkedListBox.SetItemChecked(i, true);
                            }
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                foreach (object item in frm.CheckedItems)
                                {
                                    sr.Restrictions.Add(((ReportRestriction)item).MetaColumnGUID);
                                }
                                _metaColumn.SubReports.Add(sr);
                                MessageBox.Show(string.Format("The Sub-Report named '{0}' has been added with {1} restriction(s).", Path.GetFileName(dlg.FileName), sr.Restrictions.Count), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                _metaColumn.UpdateEditor();
                                setModified();
                            }
                        }
                    }
                    else if (context.PropertyDescriptor.Name == "HelperOpenSubReportFolder")
                    {
                        var p = new Process();
                        p.StartInfo = new ProcessStartInfo(_metaColumn.Source.Repository.SubReportsFolder)
                        {
                            UseShellExecute = true
                        };
                        p.Start();
                    }
                }
                else if (_metaJoin != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperCheckJoin")
                    {
                        _metaJoin.CheckJoin();
                    }
                }
                else if (_model != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperViewJoins")
                    {
                        try
                        {
                            _model.JoinPaths = new StringBuilder();
                            _model.BuildQuery();

                            var frm = new ExecutionForm(null);
                            frm.Text = "List of Joins";
                            frm.cancelToolStripButton.Visible = false;
                            frm.pauseToolStripButton.Visible  = false;
                            frm.logTextBox.Text            = _model.JoinPaths.ToString();
                            frm.logTextBox.SelectionStart  = 0;
                            frm.logTextBox.SelectionLength = 0;
                            frm.ShowDialog();
                        }
                        finally
                        {
                            _model.JoinPaths = null;
                        }
                    }
                }
                else if (_reportView != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperReloadConfiguration")
                    {
                        _reportView.ReloadConfiguration();
                    }
                    else if (context.PropertyDescriptor.Name == "HelperResetParameters")
                    {
                        _reportView.InitParameters(true);
                        setModified();
                    }
                    else if (context.PropertyDescriptor.Name == "HelperResetPDFConfigurations")
                    {
                        _reportView.PdfConfigurations = _reportView.Report.Repository.Configuration.PdfConfigurations.ToList();
                        _reportView.PdfConverter      = null;
                        _reportView.Information       = Helper.FormatMessage("The PDF configuration values have been reset");
                        setModified();
                    }
                    else if (context.PropertyDescriptor.Name == "HelperResetExcelConfigurations")
                    {
                        _reportView.ExcelConfigurations = new List <string>();
                        _reportView.ExcelConverter      = null;
                        _reportView.Information         = Helper.FormatMessage("The Excel configuration values have been reset");
                        setModified();
                    }
                }
                else if (_configuration != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperResetPDFConfigurations")
                    {
                        _configuration.PdfConfigurations = new List <string>();
                        _configuration.PdfConverter      = null;
                    }
                    else if (context.PropertyDescriptor.Name == "HelperResetExcelConfigurations")
                    {
                        _configuration.ExcelConfigurations = new List <string>();
                        _configuration.ExcelConverter      = null;
                    }
                }
                else if (_reportSchedule != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperRunTaskScheduler")
                    {
                        var p = new Process();
                        p.StartInfo = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "taskschd.msc"), "/s")
                        {
                            UseShellExecute = true
                        };
                        p.Start();
                    }
                }
                else if (_parameter != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperResetParameterValue")
                    {
                        _parameter.Value = _parameter.ConfigValue;
                        setModified();
                    }
                }
                else if (_security != null)
                {
                    if (context.PropertyDescriptor.Name == "HelperSimulateLogin")
                    {
                        SecurityUser user = new SecurityUser(_security);
                        user.WebUserName = _security.TestUserName;
                        user.WebPassword = _security.TestPassword;
                        if (_security.TestCurrentWindowsUser)
                        {
                            user.WebPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                        }
                        user.Authenticate();
                        try
                        {
                            Cursor.Current = Cursors.WaitCursor;
                            ExecutionForm frm = new ExecutionForm(null);
                            frm.Text = "Test a login";
                            frm.cancelToolStripButton.Visible = false;
                            frm.pauseToolStripButton.Visible  = false;
                            frm.logTextBox.Text            = user.AuthenticationSummary;
                            frm.logTextBox.SelectionStart  = 0;
                            frm.logTextBox.SelectionLength = 0;
                            frm.ShowDialog();
                        }
                        finally
                        {
                            Cursor.Current = Cursors.Default;
                        }
                    }
                }
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }

            return(value);
        }
Example #28
0
 public void CreateTest <T>([PexAssumeNotNull] Repository <T> target, T entity)
     where T : class, new()
 {
     target.Create(entity);
 }
 public void Create()
 {
     Repository.Create(this);
 }
Example #30
0
        public bool CrearCompra(Cliente arg, DateTime fecha, string NumFacura, List <PurchasesBLL> detalle, decimal?flete)
        {
            bool    Resul = true;
            Cliente cliente;

            using (var resp = new Repository <Cliente>())
            {
                cliente = resp.Find(x => x.Cedula == arg.Cedula);
                if (cliente == null)
                {
                    var row = resp.GetAll().Count;
                    row++;
                    arg.IDCliente = row;
                    cliente       = resp.Create(arg);
                }
                if (cliente == null)
                {
                    Resul = false;
                    error = resp.Error;
                }
            }

            Factura factura = null;

            if (Resul)
            {
                using (var resp = new Repository <Factura>())
                {
                    var row = resp.GetAll().Count;
                    row++;
                    factura = resp.Create(new Factura
                    {
                        IDFactura    = row,
                        IDCliente    = cliente.IDCliente,
                        Numero       = NumFacura,
                        Fecha        = fecha,
                        Estado       = "A",
                        IDTerminal   = Convert.ToInt16(General.Terminal),
                        FechaSistema = DateTime.Now,
                        Flete        = flete
                    });
                    if (factura == null)
                    {
                        Resul = false;
                        error = resp.Error;
                    }
                }
            }
            ParametrosBLL p = new ParametrosBLL();

            if (Resul)
            {
                //con iva
                foreach (PurchasesBLL d in detalle)
                {
                    if (d.IDProducto != 0)
                    {
                        Repository <FacturaDetalle> de = new Repository <FacturaDetalle>();
                        if (d.UconIva > 0 && d.PUconIva > 0)
                        {
                            if (!de.SQLQuery <FacturaDetalle>("EXEC Sp_FacturaDetalleGrabar {0}, {1}, {2}, {3}, {4}, {5}",
                                                              new object[] {
                                d.IDProducto,
                                d.PUconIva,
                                d.UconIva,
                                factura.IDFactura,
                                "C",
                                p.myIva
                            }))
                            {
                                Resul = false;
                                error = de.Error;
                                break;
                            }
                        }
                        if (d.UsinIva > 0 && d.PUsinIva > 0)
                        {
                            if (!de.SQLQuery <FacturaDetalle>("EXEC Sp_FacturaDetalleGrabar {0}, {1}, {2}, {3}, {4}, {5}",
                                                              new object[] {
                                d.IDProducto,
                                d.PUconIva,
                                d.UconIva,
                                factura.IDFactura,
                                "C",
                                0
                            }))
                            {
                                Resul = false;
                                error = de.Error;
                                break;
                            }
                        }
                    }
                }
            }

            return(Resul);
        }
Example #31
0
 private void CreateCategory(Category category) => _categoryRepository.Create(category);
        public ValidationInformation UserCreation(UIOrganization uIOrganization)
        {
            ValidationInformation validation = this.userBValidation.RegistrationValidation(uIOrganization);

            if (validation.IsSuccess)
            {
                string   password  = GenerateTempPassword(8, 2);
                string[] sector    = new string[2];
                string[] subSector = new string[2];
                Others   other     = new Others();

                bool isOthers = false;
                if (uIOrganization.Sector.Contains(Utilities.OthersValue))
                {
                    sector = uIOrganization.Sector.Split(Utilities.SplitValue);
                    uIOrganization.Sector = sector[0];
                    other.Sector          = sector[1];
                    isOthers = true;
                }
                else
                {
                    other.Sector = string.Empty;
                }

                if (uIOrganization.SubSector.Contains(Utilities.OthersValue))
                {
                    subSector = uIOrganization.SubSector.Split(Utilities.SplitValue);
                    uIOrganization.SubSector = subSector[0];
                    other.SubSector          = subSector[1];
                    isOthers = true;
                }
                else
                {
                    other.SubSector = string.Empty;
                }


                using (Repository <Organization> repository = new Repository <Organization>())
                {
                    Organization organization = this.organizationMapper.Registration(uIOrganization);
                    organization.Cities         = repository.AssessmentContext.cities.FirstOrDefault(q => q.Id == organization.CityId);
                    organization.States         = repository.AssessmentContext.states.FirstOrDefault(q => q.Id == organization.StateId);
                    organization.Revenues       = repository.AssessmentContext.revenues.FirstOrDefault(q => q.Id == organization.RevenueId);
                    organization.TypesOfService = repository.AssessmentContext.serviceTypes.FirstOrDefault(q => q.Id == organization.Id);

                    //organization.Sectors = repository.AssessmentContext.sectors.FirstOrDefault(q => q.Id == organization.SectorId);
                    //organization.SubSectors = repository.AssessmentContext.subSectors.FirstOrDefault(q => q.Id == organization.SubSectorId);
                    organization.SectorId    = isOthers ? Convert.ToInt16(Utilities.SectorValue) : repository.AssessmentContext.sectors.FirstOrDefault(q => q.Id == organization.SectorId).Id;
                    organization.SubSectorId = isOthers ? Convert.ToInt16(Utilities.SectorValue) : repository.AssessmentContext.subSectors.FirstOrDefault(q => q.Id == organization.SubSectorId).Id;

                    int assessmentid  = 0;
                    var listAssesment = new List <Assessment>();
                    int sectorValue   = Convert.ToInt16(Utilities.SectorValue);

                    listAssesment = repository.AssessmentContext.assessments.Where(q => q.Sector == organization.SectorId).ToList();

                    if (listAssesment == null || listAssesment.Count == 0)
                    {
                        listAssesment = repository.AssessmentContext.assessments.Where(q => q.Sector == sectorValue).ToList();
                    }

                    if (listAssesment != null && listAssesment.Count > 0)
                    {
                        var subAssessment = listAssesment.FirstOrDefault(q => q.SubSector == organization.SubSectorId);
                        if (subAssessment != null && subAssessment.Id > 0)
                        {
                            assessmentid = subAssessment.Id;
                        }
                        else
                        {
                            assessmentid = listAssesment[0].Id;
                        }
                    }
                    organization.AssessmentId = assessmentid;

                    organization.TempPassword = password;
                    repository.Create(organization);
                    repository.SaveChanges();
                }

                if (isOthers)
                {
                    other.OrganizationId = uIOrganization.Name.Substring(0, 6);
                    using (Repository <Others> repository = new Repository <Others>())
                    {
                        //other.Organizations = repository.AssessmentContext.UserInfo.FirstOrDefault(q => q.Name == other.OrganizationId);
                        repository.Create(other);
                        repository.SaveChanges();
                    }
                }

                validation.IsSuccess = true;

                Repository <Template> template = new Repository <Template>();
                var registrationTemplate       = template.Filter(q => q.Name.StartsWith(Utilities.RegistrationTemplateName)).FirstOrDefault();
                if (registrationTemplate != null && !string.IsNullOrWhiteSpace(registrationTemplate.Description))
                {
                    RegistrationSendMail.SendMail(registrationTemplate.Description, Utilities.RegistrationSubject, uIOrganization.Email, uIOrganization.Name);
                }
                //this.registrationSendMail.Send(new MailConfiguration());
            }
            else
            {
                validation.IsSuccess = false;
            }
            return(validation);
        }
Example #33
0
        static void Main(string[] args)
        {
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(ExceptionHandler);

            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Set repository configuration path
            Repository.RepositoryConfigurationPath = Properties.Settings.Default.RepositoryPath;

            bool   execute             = (args.Length >= 1 && args[0].ToLower() == "/e");
            bool   executeOutputOrView = (args.Length >= 1 && args[0].ToLower() == "/x");
            string reportToOpen        = null;

            if (args.Length >= 2 && File.Exists(args[1]))
            {
                reportToOpen = args[1];
            }

            if ((execute || executeOutputOrView) && reportToOpen != null)
            {
                //Execute only
                var    report = Report.LoadFromFile(reportToOpen, Repository.Create());
                string outputGUID = null, viewGUID = null;
                if (executeOutputOrView)
                {
                    string guid = (args.Length >= 3 ? args[2] : "");
                    if (!string.IsNullOrEmpty(guid))
                    {
                        if (report.Views.Exists(i => i.GUID == guid))
                        {
                            viewGUID = guid;
                        }
                        if (report.Outputs.Exists(i => i.GUID == guid))
                        {
                            outputGUID = guid;
                        }
                    }
                    else
                    {
                        //by default execute first output
                        if (report.Outputs.Count > 0)
                        {
                            outputGUID = report.Outputs[0].GUID;
                        }
                    }
                }
                var reportViewer = new ReportViewerForm(true, Properties.Settings.Default.ShowScriptErrors);
                reportViewer.ViewReport(report, false, viewGUID, outputGUID, report.FilePath);

                Application.Run();
            }
            else
            {
                Application.Run(new ReportDesigner());
            }
        }
Example #34
0
        public static Page <Role> FindPage(Guid organizationId, string name, int pageIndex, int pageSize)
        {
            var repository = Repository.Create <IRoleRepository>();

            return(repository.FindPage(organizationId, name, pageIndex, pageSize));
        }
Example #35
0
        private void SaveTo(User user)
        {
            var repository = Repository.Create <IUserRepository>();

            repository.Update(user);
        }
Example #36
0
 public void ShouldSetCreatedAtAndUpdatedAtOnCreate()
 {
     var before = DateTime.Now;
     using (var session = _documentStore.OpenSession())
     {
         var page = new StaticPage {Title = "test"};
         var repository = new Repository(session);
         var createdPage = repository.Create(page);
         Assert.IsTrue(before <= createdPage.CreatedAt);
         Assert.AreEqual(createdPage.CreatedAt, createdPage.UpdatedAt);
     }
 }
Example #37
0
        private Car GetCar(Guid id)
        {
            var repository = Repository.Create <ICarRepository>();

            return(repository.Find(id, QueryLevel.None));
        }
Example #38
0
 public void Add(AccountBook accountBook)
 {
     repository.Create(accountBook);
 }
Example #39
0
        private Parametr _botParam; //с каким ботом телеграмма работаем

        public void Start() //метод вызывается при старте службы
        {
            try
            {
                Sender.Send(
                    "https://api.telegram.org/bot179261100:AAGqaQ8Fum0xK8JQL0FE_N4LugS_MmO36zM/sendmessage?chat_id=38651047&text=" +
                    "Запущен сервис DutyBot");
                try
                {
                    using (var repository = new Repository<DutyBotDbContext>())
                    {
                        var logReccord = new Log
                        {
                            Date = DateTime.Now,
                            MessageTipe = "info",
                            UserId = 0,
                            Operation = "StartService",
                            Exception = "",
                            AddInfo = ""
                        };
                        repository.Create(logReccord);
                    }
                }
                catch (Exception ex)
                {
                    Thread.Sleep(30000); // еcли не доступна БД и не получается залогировать запуск, ждём 30 секунд и пробуем еще раз.
                    try
                    {
                        using (var repository = new Repository<DutyBotDbContext>())
                        {
                            var exReccord = new Log
                            {
                                Date = DateTime.Now,
                                MessageTipe = "error",
                                UserId = 0,
                                Operation = "StartService",
                                Exception = ex.GetType() + ": " + ex.Message,
                                AddInfo = ""
                            };
                            repository.Create(exReccord);
                            var logReccord = new Log
                            {
                                Date = DateTime.Now,
                                MessageTipe = "info",
                                UserId = 0,
                                Operation = "StartService2",
                                Exception = "",
                                AddInfo = ""
                            };
                            repository.Create(logReccord);
                        }
                    }
                    catch
                    {
                        Sender.Send(
                            "https://api.telegram.org/bot179261100:AAGqaQ8Fum0xK8JQL0FE_N4LugS_MmO36zM/sendmessage?chat_id=38651047&text=Произошла ошибка при запуске службы. Подождал 10 секунд, попробовал еще раз, но ошибка осталась: " +
                            ex);
                    }
                }

                using (var repository = new Repository<DutyBotDbContext>()) //инициализирую парамтры приложения
                {
                    _botParam = repository.Get<Parametr>(p => p.Name == "TelegramBot");
                    _jiraParam = repository.Get<Parametr>(p => p.Name == "jira");
                    _userLoginParam = repository.Get<Parametr>(p => p.Name == "dafaultuserlogin");
                    _userPasswordParam = repository.Get<Parametr>(p => p.Name == "dafaultuserpassword");
                    _filterParam = repository.Get<Parametr>(p => p.Name == "Filter");
                }
                _bot = new TelegramBot(_botParam.Value);
                BufferBlock<Message> queue = new BufferBlock<Message>();
                Task.WhenAll(ReadMessages(queue), ProcessMessages(queue), Checkjira(), queue.Completion); //запускаю задачи по считыванию и обработке сообщений из telegramm
            }
            catch (Exception ex)
            {
                Sender.Send(
                    "https://api.telegram.org/bot179261100:AAGqaQ8Fum0xK8JQL0FE_N4LugS_MmO36zM/sendmessage?chat_id=38651047&text=" +
                    ex.Message);
                using (var repository = new Repository<DutyBotDbContext>())
                {
                    var logReccord = new Log
                    {
                        Date = DateTime.Now,
                        MessageTipe = "fatal",
                        UserId = 0,
                        Operation = "StartService",
                        Exception = ex.GetType() + ": " + ex.Message,
                        AddInfo = ""
                    };
                    repository.Create(logReccord);
                }
            }
        }
Example #40
0
        public virtual void setUp()
        {
            Configure();

            string name = GetType().Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

            // Cleanup old failed stuff
            recursiveDelete(new DirectoryInfo(trashParent.FullName), true, name, false);

            trash = new DirectoryInfo(trashParent + "/trash" + DateTime.Now.Ticks + "." + (_testcount++));
            trash_git = new DirectoryInfo(Path.GetFullPath(trash + "/.git"));

            var mockSystemReader = new MockSystemReader();
            mockSystemReader.userGitConfig = new FileBasedConfig(
                new FileInfo(Path.Combine(trash_git.FullName, "usergitconfig")));
            SystemReader.setInstance(mockSystemReader);

            db = new Repository(trash_git);
            db.Create();

            string[] packs = {
                "pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f",
                "pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371",
                "pack-9fb5b411fe6dfa89cc2e6b89d2bd8e5de02b5745",
                "pack-546ff360fe3488adb20860ce3436a2d6373d2796",
                "pack-e6d07037cbcf13376308a0a995d1fa48f8f76aaa",
                "pack-3280af9c07ee18a87705ef50b0cc4cd20266cf12"
            };

            var packDir = new DirectoryInfo(db.ObjectsDirectory + "/pack");

            foreach (var packname in packs)
            {
                new FileInfo("Resources/" + GitSharp.Transport.IndexPack.GetPackFileName(packname)).CopyTo(packDir + "/" + GitSharp.Transport.IndexPack.GetPackFileName(packname), true);
                new FileInfo("Resources/" + GitSharp.Transport.IndexPack.GetIndexFileName(packname)).CopyTo(packDir + "/" + GitSharp.Transport.IndexPack.GetIndexFileName(packname), true);
            }

            new FileInfo("Resources/packed-refs").CopyTo(trash_git.FullName + "/packed-refs", true);
        }
Example #41
0
    // Start is called before the first frame update
    void Start()
    {
        var model = new SampleTable(-1, "Hello World");

        Repository.Create("http://localhost:54904/", model, OnCreateSuccess, OnCreateFailed);
    }
Example #42
0
 protected sealed override IObservable <TTestModel> Create(TTestModel testModel)
 => Repository.Create(testModel);
        public static Organization FindBy(Guid orgId, QueryLevel level)
        {
            var repository = Repository.Create <IOrganizationRepository>();

            return(repository.Find(orgId, level));
        }
Example #44
0
        public static void Test(string connString)
        {
            int count = 0;
            var user  = new User {
                UniqueId = 1, UserName = "******", Age = 28, Sex = Sex.Male, DeptId = 1, UpdatedAt = DateTime.Now
            };
            var user1 = new User {
                UniqueId = 2, UserName = "******", Age = 24, Sex = Sex.Female, DeptId = 2, UpdatedAt = DateTime.Now
            };
            var repository = new Repository <User>(connString);

            //删除
            count = repository.Delete(user);
            count = repository.Delete(user1);

            //创建
            count = repository.Create(user);
            count = repository.Create(user1);

            //获取
            user = repository.QueryFirst("SELECT Id UniqueId,UserName,Sex FROM Coin_User WHERE Id=@UniqueId", user);
            user = repository.Get(user);

            //全量更新
            repository.Update(user);
            //更新
            user.UserName = "******";
            user.Sex      = Sex.Female;
            count         = repository.Update(f => f.Sex, user);
            count         = repository.Update(f => new { f.UserName, f.Sex }, user);

            count = repository.Update(user);

            //动态SQL更新
            var builder = new SqlBuilder();

            builder.RawSql("UPDATE Coin_User SET UserName=@UserName")
            .AndWhere(user.Sex.HasValue, "Sex=@Sex")
            .RawSql("WHERE Id=@UniqueId")
            .AndWhere(user.UpdatedAt.HasValue, "UpdatedAt>@UpdatedAt");
            count = repository.Update(builder.BuildSql(), user);

            count = repository.Update(f =>
            {
                f.RawSql("UPDATE Coin_User SET UserName=@UserName", user.UserName)
                .AddField(user.Sex.HasValue, "Sex=@Sex", user.Sex)
                .RawSql("WHERE Id=@UniqueId", user.UniqueId)
                .AndWhere(user.UpdatedAt.HasValue, "UpdatedAt>@UpdatedAt", user.UpdatedAt);
            });

            //查询&动态SQL
            var list = repository.Query(f =>
                                        f.RawSql("SELECT * FROM Coin_User")
                                        .AndWhere(user.Sex.HasValue, "Sex=@Sex", user.Sex)
                                        .AndWhere(user.UpdatedAt.HasValue, "UpdatedAt>@UpdatedAt", user.UpdatedAt)
                                        .RawSql("ORDER BY UpdatedAt DESC"));

            //分页
            var userInfoList = repository.QueryPage <UserInfo>("SELECT Id UniqueId,UserName,Sex FROM Coin_User WHERE Id>@UniqueId", 0, 10, "ORDER BY Id", user);

            userInfoList = repository.QueryPage <UserInfo>(f =>
                                                           f.RawSql("SELECT * FROM Coin_User")
                                                           .AndWhere(user.Sex.HasValue, "Sex=@Sex", user.Sex)
                                                           .AndWhere(user.UpdatedAt.HasValue, "UpdatedAt>@UpdatedAt", user.UpdatedAt)
                                                           .RawSql("ORDER BY UpdatedAt DESC"), 0, 10, "ORDER BY Id");
            //事务
            var context = new RepositoryContext(connString);

            try
            {
                var repository1    = context.RepositoryFor();
                var repositoryUser = context.RepositoryFor <User>();
                var repositoryDept = context.RepositoryFor <Dept>();
                context.Begin();
                var deptInfo = repository1.QueryFirst <DeptInfo>("SELECT A.DeptId,B.PersonTotal FROM Coin_User A,Coin_Dept B WHERE A.DeptId=B.Id AND A.Id=@UniqueId", new { UniqueId = 1 });
                repositoryUser.Delete(new User {
                    UniqueId = 1
                });
                repositoryDept.Update(f => f.PersonTotal, new Dept {
                    UniqueId = deptInfo.DeptId, PersonTotal = deptInfo.PersonTotal - 1
                });
                context.Commit();
            }
            catch (Exception ex)
            {
                context.Rollback();
            }
            //多结果集
            var order = new Order {
                Id = 1
            };
            var orderRepository = new Repository <Order>(connString);
            var sql             = "SELECT * FROM Coin_Order WHERE Id=@Id;SELECT * FROM Coin_OrderLine WHERE OrderId=@Id";
            var reader          = orderRepository.QueryMultiple(sql, order);

            order       = reader.Read <Order>();
            order.Lines = reader.ReadList <OrderLine>();

            order = orderRepository.QueryMap(map =>
            {
                var result   = map.Read <Order>();
                result.Lines = map.ReadList <OrderLine>();
                return(result);
            }, sql, order);

            order.Number = "123456789";
            orderRepository.Update(f => f.Number, order);

            //查询字典
            var dictRepository = new Repository();
            var dict           = dictRepository.QueryDictionary <int, string>("SELECT Id Key,UserName Value FROM Coin_User");

            dict = repository.QueryDictionary <int, string>("SELECT Id Key,UserName Value FROM Coin_User");
        }
Example #45
0
 protected virtual TEntity CreateEntity()
 {
     return(Repository.Create());
 }
Example #46
0
        private static void TestCreatingInvoiceWithValidationErrors(Repository repository)
        {
            // Try and create an invoice - but using incorrect data. This should hopefully be rejected by the Xero API
            Invoice invoiceToCreate = new Invoice
                {
                    Contact = new Contact
                        {
                            Name = TestContactName
                        },
                    Type = "ACCREC",
                    Date = DateTime.Today,
                    LineItems = new LineItems
                        {
                            new LineItem
                                {
                                    AccountCode = "200",
                                    Description = "Blue Widget",
                                    UnitAmount = 10m,
                                    TaxAmount = 2m,
                                    LineAmount = 12m
                                }
                        }
                };

            Console.WriteLine("Creating an invoice that should cause a validation error...");
            var createdInvoice = repository.Create(invoiceToCreate);

            if (createdInvoice.ValidationStatus == ValidationStatus.ERROR)
            {
                foreach (var message in createdInvoice.ValidationErrors)
                {
                    Console.WriteLine("Validation Error: " + message.Message);
                }
            }
        }
Example #47
0
        public void Test_DailyLogDetailDelete()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();

            try {
                var options = new DbContextOptionsBuilder <HOSContext>()
                              .UseSqlite(connection)
                              .Options;

                using (var context = new HOSContext(options))
                {
                    context.Database.EnsureCreated();
                }

                using (var context = new HOSContext(options))
                {
                    HOSTestData.LoadDutyStatusActivityTable(context);
                    HOSTestData.LoadDutyStatusTable(context);
                    HOSTestData.LoadStateProvinceCodeTable(context);
                    HOSTestData.LoadCompanyTable(context);
                    HOSTestData.LoadAppUserTable(context);
                }

                using (var context = new HOSContext(options))
                {
                    IRepository repository = new Repository(context);

                    var dailyLog = new DailyLog
                    {
                        LogID            = 1,
                        LogDate          = new DateTime(2016, 9, 7),
                        BeginningMileage = 899201,
                        EndingMileage    = 899423,
                        TruckNumber      = "3082",
                        TrailerNumber    = "9225",
                        IsSigned         = true,
                        Notes            = "Dropped trailer  9225 at Whirlpool and picked up loaded trailer 9159",
                        DriverID         = 4
                    };

                    var logDetail = new DailyLogDetail
                    {
                        LogDetailID          = 1,
                        DutyStatusID         = 4,
                        StartTime            = new DateTime(2016, 9, 7, 12, 45, 0),
                        StopTime             = new DateTime(2016, 9, 7, 13, 0, 0),
                        LocationCity         = "Ft Worth",
                        StateProvinceId      = 45,
                        DutyStatusActivityID = 1,
                        LogID = 1
                    };

                    dailyLog.DailyLogDetails.Add(logDetail);
                    repository.Create <DailyLog>(dailyLog);
                    repository.Save();

                    var test          = repository.Find <DailyLog>(log => log.LogID == dailyLog.LogID);
                    var logDetailTest = test.DailyLogDetails.FirstOrDefault();

                    Assert.NotNull(logDetailTest);
                    test.DailyLogDetails.Remove(logDetailTest);
                    repository.Save();
                    logDetailTest = test.DailyLogDetails.FirstOrDefault();

                    Assert.Null(logDetailTest);
                }
            } finally {
                connection.Close();
            }
        }
Example #48
0
 public virtual void Create(DTO dto)
 {
     _repository.Create(ConvertDtoToDB(dto));
 }
Example #49
0
 public void ShouldOnlySetUpdatedAtOnUpdate()
 {
     using (var session = _documentStore.OpenSession())
     {
         var page = new StaticPage { Title = "test" };
         var repository = new Repository(session);
         var createdPage = repository.Create(page);
         var created_at = createdPage.CreatedAt;
         createdPage.Title = "new title";
         var before = DateTime.Now;
         Thread.Sleep(100);
         repository.Edit(createdPage);
         Assert.IsTrue(before <= createdPage.UpdatedAt);
         Assert.AreEqual(created_at, createdPage.CreatedAt);
     }
 }
Example #50
0
 public void Post([FromBody] MTrip value)
 {
     _repository.Create(value);
 }
Example #51
0
		private static void TestCreatingInvoiceAsSubmittedForApproval( Repository repository )
		{
			// Try and create an invoice - but using incorrect data. This should hopefully be rejected by the Xero API
			Invoice invoiceToCreate = new Invoice
			{
				Contact = new Contact
				{
					Name = TestContactName
				},
				Type = "ACCREC",
				Date = DateTime.Today,
				Status = "SUBMITTED",
				LineItems = new LineItems
                        {
                            new LineItem
                                {
                                    AccountCode = "200",
                                    Description = "Blue Widget",
                                    UnitAmount = 10,
									Quantity = 1
                                }
                        },
				DueDate = DateTime.Now
			};

			Console.WriteLine( "Creating an invoice as submitted..." );
			var createdInvoice = repository.Create( invoiceToCreate );

			if ( createdInvoice.ValidationStatus == ValidationStatus.ERROR )
			{
				foreach ( var message in createdInvoice.ValidationErrors )
				{
					Console.WriteLine( "Validation Error: " + message.Message );
				}
			}
			else
			{
				// Now try to approve it.
				Console.WriteLine( "Approving submitted invoice" );
				createdInvoice.Status = "AUTHORISED";
				createdInvoice = repository.UpdateOrCreate( createdInvoice );

			}
		}
Example #52
0
 // POST api/values
 public void Post([FromBody] Rating place)
 {
     Repository.Create(place, "elcapo");
     Repository.Save();
 }
Example #53
0
        static void ExerciseOrganisation(Repository repository)
        {
            if (repository == null)
            {
                return;
            }

            // Make a call to api.xero.com to check that we can use the access token.
            Organisation organisation = repository.Organisation;
            Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisation.Name));

            

            // Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }
            
            Contact contact = new Contact { Name = contactName };
            
            contact = repository.UpdateOrCreate(contact);
            Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contact.Name, contact.ContactID));
            Console.WriteLine(string.Format("The validation status was: {0}", contact.ValidationStatus));

            


            // Try to update the contact that's just been created, but this time use a POST method
            contact.EmailAddress = string.Format("{0}@nowhere.com", contact.Name.ToLower().Replace(" ", "."));
            
            contact = repository.UpdateOrCreate(contact);
            Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contact.Name, contact.EmailAddress));

            

            // Get the contact by it's Id...
            var reReadContact = repository.Contacts.First(c => c.ContactID == contact.ContactID);
            Console.WriteLine(string.Format("The contact '{0}' was re-read using it's ContactID: {1}", reReadContact.Name, reReadContact.ContactID));



            // Construct a linq expression to call 'GET Contacts'...
            int invoiceCount = repository.Contacts
                .Where(c => c.UpdatedDateUTC >= DateTime.UtcNow.AddMonths(-1))
                .Count();

            Console.WriteLine(string.Format("There were {0} contacts created or updated in the last month.", invoiceCount));


            // Construct a linq expression to call 'GET Contacts'...
            var customers = repository.Contacts.Where(c => c.IsCustomer == true).ToList();

            Console.WriteLine(string.Format("There are {0} contacts that are customers.", customers.Count));

            if (customers.Any(c => !c.IsCustomer))
            {
                Console.WriteLine("Filtering contacts on the IsCustomer flag didn't work!");
            }



            // Try out the 'Single' linq method (http://answers.xero.com/developer/question/36501/)
            var organisation2 = repository.Organisations.Single();

            


            // Find out how many bank accounts are defined for the organisation...
            var bankAccounts = repository.Accounts
                .Where(account => account.Type == "BANK")
                .OrderBy(account => account.Name)
                .ToList();

            Console.WriteLine(string.Format("There were {0} bank accounts in this organisation.", bankAccounts.Count()));

            foreach (var bankAaccount in bankAccounts)
            {
                Console.WriteLine(string.Format("Bank Account Name:{0} Code:{1} Number:{2}", bankAaccount.Name, bankAaccount.Code, bankAaccount.BankAccountNumber));
            }




            // Get the tracking categories in this org
            IQueryable<TrackingCategory> trackingCategories = repository.TrackingCategories;

            foreach (var trackingCategory in trackingCategories)
            {
                Console.WriteLine(string.Format("Tracking Category: {0}", trackingCategory.Name));

                foreach (var trackingOption in trackingCategory.Options)
                {
                    Console.WriteLine(string.Format("    Option: {0}", trackingOption.Name));
                }
            }



            // Try the linq syntax to select items with sales details..
            var itemQuery = from item in repository.Items
                        where item.SalesDetails != null
                        select item;

            var itemList = itemQuery.ToList();

            Console.WriteLine("There are {0} inventory items", itemList.Count);

            foreach (var item in itemList)
            {
                Console.WriteLine(string.Format("   Item {0} is sold at price: {1} {2}", item.Description, item.SalesDetails.UnitPrice, organisation.BaseCurrency));
            }


            // Try and create an invoice - but using incorrect data. This should hopefully be rejected by the Xero API
            Invoice invoiceToCreate = new Invoice
            {
                Contact = contact,
                Type = "ACCREC",
                Date = DateTime.Today,
                LineItems = new LineItems
                {
                    new LineItem
                    {
                        AccountCode = "200",
                        Description = "Blue Widget",
                        UnitAmount = 10m,
                        TaxAmount = 2m,
                        LineAmount = 12m
                    }
                }
            };

            Console.WriteLine("Creating an invoice that should cause a validation error...");
            var createdInvoice = repository.Create(invoiceToCreate);

            if (createdInvoice.ValidationStatus == ValidationStatus.ERROR)
            {
                foreach (var message in createdInvoice.ValidationErrors)
                {
                    Console.WriteLine("Validation Error: " + message.Message);
                }
            } 


            // Download a PDF of the first AR invoice in the system
            Invoice firstInvoice = repository.Invoices.First(invoice => invoice.Type == "ACCREC");
            


            // Test the FindById to see if we can re-fetch the invoice WITH the line items this time
            firstInvoice = repository.FindById<Invoice>(firstInvoice.InvoiceID);



            if (firstInvoice != null)
            {
                Console.WriteLine(string.Format("Downloading the PDF of invoice {0}...", firstInvoice.InvoiceNumber));

                byte[] invoicePdf = repository.FindById<Invoice>(firstInvoice.InvoiceID.ToString(), MimeTypes.ApplicationPdf);
                string invoicePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), firstInvoice.InvoiceNumber + ".pdf");

                FileInfo file = new FileInfo(invoicePath);

                if (file.Exists)
                {
                    file.Delete();
                }

                using (FileStream fs = file.OpenWrite())
                {
                    fs.Write(invoicePdf, 0, invoicePdf.Length);
                }

                Console.WriteLine("PDF for invoice '{0}' has been saved to:", firstInvoice.InvoiceNumber);
                Console.WriteLine(invoicePath);

                // This commented-out line of code will try and start a PDF viewer to view the invoice PDF.
                //Process.Start(invoicePath);
            }



            // Find all invoices that were against the same contact as the first AR invoice that we've just found (http://answers.xero.com/developer/question/36911/)
            if (firstInvoice != null)
            {
                Console.WriteLine("Getting a list of all invoice created for {0}", firstInvoice.Contact.Name);

                Guid contactId = firstInvoice.Contact.ContactID;
                var invoicesForContact = repository.Invoices.Where(invoice => invoice.Contact.ContactID == contactId).ToList();

                Console.WriteLine("There are {0} invoices raised for {1}", invoicesForContact.Count, firstInvoice.Contact.Name);

                foreach (var invoiceForContact in invoicesForContact)
                {
                    Console.WriteLine("Invoice {0} was raised against {1} on {2} for {3}{4}", invoiceForContact.InvoiceNumber,
                                        invoiceForContact.Contact.Name, invoiceForContact.Date, invoiceForContact.Total,
                                        invoiceForContact.CurrencyCode);
                }
            }



            // Find the subscriber for this organisation
            User subscriber = repository.Users.FirstOrDefault(user => user.IsSubscriber == true);

            if (subscriber == null)
            {
                Console.WriteLine("There is no subscriber for this organisation. Maybe a demo organisation? Maybe this endpoint hasn't been released yet?");
            }
            else
            {
                Console.WriteLine("The subscriber for this organisation is " + subscriber.FullName);


                // Create a receipt
                Receipt receipt = new Receipt
                {
                    Contact = new Contact { Name = "Mojo Coffee" },
                    User = subscriber,
                    Date = DateTime.Today.Date,
                    LineAmountTypes = LineAmountType.Inclusive,
                    LineItems = new LineItems
                    {
                        new LineItem
                            {
                                Description = "Flat White",
                                Quantity = 1m,
                                AccountCode = "429",
                                UnitAmount = 3.8m
                            },
                                           
                        new LineItem
                            {
                                Description = "Mocha",
                                Quantity = 1m,
                                AccountCode = "429",
                                UnitAmount = 4.2m
                            }
                    }
                };


                // Save the receipt to Xero
                receipt = repository.Create(receipt);

                Console.WriteLine("Receipt {0} was created for {1} for user {2}", receipt.ReceiptID, receipt.Contact.Name, receipt.User.FullName);



                // Upload an attachment against the newly creacted receipt
                FileInfo attachmentFileInfo = new FileInfo(@".\Attachments\Receipt.png");

                if (!attachmentFileInfo.Exists)
                {
                    Console.WriteLine("The Receipt.png file cannot be loaded from disk!" + subscriber.FullName);
                    return;
                }


                // Upload the attachment against the receipt
                Console.WriteLine("Attaching file {0} to Receipt {1}...", attachmentFileInfo.Name, receipt.ReceiptID);
                repository.Attachments.UpdateOrCreate(receipt, attachmentFileInfo);


                // Fetch the attachment that was just uploaded
                Attachment attachment = repository.Attachments.GetAttachmentFor(receipt);

                if (attachment.ContentLength != attachmentFileInfo.Length)
                {
                    Console.WriteLine("The uploaded attachment filesize {0} does not match the original filesize {1}", attachment.ContentLength, attachmentFileInfo.Length);
                }
                else if (attachment.Filename != attachmentFileInfo.Name)
                {
                    Console.WriteLine("The uploaded attachment filename '{0}' does not match the original filename '{1}'", attachment.Filename, attachmentFileInfo.Name);
                }
                else
                {
                    Console.WriteLine("Attachment succesfully uploaded!");
                }

            }


            // Get a list of all expense claims
            Console.WriteLine("Getting a list of all submitted expense claims...");

            foreach (var expenseClaim in repository.ExpenseClaims.Where(expenseClaim => expenseClaim.Status != "CURRENT"))
            {
                Console.WriteLine("Expense claim {0} for user {1} for amount {2} with status {3}", expenseClaim.ExpenseClaimID, expenseClaim.User.EmailAddress, expenseClaim.Total, expenseClaim.Status);
            }


            // Get a trial balance report (as per http://answers.xero.com/developer/question/36201/)
            Console.WriteLine("Running Trial Balance Report...");
            Report trialBalance = repository.Reports.RunDynamicReport(new TrialBalanceReport());

            if (trialBalance != null)
            {
                foreach (var reportTitle in trialBalance.ReportTitles)
                {
                    Console.WriteLine("\t" + reportTitle);
                }

                foreach (var reportRow in trialBalance.Rows)
                {
                    Console.WriteLine("    " + reportRow.Title);

                    if (reportRow.Rows != null)
                    {
                        foreach (var subRow in reportRow.Rows)
                        {
                            Console.Write("         Row: " + subRow.RowType);

                            foreach (var cell in subRow.Cells)
                            {
                                Console.Write(cell.Value + ", ");
                            }

                            Console.WriteLine();
                        }
                    }
                }
            }

            
            Console.WriteLine("All done!");
        }
Example #54
0
        private Animal GetAnimal(Guid id)
        {
            var repository = Repository.Create <IAnimalRepository>();

            return(repository.Find(id, QueryLevel.None));
        }
Example #55
0
        /// <summary>
        /// Helper for creating extra empty repos
        /// </summary>
        /// <returns>
        /// A new empty git repository for testing purposes
        /// </returns>
        protected Repository createNewEmptyRepo(bool bare)
        {
            var newTestRepo = new DirectoryInfo(Path.GetFullPath(trashParent + "/new" + DateTime.Now.Ticks + "." + (_testcount++) + (bare ? "" : "/") + ".git"));
            Assert.IsFalse(newTestRepo.Exists);
            var newRepo = new Repository(newTestRepo);
            newRepo.Create();
            string name = GetType().Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

            Microsoft.Win32.SystemEvents.SessionEnded += (o, args) => // cleanup
                                                  recursiveDelete(new DirectoryInfo(newTestRepo.FullName), false, name, false);
            _repositoriesToClose.Add(newRepo);
            return newRepo;
        }
Example #56
0
 public void Create(BllUser entity)
 {
     _repository.Create(entity.ToDB());
 }
Example #57
0
        private static void TestCreatingReceiptsForAUser(Repository repository)
        {
            User[] allUsers = repository.Users.ToArray();

            var anyUserWithAnId = allUsers.FirstOrDefault(it => it.UserID != null);
            
            if (anyUserWithAnId == null)
            {
                Console.WriteLine("Again, this is probably a demo organisation. There are no UserIDs returned for these organisations.");
                return;
            }

            // Create a receipt
            Receipt receipt = new Receipt
                {
                    Contact = new Contact {Name = "Mojo Coffee"},
                    User = anyUserWithAnId,
                    Date = DateTime.Today.Date,
                    LineAmountTypes = LineAmountType.Inclusive,
                    LineItems = new LineItems
                        {
                            new LineItem
                                {
                                    Description = "Flat White",
                                    Quantity = 1m,
                                    AccountCode = "429",
                                    UnitAmount = 3.8m
                                },
                            new LineItem
                                {
                                    Description = "Mocha",
                                    Quantity = 1m,
                                    AccountCode = "429",
                                    UnitAmount = 4.2m
                                }
                        }
                };


            // Save the receipt to Xero
            receipt = repository.Create(receipt);

            if (receipt.ReceiptID == Guid.Empty)
            {
                string message = string.Format("The receipt was not succesfully created: {0}", receipt.ValidationErrors.Select(it => it.Message).Aggregate((s1, s2) => string.Concat(s1, ";", s2)));
                throw new ApplicationException(message);
            }

            Console.WriteLine("Receipt {0} was created for {1} for user {2}", receipt.ReceiptID, receipt.Contact.Name, receipt.User.FullName);


            // Upload an attachment against the newly creacted receipt
            FileInfo attachmentFileInfo = new FileInfo(AnyAttachmentFilename);

            if (!attachmentFileInfo.Exists)
            {
                throw new ApplicationException("The Receipt.png file cannot be loaded from disk!");
            }


            // Upload the attachment against the receipt
            Console.WriteLine("Attaching file {0} to Receipt {1}...", attachmentFileInfo.Name, receipt.ReceiptID);
            repository.Attachments.UpdateOrCreate(receipt, attachmentFileInfo);


            // Fetch the attachment that was just uploaded
            Attachment attachment = repository.Attachments.GetAttachmentFor(receipt);

            if (attachment.ContentLength != attachmentFileInfo.Length)
            {
                Console.WriteLine("The uploaded attachment filesize {0} does not match the original filesize {1}", attachment.ContentLength, attachmentFileInfo.Length);
            }
            else if (attachment.Filename != attachmentFileInfo.Name)
            {
                Console.WriteLine("The uploaded attachment filename '{0}' does not match the original filename '{1}'", attachment.Filename, attachmentFileInfo.Name);
            }
            else
            {
                Console.WriteLine("Attachment succesfully uploaded!");
            }
        }
Example #58
0
 // Create the repository with no sources
 public void CreateRepository()
 {
     _repository = Repository.Create();
     _repository.Sources.Clear();
 }
Example #59
0
        private static Invoice CreateAnyPurchasesInvoice(Repository repository)
        {
            var invoice = new Invoice
                {
                    Type = "ACCPAY",
                    Contact = new Contact {Name = TestContactName},
                    Date = DateTime.Today,
                    DueDate = DateTime.Today.AddDays(14),
                    Status = "DRAFT",
                    LineItems = new LineItems
                        {
                            new LineItem
                                {
                                    Description = "Services Rendered",
                                    Quantity = 1,
                                    UnitAmount = 1,
                                }
                        }
                };

            return repository.Create(invoice);
        }
Example #60
0
 protected override TEntity CreateReturnEntity(TDto model) => Repository.Create(model);