public void Setup()
 {
     _account = new Account();
     _mockRepository = new Mock<IAccountRepository>();
     _mockFactory = new Mock<IAccountFactory>();
     _sut = new AccountService(_mockRepository.Object, _mockFactory.Object);
 }
Exemple #2
0
 public AccountContext()
 {
     rUser = new GenericRepository<User>((u,n)=>u.Name ==n);
     rAccount = new GenericRepository<Account>((a,n)=>a.Number==n);
     AccountService = new AccountService(rUser, rAccount);
     cb = new ControllerBuilder(AccountService);
 }
 public useradminController(IAccountRepository _rightRepository, IDataCenterRepository _datacenterRepository, IMaterialRepository _materialRepository, ICostanalysisRepository _costanalysisRepository)
 {
     accountService = new AccountService(_rightRepository);
     centerService = new DataCenterService(_datacenterRepository);
     materialService = new MaterialService(_materialRepository);
     costanalysisService = new CostanalysisService(_costanalysisRepository);
 }
Exemple #4
0
        public static UserModel GetUser(this IIdentity identity)
        {

            try
            {
                var customIdentity = identity as CustomIdentity;
                Account user = null;
                if (customIdentity == null)
                {
                    var _identity = identity as ClaimsIdentity;

                    if (_identity != null)
                    {
                        var userId = _identity.Claims.Where(n => n.Type == "Id").Select(n => n.Value).FirstOrDefault();
                        if (userId != null)
                        {
                            user = new AccountService(new NicoleDataContext()).GetAccount(new Guid(userId));
                        }
                    }
                }
                else
                {
                    user = customIdentity.User;
                }
                Mapper.CreateMap<Account, UserModel>().ForMember(n=>n.AccountId,opt=>opt.MapFrom(src=>src.Id))
                    .ForMember(n => n.EmployeeId, opt => opt.MapFrom(src => src.Employee.Id));
                return Mapper.Map<Account, UserModel>(user);
            }
            catch (Exception)
            {
                //this.GetLogger().Error(ex.Message);
            }
            return null;
        }
Exemple #5
0
        public void TestAccountExistsReturnsFalseIfAccountDoesNotExist()
        {
            var mirrorRepository = new Mirror<IAccountRepository>();
            var accountService = new AccountService(mirrorRepository.It);

            Assert.IsFalse(accountService.AccountExists(456));
        }
Exemple #6
0
        public void TransferMoneyMethodTest()
        {
            //Arrange
            Account accountFrom = new Account {
                Name = "Tom",
                AccountNumber = "1234567890",
                Balance = 35.00m,
                AccountType = "Checking"
            };

            Account accountTo = new Account {
                Name = "Dave",
                AccountNumber = "0987654321",
                Balance = 732.21m,
                AccountType = "Savings"
            };

            var accService = new AccountService(new Repository(new DataContext()));

            //Act
            accService.TransferMoney(accountFrom, accountTo, 20.0m);
            var result = accountFrom.Balance;
            //Assert

            Assert.AreEqual(result, 15m);
        }
Exemple #7
0
 public HomeController(IDataCenterRepository _centerRepository, IMaterialRepository _materialRepository, IAccountRepository _rightRepository, IManagementRepository _managementRepository)
 {
     centerService = new DataCenterService(_centerRepository);
     accountService = new AccountService(_rightRepository);
     materialService = new MaterialService(_materialRepository);
     managementService = new ManagementService(_managementRepository);
 }
        public void TestMakeTransfer_debit()
        {
            var operationsList = new List<Operation>();

            SIOperationRepository opRepository = new SIOperationRepository();
            opRepository.CreateOperationOperation = (x) =>
            {
                operationsList.Add(x);
            };

            SIAccountRepository acRepository = new SIAccountRepository();
            acRepository.UpdateAccountAccount = (x) =>
            {
                var acc1 = _accounts.SingleOrDefault(y => y.Id == x.Id);
                acc1.Operations = x.Operations;
            };

            AccountService service = new AccountService(acRepository, opRepository);
            service.MakeTransfer(_accounts[1], _accounts[0], 200);
            Assert.AreEqual(_accounts[1].Balance, 200);
            Assert.AreEqual(_accounts[0].Balance, 100);
            Assert.AreEqual(operationsList.Count, 2);
            Assert.AreEqual(_accounts[1].Operations.Count, 2);
            Assert.AreEqual(_accounts[0].Operations.Count, 3);
        }
        public AccountServiceShould()
        {
            _transactionRepository = Substitute.For<ITransactionRepository>();
            _transactionFactory = Substitute.For<ITransactionFactory>();
            _statementPrinter = Substitute.For<IStatementPrinter>();

            _accountService = new AccountService(_transactionRepository, _transactionFactory, _statementPrinter);
        }
Exemple #10
0
    public void CorrectCredentials()
    {
        var accountService = new AccountService();

            bool result = accountService.DoLogin("test", "test");

            Assert.IsTrue(result);
    }
        public void ComputeInterest()
        {
            AccountService service = new AccountService(null, null);

            decimal result = service.ComputeInterest(new Account { Balance = 120 }, 0.1, 20);

            Assert.AreEqual(result, 20);
        }
Exemple #12
0
        public void TestAccountExistsReturnsTrueIfAccountExists()
        {
            var mirrorRepository = new Mirror<IAccountRepository>();
            mirrorRepository.Returns(r => r.GetAccount(123), new Account());
            var accountService = new AccountService(mirrorRepository.It);

            Assert.IsTrue(accountService.AccountExists(123));
        }
        public ActionResult Register(FormCollection formCollection)
        {
            AccountService accountService = new AccountService();

            var account = accountService.Register(formCollection["name"], formCollection["lastName"], formCollection["email"], formCollection["phone"], formCollection["password"]);

            return View("~/Views/Account/Login.cshtml");
        }
        public void AddingTransactionToAccountDelegatesToAccountInstanceFake()
        {
            var fakeRepo = new FakeAccountRepository(_account);
            var sut = new AccountService(fakeRepo, _mockFactory.Object);
            sut.AddTransactionToAccount("Trading Account", 200m);

            Assert.AreEqual(200m, _account.Balance);
        }
        public PrintStatementFeature()
        {
            _console = Substitute.For<IConsole>();
            _clock = Substitute.For<IClock>();

            _accountService = new AccountService(
                new InMemoryTransactionRepository(),
                new TransactionFactory(_clock),
                new ConsoleStatementPrinter(_console));
        }
        public void Should_return_error()
        {
            var repository = Substitute.For<IAccountRepository>();
            repository.GetUserByEmail(Arg.Any<string>()).Returns(new Person());

            var target = new AccountService(repository);

            var result = target.Create(new Person());
            Assert.NotEmpty(result);
        }
Exemple #17
0
 public override bool LogIn(string username, string password, bool remember)
 {
     AccountService accountService = new AccountService();
     var account =accountService.Login(username, password,"Admin");
     if (account!=null)
     {
         HttpContext.Current.Session["Admin"] = account;
         return true;
     }
     return false;
 }
        public void Should_return_null_if_no_user_found()
        {
            var repository = Substitute.For<IAccountRepository>();
            repository.GetLoggedInUser(2).Returns(x => null);

            var target = new AccountService(repository);

            var user = target.GetLoggedInUser(2);

            Assert.Null(user);
        }
        public void AuthenticateUser_WithInvalidUsernamePassword_ReturnsZero()
        {
            // Arrange
            var service = new AccountService(_users.Object);

            // Act
            var result = service.AuthenticateUser("invalid", "invalid");

            // Assert
            Assert.That(result, Is.EqualTo(0));
        }
