Exemple #1
0
        public Consumer(string groupName, ConsumerSetting setting, string consumerName = null)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException("groupName");
            }

            Name = consumerName;
            GroupName = groupName;
            Setting = setting ?? new ConsumerSetting();

            if (Setting.NameServerList == null || Setting.NameServerList.Count() == 0)
            {
                throw new Exception("Name server address is not specified.");
            }

            _subscriptionTopics = new Dictionary<string, HashSet<string>>();
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            var clientSetting = new ClientSetting
            {
                ClientName = Name,
                ClusterName = Setting.ClusterName,
                NameServerList = Setting.NameServerList,
                SocketSetting = Setting.SocketSetting,
                OnlyFindMasterBroker = true,
                SendHeartbeatInterval = Setting.HeartbeatBrokerInterval,
                RefreshBrokerAndTopicRouteInfoInterval = Setting.RefreshBrokerAndTopicRouteInfoInterval
            };
            _clientService = new ClientService(clientSetting, null, this);
            _pullMessageService = new PullMessageService(this, _clientService);
            _commitConsumeOffsetService = new CommitConsumeOffsetService(this, _clientService);
            _rebalanceService = new RebalanceService(this, _clientService, _pullMessageService, _commitConsumeOffsetService);
        }
        /// <summary>
        /// Constructs the Freshbooks API authentication and wrapper class
        /// </summary>
        /// <param name="accountName">The account name for which you are trying to access</param>
        /// <param name="consumerKey">The developer's freshbooks account name</param>
        /// <param name="oauthSecret">The developer's oauth-secret provided by freshbooks</param>
        public FreshbooksApi(string accountName, string consumerKey, string oauthSecret)
        {
            _accountName = accountName;
            _consumerKey = consumerKey;
            _oauthSecret = oauthSecret ?? String.Empty;

            _baseUri = new UriBuilder { Scheme = "https", Host = accountName + ".freshbooks.com" }.Uri;
            _serviceUri = new Uri(_baseUri, "/api/2.1/xml-in");
            Clear();

            UserAgent = String.Format("{0}/{1} ({2})", 
                GetType().Name,
                GetType().Assembly.GetName().Version.ToString(2), 
                GetType().Assembly.FullName);

            Callback = new CallbackService(new ServiceProxy(this, "callback"));
            Category = new CategoryService(new ServiceProxy(this, "category"));
            Client = new ClientService(new ServiceProxy(this, "client"));
            Estimate = new EstimateService(new ServiceProxy(this, "estimate"));
            Expense = new ExpenseService(new ServiceProxy(this, "expense"));
            Gateway = new GatewayService(new ServiceProxy(this, "gateway"));
            Invoice = new InvoiceService(new ServiceProxy(this, "invoice"));
            Item = new ItemService(new ServiceProxy(this, "item"));
            Language = new LanguageService(new ServiceProxy(this, "language"));
            Payment = new PaymentService(new ServiceProxy(this, "payment"));
            Project = new ProjectService(new ServiceProxy(this, "project"));
            Recurring = new RecurringService(new ServiceProxy(this, "recurring"));
            System = new SystemService(new ServiceProxy(this, "system"));
            Staff = new StaffService(new ServiceProxy(this, "staff"));
            Task = new TaskService(new ServiceProxy(this, "task"));
            Tax = new TaxService(new ServiceProxy(this, "tax"));
            TimeEntry = new TimeEntryService(new ServiceProxy(this, "time_entry"));
        }
Exemple #3
0
        public Producer(ProducerSetting setting = null, string name = null)
        {
            Name = name;
            Setting = setting ?? new ProducerSetting();

            if (Setting.NameServerList == null || Setting.NameServerList.Count() == 0)
            {
                throw new Exception("Name server address is not specified.");
            }

            _queueSelector = ObjectContainer.Resolve<IQueueSelector>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            var clientSetting = new ClientSetting
            {
                ClientName = Name,
                ClusterName = Setting.ClusterName,
                NameServerList = Setting.NameServerList,
                SocketSetting = Setting.SocketSetting,
                OnlyFindMasterBroker = true,
                SendHeartbeatInterval = Setting.HeartbeatBrokerInterval,
                RefreshBrokerAndTopicRouteInfoInterval = Setting.RefreshBrokerAndTopicRouteInfoInterval
            };
            _clientService = new ClientService(clientSetting, this, null);
        }
 public DataServices(DbContext ctx)
 {
     DataContext = ctx as BizConnectEntities;
     Layouts = new LayoutService(DataContext);
     InvoiceData = new InvoiceDataService(DataContext);
     Client = new ClientService(DataContext);
     Invoice = new InvoiceService(DataContext);
 }
        public static void CreateNewAccount(string username, string password, string email, string captchaToken, string captchaAnswer, ClientService.CreateLoginCompletedEventHandler onCreateLoginCompleted)
        {
            ClientService.ClientService clientService = ServiceHandler.Service;

            clientService.CreateLoginCompleted += onCreateLoginCompleted;

            clientService.CreateLoginAsync(username, password, email, captchaToken, captchaAnswer);
        }
        //private static ClientService.ClientService GetNewClientService()
        //{
        //    ClientService.ClientService clientService = new ClientService.ClientService();
        //    clientService.Url = AllegianceRegistry.ClientService;
        //    return clientService;
        //}
        public static void GetCaptchaAsync(int width, int height, ClientService.GetCaptchaCompletedEventHandler onGetCaptchaComplete)
        {
            ClientService.ClientService clientService = ServiceHandler.Service;

            clientService.GetCaptchaCompleted += new ClientService.GetCaptchaCompletedEventHandler(onGetCaptchaComplete);

            clientService.GetCaptchaAsync(width, true, height, true);
        }
        private void call_rpc(ClientService.Iface client)
        {
            bool foo = client.foo();
            Assert.IsTrue(foo);

            bool bar = client.bar();
            Assert.IsTrue(bar);
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new MainForm());

            // for the prototype, we're accepting untrusted server certificates
            ServicePointManager.ServerCertificateValidationCallback
                = new RemoteCertificateValidationCallback(ValidateServerCertificate);

            AuthenticatedData.SetLogin("Orion", Hash("Test"));

            using (var auth = new ClientService())
            {
                //Retrieve AutoUpdate data
                AutoUpdateClient.Check(auth);

                //Login, and then perform initial check-in

                Console.WriteLine("Logging in. {0}", DateTime.Now);

                Assembly blackbox = null;

                var loginResult = auth.Login(new LoginData()
                {
                    Alias = "Orion"
                });

                Console.WriteLine("Login Status: {0} - {1}", loginResult.Status, DateTime.Now);

                if (loginResult.Status != LoginStatus.Authenticated)
                    return;

                //Retrieve all messages for this login
                ReceiveMessages();

                ReceivePolls();

                blackbox = Assembly.Load(loginResult.BlackboxData);

                var validatorType = blackbox.GetType("Allegiance.CommunitySecuritySystem.Blackbox.Validator");
                var machineInfoType = blackbox.GetType("Allegiance.CommunitySecuritySystem.Blackbox.MachineInformation");
                var machineInfo = Activator.CreateInstance(machineInfoType);

                GatherMachineInfo(machineInfoType, machineInfo);

                var method = validatorType.GetMethod("Check", BindingFlags.Static | BindingFlags.Public);
                var results = method.Invoke(null, new object[] { machineInfo }) as byte[];

                var checkInResult = auth.CheckIn(new CheckInData()
                {
                    SessionIdSpecified = false,
                    EncryptedData = results,
                });

                Console.WriteLine("Initial Check-In Status: {0} - {1}", checkInResult.Status, DateTime.Now);
            }
        }
 public void Init(ClientService clientService)
 {
     var hierarchy = clientService.GetHierarchy();
     ExtractProjects(hierarchy);
     this.Fields = new FieldList(clientService.GetFields());
     this.Constants = clientService.GetConstants();
     ExtractWorkItemTypes(clientService);
     ExtractActions(clientService);
 }
 public void Connect(string apiUrl, string apiKey)
 {
     PaymillWrapper.Paymill.ApiKey = apiKey;
     PaymillWrapper.Paymill.ApiUrl = apiUrl;
     clientService = Paymill.GetService<ClientService>();
     paymentService = Paymill.GetService<PaymentService>();
     transactionService = Paymill.GetService<TransactionService>();
     refundService = Paymill.GetService<RefundService>();
 }
Exemple #11
0
        public SPlayer(Player player, ClientService session)
            : base(player)
        {
            Session = session;

            Handler = new PlayerHandler(this);

            OnDirectionEnablement += new DirectionEventHandler(SPlayer_OnDirectionEnablement);
            OnDirectionDisablement += new DirectionEventHandler(SPlayer_OnDirectionEnablement);
        }