Exemple #20
0
 public IUserIdentity Validate(string AccountSid, string AuthToken)
 {
     AccountService acc = new AccountService();
     if (acc.Validate(AccountSid, AuthToken))
     {
         return new UserIdentity { UserName = AccountSid };
     }
     else
     {
         return null;
     }
 }
        public AccountServiceTests()
        {
            context = new TestingContext();
            hasher = Substitute.For<IHasher>();
            hasher.HashPassword(Arg.Any<String>()).Returns(info => info.Arg<String>() + "Hashed");

            context.DropData();
            SetUpData();

            Authorization.Provider = Substitute.For<IAuthorizationProvider>();
            service = new AccountService(new UnitOfWork(context), hasher);
            service.CurrentAccountId = account.Id;
        }
        public void GetOperationsForAccount_AccountFound()
        {
            SIAccountRepository accountRepository = new SIAccountRepository();
            accountRepository.GetAccountInt32 = (x) =>
            {
                return _accounts.SingleOrDefault(a => a.Id == x);
            };

            SIOperationRepository operationRepository = new SIOperationRepository();
            AccountService service = new AccountService(accountRepository, operationRepository);

            List<Operation> result = service.GetOperationsForAccount(1);
            Assert.AreEqual(result.Count, 2);
        }
        public void AuthenticateUser_WithMultipleUsernamePassword_ThrowsException()
        {
            // Arrange

            _users.Setup(u => u.AuthenticateUser(It.IsAny<string>(), It.IsAny<string>())).Throws
                <InvalidOperationException>();
            var service = new AccountService(_users.Object);

            // Act
            var ex = Assert.Throws<InvalidOperationException>(() => service.AuthenticateUser(It.IsAny<string>(), It.IsAny<string>()));

            // Assert
            Assert.That(ex.Message, Is.EqualTo("Operation is not valid due to the current state of the object."));
        }
        public void AuthenticateUser_WithValidUsernamePassword_ReturnsUserId()
        {
            // Arrange
            const string username = "******";
            const string password = "******";
            const int userId = 1;
            var service = new AccountService(_users.Object);

            _users.Setup(u => u.AuthenticateUser(username, password)).Returns(userId);
            // Act
            var result = service.AuthenticateUser(username, password);

            // Assert
            Assert.That(result, Is.EqualTo(userId));
        }
        public void Should_return_user()
        {
            var repository = Substitute.For<IAccountRepository>();
            repository.GetLoggedInUser(1).Returns(
                new Person {
                    Id = 1,
                    FirstName = "John",
                    LastName = "Smith",
                    EmailAddress = "*****@*****.**"
                });

            var target = new AccountService(repository);

            var user = target.GetLoggedInUser(1);

            Assert.Equal("John", user.FirstName);
        }
        public void CreateUser_WithValidUsernamePassword_ReturnsUserId()
        {
            // Arrange
            const string username = "******";
            const string password = "******";
            const string email = "email";
            const int userId = 1;
            var service = new AccountService(_users.Object);
            var createdUser = new User{ Id = userId};
            _users.Setup(u => u.CreateUser(It.IsAny<User>())).Returns(createdUser);
            // Act

            var result = service.CreateUser(username, email, password);

            // Assert
            Assert.That(result, Is.EqualTo(userId));
        }
        public void Should_return_no_errors()
        {
            var repository = Substitute.For<IAccountRepository>();
            repository.Create(Arg.Any<Person>());

            var newPerson = new Person {
                FirstName = "Jane",
                LastName = "Doe",
                EmailAddress = "*****@*****.**"
            };

            var target = new AccountService(repository);

            var result = target.Create(newPerson);

            Assert.Empty(result);
        }
        public ActionResult Login(FormCollection formCollection)
        {
            AccountService accountService = new AccountService();

            Account auth = accountService.Authenticate(formCollection["user"], formCollection["pass"]);

            if (auth != null)
            {
                Session.Add("Account", auth);

                PlaceService placeService = new PlaceService();

                Place[] places = placeService.GetRatedPlaceByAccount(auth.AccountID);

                return View("~/Views/Account/Dashboard.cshtml", places);
            }

            return View();
        }
Exemple #29
0
        public override bool ChangePassword(string password, string newpassword)
        {
            AccountService accountService = new AccountService();
            var account = HttpContext.Current.Session["Admin"] as Account;
            if (account == null) return false;
            var account2 = accountService.getUser(account.UserName, password);
            if (account2 == null) return false;

            try
            {
                account2.Password = newpassword;
                accountService.Update(account2);
                return true;
            }
            catch
            {
                throw;
            }
            return false;
        }
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (IAccountService service = new AccountService())
            {
                Account user = service.Authenticate(context.UserName, context.Password);
                if (user != null)
                {

                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("AccountID", user.AccountID.ToString()));
                    context.Validated(identity);
                    return Task.FromResult<object>(null);
                }
                else
                {
                    context.SetError("invalid_grant", "Usuário ou senha são válidos!");
                    return Task.FromResult<object>(null);
                }
            }
        }
Exemple #31
0
 public AdminController(AccountService accountService)
 {
     _accountService = accountService;
 }
Exemple #32
0
        private async static Task <int> MainMenu(int accountInput, int pinInput)
        {
            var accountService     = new AccountService(accountInput, pinInput);
            var transactionService = new TransactionService(accountInput);

            ATMUtilities.NavigationMenu();

            var input = Console.ReadKey().Key;

            while (true)
            {
                switch (input)
                {
                case ConsoleKey.NumPad1:
                    Console.Clear();
                    ATMUtilities.DisplayBalance(accountService.GetBalanceAsync().Result);
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad2:
                    Console.Clear();
                    await transactionService.WithdrawAsync(ATMUtilities.WithdrawalPrompt());

                    Console.Clear();
                    ATMUtilities.NewBalance(accountService.GetBalanceAsync().Result);
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad3:
                    Console.Clear();
                    await transactionService.DepositAsync(ATMUtilities.DepositPrompt());

                    Console.Clear();
                    ATMUtilities.NewBalance(accountService.GetBalanceAsync().Result);
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad4:
                    Console.Clear();

                    var returnValue = accountService.ChangePinAsync(ATMUtilities.PinChanger());
                    if (returnValue.Result)
                    {
                        Console.Clear();
                        ATMUtilities.PinChangeSuccess();
                    }
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad5:
                    Console.Clear();
                    var target = ATMUtilities.TransferAccountPrompt();
                    Console.Clear();
                    var amount = ATMUtilities.TransferAmountPrompt();
                    Console.Clear();
                    await transactionService.TransferAsync(target, amount);

                    ATMUtilities.TransferSuccess(accountService.GetBalanceAsync().Result);
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad6:
                    Console.Clear();
                    ATMUtilities.GetHistory();
                    Thread.Sleep(500);
                    var transactions = transactionService.GetAccountHistoryAsync();
                    ATMUtilities.HistoryRow(transactions.Result);
                    Thread.Sleep(3000);
                    ATMUtilities.NewMenuScreen();
                    input = Console.ReadKey().Key;
                    break;

                case ConsoleKey.NumPad7:
                    Console.Clear();
                    ATMUtilities.SignOut();
                    Thread.Sleep(3000);
                    Console.Clear();
                    Login();
                    break;
                }

                return(0);
            }
        }
        public INdmConsumerServices Init(INdmServices services)
        {
            AddDecoders();
            var ndmConfig       = services.RequiredServices.NdmConfig;
            var configId        = ndmConfig.Id;
            var dbConfig        = services.RequiredServices.ConfigProvider.GetConfig <IDbConfig>();
            var contractAddress = string.IsNullOrWhiteSpace(ndmConfig.ContractAddress)
                ? Address.Zero
                : new Address(ndmConfig.ContractAddress);
            var logManager      = services.RequiredServices.LogManager;
            var rocksDbProvider = new ConsumerRocksDbProvider(services.RequiredServices.BaseDbPath, dbConfig,
                                                              logManager);
            var depositDetailsRlpDecoder  = new DepositDetailsDecoder();
            var depositApprovalRlpDecoder = new DepositApprovalDecoder();
            var receiptRlpDecoder         = new DataDeliveryReceiptDetailsDecoder();
            var sessionRlpDecoder         = new ConsumerSessionDecoder();
            var receiptRequestValidator   = new ReceiptRequestValidator(logManager);

            IDepositDetailsRepository          depositRepository;
            IConsumerDepositApprovalRepository depositApprovalRepository;
            IProviderRepository        providerRepository;
            IReceiptRepository         receiptRepository;
            IConsumerSessionRepository sessionRepository;

            switch (ndmConfig.Persistence?.ToLowerInvariant())
            {
            case "mongo":
                var database = services.RequiredServices.MongoProvider.GetDatabase();
                depositRepository         = new DepositDetailsMongoRepository(database);
                depositApprovalRepository = new ConsumerDepositApprovalMongoRepository(database);
                providerRepository        = new ProviderMongoRepository(database);
                receiptRepository         = new ReceiptMongoRepository(database, "consumerReceipts");
                sessionRepository         = new ConsumerSessionMongoRepository(database);
                break;

            default:
                depositRepository = new DepositDetailsRocksRepository(rocksDbProvider.DepositsDb,
                                                                      depositDetailsRlpDecoder);
                depositApprovalRepository = new ConsumerDepositApprovalRocksRepository(

                    rocksDbProvider.ConsumerDepositApprovalsDb, depositApprovalRlpDecoder);
                providerRepository = new ProviderRocksRepository(rocksDbProvider.DepositsDb,
                                                                 depositDetailsRlpDecoder);
                receiptRepository = new ReceiptRocksRepository(rocksDbProvider.ConsumerReceiptsDb,
                                                               receiptRlpDecoder);
                sessionRepository = new ConsumerSessionRocksRepository(rocksDbProvider.ConsumerSessionsDb,
                                                                       sessionRlpDecoder);
                break;
            }

            var requiredBlockConfirmations = ndmConfig.BlockConfirmations;
            var abiEncoder                = services.CreatedServices.AbiEncoder;
            var blockchainBridge          = services.CreatedServices.BlockchainBridge;
            var blockProcessor            = services.RequiredServices.BlockProcessor;
            var configManager             = services.RequiredServices.ConfigManager;
            var consumerAddress           = services.CreatedServices.ConsumerAddress;
            var cryptoRandom              = services.RequiredServices.CryptoRandom;
            var depositService            = services.CreatedServices.DepositService;
            var gasPriceService           = services.CreatedServices.GasPriceService;
            var ecdsa                     = services.RequiredServices.Ecdsa;
            var ethRequestService         = services.RequiredServices.EthRequestService;
            var jsonRpcNdmConsumerChannel = services.CreatedServices.JsonRpcNdmConsumerChannel;
            var ndmNotifier               = services.RequiredServices.Notifier;
            var nodePublicKey             = services.RequiredServices.Enode.PublicKey;
            var timestamper               = services.RequiredServices.Timestamper;
            var wallet                    = services.RequiredServices.Wallet;
            var httpClient                = services.RequiredServices.HttpClient;
            var jsonRpcClientProxy        = services.RequiredServices.JsonRpcClientProxy;
            var ethJsonRpcClientProxy     = services.RequiredServices.EthJsonRpcClientProxy;
            var transactionService        = services.CreatedServices.TransactionService;

            var dataRequestFactory     = new DataRequestFactory(wallet, nodePublicKey);
            var transactionVerifier    = new TransactionVerifier(blockchainBridge, requiredBlockConfirmations);
            var depositUnitsCalculator = new DepositUnitsCalculator(sessionRepository, timestamper);
            var depositProvider        = new DepositProvider(depositRepository, depositUnitsCalculator, logManager);
            var kycVerifier            = new KycVerifier(depositApprovalRepository, logManager);
            var consumerNotifier       = new ConsumerNotifier(ndmNotifier);

            var dataAssetService   = new DataAssetService(providerRepository, consumerNotifier, logManager);
            var providerService    = new ProviderService(providerRepository, consumerNotifier, logManager);
            var dataRequestService = new DataRequestService(dataRequestFactory, depositProvider, kycVerifier, wallet,
                                                            providerService, timestamper, sessionRepository, consumerNotifier, logManager);

            var sessionService = new SessionService(providerService, depositProvider, dataAssetService,
                                                    sessionRepository, timestamper, consumerNotifier, logManager);
            var dataConsumerService = new DataConsumerService(depositProvider, sessionService,
                                                              consumerNotifier, timestamper, sessionRepository, logManager);
            var dataStreamService = new DataStreamService(dataAssetService, depositProvider,
                                                          providerService, sessionService, wallet, consumerNotifier, sessionRepository, logManager);
            var depositApprovalService = new DepositApprovalService(dataAssetService, providerService,
                                                                    depositApprovalRepository, timestamper, consumerNotifier, logManager);
            var depositConfirmationService = new DepositConfirmationService(blockchainBridge, consumerNotifier,
                                                                            depositRepository, depositService, logManager, requiredBlockConfirmations);
            var depositManager = new DepositManager(depositService, depositUnitsCalculator, dataAssetService,
                                                    kycVerifier, providerService, abiEncoder, cryptoRandom, wallet, gasPriceService, depositRepository,
                                                    timestamper, logManager, requiredBlockConfirmations);
            var depositReportService = new DepositReportService(depositRepository, receiptRepository, sessionRepository,
                                                                timestamper);
            var receiptService = new ReceiptService(depositProvider, providerService, receiptRequestValidator,
                                                    sessionService, timestamper, receiptRepository, sessionRepository, abiEncoder, wallet, ecdsa,
                                                    nodePublicKey, logManager);
            var refundService = new RefundService(blockchainBridge, abiEncoder, wallet, depositRepository,
                                                  contractAddress, logManager);
            var refundClaimant = new RefundClaimant(refundService, blockchainBridge, depositRepository,
                                                    transactionVerifier, gasPriceService, timestamper, logManager);
            var accountService = new AccountService(configManager, dataStreamService, providerService,
                                                    sessionService, consumerNotifier, wallet, configId, consumerAddress, logManager);
            var proxyService    = new ProxyService(jsonRpcClientProxy, configManager, configId, logManager);
            var consumerService = new ConsumerService(accountService, dataAssetService, dataRequestService,
                                                      dataConsumerService, dataStreamService, depositManager, depositApprovalService, providerService,
                                                      receiptService, refundService, sessionService, proxyService);
            var ethPriceService             = new EthPriceService(httpClient, timestamper, logManager);
            var consumerTransactionsService = new ConsumerTransactionsService(transactionService, depositRepository,
                                                                              timestamper, logManager);

            IPersonalBridge personalBridge = services.RequiredServices.EnableUnsecuredDevWallet
                ? new PersonalBridge(ecdsa, wallet)
                : null;

            services.RequiredServices.RpcModuleProvider.Register(
                new SingletonModulePool <INdmRpcConsumerModule>(new NdmRpcConsumerModule(consumerService,
                                                                                         depositReportService, jsonRpcNdmConsumerChannel, ethRequestService, ethPriceService,
                                                                                         gasPriceService, consumerTransactionsService, personalBridge, timestamper), true));

            var useDepositTimer = ndmConfig.ProxyEnabled;
            var consumerServicesBackgroundProcessor = new ConsumerServicesBackgroundProcessor(accountService,
                                                                                              refundClaimant, depositConfirmationService, ethPriceService, gasPriceService, blockProcessor,
                                                                                              depositRepository, consumerNotifier, logManager, useDepositTimer: useDepositTimer,
                                                                                              ethJsonRpcClientProxy: ethJsonRpcClientProxy);

            consumerServicesBackgroundProcessor.Init();

            return(new NdmConsumerServices(accountService, consumerService));
        }
 public AccountController(AccountService accountService)
 {
     AccountService = accountService;
 }
 /// <inheritdoc cref="AccountService.GenerateExchangeCode"/>
 public async Task <ExchangeCode> GenerateExchangeCode()
 => await AccountService.GenerateExchangeCode(this).ConfigureAwait(false);