Exemple #12
0
 public Client(int ClientID)
 {
     this.clientID = ClientID;
     ClientService cs=new ClientService();
     DataSet ds = cs.GetClientDetailsByID(ClientID);
     this.cityID = Convert.ToInt32(ds.Tables[0].Rows[0]["CityID"]);
     this.email = ds.Tables[0].Rows[0]["Email"].ToString();
     this.address = ds.Tables[0].Rows[0]["Address"].ToString();
     this.phone = ds.Tables[0].Rows[0]["Phone"].ToString() ;
 }
 public CommitConsumeOffsetService(Consumer consumer, ClientService clientService)
 {
     _consumeOffsetInfoDict = new ConcurrentDictionary<string, ConsumeOffsetInfo>();
     _consumer = consumer;
     _clientService = clientService;
     _clientId = clientService.GetClientId();
     _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
     _scheduleService = ObjectContainer.Resolve<IScheduleService>();
     _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
 }
        private void ExtractWorkItemTypes(ClientService clientService)
        {
            var types = clientService.GetWorkItemTypes();
//            foreach (var type in types)
//            {
//                var type1 = type;
//                type.Project = this.Projects.Single(p => p.Id == type1.ProjectId);
//                type.Name = this.Constants.Single(c => c.Id == type1.NameConstantId);
//            }
            WorkItemTypes = types;
        }