Exemple #36
0
 public MenusController(Sys_MenuService _service, AccountService _accountService)
     : base("e5d4da6b-aab0-4aaa-982f-43673e8152c0", _service, _service)
 {
     this.accountService = _accountService;
 }
 public AccountServiceTests()
 {
     _accountRepositoryMock = new Mock <IAccountRepository>();
     _userRepositoryMock    = new Mock <IUserRepository>();
     _accountService        = new AccountService(AccountRepository, UserRepository);
 }
Exemple #38
0
 public UserController()
 {
     service = new AccountService(Startup.DataProtectionProvider);
 }
 public AccountsController(AccountService accountService, UserService userService)
 {
     _accountService = accountService;
     _userService    = userService;
 }
Exemple #40
0
        private static void RunServer()
        {
            //Start ServerStartTime
            Stopwatch serverStartStopwatch = Stopwatch.StartNew();

            AppDomain.CurrentDomain.UnhandledException += UnhandledException;

            //CheckServerMode
            CheckServerMode();

            //ConsoleOutput-Infos
            PrintServerLicence();
            PrintServerInfo();

            //Initialize TcpServer
            TcpServer = new TcpServer("*", Configuration.Network.GetServerPort(), Configuration.Network.GetServerMaxCon());
            Connection.SendAllThread.Start();

            //Initialize Server OpCodes
            OpCodes.Init();
            Console.WriteLine("----------------------------------------------------------------------------\n"
                              + "---===== OpCodes - Revision: " + OpCodes.Version + " EU initialized!");

            //Global Services
            #region global_components
            //Services
            FeedbackService    = new FeedbackService();
            AccountService     = new AccountService();
            PlayerService      = new PlayerService();
            MapService         = new MapService();
            ChatService        = new ChatService();
            VisibleService     = new VisibleService();
            ControllerService  = new ControllerService();
            CraftService       = new CraftService();
            ItemService        = new ItemService();
            AiService          = new AiService();
            GeoService         = new GeoService();
            StatsService       = new StatsService();
            ObserverService    = new ObserverService();
            AreaService        = new AreaService();
            TeleportService    = new TeleportService();
            PartyService       = new PartyService();
            SkillsLearnService = new SkillsLearnService();
            CraftLearnService  = new CraftLearnService();
            GuildService       = new GuildService();
            EmotionService     = new EmotionService();
            RelationService    = new RelationService();
            DuelService        = new DuelService();
            StorageService     = new StorageService();
            TradeService       = new TradeService();
            MountService       = new MountService();

            //Engines
            ActionEngine = new ActionEngine.ActionEngine();
            AdminEngine  = new AdminEngine.AdminEngine();
            SkillEngine  = new SkillEngine.SkillEngine();
            QuestEngine  = new QuestEngine.QuestEngine();
            #endregion

            //Set SqlDatabase Connection
            GlobalLogic.ServerStart("SERVER=" + DAOManager.MySql_Host + ";DATABASE=" + DAOManager.MySql_Database + ";UID=" + DAOManager.MySql_User + ";PASSWORD="******";PORT=" + DAOManager.MySql_Port + ";charset=utf8");
            Console.ForegroundColor = ConsoleColor.Gray;

            //Start Tcp-Server Listening
            Console.WriteLine("----------------------------------------------------------------------------\n"
                              + "---===== Loading GameServer Service.\n"
                              + "----------------------------------------------------------------------------");
            TcpServer.BeginListening();

            //Stop ServerStartTime
            serverStartStopwatch.Stop();
            Console.WriteLine("----------------------------------------------------------------------------");
            Console.WriteLine("---===== GameServer start in {0}", (serverStartStopwatch.ElapsedMilliseconds / 1000.0).ToString("0.00s"));
            Console.WriteLine("----------------------------------------------------------------------------");
        }
 /// <inheritdoc cref="AccountService.GetDeviceAuth"/>
 public async Task <DeviceAuth> GetDeviceAuth(string deviceId)
 => await AccountService.GetDeviceAuth(this, deviceId).ConfigureAwait(false);
 /// <inheritdoc cref="AccountService.GetDeviceAuths"/>
 public async Task <List <DeviceAuth> > GetDeviceAuths()
 => await AccountService.GetDeviceAuths(this).ConfigureAwait(false);
Exemple #43
0
        public const int LogoutTimeout = 1; //TODO: 10

        public static void TryAuthorize(IConnection connection, string accountName, string session)
        {
            //TODO: session check
            AccountService.Authorized(connection, accountName);
            FeedbackService.OnAuthorized(connection);
        }
        public async Task GetCaptcha()
        {
            var captcha = await AccountService.GetCaptchaAsync(_model.Mobile);

            await Message.Success($"获取验证码成功!验证码为:{captcha}");
        }
Exemple #45
0
 public IndexModel(ILogger <IndexModel> logger, AccountService accountService)
 {
     _logger        = logger;
     AccountService = accountService;
 }
        public dynamic ChangePassword(FormDataCollection formData)
        {
            List <string> errors   = new List <string>();
            List <string> response = new List <string>();

            var user = this.User.Identity;

            if (user == null)
            {
                return(new { Error = "Unauthorized" });
            }

            AccountService service        = new AccountService(db, UserManager);
            Member         validateMember = service.findMember(user.Name);

            if (validateMember == null)
            {
                return(new { Error = "Member not found" });
            }

            if (formData != null)
            {
                if (formData["oldPassword"] == null)
                {
                    errors.Add("Old Password is required");
                }

                if (formData["newPassword"] == null)
                {
                    errors.Add("New Password is required");
                }

                if (formData["confirmPassword"] == null)
                {
                    errors.Add("Confirm Password is required");
                }

                if (errors.Count > 0)
                {
                    var e = Enumerable.Range(0, errors.Count).ToDictionary(x => "Error" + x, x => errors[x]);
                    return(e);
                }

                string oldPassword     = formData.Get("oldPassword");
                string newPassword     = formData.Get("newPassword");
                string confirmPassword = formData.Get("confirmPassword");

                // Validation section - cascade errors

                if (string.IsNullOrEmpty(oldPassword))
                {
                    errors.Add("Old Password is required.");
                }

                if (string.IsNullOrEmpty(newPassword))
                {
                    errors.Add("Password is required.");
                }

                if (string.IsNullOrEmpty(confirmPassword))
                {
                    errors.Add("Confirm Password is required.");
                }

                if (newPassword.Trim() != confirmPassword.Trim())
                {
                    errors.Add("Passwords don't match");
                }

                if (errors.Count > 0)
                {
                    var e = Enumerable.Range(0, errors.Count).ToDictionary(x => "Error" + x, x => errors[x]);
                    return(e);
                }

                string AuthToken = this.UpdatePassword(oldPassword, newPassword);
                if (AuthToken.ToLower().Contains("error"))
                {
                    errors.Add(AuthToken);
                    var e = Enumerable.Range(0, errors.Count).ToDictionary(x => "Error" + x, x => errors[x]);
                    return(e);
                }
                var s = new { AuthToken = AuthToken, Status = "Password changed successfully" };
                return(s);
            }
            return(new { Error = "No data available (oldPassword, newPassword, confirmPassword expected.)" });
        }