Exemple #15
0
        public BO(IDAO dao)
        {
            if (dao == null) throw new ArgumentNullException(nameof(dao));

            DAO = dao;
            ClientService = new ClientService(dao.ClientRepository);
            GoodsService = new GoodsService(dao.GoodsRepository);
            ManagerService = new ManagerService(dao.ManagerRepository);
            SaleService = new SaleService(dao.SaleRepository);
            Log.Trace("BO created.");
        }
    public static void StartListening()
    {
        ClientService ClientTask  ;

        // Client Connections Pool
        ClientConnectionPool ConnectionPool = new ClientConnectionPool()  ;

        // Client Task to handle client requests
        ClientTask = new ClientService(ConnectionPool) ;

        ClientTask.Start() ;

        TcpListener listener = new TcpListener(portNum);
        try
        {
            listener.Start();

            int TestingCycle = 3 ; // Number of testing cycles
            int ClientNbr = 0 ;

            // Start listening for connections.
            Console.WriteLine("Waiting for a connection...");
            while ( TestingCycle > 0 )
            {

                TcpClient handler = listener.AcceptTcpClient();

                if (  handler != null)
                {
                    Console.WriteLine("Client#{0} accepted!", ++ClientNbr) ;

                    // An incoming connection needs to be processed.
                    ConnectionPool.Enqueue( new ClientHandler(handler) ) ;

                    //--TestingCycle ;
                }
                else
                    break;
            }
            listener.Stop();

            // Stop client requests handling
            ClientTask.Stop() ;

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
        internal void FillForm(ClientService.Poll poll)
        {
            this.Tag            = poll;
            _questionText.Text  = poll.Question;
            _dateLabel.Text     = string.Format("Sent {0:M/d/yy} at {0:h:mm tt}", poll.DateCreated);
            _pollHeaderLabel.Text = "Poll #" + poll.Id;

            _optionList.Items.Clear();

            foreach (var option in poll.PollOptions)
                _optionList.Items.Add(option);
        }
        private void ExtractActions(ClientService clientService)
        {
            var actions = clientService.GetActions();
//            foreach (var action in actions)
//            {
//                var action1 = action;
//                action.WorkItemType = this.WorkItemTypes.Single(t => t.Id == action1.WorkItemTypeId);
//                action.FromState = this.Constants.Single(c => c.Id == action1.FromStateId);
//                action.ToState = this.Constants.Single(c => c.Id == action1.ToStateId);
//            }
            Actions = actions;
        }
        public frmMain()
        {
            InitializeComponent();

            server = new ClientService(connectionPool);

            server.Logged += new EventHandler<LogEventArgs>(ServerMessageLogged);
            client = new Client();

            client.MessageReceived += new EventHandler<ServerMessageEventArgs>(MessageReceived);
            client.Connected += new EventHandler(ClientConnected);
            client.Disconnected += new EventHandler(ClientDisconnected);
        }
Exemple #20
0
 public RebalanceService(Consumer consumer, ClientService clientService, PullMessageService pullMessageService, CommitConsumeOffsetService commitConsumeOffsetService)
 {
     _consumer = consumer;
     _clientService = clientService;
     _clientId = clientService.GetClientId();
     _pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
     _allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
     _pullMessageService = pullMessageService;
     _commitConsumeOffsetService = commitConsumeOffsetService;
     _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
     _scheduleService = ObjectContainer.Resolve<IScheduleService>();
     _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
 }
 public void Setup() {
     clientService = new ClientService(
         userService = new UserService(
             userStore = new DictionaryUserSource()));
     userStore[SecurityConst.ROLE_ADMIN.ToLowerInvariant()] = new User {Login = SecurityConst.ROLE_ADMIN,IsAdmin = true}.Activate();
     userStore[SecurityConst.ROLE_SECURITY_ADMIN.ToLowerInvariant()] = new User {Login = SecurityConst.ROLE_SECURITY_ADMIN, Roles = new [] {SecurityConst.ROLE_SECURITY_ADMIN}}.Activate();
     userStore[SecurityConst.ROLE_USER.ToLowerInvariant()] = new User {Login = SecurityConst.ROLE_USER }.Activate();
     userStore["existed@groups"] = new User {Login = "******",IsGroup = true}.Activate();
     minimalValidRequest = new ClientRecord {Name = "ОАО Тест",IsDemo = true};
     doubleRequest = new ClientRecord {Name = "ОАО Existed",IsDemo = true};
     passwordManager = new PasswordManager();
     passLogon = new PasswordLogon {UserService = userService};
     userStateChecker = new UserStateChecker {UserService = userService};
 }
        private void call_rpc(ClientService.Iface client)
        {
            // This no longer compiles after updating to the latest Client.thrift file.
            //bool foo = client.foo();

            bool negativeNumbersReturnFalse = client.fooEx(-1);
            Assert.IsFalse(negativeNumbersReturnFalse);

            bool positiveNumbersReturnTrue = client.fooEx(1);
            Assert.IsTrue(positiveNumbersReturnTrue);

            bool bar = client.bar();
            Assert.IsTrue(bar);
        }
		public static PendingUpdates GetPendingUpdateQueues(ClientService.ClientService service)
		{
			PendingUpdates returnValue = new PendingUpdates();

			var lobbies = ServiceHandler.Service.CheckAvailableLobbies();
			foreach (LobbyResult lobby in lobbies)
			{
				//Get autoupdate files associated with lobby
				var results = service.CheckForUpdates(lobby.LobbyId, true);

				List<FindAutoUpdateFilesResult> updateQueue = ProcessPendingUpdates(lobby, results);

				returnValue.AutoUpdateBaseAddress.Add(lobby.LobbyId, results.AutoUpdateBaseAddress);
				returnValue.AllFilesInUpdatePackage.Add(lobby.LobbyId, results.Files);
				returnValue.PendingUpdateList.Add(lobby.LobbyId, updateQueue);
			}

			return returnValue;
		}
    private void InternalStartTask(ClientService client)
    {
        while (!stopThread)
        {
            try
            {
                MachineInfo info = GetMachineInfo();
                info.CPUsage = cpuCounter.NextValue();
                info.Memory = ramCounter.NextValue();
                info.DateEvent = DateTime.Now;
                bool toSend = false ;
                if (info.CPUsage > 80)
                {
                    info.Message = " ** CPU ALARM ** ";
                    toSend = true;
                }
                if (info.Memory > 800)
                {
                    toSend = true;
                    info.Message += " ** MEMORY ALARM ** ";
                }

                if (toSend)
                {
                    client.SendMachineInfo(info);
                    Console.WriteLine(DateTime.Now + ": Info sent " + info.Message);
                }
                else Console.WriteLine(DateTime.Now + ": Everything ok");

                Thread.Sleep(1000);
            }
            catch (Exception e)
            {
                stopThread = true;
                Console.WriteLine(e);
            }
        }
    }
        public PullMessageService(Consumer consumer, ClientService clientService)
        {
            _consumer = consumer;
            _clientService = clientService;
            _clientId = clientService.GetClientId();
            _binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
            _scheduleService = ObjectContainer.Resolve<IScheduleService>();
            _logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);

            if (consumer.Setting.AutoPull)
            {
                if (consumer.Setting.MessageHandleMode == MessageHandleMode.Sequential)
                {
                    _consumingMessageQueue = new BlockingCollection<ConsumingMessage>();
                    _consumeMessageWorker = new Worker("ConsumeMessage", () => HandleMessage(_consumingMessageQueue.Take()));
                }
                _messageRetryQueue = new BlockingCollection<ConsumingMessage>();
            }
            else
            {
                _pulledMessageQueue = new BlockingCollection<QueueMessage>();
            }
        }
		public virtual void Init()
		{
			WorkspaceService = new WorkspaceService(Constants.ApiToken);
			var workspaces = WorkspaceService.List();

			ClientService = new ClientService(Constants.ApiToken);
			TaskService = new TaskService(Constants.ApiToken);
			TagService = new TagService(Constants.ApiToken);
			ProjectService = new ProjectService(Constants.ApiToken);
			UserService = new UserService(Constants.ApiToken);
			TimeEntryService = new TimeEntryService(Constants.ApiToken);
			ReportService = new ReportService(Constants.ApiToken);

			foreach (var workspace in workspaces)
			{
				var projects = WorkspaceService.Projects(workspace.Id.Value);
				var tasks = WorkspaceService.Tasks(workspace.Id.Value);
				var tags = WorkspaceService.Tags(workspace.Id.Value); // TODO
				var users = WorkspaceService.Users(workspace.Id.Value); // TODO
				var clients = WorkspaceService.Clients(workspace.Id.Value);
				var rte = new TimeEntryParams { StartDate = DateTime.Now.AddYears(-1)};
				var timeEntries = TimeEntryService.List(rte);

				Assert.IsTrue(TimeEntryService.DeleteIfAny(timeEntries.Select(te => te.Id.Value).ToArray()));
				Assert.IsTrue(ProjectService.DeleteIfAny(projects.Select(p => p.Id.Value).ToArray()));				
				Assert.IsTrue(TaskService.DeleteIfAny(tasks.Select(t => t.Id.Value).ToArray()));
				Assert.IsTrue(ClientService.DeleteIfAny(clients.Select(c => c.Id.Value).ToArray()));

				Assert.IsFalse(WorkspaceService.Projects(workspace.Id.Value).Any());
				Assert.IsFalse(WorkspaceService.Tasks(workspace.Id.Value).Any());
				Assert.IsFalse(WorkspaceService.Clients(workspace.Id.Value).Any());
				Assert.IsFalse(TimeEntryService.List(rte).Any());
			}

			DefaultWorkspaceId = workspaces.First().Id.Value;
		}
        public async Task GetClientPreview()
        {
            var options = TestHelper.GetDbContext("GetClientPreview");

            var user1 = TestHelper.InsertUserDetailed(options);

            //Given
            var mem1 = new ClientEntity
            {
                Id             = Guid.NewGuid(),
                OrganisationId = user1.Organisation.Id
            };

            var mem2 = new ClientEntity
            {
                Id             = Guid.NewGuid(),
                ClientTypeId   = Guid.NewGuid(),
                FirstName      = "FN 1",
                LastName       = "LN 1",
                IdNumber       = "321654",
                DateOfBirth    = new DateTime(1982, 10, 3),
                OrganisationId = user1.Organisation.Id
            };

            var policy1 = new PolicyEntity
            {
                Id       = Guid.NewGuid(),
                ClientId = mem2.Id,
                UserId   = user1.User.Id
            };

            var policy2 = new PolicyEntity
            {
                Id       = Guid.NewGuid(),
                ClientId = mem2.Id,
                UserId   = user1.User.Id
            };

            var contact1 = new ContactEntity
            {
                Id            = Guid.NewGuid(),
                ClientId      = mem2.Id,
                ContactTypeId = ContactType.CONTACT_TYPE_EMAIL,
                Value         = "*****@*****.**"
            };

            using (var context = new DataContext(options))
            {
                context.Client.Add(mem1);
                context.Client.Add(mem2);

                context.Policy.Add(policy1);
                context.Policy.Add(policy2);

                context.Contact.Add(contact1);

                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var auditService = new AuditServiceMock();
                var service      = new ClientService(context, auditService);

                //When
                var scopeOptions = TestHelper.GetScopeOptions(user1);
                var actual       = await service.GetClientPreview(scopeOptions, mem2.Id);

                //Then
                Assert.Equal(mem2.Id, actual.Id);
                Assert.Equal(mem2.ClientTypeId, actual.ClientTypeId);
                Assert.Equal(mem2.FirstName, actual.FirstName);
                Assert.Equal(mem2.LastName, actual.LastName);
                Assert.Equal(mem2.IdNumber, actual.IdNumber);
                Assert.Equal(mem2.DateOfBirth, actual.DateOfBirth);

                Assert.Equal(2, actual.PolicyCount);
                Assert.Equal(1, actual.ContactCount);
            }
        }
 public ClientController()
 {
     service = new ClientService();
 }
 internal static void LogIn(TokenResponse user)
 {
     ClientService.SetAutenticationHeader(user);
     User = user;
     LoggedIn?.Invoke(user.UserId, user.Roles.Any(r => r == "admin"));
 }
Exemple #30
0
        public async Task ImportClient_UpdatePolicy()
        {
            var options = TestHelper.GetDbContext("ImportClient_UpdatePolicy");

            var user1   = TestHelper.InsertUserDetailed(options);
            var client1 = TestHelper.InsertClient(options, user1.Organisation, "8210035032082");

            var user2 = TestHelper.InsertUserDetailed(options, user1.Organisation);

            var policyType1 = TestHelper.InsertPolicyType(options);
            var policyType2 = TestHelper.InsertPolicyType(options);

            var company = TestHelper.InsertCompany(options);

            //Given
            var policyEntity1 = new PolicyEntity
            {
                Id           = Guid.NewGuid(),
                CompanyId    = company.Id,
                ClientId     = client1.Client.Id,
                UserId       = user2.User.Id,
                PolicyTypeId = policyType2.Id,
                Premium      = 2000,
                StartDate    = DateTime.Now,
                Number       = "123465"
            };

            using (var context = new DataContext(options))
            {
                context.Policy.Add(policyEntity1);

                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var auditService           = new AuditServiceMock();
                var clientService          = new ClientService(context, auditService);
                var policyService          = new PolicyService(context, auditService);
                var lookupService          = new ClientLookupService(context);
                var directoryLookupService = new DirectoryLookupService(context);
                var service = new ClientImportService(context, clientService, policyService, null, lookupService, directoryLookupService);

                //When
                var data = new ImportClient()
                {
                    IdNumber           = client1.Client.IdNumber,
                    LastName           = "LN",
                    PolicyNumber       = policyEntity1.Number,
                    PolicyCompanyId    = policyEntity1.CompanyId,
                    PolicyTypeCode     = policyType1.Code,
                    PolicyPremium      = 6000,
                    PolicyStartDate    = DateTime.Now.AddDays(-100),
                    PolicyUserFullName = $"{user1.User.FirstName} {user1.User.LastName}"
                };

                var scope = TestHelper.GetScopeOptions(user1);

                var result = await service.ImportClient(scope, data);

                //Then
                Assert.True(result.Success);

                var actual = await context.Policy.FirstOrDefaultAsync(m => m.Number == data.PolicyNumber);

                Assert.Equal(data.PolicyCompanyId, actual.CompanyId);
                Assert.Equal(user1.User.Id, actual.UserId);
                Assert.Equal(data.PolicyPremium, actual.Premium);
                Assert.Equal(data.PolicyStartDate, actual.StartDate);
                Assert.Equal(policyType1.Id, actual.PolicyTypeId);
            }
        }
Exemple #31
0
        public async Task ImportClient_Update()
        {
            var options = TestHelper.GetDbContext("ImportClient_Update");

            var user1 = TestHelper.InsertUserDetailed(options);
            var user2 = TestHelper.InsertUserDetailed(options, user1.Organisation);

            var mem = new ClientEntity
            {
                Id             = Guid.NewGuid(),
                ClientTypeId   = ClientType.CLIENT_TYPE_INDIVIDUAL,
                FirstName      = "FN 1",
                LastName       = "LN 1",
                TaxNumber      = "987654",
                DateOfBirth    = DateTime.Now,
                IdNumber       = "8210035032082",
                OrganisationId = user1.Organisation.Id
            };

            using (var context = new DataContext(options))
            {
                context.Client.Add(mem);

                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var auditService           = new AuditServiceMock();
                var clientService          = new ClientService(context, auditService);
                var lookupService          = new ClientLookupService(context);
                var directoryLookupService = new DirectoryLookupService(context);
                var service = new ClientImportService(context, clientService, null, null, lookupService, directoryLookupService);

                //When
                var data = new ImportClient()
                {
                    IdNumber    = mem.IdNumber,
                    FirstName   = "FN updated",
                    LastName    = "LN updated",
                    TaxNumber   = "456789",
                    DateOfBirth = DateTime.Now.AddDays(-20),
                };

                var scope = TestHelper.GetScopeOptions(user1);

                var result = await service.ImportClient(scope, data);

                //Then
                Assert.True(result.Success);

                var actual = await context.Client.FirstOrDefaultAsync(m => m.IdNumber == data.IdNumber);

                Assert.Equal(user1.Organisation.Id, actual.OrganisationId);
                Assert.Equal(mem.ClientTypeId, actual.ClientTypeId); //Should not have changed
                Assert.Equal(data.FirstName, actual.FirstName);
                Assert.Equal(data.LastName, actual.LastName);
                Assert.Equal(data.TaxNumber, actual.TaxNumber);
                Assert.Equal(data.DateOfBirth, actual.DateOfBirth);
            }
        }
 public OClientsController(ClientService clientService)
 {
     this.clientService = clientService;
 }
Exemple #33
0
 public OrderController(ILoggerFactory loggerFactory, ApplicationDbContext appContext, OrderService orderService, ClientService clientService)
 {
     this.orderService  = orderService;
     this.clientService = clientService;
     Logger             = loggerFactory.CreateLogger <OrderController>();
     AppContext         = appContext;
 }
Exemple #34
0
        public override async void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

            if (_interactionStarted)
            {
                return;
            }
            _interactionStarted = true;

            var client = await ClientService.GetClient();

            if (client == null)
            {
                return;
            }

            _cts = new CancellationTokenSource();

            var parameters    = FileDownloadPageParameters.Deserialize(e.Parameter);
            var resourceInfo  = parameters?.ResourceInfo;
            var resourceInfos = parameters?.ResourceInfos;

            if (resourceInfo != null)
            {
                ResourceInfo = resourceInfo;

                await Download(resourceInfo, client, null);
            }
            else if (resourceInfos != null)
            {
                ResourceInfos = resourceInfos;

                var folderPicker = new FolderPicker
                {
                    SuggestedStartLocation = PickerLocationId.Desktop
                };
                folderPicker.FileTypeFilter.Add(".zip");

                var folder = await folderPicker.PickSingleFolderAsync();

                if (folder != null)
                {
                    // Application now has read/write access to all contents in the picked folder (including other sub-folder contents)
                    StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
                }
                else
                {
                    _interactionStarted = false;
                    return;
                }

                foreach (var resInfo in ResourceInfos)
                {
                    await Download(resInfo, client, folder);
                }
                _interactionStarted = false;
            }
            else
            {
                _interactionStarted = false;
                return;
            }

            _navigationService.GoBack();
        }