Exemple #47
0
 public CreateTokenHandler(AccountService accountService, JwtService jwtService, IMemoryCache cache)
 {
     this.accountService = accountService;
     this.jwtService     = jwtService;
     this.cache          = cache;
 }
Exemple #48
0
 /// <summary>
 /// 跟据公司ID查询公司名
 /// </summary>
 /// <param name="aid"></param>
 /// <returns></returns>
 public string getAccountName(string aid)
 {
     return(AccountService.GetAccountById(aid).CompanyName.ToString());
 }
 /// <inheritdoc cref="AccountService.CreateDeviceAuth"/>
 public async Task <DeviceAuth> CreateDeviceAuth()
 => await AccountService.CreateDeviceAuth(this).ConfigureAwait(false);
 /// <inheritdoc cref="AccountService.KillOAuthSession"/>
 public async Task KillSession()
 => await AccountService.KillOAuthSession(this).ConfigureAwait(false);
Exemple #51
0
 public MessageHub(UnitOfWork unitOfWork, MessageService messageService, AccountService accountService)
 {
     _unitOfWork     = unitOfWork;
     _messageService = messageService;
     _accountService = accountService;
 }
 /// <inheritdoc cref="AccountService.DeleteDeviceAuth"/>
 public async Task DeleteDeviceAuth(string deviceId)
 => await AccountService.DeleteDeviceAuth(this, deviceId).ConfigureAwait(false);