Exemple #35
0
 public ProjectController()
 {
     UserService   = new UserService(context);
     clientService = new ClientService(context);
 }
        void OnCreateLoginCompleted(object sender, ClientService.CreateLoginCompletedEventArgs args)
        {
            _accountCreationTimer.Stop();

            this.ParentForm.Enabled = true;
            this.ParentForm.Cursor = Cursors.Default;

            switch (args.Result.MembershipCreateStatus)
            {
                case ClientService.MembershipCreateStatus.InvalidAnswer:
                    MessageBox.Show("Please check the verification code you entered and try again.");
                    _verificationCodeTextBox.Focus();
                    _verificationCodeTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.DuplicateEmail:
                    MessageBox.Show("This email address is already in use. Please check the email address and try again.");
                    _emailTextBox.Focus();
                    _emailTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.DuplicateUserName:
                    MessageBox.Show("This user name is already in use. Please check the user name and try again.");
                    _usernameTextBox.Focus();
                    _usernameTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.InvalidEmail:
                    MessageBox.Show("Your email is invalid. Please check the email address and try again.");
                    _emailTextBox.Focus();
                    _emailTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.InvalidPassword:
                    MessageBox.Show("Your password is invalid. Please check the password and try again.");
                    _verifyPasswordTextBox.Text = String.Empty;
                    _passwordTextBox.Focus();
                    _passwordTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.InvalidUserName:
                    MessageBox.Show("This user name is invalid. Please check the user name and try again.");
                    _usernameTextBox.Focus();
                    _usernameTextBox.SelectAll();
                    break;

                case ClientService.MembershipCreateStatus.ProviderError:
                    MessageBox.Show("There was a provider error creating your account. Please try again.");
                    break;

                case ClientService.MembershipCreateStatus.Success:
                    MessageBox.Show("Your account has been created.");
                    if (AccountCreatedSuccess != null)
                        AccountCreatedSuccess(_usernameTextBox.Text, _passwordTextBox.Text);
                    break;

                case ClientService.MembershipCreateStatus.UserRejected:
                    MessageBox.Show("The user name was rejected. Please check the user name and try again.");
                    _usernameTextBox.Focus();
                    _usernameTextBox.SelectAll();
                    break;

                default:
                    MessageBox.Show("Your account was not created.");
                    break;
            }

            if(args.Result.MembershipCreateStatus != ClientService.MembershipCreateStatus.Success)
                LoadCaptchaImage();
        }
 private void SetCaptchaImage(ClientService.CaptchaResult captchaResult)
 {
     if (this.InvokeRequired == true)
     {
         this.Invoke(new SetCaptchaImageDelegate(SetCaptchaImage), captchaResult);
     }
     else
     {
         _animatedThrobber.Visible = false;
         _verificationCodeTextBox.Enabled = true;
         _captchaToken = new Guid(captchaResult.CaptchaToken);
         _verificationCodePictureBox.Image = Image.FromStream(new MemoryStream(captchaResult.CaptchaImage));
         _verificationCodePictureBox.Visible = true;
     }
 }
 public ModeAdminController(ApplicationDbContext context, ProjectService project, EmployeeService employee, HourService hour, ProjectTeamService projectTeam, ClientService client, Files files, IConfiguration config, IHostingEnvironment env)
 {
     _context            = context;
     _projectService     = project;
     _projectTeamService = projectTeam;
     _employeeService    = employee;
     _hourService        = hour;
     _clientService      = client;
     _files          = files;
     _config         = config;
     _appEnvironment = env;
 }
Exemple #39
0
 public UserManager(DataBaseContext db)
 {
     userService   = new UserService(db);
     clientService = new ClientService(db);
     uaService     = new UserActionService(db);
 }
        private IClientService GetClientService(IClientRepository repository, IClientServiceResources resources, IAuditEventLogger auditEventLogger)
        {
            IClientService clientService = new ClientService(repository, resources, auditEventLogger);

            return(clientService);
        }
        public void TestBan()
        {
            DataAccess.BanType banType = Initialize();

            //Test Set, ListBans, Remove, ensure user has requisite permissions.
            var adminService = new Administration();
            var result       = adminService.SetBan(new BanData()
            {
                BanMode   = BanMode.Auto,
                BanTypeId = banType.Id,
                Username  = "******",
                Password  = "******",
                Reason    = "#1 Orion is being a general dick.",
                Alias     = "Orion",
            });

            Assert.IsTrue(result);

            //Ensure banned user can no longer log in
            var clientService = new ClientService();
            var loginResult   = clientService.Login(new LoginData()
            {
                Username = "******",
                Password = "******",
                Alias    = "Orion"
            });

            Assert.AreEqual(LoginStatus.AccountLocked, loginResult.Status);

            //List bans
            var bans = adminService.ListBans(new AuthenticatedData()
            {
                Username = "******",
                Password = "******"
            }, "Orion");

            //Remove all bans
            var ban = bans.FirstOrDefault();

            adminService.RemoveBan(new BanData()
            {
                Username = "******",
                Password = "******",
                BanId    = ban.Id
            });

            bans = adminService.ListBans(new AuthenticatedData()
            {
                Username = "******",
                Password = "******"
            }, "Orion");

            Assert.AreEqual(0, bans.Where(p => p.InEffect == true).Count());

            //Ensure user can log in.
            clientService = new ClientService();
            loginResult   = clientService.Login(new LoginData()
            {
                Username = "******",
                Password = "******",
                Alias    = "Orion",
                LobbyId  = 1
            });
            Assert.AreEqual(LoginStatus.Authenticated, loginResult.Status);

            //Set two sequential bans.
            result = adminService.SetBan(new BanData()
            {
                BanMode   = BanMode.Auto,
                Username  = "******",
                Password  = "******",
                BanTypeId = banType.Id,
                Reason    = "#2 Orion is being a general dick.",
                Alias     = "Orion",
            });
            Assert.IsTrue(result);

            result = adminService.SetBan(new BanData()
            {
                BanMode   = BanMode.Auto,
                Username  = "******",
                Password  = "******",
                BanTypeId = banType.Id,
                Reason    = "#3 Orion is /STILL/ being a general dick.",
                Alias     = "Orion",
            });
            Assert.IsTrue(result);

            //Retrieve ban
            bans = adminService.ListBans(new AuthenticatedData()
            {
                Username = "******",
                Password = "******"
            }, "Orion");

            Assert.AreEqual(2, bans.Where(p => p.InEffect == true).Count());

            var firstBan = bans.Where(p => p.InEffect == true).OrderBy(p => p.DateCreated).First();
            var lastBan  = bans.Where(p => p.InEffect == true).OrderBy(p => p.DateCreated).Last();

            var firstDuration = (firstBan.DateExpires.Value - firstBan.DateCreated).TotalMinutes;
            var lastDuration  = (lastBan.DateExpires.Value - lastBan.DateCreated).TotalMinutes;

            Assert.IsTrue(lastDuration > firstDuration);

            //Reset ban length
            adminService.SetBan(new BanData()
            {
                Username = "******",
                Password = "******",
                BanId    = firstBan.Id,
                BanMode  = BanMode.Custom,
                Duration = TimeSpan.MinValue,
                Alias    = "Orion"
            });

            adminService.SetBan(new BanData()
            {
                Username = "******",
                Password = "******",
                BanId    = lastBan.Id,
                BanMode  = BanMode.Custom,
                Duration = TimeSpan.MinValue,
                Alias    = "Orion"
            });

            bans = adminService.ListBans(new AuthenticatedData()
            {
                Username = "******",
                Password = "******"
            }, "Orion");

            Assert.AreEqual(2, bans.Where(p => p.InEffect == true).Count());

            Assert.AreEqual(0, bans.Where(p => p.InEffect == true && p.DateExpires > DateTime.Now).Count());
        }
Exemple #42
0
 public void SetUp()
 {
     _client = new ClientService();
 }
Exemple #43
0
        public async Task UpdateApiScopeAsync()
        {
            using (var context = new AdminDbContext(_dbContextOptions, _storeOptions, _operationalStore))
            {
                IApiResourceRepository apiResourceRepository = new ApiResourceRepository(context);
                IClientRepository      clientRepository      = new ClientRepository(context);

                var localizerApiResourceMock = new Mock <IApiResourceServiceResources>();
                var localizerApiResource     = localizerApiResourceMock.Object;

                var localizerClientResourceMock = new Mock <IClientServiceResources>();
                var localizerClientResource     = localizerClientResourceMock.Object;

                IClientService      clientService      = new ClientService(clientRepository, localizerClientResource);
                IApiResourceService apiResourceService = new ApiResourceService(apiResourceRepository, localizerApiResource, clientService);

                //Generate random new api resource
                var apiResourceDto = ApiResourceDtoMock.GenerateRandomApiResource(0);

                await apiResourceService.AddApiResourceAsync(apiResourceDto);

                //Get new api resource
                var apiResource = await context.ApiResources.Where(x => x.Name == apiResourceDto.Name).SingleOrDefaultAsync();

                var newApiResourceDto = await apiResourceService.GetApiResourceAsync(apiResource.Id);

                //Assert new api resource
                apiResourceDto.ShouldBeEquivalentTo(newApiResourceDto, options => options.Excluding(o => o.Id));

                //Generate random new api scope
                var apiScopeDtoMock = ApiResourceDtoMock.GenerateRandomApiScope(0, newApiResourceDto.Id);

                //Add new api scope
                await apiResourceService.AddApiScopeAsync(apiScopeDtoMock);

                //Get inserted api scope
                var apiScope = await context.ApiScopes.Where(x => x.Name == apiScopeDtoMock.Name && x.ApiResource.Id == newApiResourceDto.Id)
                               .SingleOrDefaultAsync();

                //Map entity to model
                var apiScopesDto = apiScope.ToModel();

                //Get new api scope
                var newApiScope = await apiResourceService.GetApiScopeAsync(apiScopesDto.ApiResourceId, apiScopesDto.ApiScopeId);

                //Assert
                newApiScope.ShouldBeEquivalentTo(apiScopesDto, o => o.Excluding(x => x.ResourceName));

                //Detached the added item
                context.Entry(apiScope).State = EntityState.Detached;

                //Update api scope
                var updatedApiScope = ApiResourceDtoMock.GenerateRandomApiScope(apiScopesDto.ApiScopeId, apiScopesDto.ApiResourceId);

                await apiResourceService.UpdateApiScopeAsync(updatedApiScope);

                var updatedApiScopeDto = await apiResourceService.GetApiScopeAsync(apiScopesDto.ApiResourceId, apiScopesDto.ApiScopeId);

                //Assert updated api scope
                updatedApiScope.ShouldBeEquivalentTo(updatedApiScopeDto, o => o.Excluding(x => x.ResourceName));
            }
        }
Exemple #44
0
        public ActionResult DeleteEvent(int Id)
        {
            bool Status = ClientService.DeleteClient(Id);

            return(Json(Status));
        }
        /// <summary>
        /// </summary>
        /// 微信登录回调
        public void WXLoginBack()
        {
            Client     customer    = new Client();
            WeiXinUser weiXinUser  = WeiXinService.GetWeiXinUser(string.Empty, Request.Params["code"].ToString());
            string     callbackUrl = Request.QueryString["state"].ToString();

            if (weiXinUser != null && !string.IsNullOrEmpty(weiXinUser.Openid))
            {
                Client cusomerInfo = ClientService.LoadClientByAppCustomerID(weiXinUser.Openid);
                if (cusomerInfo != null && cusomerInfo.SysNo > 0)
                {
                    //更新用户头像以及昵称
                    cusomerInfo.Name        = weiXinUser.NickName;
                    cusomerInfo.HeaderImage = weiXinUser.HeadImgUrl;
                    cusomerInfo.EditTime    = DateTimeHelper.GetTimeZoneNow();

                    ClientService.UpdateClient(cusomerInfo);

                    var appuser = new AppUserInfo()
                    {
                        AppCustomerID   = weiXinUser.Openid,
                        UserSysNo       = cusomerInfo.SysNo,
                        UserID          = HttpUtility.UrlEncode(cusomerInfo.Name),
                        HeadImage       = cusomerInfo.HeaderImage,
                        UserDisplayName = HttpUtility.UrlEncode(cusomerInfo.Name),

                        ManagerSysNo      = cusomerInfo.ManagerSysNo,
                        UserType          = UserType.Common,
                        LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss"),
                        ManagerLoginName  = cusomerInfo.ManagerLoginName,
                        ManagerName       = HttpUtility.UrlEncode(cusomerInfo.ManagerName)
                    };

                    if (cusomerInfo.ManagerSysNo.HasValue && cusomerInfo.ManagerSysNo.Value > 0)
                    {
                        appuser.UserType = UserType.Manager;
                        var company = CompanyService.GetCompanyUser(cusomerInfo.ManagerSysNo.Value);
                        if (company != null)
                        {
                            appuser.UserType = UserType.Installer;
                        }
                    }

                    UserMgr.Logout();
                    UserMgr.WriteUserInfo(appuser);
                    if (!string.IsNullOrEmpty(callbackUrl))
                    {
                        Response.Redirect(callbackUrl);
                        return;
                    }
                    Response.Redirect("/smoke/userInfo");
                    return;
                }
                else//新建client
                {
                    customer.AppCustomerID = weiXinUser.Openid;
                    customer.Name          = weiXinUser.NickName;
                    customer.HeaderImage   = weiXinUser.HeadImgUrl;
                    customer.EditTime      = DateTimeHelper.GetTimeZoneNow();
                    customer.RegisterTime  = DateTimeHelper.GetTimeZoneNow();
                    //创建用户
                    customer.SysNo = ClientService.InsertClient(customer);
                    var appuser = new AppUserInfo()
                    {
                        AppCustomerID     = weiXinUser.Openid,
                        UserSysNo         = customer.SysNo,
                        UserID            = HttpUtility.UrlEncode(customer.Name),
                        UserDisplayName   = HttpUtility.UrlEncode(customer.Name),
                        HeadImage         = customer.HeaderImage,
                        UserType          = UserType.Common,
                        LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss")
                    };
                    UserMgr.Logout();
                    UserMgr.WriteUserInfo(appuser);
                    if (!string.IsNullOrEmpty(callbackUrl))
                    {
                        Response.Redirect(callbackUrl);
                        return;
                    }
                    Response.Redirect("/smoke/userInfo");
                    return;
                }
            }
        }
Exemple #46
0
        private IClientService GetClientService(IClientRepository repository, IClientServiceResources resources)
        {
            IClientService clientService = new ClientService(repository, resources);

            return(clientService);
        }
Exemple #47
0
        public async Task ImportClient_Update_WithContacts()
        {
            var options = TestHelper.GetDbContext("ImportClient_Update_WithContacts");

            var user1 = TestHelper.InsertUserDetailed(options);

            var mem = new ClientEntity
            {
                Id             = Guid.NewGuid(),
                ClientTypeId   = ClientType.CLIENT_TYPE_INDIVIDUAL,
                IdNumber       = "8210035032082",
                OrganisationId = user1.Organisation.Id
            };

            var contact1 = new ContactEntity
            {
                ClientId      = mem.Id,
                ContactTypeId = ContactType.CONTACT_TYPE_EMAIL,
                Value         = "*****@*****.**"
            };

            var contact2 = new ContactEntity
            {
                ClientId      = mem.Id,
                ContactTypeId = ContactType.CONTACT_TYPE_CELLPHONE,
                Value         = "0825728997"
            };

            using (var context = new DataContext(options))
            {
                context.Client.Add(mem);
                context.Contact.Add(contact1);
                context.Contact.Add(contact2);

                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var auditService           = new AuditServiceMock();
                var clientService          = new ClientService(context, auditService);
                var contactService         = new ContactService(context, auditService);
                var lookupService          = new ClientLookupService(context);
                var directoryLookupService = new DirectoryLookupService(context);
                var service = new ClientImportService(context, clientService, null, contactService, lookupService, directoryLookupService);

                //When
                var data = new ImportClient()
                {
                    IdNumber  = "8210035032082",
                    Email     = contact1.Value,
                    Cellphone = "082 572-8997"
                };

                var scope = TestHelper.GetScopeOptions(user1);

                var result = await service.ImportClient(scope, data);

                //Then
                Assert.True(result.Success);

                var client = await context.Client.FirstOrDefaultAsync(m => m.IdNumber == data.IdNumber);

                var contacts = await context.Contact.Where(c => c.ClientId == client.Id).ToListAsync();

                Assert.Equal(2, contacts.Count);
                var actual = contacts.First();
                Assert.Equal(data.Email, actual.Value);
                Assert.Equal(ContactType.CONTACT_TYPE_EMAIL, actual.ContactTypeId);

                actual = contacts.Last();
                Assert.Equal(contact2.Value, actual.Value);
                Assert.Equal(ContactType.CONTACT_TYPE_CELLPHONE, actual.ContactTypeId);
            }
        }