Exemple #53
0
 public AccountController(IConfiguration config)
 {
     _accountService = new AccountService(config);
 }
 /// <inheritdoc cref="AccountService.GetExternalAuths"/>
 public async Task <List <ExternalAuth> > GetExternalAuths()
 => await AccountService.GetExternalAuths(this).ConfigureAwait(false);
        private void DrawSetupPhoton()
        {
            this.DrawInputWithLabel("Photon Cloud Setup", () =>
            {
                GUILayout.BeginVertical();
                GUILayout.Space(5);
                GUILayout.Label(WizardText.PHOTON, this.textLabelStyle);
                GUILayout.EndVertical();

                GUILayout.Space(5);
                GUILayout.BeginHorizontal();
                GUILayout.Label(WizardText.PHOTON_DASH, this.textLabelStyle);
                if (GUILayout.Button("Visit Dashboard", this.minimalButtonStyle))
                {
                    string mail = (this.inputState == InputState.Email) ? appIdOrEmail : string.Empty;
                    this.OpenURL(EditorIntegration.UrlCloudDashboard + mail)();
                }

                GUILayout.EndHorizontal();
            }, false);
            GUILayout.Space(15);

            this.DrawInputWithLabel("Photon AppID or Email", () =>
            {
                GUILayout.BeginVertical();

                appIdOrEmail = EditorGUILayout.TextField(appIdOrEmail, this.centerInputTextStyle).Trim();   // trimming all input in/of this field

                GUILayout.EndVertical();
            }, false, true, 300);


            // input state check to show dependent info / buttons
            if (AccountService.IsValidEmail(appIdOrEmail))
            {
                this.inputState = InputState.Email;
            }
            else
            {
                this.inputState = AppSettings.IsAppId(appIdOrEmail) ? InputState.Appid : InputState.NotFinished;
            }

            // button to skip setup
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Skip", GUILayout.Width(100)))
            {
                this.requestHighlighSettings = true;
                this.setupState = SetupState.Skip;
            }

            // SETUP button
            EditorGUI.BeginDisabledGroup(this.inputState == InputState.NotFinished || requestingAppId);
            if (GUILayout.Button("Setup", GUILayout.Width(100)))
            {
                this.requestHighlighSettings = true;
                GUIUtility.keyboardControl   = 0;
                if (this.inputState == InputState.Email && !requestingAppId)
                {
                    requestingAppId = new AccountService().RegisterByEmail(appIdOrEmail, new List <ServiceTypes>()
                    {
                        ServiceTypes.Realtime
                    }, SuccessCallback, ErrorCallback, this.originAssetVersion);
                    if (requestingAppId)
                    {
                        EditorUtility.DisplayProgressBar(WizardText.CONNECTION_TITLE, WizardText.CONNECTION_INFO, 0.5f);
                        this.setupState = SetupState.SendingEmail;
                    }
                }
                else if (this.inputState == InputState.Appid)
                {
                    this.setupState = SetupState.AppIdApplied;

                    // Save App ID
                    AppSettingsInstance.AppIdRealtime = appIdOrEmail;
                }
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.Space(10);

            switch (this.setupState)
            {
            case SetupState.RegisteredSuccessful:
                GUILayout.Label(WizardText.RegisteredNewAccountInfo, this.textLabelStyle);
                GUILayout.Label(WizardText.SetupCompleteInfo, this.textLabelStyle);
                this.HighlightSettings();
                break;

            case SetupState.AppIdApplied:
                GUILayout.Label(WizardText.AppliedToSettingsInfo, this.textLabelStyle);
                GUILayout.Label(WizardText.SetupCompleteInfo, this.textLabelStyle);
                this.HighlightSettings();
                break;

            case SetupState.AlreadyRegistered:
                GUILayout.Label(WizardText.AlreadyRegisteredInfo, this.textLabelStyle);
                this.HighlightSettings();
                break;

            case SetupState.RegistrationError:
                GUILayout.Label(WizardText.RegistrationError, this.textLabelStyle);
                this.HighlightSettings();
                break;

            case SetupState.Skip:
                GUILayout.Label(WizardText.SkipRegistrationInfo, this.textLabelStyle);
                this.HighlightSettings();
                break;
            }
        }
        public List <dynamic> RegisterFull(FormDataCollection formData)
        {
            List <string> errors   = new List <string>();
            List <string> response = new List <string>();

            if (formData != null)
            {
                string name            = formData.Get("name");
                string surname         = formData.Get("surname");
                string password        = formData.Get("password");
                string confirmPassword = formData.Get("confirmPassword");
                string email           = formData.Get("email");
                string country         = formData.Get("country");
                string state           = formData.Get("state");
                string city            = formData.Get("city");
                string mobile          = formData.Get("mobile");
                string promo           = formData.Get("promo");
                string membershipType  = formData.Get("membershipType");
                string tnc             = formData.Get("TermsAndConditions");

                // Validation section - cascade errors
                if (string.IsNullOrEmpty(name))
                {
                    errors.Add("Name is required.");
                }

                if (string.IsNullOrEmpty(surname))
                {
                    errors.Add("Surname is required.");
                }

                if (string.IsNullOrEmpty(password))
                {
                    errors.Add("Password is required.");
                }

                if (string.IsNullOrEmpty(confirmPassword))
                {
                    errors.Add("Confirm Password is required.");
                }
                else
                {
                    if (password.Trim() != confirmPassword.Trim())
                    {
                        errors.Add("Passwords don't match");
                    }
                }

                if (string.IsNullOrEmpty(email))
                {
                    errors.Add("Email is required.");
                }
                else
                {
                    // check for existing.
                }

                if (string.IsNullOrEmpty(country))
                {
                    errors.Add("Country is required.");
                }
                else
                {
                    // validate country ID
                }

                if (string.IsNullOrEmpty(membershipType))
                {
                    errors.Add("Membership Type is required.");
                }
                else
                {
                    // validate membership type
                }

                if (string.IsNullOrEmpty(tnc))
                {
                    errors.Add("Terms and Conditions required.");
                }
                else
                {
                    if (tnc.Trim() != "1")
                    {
                        errors.Add("Terms and Conditions required.");
                    }
                }

                promo  = (string.IsNullOrEmpty(promo)) ? null : promo;
                city   = (string.IsNullOrEmpty(city)) ? "" : city;
                state  = (string.IsNullOrEmpty(state)) ? "" : state;
                mobile = (string.IsNullOrEmpty(mobile)) ? "" : mobile;

                if (errors.Count > 0)
                {
                    return(errors.ToList <dynamic>());
                }

                // No apparent errors, continue creation.
                int countryID = Convert.ToInt32(country.Trim());
                int?cityID    = null;
                int?stateID   = null;

                if (!(string.IsNullOrEmpty(city)))
                {
                    cityID = Convert.ToInt32(city.Trim());
                }

                if (!(string.IsNullOrEmpty(state)))
                {
                    stateID = Convert.ToInt32(state.Trim());
                }

                int    membershipTypeID = Convert.ToInt32(membershipType.Trim());
                int?   OwnerID          = getOwner(countryID, stateID, cityID, promo);
                string MobileNumber     = "";
                if (!string.IsNullOrEmpty(mobile))
                {
                    MobileNumber = Regex.Replace(mobile, @"\s+", "");
                }

                AccountHelper    accountHelper = new AccountHelper();
                AccountService   service       = new AccountService(db, UserManager);
                ApplicationUser  user;
                AccountViewModel avm = new AccountViewModel();
                avm.Email     = email.Trim();
                avm.CountryID = countryID;
                avm.CityID    = cityID;
                avm.FirstName = name.Trim();
                avm.LastName  = surname.Trim();
                avm.MemberSubscriptionType = membershipTypeID;
                avm.ownerID            = OwnerID;
                avm.Password           = password.Trim();
                avm.ConfirmPassword    = confirmPassword.Trim();
                avm.MobileNumber       = MobileNumber;
                avm.PromoCode          = (string.IsNullOrEmpty(promo)) ? "" : promo.Trim();
                avm.StateID            = stateID;
                avm.TermsAndConditions = Convert.ToBoolean(Convert.ToInt32(tnc.Trim()));
                IEnumerable <string> Ierrors;
                System.Web.Http.Routing.UrlHelper urlHelper = new System.Web.Http.Routing.UrlHelper(Request);

                if (service.createUser(accountHelper.ToMember(avm), avm.Password, out user, out Ierrors, urlHelper))
                {
                    GameDao gd = new GameDao(db);
                    gd.AddMemberToGame(user);
                    // Do user sign-in
                    string AuthToken = this.Authenticate(avm.Email, avm.Password);
                    // Get Member ID

                    Member member = service.findMember(avm.Email);
                    if (member == null)
                    {
                        errors.Add("Member not generated");
                        return(errors.ToList <dynamic>());
                    }

                    response.Add("AuthorizationToken::" + AuthToken);
                    response.Add("MemberID::" + member.MemberID);
                }
                if (Ierrors.Count() > 0)
                {
                    return(Ierrors.ToList <dynamic>());
                }
            }
            return(response.ToList <dynamic>());
        }
Exemple #57
0
    public void OnGUI()
    {
        if (currentSettings == null)
        {
            currentSettings = ChatSettings.Load();
        }

        GUI.skin.label.wordWrap = true;
        GUI.skin.label.richText = true;
        if (string.IsNullOrEmpty(mailOrAppId))
        {
            mailOrAppId = string.Empty;
        }

        GUILayout.Label("Chat Settings", EditorStyles.boldLabel);
        GUILayout.Label(this.WelcomeText);
        GUILayout.Space(15);


        GUILayout.Label("AppId or Email");
        string input = EditorGUILayout.TextField(this.mailOrAppId);


        if (GUI.changed)
        {
            this.mailOrAppId = input.Trim();
        }

        bool isMail       = false;
        bool minimumInput = false;
        bool isAppId      = false;

        if (IsValidEmail(this.mailOrAppId))
        {
            // this should be a mail address
            minimumInput = true;
            isMail       = true;
        }
        else if (IsAppId(this.mailOrAppId))
        {
            // this should be an appId
            minimumInput = true;
            isAppId      = true;
        }


        EditorGUI.BeginDisabledGroup(!minimumInput);


        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        bool setupBtn = GUILayout.Button("Setup", GUILayout.Width(205));

        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();

        if (setupBtn)
        {
            this.showDashboardLink     = false;
            this.showRegistrationDone  = false;
            this.showRegistrationError = false;

            if (isMail)
            {
                EditorUtility.DisplayProgressBar("Fetching Account", "Trying to register a Photon Cloud Account.", 0.5f);
                AccountService service = new AccountService();
                service.RegisterByEmail(this.mailOrAppId, AccountService.Origin.Pun);
                EditorUtility.ClearProgressBar();

                if (service.ReturnCode == 0)
                {
                    currentSettings.AppId = service.AppId;
                    EditorUtility.SetDirty(currentSettings);
                    this.showRegistrationDone = true;

                    Selection.objects = new UnityEngine.Object[] { currentSettings };
                }
                else
                {
                    if (service.Message.Contains("registered"))
                    {
                        this.showDashboardLink = true;
                    }
                    else
                    {
                        this.showRegistrationError = true;
                    }
                }
            }
            else if (isAppId)
            {
                currentSettings.AppId = this.mailOrAppId;
                EditorUtility.SetDirty(currentSettings);
                showRegistrationDone = true;
            }

            EditorGUIUtility.PingObject(currentSettings);
        }
        EditorGUI.EndDisabledGroup();

        if (this.showDashboardLink)
        {
            // button to open dashboard and get the AppId
            GUILayout.Space(15);
            GUILayout.Label(AlreadyRegisteredInfo);


            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(new GUIContent(OpenCloudDashboardText, OpenCloudDashboardTooltip), GUILayout.Width(205)))
            {
                EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
                this.mailOrAppId       = string.Empty;
                this.showDashboardLink = false;
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
        if (this.showRegistrationError)
        {
            GUILayout.Space(15);
            GUILayout.Label(FailedToRegisterAccount);

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(new GUIContent(OpenCloudDashboardText, OpenCloudDashboardTooltip), GUILayout.Width(205)))
            {
                EditorUtility.OpenWithDefaultApp(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
                this.mailOrAppId       = string.Empty;
                this.showDashboardLink = false;
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
        if (this.showRegistrationDone)
        {
            GUILayout.Space(15);
            GUILayout.Label("Registration done");
            if (isMail)
            {
                GUILayout.Label(RegisteredNewAccountInfo);
            }
            else
            {
                GUILayout.Label(AppliedToSettingsInfo);
            }

            // setup-complete info
            GUILayout.Space(15);
            GUILayout.Label(SetupCompleteInfo);


            // close window (done)
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(CloseWindowButton, GUILayout.Width(205)))
            {
                this.Close();
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }
    }
Exemple #58
0
 public AdminController(AccountService accountService, CategoryService categoryService, LeaderboardService leaderboardService)
     : base(accountService, categoryService)
 {
     _leaderboardService = leaderboardService;
 }
 /// <inheritdoc cref="AccountService.GetInformation(OAuthSession)"/>
 public async Task <AccountInfo> GetAccountInfo()
 => await AccountService.GetInformation(this).ConfigureAwait(false);
        public Dictionary <string, string> MemberAccount(FormDataCollection formData)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            AccountService service = new AccountService(db, UserManager);

            var user = this.User.Identity;

            if (user == null)
            {
                result.Add("Error", "Unathorized");
                return(result);
            }

            Member validateMember = service.findMember(user.Name);

            if (validateMember == null)
            {
                result.Add("Error", "Member not found");
                return(result);
            }

            bool dataUpdate = false;

            if (formData != null)
            {
                string memberID = formData.Get("memberID");
                if (memberID == null)
                {
                    result.Add("Error", "MemberID required.");
                    return(result);
                }

                int MemberID = Convert.ToInt32(memberID);

                if (MemberID != validateMember.MemberID)
                {
                    result.Add("Error", "MemberID does not match authenticated user");
                    return(result);
                }
                //  At this point, the authenticated user and memberID parameter have been successfully verified.

                // get member, Billing & postal (delivery) address and interests
                Member         member         = db.Members.Find(MemberID);
                Address        billAddress    = db.Addresses.Where(x => x.MemberID == member.MemberID && x.AddressType.ToLower().Equals("billing")).FirstOrDefault();
                Address        delAddress     = db.Addresses.Where(x => x.MemberID == member.MemberID && x.AddressType.ToLower().Equals("postal")).FirstOrDefault();
                MemberInterest memberInterest = member.MemberInterests.Where(x => x.MemberID == member.MemberID).FirstOrDefault();

                if (formData["name"] != null || formData["surname"] != null || formData["email"] != null || formData["gender"] != null || formData["dateOfBirth"] != null || formData["mobile"] != null | formData["ethnicGroup"] != null || formData["maritalStatus"] != null || formData["children"] != null || formData["industry"] != null || formData["designation"] != null)
                {
                    dataUpdate         = true;
                    member.DateUpdated = DateTime.Now;
                    // Perform member details updates
                    if (formData["name"] != null)
                    {
                        member.FirstName = formData.Get("name").Trim();
                    }

                    if (formData["surname"] != null)
                    {
                        member.LastName = formData.Get("surname").Trim();
                    }

                    if (formData["email"] != null)
                    {
                        member.EmailAddress = formData.Get("email").Trim();
                    }

                    if (formData["gender"] != null)
                    {
                        member.Gender = formData.Get("gender").Trim();
                    }

                    if (formData["dateOfBirth"] != null)
                    {
                        member.DateOfBirth = Convert.ToDateTime(formData.Get("dateOfBirth").Trim());
                    }

                    if (formData["mobile"] != null)
                    {
                        member.TelephoneMobile = formData.Get("mobile").Trim();
                    }

                    if (formData["ethnicGroup"] != null)
                    {
                        member.Ethnicity = formData.Get("ethnicGroup").Trim();
                    }

                    if (formData["maritalStatus"] != null)
                    {
                        member.MaritalStatus = formData.Get("maritalStatus").Trim();
                    }

                    if (formData["children"] != null)
                    {
                        member.Children = formData.Get("children").Trim();
                    }

                    if (formData["industry"] != null)
                    {
                        member.Industry = formData.Get("industry").Trim();
                    }

                    if (formData["designation"] != null)
                    {
                        member.Designation = formData.Get("designation").Trim();
                    }
                }
                bool addNewDelAddress = false;
                if (formData["countryDelivery"] != null || formData["stateDelivery"] != null || formData["cityDelivery"] != null || formData["postalDelivery"] != null || formData["addressLine1Delivery"] != null || formData["addressLine2Delivery"] != null)
                {
                    dataUpdate = true;
                    if (delAddress == null)
                    {
                        addNewDelAddress        = true;
                        delAddress              = new Address();
                        delAddress.AddressType  = "Postal";
                        delAddress.DateInserted = DateTime.Now;
                        delAddress.MemberID     = member.MemberID;
                        delAddress.USR          = "******";
                    }

                    delAddress.DateUpdated = DateTime.Now;
                    // perform delivery address information updates
                    if (formData["countryDelivery"] != null)
                    {
                        delAddress.Country = formData.Get("countryDelivery").Trim();
                    }

                    if (formData["stateDelivery"] != null)
                    {
                        delAddress.StateOrProvince = formData.Get("stateDelivery").Trim();
                    }

                    if (formData["cityDelivery"] != null)
                    {
                        delAddress.CityName = formData.Get("cityDelivery").Trim();
                    }

                    if (formData["postalDelivery"] != null)
                    {
                        delAddress.ZipOrPostalCode = formData.Get("postalDelivery").Trim();
                    }

                    if (formData["addressLine1Delivery"] != null)
                    {
                        delAddress.AddressLine1 = formData.Get("addressLine1Delivery").Trim();
                    }

                    if (formData["addressLine2Delivery"] != null)
                    {
                        delAddress.AddressLine2 = formData.Get("addressLine2Delivery").Trim();
                    }
                }

                bool addNewBillAddress = false;
                if (formData["countryBill"] != null || formData["stateBill"] != null || formData["cityBill"] != null || formData["postalBill"] != null || formData["addressLine1Bill"] != null || formData["addressLine2Bill"] != null)
                {
                    dataUpdate = true;
                    if (billAddress == null)
                    {
                        addNewBillAddress        = true;
                        billAddress              = new Address();
                        billAddress.AddressType  = "Billing";
                        billAddress.MemberID     = member.MemberID;
                        billAddress.USR          = "******";
                        billAddress.DateInserted = DateTime.Now;
                    }

                    billAddress.DateUpdated = DateTime.Now;
                    // perform billing address information updates
                    if (formData["countryBill"] != null)
                    {
                        billAddress.Country = formData.Get("countryBill").Trim();
                    }

                    if (formData["stateBill"] != null)
                    {
                        billAddress.StateOrProvince = formData.Get("stateBill").Trim();
                    }

                    if (formData["cityBill"] != null)
                    {
                        billAddress.CityName = formData.Get("cityBill").Trim();
                    }

                    if (formData["postalBill"] != null)
                    {
                        billAddress.ZipOrPostalCode = formData.Get("postalBill").Trim();
                    }

                    if (formData["addressLine1Bill"] != null)
                    {
                        billAddress.AddressLine1 = formData.Get("addressLine1Bill").Trim();
                    }

                    if (formData["addressLine2Bill"] != null)
                    {
                        billAddress.AddressLine2 = formData.Get("addressLine2Bill").Trim();
                    }
                }

                bool addNewMemberInterest = false;
                if (formData["interestAutomotive"] != null || formData["interestEntertainment"] != null || formData["interestFashion"] != null || formData["interestArt"] != null || formData["interestDecor"] != null || formData["interestExperiences"] != null || formData["interestAppliances"] != null || formData["interestBeauty"] != null || formData["interestTechnology"] != null || formData["interestToys"] != null || formData["interestDining"] != null || formData["interestTravel"] != null || formData["interestOther"] != null)
                {
                    dataUpdate = true;
                    if (memberInterest == null)
                    {
                        addNewMemberInterest        = true;
                        memberInterest              = new MemberInterest();
                        memberInterest.MemberID     = member.MemberID;
                        memberInterest.DateInserted = DateTime.Now;
                        memberInterest.USR          = "******";
                        // I don't know what this productCategory table is supposed to represent here.... making it a 1 for now.
                        memberInterest.ProductCategoryID = 1;
                    }

                    memberInterest.DateUpdated = DateTime.Now;
                    // perform interests update
                    if (formData["interestAutomotive"] != null)
                    {
                        memberInterest.MemberInterestAutomotive = Convert.ToBoolean(formData.Get("interestAutomotive").Trim());
                    }

                    if (formData["interestEntertainment"] != null)
                    {
                        memberInterest.MemberInterestEntertainment = Convert.ToBoolean(formData.Get("interestEntertainment").Trim());
                    }

                    if (formData["interestFashion"] != null)
                    {
                        memberInterest.MemberInterestFashionAccessories = Convert.ToBoolean(formData.Get("interestFashion").Trim());
                    }

                    if (formData["interestArt"] != null)
                    {
                        memberInterest.MemberInterestArtCollectibles = Convert.ToBoolean(formData.Get("interestArt").Trim());
                    }

                    if (formData["interestDecor"] != null)
                    {
                        memberInterest.MemberInterestDecorDesign = Convert.ToBoolean(formData.Get("interestDecor").Trim());
                    }

                    if (formData["interestExperiences"] != null)
                    {
                        memberInterest.MemberInterestExperiences = Convert.ToBoolean(formData.Get("interestExperiences").Trim());
                    }

                    if (formData["interestAppliances"] != null)
                    {
                        memberInterest.MemberInterestHomeAppliances = Convert.ToBoolean(formData.Get("interestAppliances").Trim());
                    }

                    if (formData["interestBeauty"] != null)
                    {
                        memberInterest.MemberInterestHealthBeauty = Convert.ToBoolean(formData.Get("interestBeauty").Trim());
                    }

                    if (formData["interestTechnology"] != null)
                    {
                        memberInterest.MemberInterestTechnology = Convert.ToBoolean(formData.Get("interestTechnology").Trim());
                    }

                    if (formData["interestToys"] != null)
                    {
                        memberInterest.MemberInterestToys = Convert.ToBoolean(formData.Get("interestToys").Trim());
                    }

                    if (formData["interestDining"] != null)
                    {
                        memberInterest.MemberInterestWiningDining = Convert.ToBoolean(formData.Get("interestDining").Trim());
                    }

                    if (formData["interestTravel"] != null)
                    {
                        memberInterest.MemberInterestTravel = Convert.ToBoolean(formData.Get("interestTravel").Trim());
                    }

                    if (formData["interestOther"] != null)
                    {
                        memberInterest.MemberInterestOther = formData.Get("interestOther").Trim();
                    }
                }

                if (!dataUpdate)
                {
                    // No updates to process, just return account detail.
                    Dictionary <string, string> accountDetails = new Dictionary <string, string>();

                    accountDetails.Add("name", member.FirstName.Trim());
                    accountDetails.Add("surname", member.LastName.Trim());

                    string email         = (member.EmailAddress != null) ? member.EmailAddress.Trim() : "";
                    string gender        = (member.Gender != null) ? member.Gender.Trim() : "";
                    string dob           = (member.DateOfBirth != null) ? ((DateTime)member.DateOfBirth).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) : "";
                    string mobile        = (member.TelephoneMobile != null) ? member.TelephoneMobile.Trim() : "";
                    string ethnicGroup   = (member.Ethnicity != null) ? member.Ethnicity.Trim() : "";
                    string maritalStatus = (member.MaritalStatus != null) ? member.MaritalStatus.Trim() : "";
                    string children      = (member.Children != null) ? member.Children.Trim() : "";
                    string industry      = (member.Industry != null) ? member.Industry.Trim() : "";
                    string designation   = (member.Designation != null) ? member.Designation.Trim() : "";

                    accountDetails.Add("email", email);
                    accountDetails.Add("gender", gender);
                    accountDetails.Add("dateOfBirth", dob);
                    accountDetails.Add("mobile", mobile);
                    accountDetails.Add("ethnicGroup", ethnicGroup);
                    accountDetails.Add("maritalStatus", maritalStatus);
                    accountDetails.Add("children", children);
                    accountDetails.Add("industry", industry);
                    accountDetails.Add("designation", designation);

                    if (billAddress != null)
                    {
                        string countryBill      = (billAddress.Country != null) ? billAddress.Country.Trim() : "";
                        string stateBill        = (billAddress.StateOrProvince != null) ? billAddress.StateOrProvince.Trim() : "";
                        string cityBill         = (billAddress.CityName != null) ? billAddress.CityName.Trim() : "";
                        string postalBill       = (billAddress.ZipOrPostalCode != null) ? billAddress.ZipOrPostalCode.Trim() : "";
                        string addressLine1Bill = (billAddress.AddressLine1 != null) ? billAddress.AddressLine1.Trim() : "";
                        string addressLine2Bill = (billAddress.AddressLine2 != null) ? billAddress.AddressLine2.Trim() : "";

                        accountDetails.Add("countryBill", countryBill);
                        accountDetails.Add("stateBill", stateBill);
                        accountDetails.Add("cityBill", cityBill);
                        accountDetails.Add("postalBill", postalBill);
                        accountDetails.Add("addressLine1Bill", addressLine1Bill);
                        accountDetails.Add("addressLine2Bill", addressLine2Bill);
                    }

                    if (delAddress != null)
                    {
                        string countryDelivery      = (delAddress.Country != null) ? delAddress.Country.Trim() : "";
                        string stateDelivery        = (delAddress.StateOrProvince != null) ? delAddress.StateOrProvince.Trim() : "";
                        string cityDelivery         = (delAddress.CityName != null) ? delAddress.CityName.Trim() : "";
                        string postalDelivery       = (delAddress.ZipOrPostalCode != null) ? delAddress.ZipOrPostalCode.Trim() : "";
                        string addressLine1Delivery = (delAddress.AddressLine1 != null) ? delAddress.AddressLine1.Trim() : "";
                        string addressLine2Delivery = (delAddress.AddressLine2 != null) ? delAddress.AddressLine2.Trim() : "";

                        accountDetails.Add("countryDelivery", countryDelivery);
                        accountDetails.Add("stateDelivery", stateDelivery);
                        accountDetails.Add("cityDelivery", cityDelivery);
                        accountDetails.Add("postalDelivery", postalDelivery);
                        accountDetails.Add("addressLine1Delivery", addressLine1Delivery);
                        accountDetails.Add("addressLine2Delivery", addressLine2Delivery);
                    }

                    if (memberInterest != null)
                    {
                        string interestOther = (memberInterest.MemberInterestOther != null) ? memberInterest.MemberInterestOther.Trim() : "";

                        accountDetails.Add("interestAutomotive", memberInterest.MemberInterestAutomotive.ToString());
                        accountDetails.Add("interestEntertainment", memberInterest.MemberInterestEntertainment.ToString());
                        accountDetails.Add("interestFashion", memberInterest.MemberInterestFashionAccessories.ToString());
                        accountDetails.Add("interestArt", memberInterest.MemberInterestArtCollectibles.ToString());
                        accountDetails.Add("interestDecor", memberInterest.MemberInterestDecorDesign.ToString());
                        accountDetails.Add("interestExperiences", memberInterest.MemberInterestExperiences.ToString());
                        accountDetails.Add("interestAppliances", memberInterest.MemberInterestHomeAppliances.ToString());
                        accountDetails.Add("interestBeauty", memberInterest.MemberInterestHealthBeauty.ToString());
                        accountDetails.Add("interestTechnology", memberInterest.MemberInterestTechnology.ToString());
                        accountDetails.Add("interestToys", memberInterest.MemberInterestToys.ToString());
                        accountDetails.Add("interestDining", memberInterest.MemberInterestWiningDining.ToString());
                        accountDetails.Add("interestTravel", memberInterest.MemberInterestTravel.ToString());
                        accountDetails.Add("interestOther", interestOther);
                    }

                    return(accountDetails);
                }
                else
                {
                    try
                    {
                        if (addNewBillAddress)
                        {
                            db.Addresses.Add(billAddress);
                        }

                        if (addNewDelAddress)
                        {
                            db.Addresses.Add(delAddress);
                        }

                        if (addNewMemberInterest)
                        {
                            db.MemberInterests.Add(memberInterest);
                        }

                        db.SaveChanges();
                        result.Add("Success", "Successfully saved changes");
                        return(result);
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException e)
                    {
                        foreach (var eve in e.EntityValidationErrors)
                        {
                            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                              eve.Entry.Entity.GetType().Name, eve.Entry.State);
                            foreach (var ve in eve.ValidationErrors)
                            {
                                System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                                   ve.PropertyName, ve.ErrorMessage);
                                result.Add("Property: " + ve.PropertyName, " Error: " + ve.ErrorMessage);
                            }
                        }
                        result.Add("Error", "During Save");
                        return(result);
                    }
                }
            }
            else
            {
                result.Add("Input Error", "No Valid Data");
            }
            return(result);
        }