Exemple #48
0
 public ClientController()
 {
     this._clientService = new Services.ClientService();
 }
 static App()
 {
     ServerAdress  = ConfigurationManager.ConnectionStrings["ServerAdress"].ConnectionString;
     ClientService = new ClientService(ServerAdress);
 }
        public async Task MergeClients()
        {
            var options = TestHelper.GetDbContext("MergeClients");

            //Given
            var user = TestHelper.InsertUserDetailed(options);

            var clientSource1 = TestHelper.InsertClient(options, user.Organisation, "8210035032082");
            var clientSource2 = TestHelper.InsertClient(options, user.Organisation);
            var client3       = TestHelper.InsertClient(options, user.Organisation);

            var user2   = TestHelper.InsertUserDetailed(options);
            var client4 = TestHelper.InsertClient(options, user2.Organisation, "8210035032082"); //Same Id but different organisation

            var target = new ClientEdit
            {
                ClientTypeId     = ClientType.CLIENT_TYPE_INDIVIDUAL,
                FirstName        = "FN 1",
                LastName         = "LN 1",
                MaidenName       = "MN 1",
                Initials         = "INI 1",
                PreferredName    = "PN 1",
                IdNumber         = "8210035032082",
                DateOfBirth      = new DateTime(1982, 10, 3),
                TaxNumber        = "889977",
                MarritalStatusId = Guid.NewGuid(),
                MarriageDate     = new DateTime(2009, 11, 13),
            };

            using (var context = new DataContext(options))
            {
                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var auditService = new AuditServiceMock();
                var service      = new ClientService(context, auditService);

                var merge = new MergeClients()
                {
                    TargetClient    = target,
                    SourceClientIds = new List <Guid>()
                    {
                        clientSource1.Client.Id, clientSource2.Client.Id
                    }
                };

                //When
                var scope  = TestHelper.GetScopeOptions(user.Organisation.Id);
                var result = await service.MergeClients(scope, merge);

                //Then
                Assert.True(result.Success);

                //Check new client added
                var clientId = ((ClientEdit)result.Tag).Id;
                var actual   = context.Client.Find(clientId);
                Assert.Equal(target.FirstName, actual.FirstName);
                Assert.Equal(target.LastName, actual.LastName);
                Assert.Equal(target.MaidenName, actual.MaidenName);
                Assert.Equal(target.Initials, actual.Initials);
                Assert.Equal(target.PreferredName, actual.PreferredName);
                Assert.Equal(target.IdNumber, actual.IdNumber);
                Assert.Equal(target.DateOfBirth, actual.DateOfBirth);
                Assert.Equal(target.TaxNumber, actual.TaxNumber);
                Assert.Equal(target.MarritalStatusId, actual.MarritalStatusId);
                Assert.Equal(target.MarriageDate, actual.MarriageDate);
                Assert.False(actual.IsDeleted);

                //Check old clients deleted
                actual = context.Client.Find(clientSource1.Client.Id);
                Assert.True(actual.IsDeleted);
                actual = context.Client.Find(clientSource2.Client.Id);
                Assert.True(actual.IsDeleted);

                //Dummy un-effected
                actual = context.Client.Find(client3.Client.Id);
                Assert.False(actual.IsDeleted);

                //Different Organisation un-effected
                actual = context.Client.Find(client4.Client.Id);
                Assert.False(actual.IsDeleted);
            }
        }
Exemple #51
0
 public MainViewModel(ClientService service)
 {
     _service = service ?? throw new ArgumentNullException(nameof(service));
     Jucatori = new ObservableCollection <JucatorViewModel>();
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool update = true;
            if (client == null)
            {
                client = new Client();
                client.ClientId = System.Guid.NewGuid().ToString();
                update = false;
            }

            client.SSN = SSN.Text;
            client.FirstName = FirstName.Text;
            client.MiddleInitial = MiddleInitial.Text;
            client.LastName = LastName.Text;
            if (DateOfBirth.Text.Length > 0) client.DateOfBirth = DateTime.Parse(DateOfBirth.Text);
            client.Address1 = AddressLine1.Text;
            client.Address2 = AddressLine2.Text;
            client.City = City.Text;
            client.State = "MS";
            client.Zip = Zip.Text;
            client.Phone = Phone.Text;
            client.County = County.SelectedValue;
            client.Email = Email.Text;
            client.Gender = Gender.SelectedValue;
            client.PersonResidenceCode = ResidenceCode.SelectedValue;
            client.OtherComments = OtherInfo.Text;
            client.Medicaid = Medicaid.Text;
            client.Medicare = Medicare.Text;
            client.ContactPerson = ContactPerson.Text;
            client.RelationshipToClient = RelationshiptoClient.Text;
            client.ContactPhone = ContactPhone.Text;
            client.Direction = Directions.Text;
            client.ReferralSoruce = ReferralSource.Text;
            client.ReferralPhone = ReferralPhone.Text;
            client.Physician = Physician.Text;
            client.PhysicianPhone = PhysicianPhone.Text;
            client.PhysicianAddress = PhysicianAddress.Text;
            client.PhysicianCity = PhysicianCity.Text;
            client.PhysicianZip = PhysicianZip.Text;
            client.Diagnostic = Diagnosis.Text;
            foreach (ClientService clientService in client.ClientServices.ToList())
            {
                DatabaseContext.ClientServices.DeleteObject(clientService);
                DatabaseContext.SaveChanges();
            }
            string leftHandItems = ServicesNeededLeftHidden.Value;
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            List<DataItem> leftHandItemSerialize = (List<DataItem>)Newtonsoft.Json.JsonConvert.DeserializeObject(leftHandItems, typeof(List<DataItem>));
            if (leftHandItemSerialize != null)
            {
                foreach (DataItem item in leftHandItemSerialize)
                {
                    ClientService service = new ClientService
                    {
                        ClientServicesId = System.Guid.NewGuid().ToString(),
                        ServiceId = item.value
                    };
                    client.ClientServices.Add(service);
                }
            }
            if (update)
            {
                List<Detail> details = (from d in DatabaseContext.Details where d.Type == Constants.DetailTypes.SERVICES_NEEDED && d.ClientId == client.ClientId select d).ToList();
                foreach (Detail detail in details)
                {
                    DatabaseContext.Details.DeleteObject(detail);
                }
            }

            if (update)
            {
                List<ProvidersInProgress> providersInProgress = (from p in DatabaseContext.ProvidersInProgresses where p.ClientId == client.ClientId select p).ToList();
                foreach (ProvidersInProgress providerInProgress in providersInProgress)
                {
                    DatabaseContext.ProvidersInProgresses.DeleteObject(providerInProgress);
                }
            }
            foreach (ProvidersInProgress providerInProgress in client.ProvidersInProgresses)
            {
                client.ProvidersInProgresses.Remove(providerInProgress);
            }

            if (update == false)
            {
                DatabaseContext.AddToClients(client);
            }
            DatabaseContext.SaveChanges();
            if (update == false)
            {
                SendEmail("Client Created", "SWMPD - District", ConfigurationSettings.AppSettings["ToEmailAddress"]);
                Response.Redirect("~/Referrals/OnlineForm.aspx?save=true");
            }
            else
            {
                SetSuccessMessage("Client Updated Successfully.");
            }
        }
Exemple #53
0
        public override async void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

            var client = ClientService.GetClient();

            if (client == null)
            {
                return;
            }

            _cts = new CancellationTokenSource();
            var parameters   = FileUploadPageParameters.Deserialize(e.Parameter);
            var resourceInfo = parameters?.ResourceInfo;

            if (resourceInfo == null)
            {
                return;
            }
            ResourceInfo              = resourceInfo;
            SuggestedStartLocation    = parameters.PickerLocationId;
            UploadingFilesTitle       = null;
            UploadingFileProgressText = null;
            var i = 0;

            var openPicker = new FileOpenPicker
            {
                SuggestedStartLocation = SuggestedStartLocation
            };

            openPicker.FileTypeFilter.Add("*");
            var storageFiles = await openPicker.PickMultipleFilesAsync();

            foreach (var localFile in storageFiles)
            {
                _currentFile = localFile;

                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(localFile);

                if (storageFiles.Count > 1)
                {
                    UploadingFilesTitle = string.Format(_resourceLoader.GetString("UploadingFiles"), ++i, storageFiles.Count);
                }

                try
                {
                    var properties = await localFile.GetBasicPropertiesAsync();

                    BytesTotal = (long)properties.Size;

                    var stream = await localFile.OpenAsync(FileAccessMode.ReadWrite);

                    IProgress <HttpProgress> progress = new Progress <HttpProgress>(ProgressHandler);
                    await client.Upload(ResourceInfo.Path + localFile.Name, stream, localFile.ContentType, _cts, progress);
                }
                catch (ResponseError e2)
                {
                    ResponseErrorHandlerService.HandleException(e2);
                }

                // Let Windows know that we're finished changing the file so
                // the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                await CachedFileManager.CompleteUpdatesAsync(localFile);

                UploadingFileProgressText = null;
            }
            _navigationService.GoBack();
        }
        public async Task UpdateClient()
        {
            var options = TestHelper.GetDbContext("UpdateClient");

            var user1 = TestHelper.InsertUserDetailed(options);
            var user2 = TestHelper.InsertUserDetailed(options);

            //Given
            var mem1 = new ClientEntity {
                Id = Guid.NewGuid(), FirstName = "FN 1", LastName = "LN 1", OrganisationId = user1.Organisation.Id
            };
            var mem2 = new ClientEntity
            {
                Id               = Guid.NewGuid(),
                ClientTypeId     = ClientType.CLIENT_TYPE_INDIVIDUAL,
                FirstName        = "FN 1",
                LastName         = "LN 1",
                MaidenName       = "MN 1",
                Initials         = "INI 1",
                PreferredName    = "PN 1",
                IdNumber         = "8210035032082",
                DateOfBirth      = new DateTime(1982, 10, 3),
                OrganisationId   = user2.Organisation.Id,
                TaxNumber        = "889977",
                MarritalStatusId = Guid.NewGuid(),
                MarriageDate     = new DateTime(2009, 11, 13)
            };

            using (var context = new DataContext(options))
            {
                context.Client.Add(mem1);
                context.Client.Add(mem2);

                context.SaveChanges();
            }

            var client = new ClientEdit()
            {
                Id               = mem2.Id,
                ClientTypeId     = ClientType.CLIENT_TYPE_INDIVIDUAL,
                FirstName        = "FN 1 updated",
                LastName         = "LN 1 updated",
                MaidenName       = "MN 1 updated",
                Initials         = "INI 1 updated",
                PreferredName    = "PN 1 updated",
                IdNumber         = "8206090118089",
                DateOfBirth      = new DateTime(1983, 10, 3),
                TaxNumber        = "445566",
                MarritalStatusId = Guid.NewGuid(),
                MarriageDate     = new DateTime(2010, 11, 13)
            };

            using (var context = new DataContext(options))
            {
                var auditService = new AuditServiceMock();
                var service      = new ClientService(context, auditService);

                //When
                var scope  = TestHelper.GetScopeOptions(user2);
                var result = await service.UpdateClient(scope, client);

                //Then
                Assert.True(result.Success);

                var actual = await context.Client.FindAsync(client.Id);

                Assert.Equal(client.Id, actual.Id);
                Assert.Equal(client.ClientTypeId, actual.ClientTypeId);
                Assert.Equal(user2.Organisation.Id, actual.OrganisationId);
                Assert.Equal(client.FirstName, actual.FirstName);
                Assert.Equal(client.LastName, actual.LastName);
                Assert.Equal(client.MaidenName, actual.MaidenName);
                Assert.Equal(client.Initials, actual.Initials);
                Assert.Equal(client.PreferredName, actual.PreferredName);
                Assert.Equal(client.IdNumber, actual.IdNumber);
                Assert.Equal(client.DateOfBirth, actual.DateOfBirth);
                Assert.Equal(client.TaxNumber, actual.TaxNumber);
                Assert.Equal(client.MarritalStatusId, actual.MarritalStatusId);
                Assert.Equal(client.MarriageDate, actual.MarriageDate);

                //Scope check
                scope  = TestHelper.GetScopeOptions(user1);
                result = await service.UpdateClient(scope, client);

                //Then
                Assert.False(result.Success);
            }
        }
 public ClientServiceAutoMockerFixtureTests(ClientServiceAutoMockerFixture clientTestBogusFixture)
 {
     _clientTestAutoMockerFixture = clientTestBogusFixture;
     _clientService = _clientTestAutoMockerFixture.GetClientService();
 }
Exemple #56
0
        /// <summary>
        /// There's a common use for Branch, DirectorateProject and DepartmentSubProject  etc
        /// This function will help generically retrieve a unique list of the above 3 from a specified table
        /// CAUTION!! Only use this if the table you're trying to query has the above 3 "string" columns and are spelled exactly as above!
        /// If the table doesn't have, then using this function will break your request, if not spelled the same, kindly make it spelled as
        /// above to enjoy me!
        /// LOOK at /Views/PaymentRequisition/_List and then /Views/Shared/_PRCustomSearch for usage
        /// </summary>
        /// <param name="listType"></param>
        public CustomSearchModel(string listType)
        {
            SetDefaults();

            switch (listType)
            {
            case "Users":



                break;


            case "PSPs":
            case "LinkProducts":

                using (ClientService cservice = new ClientService())
                    using (ProductService pservice = new ProductService())
                    {
                        ClientOptions  = cservice.List(true);
                        ProductOptions = pservice.List(true);
                    }

                break;


            case "Regions":

                using (PSPService pservice = new PSPService())
                {
                    PSPOptions = pservice.List(true);
                }

                break;


            case "Clients":

                using (PSPService pservice = new PSPService())
                    using (ClientService cservice = new ClientService())
                    {
                        PSPOptions    = pservice.List(true);
                        ClientOptions = cservice.List(true);
                    }

                break;


            case "SetClient":
            case "ClientKPI":
            case "ReconcileLoads":
            case "MovementReport":
            case "ReconcileInvoice":
            case "ManageTransporters":

                using (ClientService cservice = new ClientService())
                {
                    ClientOptions = cservice.List(true);
                }

                break;


            case "Disputes":
            case "Exceptions":
            case "DeliveryNotes":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (DisputeReasonService drervice = new DisputeReasonService())
                        {
                            SiteOptions          = sservice.List(true);
                            ClientOptions        = cservice.List(true);
                            DisputeReasonOptions = drervice.List();
                        }

                break;


            case "ChepAudit":
            case "ClientAudit":

                using (SiteService sservice = new SiteService())
                {
                    SiteOptions = sservice.List(true);
                }

                break;


            case "DashBoard":

                using (SiteService sservice = new SiteService())
                    using (RegionService rservice = new RegionService())
                        using (ClientService cservice = new ClientService())
                            using (ProductService pservice = new ProductService())
                            {
                                SiteOptions    = sservice.List(true);
                                RegionOptions  = rservice.List(true);
                                ClientOptions  = cservice.List(true);
                                ProductOptions = pservice.List(true);
                            }

                break;


            case "AuthorisationCodes":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (TransporterService tservice = new TransporterService())
                        {
                            SiteOptions        = sservice.List(true);
                            ClientOptions      = cservice.List(true);
                            TransporterOptions = tservice.List(true);
                        }

                break;


            case "Billing":

                using (PSPService pservice = new PSPService())
                    using (PSPProductService p1service = new PSPProductService())
                    {
                        PSPOptions        = pservice.List(true);
                        PSPProductOptions = p1service.List(true);
                    }

                break;


            case "ManageSites":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (RegionService rservice = new RegionService())
                        {
                            SiteOptions   = sservice.List(true);
                            ClientOptions = cservice.List(true);
                            RegionOptions = rservice.List(true);
                        }

                break;


            case "ClientData":

                using (ClientService cservice = new ClientService())
                    using (VehicleService vservice = new VehicleService())
                        //using ( ClientSiteService csservice = new ClientSiteService() )
                        using (TransporterService tservice = new TransporterService())
                            using (OutstandingReasonService urservice = new OutstandingReasonService())
                            {
                                ClientOptions  = cservice.List(true);
                                VehicleOptions = vservice.List(true);
                                //ClientSiteOptions = csservice.List( true );
                                TransporterOptions       = tservice.List(true);
                                OutstandingReasonOptions = urservice.List(true);
                            }

                break;

            case "PODOutstanding":
            case "PoolingAgentData":
            case "OutstandingPallets":
            case "TopOustandingCustomers":
            case "TransporterLiableReport":

                using (ClientService cservice = new ClientService())
                    using (OutstandingReasonService urservice = new OutstandingReasonService())
                    {
                        ClientOptions            = cservice.List(true);
                        OutstandingReasonOptions = urservice.List(true);
                    }

                break;

            case "SiteAudits":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                    {
                        SiteOptions   = sservice.List(true);
                        ClientOptions = cservice.List(true);
                    }

                break;

            case "PODPerUser":
            case "PODUploadLog":

                using (UserService uservice = new UserService())
                {
                    User1Options = uservice.List(true, RoleType.All);
                }

                break;

            case "AuthorizationCodeAudit":

                using (UserService uservice = new UserService())
                    using (TransporterService tservice = new TransporterService())
                    {
                        TransporterOptions = tservice.List(true);
                        User1Options       = uservice.List(true, RoleType.All);
                    }

                break;

            case "AuditLogPerUser":

                using (UserService uservice = new UserService())
                    using (ClientService cservice = new ClientService())
                        using (VehicleService vservice = new VehicleService())
                            using (PODCommentService pcservice = new PODCommentService())
                                using (TransporterService tservice = new TransporterService())
                                {
                                    ClientOptions      = cservice.List(true);
                                    VehicleOptions     = vservice.List(true);
                                    PODCommentOptions  = pcservice.List(true);
                                    TransporterOptions = tservice.List(true);
                                    User1Options       = uservice.List(true, RoleType.All);
                                }

                break;
            }

            using (ClientService cservice = new ClientService())
            {
                if (cservice.SelectedClient != null && ClientId == 0)
                {
                    ClientId = cservice.SelectedClient.Id;
                }
            }
        }
Exemple #57
0
 public ClientController(ClientService clientService)
 {
     _clientService = clientService;
 }
Exemple #58
0
        private async Task SychronizeFolder(ResourceInfo resourceInfo)
        {
            if (resourceInfo == null)
            {
                return;
            }

            var           syncInfo = SyncDbUtils.GetFolderSyncInfoByPath(resourceInfo.Path);
            StorageFolder folder;

            try
            {
                Task <ContentDialogResult> firstRunDialog = null;
                if (syncInfo == null)
                {
                    // try to Get parent or initialize
                    syncInfo = SyncDbUtils.GetFolderSyncInfoBySubPath(resourceInfo.Path);

                    if (syncInfo == null)
                    {
                        // Initial Sync
                        syncInfo = new FolderSyncInfo()
                        {
                            Path = resourceInfo.Path
                        };

                        var folderPicker = new FolderPicker()
                        {
                            SuggestedStartLocation = PickerLocationId.Desktop
                        };

                        folderPicker.FileTypeFilter.Add(".txt");
                        StorageFolder newFolder = await folderPicker.PickSingleFolderAsync();

                        if (newFolder == null)
                        {
                            return;
                        }

                        StorageApplicationPermissions.FutureAccessList.AddOrReplace(syncInfo.AccessListKey, newFolder);
                        IReadOnlyList <IStorageItem> subElements = await newFolder.GetItemsAsync();

                        NextcloudClient.NextcloudClient client = await ClientService.GetClient();

                        var remoteElements = await client.List(resourceInfo.Path);

                        if (subElements.Count > 0 && remoteElements.Count > 0)
                        {
                            var dialogNotEmpty = new ContentDialog
                            {
                                Title   = _resourceLoader.GetString("SyncFoldersNotEmptyWarning"),
                                Content = new TextBlock()
                                {
                                    Text         = _resourceLoader.GetString("SyncFoldersNotEmptyWarningDetail"),
                                    TextWrapping = TextWrapping.WrapWholeWords,
                                    Margin       = new Thickness(0, 20, 0, 0)
                                },
                                PrimaryButtonText   = _resourceLoader.GetString("OK"),
                                SecondaryButtonText = _resourceLoader.GetString("Cancel")
                            };

                            var dialogResult = await _dialogService.ShowAsync(dialogNotEmpty);

                            if (dialogResult != ContentDialogResult.Primary)
                            {
                                return;
                            }
                        }

                        folder = newFolder;
                        SyncDbUtils.SaveFolderSyncInfo(syncInfo);
                        StartDirectoryListing(); // This is just to update the menu flyout - maybe there is a better way

                        var dialog = new ContentDialog
                        {
                            Title   = _resourceLoader.GetString("SyncStarted"),
                            Content = new TextBlock()
                            {
                                Text         = _resourceLoader.GetString("SyncStartedDetail"),
                                TextWrapping = TextWrapping.WrapWholeWords,
                                Margin       = new Thickness(0, 20, 0, 0)
                            },
                            PrimaryButtonText = _resourceLoader.GetString("OK")
                        };
                        firstRunDialog = _dialogService.ShowAsync(dialog);
                    }
                    else
                    {
                        string        subPath    = resourceInfo.Path.Substring(syncInfo.Path.Length);
                        StorageFolder tempFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                        foreach (string foldername in subPath.Split('/'))
                        {
                            if (foldername.Length > 0)
                            {
                                tempFolder = await tempFolder.GetFolderAsync(foldername);
                            }
                        }
                        folder = tempFolder;
                    }
                }
                else
                {
                    folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(syncInfo.AccessListKey);

                    // TODO catch exceptions
                }

                SyncService service = new SyncService(folder, resourceInfo, syncInfo);
                await service.StartSync();

                if (firstRunDialog != null)
                {
                    await firstRunDialog;
                }
            }
            catch (Exception e)
            {
                // ERROR Maybe AccessList timed out.
                Debug.WriteLine(e.Message);
            }
        }
Exemple #59
0
        public SingleVNode(TFChunkDb db, SingleVNodeSettings vNodeSettings, SingleVNodeAppSettings appSettings)
        {
            Ensure.NotNull(db, "db");
            Ensure.NotNull(vNodeSettings, "vNodeSettings");

            db.OpenVerifyAndClean();

            _tcpEndPoint = vNodeSettings.ExternalTcpEndPoint;
            _httpEndPoint = vNodeSettings.HttpEndPoint;

            _outputBus = new InMemoryBus("OutputBus");
            _controller = new SingleVNodeController(Bus, _httpEndPoint);
            _mainQueue = new QueuedHandler(_controller, "MainQueue");
            _controller.SetMainQueue(MainQueue);

            //MONITORING
            var monitoringInnerBus = new InMemoryBus("MonitoringInnerBus", watchSlowMsg: false);
            var monitoringRequestBus = new InMemoryBus("MonitoringRequestBus", watchSlowMsg: false);
            var monitoringQueue = new QueuedHandler(monitoringInnerBus, "MonitoringQueue", watchSlowMsg: true, slowMsgThresholdMs: 100);
            var monitoring = new MonitoringService(monitoringQueue, monitoringRequestBus, db.Config.WriterCheckpoint, appSettings.StatsPeriod);
            Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.SystemInit, Message>());
            Bus.Subscribe(monitoringQueue.WidenFrom<SystemMessage.BecomeShuttingDown, Message>());
            monitoringInnerBus.Subscribe<SystemMessage.SystemInit>(monitoring);
            monitoringInnerBus.Subscribe<SystemMessage.BecomeShuttingDown>(monitoring);
            monitoringInnerBus.Subscribe<MonitoringMessage.GetFreshStats>(monitoring);

            //STORAGE SUBSYSTEM
            var indexPath = Path.Combine(db.Config.Path, "index");
            var tableIndex = new TableIndex(indexPath,
                                            () => new HashListMemTable(),
                                            new InMemoryCheckpoint(),
                                            maxSizeForMemory: 1000000,
                                            maxTablesPerLevel: 2);

            var readIndex = new ReadIndex(_mainQueue,
                                          db,
                                          () => new TFChunkReader(db, db.Config.WriterCheckpoint),
                                          TFConsts.ReadIndexReaderCount,
                                          db.Config.WriterCheckpoint,
                                          tableIndex,
                                          new XXHashUnsafe());
            var writer = new TFChunkWriter(db);
            var storageWriter = new StorageWriter(_mainQueue, _outputBus, writer, readIndex);
            var storageReader = new StorageReader(_mainQueue, _outputBus, readIndex, TFConsts.StorageReaderHandlerCount);
            monitoringRequestBus.Subscribe<MonitoringMessage.InternalStatsRequest>(storageReader);

            var chaser = new TFChunkChaser(db,
                                           db.Config.WriterCheckpoint,
                                           db.Config.GetNamedCheckpoint(Checkpoint.Chaser));
            var storageChaser = new StorageChaser(_mainQueue, chaser);
            _outputBus.Subscribe<SystemMessage.SystemInit>(storageChaser);
            _outputBus.Subscribe<SystemMessage.SystemStart>(storageChaser);
            _outputBus.Subscribe<SystemMessage.BecomeShuttingDown>(storageChaser);

            var storageScavenger = new StorageScavenger(db, readIndex);
            _outputBus.Subscribe<SystemMessage.ScavengeDatabase>(storageScavenger);

            //TCP
            var tcpService = new TcpService(MainQueue, _tcpEndPoint);
            Bus.Subscribe<SystemMessage.SystemInit>(tcpService);
            Bus.Subscribe<SystemMessage.SystemStart>(tcpService);
            Bus.Subscribe<SystemMessage.BecomeShuttingDown>(tcpService);

            //HTTP
            HttpService = new HttpService(MainQueue, _httpEndPoint.ToHttpUrl());
            Bus.Subscribe<SystemMessage.SystemInit>(HttpService);
            Bus.Subscribe<SystemMessage.BecomeShuttingDown>(HttpService);
            Bus.Subscribe<HttpMessage.SendOverHttp>(HttpService);
            Bus.Subscribe<HttpMessage.UpdatePendingRequests>(HttpService);
            HttpService.SetupController(new AdminController(MainQueue));
            HttpService.SetupController(new PingController());
            HttpService.SetupController(new StatController(monitoringQueue));
            HttpService.SetupController(new ReadEventDataController(MainQueue));
            HttpService.SetupController(new AtomController(MainQueue));
            HttpService.SetupController(new WebSiteController(MainQueue));

            //REQUEST MANAGEMENT
            var requestManagement = new RequestManagementService(MainQueue, 1, 1);
            Bus.Subscribe<ReplicationMessage.EventCommited>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CreateStreamRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.WriteRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionStartRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionWriteRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.TransactionCommitRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.DeleteStreamRequestCreated>(requestManagement);
            Bus.Subscribe<ReplicationMessage.RequestCompleted>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CommitAck>(requestManagement);
            Bus.Subscribe<ReplicationMessage.PrepareAck>(requestManagement);
            Bus.Subscribe<ReplicationMessage.WrongExpectedVersion>(requestManagement);
            Bus.Subscribe<ReplicationMessage.InvalidTransaction>(requestManagement);
            Bus.Subscribe<ReplicationMessage.StreamDeleted>(requestManagement);
            Bus.Subscribe<ReplicationMessage.PreparePhaseTimeout>(requestManagement);
            Bus.Subscribe<ReplicationMessage.CommitPhaseTimeout>(requestManagement);

            var clientService = new ClientService();
            Bus.Subscribe<TcpMessage.ConnectionClosed>(clientService);
            Bus.Subscribe<ClientMessage.SubscribeToStream>(clientService);
            Bus.Subscribe<ClientMessage.UnsubscribeFromStream>(clientService);
            Bus.Subscribe<ClientMessage.SubscribeToAllStreams>(clientService);
            Bus.Subscribe<ClientMessage.UnsubscribeFromAllStreams>(clientService);
            Bus.Subscribe<ReplicationMessage.EventCommited>(clientService);

            //TIMER
            //var timer = new TimerService(new TimerBasedScheduler(new RealTimer(), new RealTimeProvider()));
            TimerService = new TimerService(new ThreadBasedScheduler(new RealTimeProvider()));
            Bus.Subscribe<TimerMessage.Schedule>(TimerService);

            MainQueue.Start();
            monitoringQueue.Start();
        }
Exemple #60
0
 public LoginWindow()
 {
     InitializeComponent();
     _clientService = new ClientService();
 }