コード例 #1
0
        public Account GetAccountDuplicate(IEnumerable <Account> accounts, ApplicationStore app)
        {
            Account account = null;

            if (app.Application.MemberType == MemberType.Consumer)
            {
                account = accounts.FirstOrDefault(a => !a.Customer.IsNull());
            }
            else
            {
                account = accounts.Where(a => a.AccountRoles.Any(ar =>
                                                                 ar.Status &&
                                                                 ar.Role.Status &&
                                                                 ar.Role.Permissions.Any(p =>
                                                                                         p.Status &&
                                                                                         p.Resource.Application.Status &&
                                                                                         p.Resource.ApplicationCode == app.ApplicationCode)

                                                                 )).FirstOrDefault();
            }

            if (account.IsNull())
            {
                account = accounts.OrderBy(a => a.SaveDate).FirstOrDefault();
            }

            return(account);
        }
コード例 #2
0
ファイル: UserMgr.cs プロジェクト: tah182/Comet
 public UserMgr(IUserSvc svc)
 {
     this.svc = svc;
     userList = (ApplicationStore<IList<IUser>>)HttpContext.Current.Application["Users"];
     if (this.userList == null || !this.userList.isValid())
         refresh();
 }
コード例 #3
0
 public ApplicationManager(IOpenIddictApplicationStore <Applications> applicationStore,
                           ILogger <OpenIddictApplicationManager <Applications> > logger,
                           ApplicationStore store
                           ) : base(applicationStore, logger)
 {
     Store = store;
 }
コード例 #4
0
        public Account GetAccount(Guid accountCode, Guid clientId, bool includeRole = false)
        {
            Account          account          = null;
            ApplicationStore applicationStore = null;

            using (var transaction = Connection.BeginTransaction())
            {
                try
                {
                    applicationStore = applicationStoreRepository.GetByClientId(clientId);

                    account = accountService.Get(accountCode, applicationStore, includeApplication: true, includeMetadata: true, includeRole: includeRole);

                    if (!account.IsNull() && !account.Customer.IsNull())
                    {
                        account.Customer.HandlerToGet();
                    }

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }

            if (!account.IsNull())
            {
                account.Metadata = metadataService.GetFieldAndFill(FieldType.Account, account.Metadata).Cast <AccountMetadata>().ToList();
            }

            return(account);
        }
コード例 #5
0
        public Account Authenticate(IEnumerable <Account> accounts, ApplicationStore applicationStore, bool unlockAccount = true)
        {
            Account account            = null;
            IEnumerable <Account> _acc = null;

            if (applicationStore.Application.MemberType == MemberType.Consumer)
            {
                _acc = accountRepository.GetOffBlacklist(accounts.Select(a => a.Code), applicationStore.StoreCode);

                if (_acc.IsNull() || _acc.Count() == 0)
                {
                    throw new AccountNotFoundException("Usuário não existe");
                }
            }
            else if (applicationStore.Application.AuthType == AuthType.Distributed)
            {
                _acc = accountRepository.GetOffBlacklistAndHasPermission(accounts.Select(a => a.Code), applicationStore.StoreCode, applicationStore.ApplicationCode);
            }
            else if (applicationStore.Store.IsMain)
            {
                _acc = accountRepository.GetOffBlacklistAndHasPermissionUnified(accounts.Select(a => a.Code), applicationStore.StoreCode, applicationStore.ApplicationCode);
            }
            else
            {
                _acc = null;
            }

            if (_acc.IsNull() || _acc.Count() == 0)
            {
                throw new AccountNotFoundException("Usuário não possui permissão para acessar esta loja ou aplicação");
            }
            else
            {
                var _accounts = _acc.Where(a => lockedUpMemberPolicy.Validate(a, false));

                if (_accounts.IsNull() || _accounts.Count() == 0)
                {
                    throw new LockedUpMemberException(_acc.FirstOrDefault());
                }
                else if (_accounts.Count() > 1)
                {
                    account = GetAccountDuplicate(_acc, applicationStore);

                    string messageFlow = unlockAccount ? "account recovery" : "login";

                    slack.Warn($"Duplicate {messageFlow} password information for IDs: {string.Join(";", _acc.Select(a => a.Code.ToString()).ToArray<string>())}");
                }
                else
                {
                    account = _accounts.FirstOrDefault();
                }

                account.SuccessfullyLogin(lockedUpMemberPolicy, lockMemberPolicy);
                Update(account);
                SetConnection(accountApplicationStoreService);
                accountApplicationStoreService.Save(new AccountApplicationStore(account.Code, applicationStore.Code));

                return(account);
            }
        }
コード例 #6
0
        public Account Get(string email, string document, ApplicationStore applicationStore, bool checkEmailAndDocument = false, bool isSave = false)
        {
            List <Account> accounts = new List <Account>();

            var listEmail = accountRepository.Get(email, null, null).ToList();

            accounts.AddRange(listEmail);

            if (!document.IsNullOrWhiteSpace())
            {
                var listDocument = accountRepository.Get(document, null, null).ToList();
                accounts.AddRange(listDocument);
            }

            var account = CreateConnect(accounts, applicationStore, string.Empty, isSave);

            if (checkEmailAndDocument && ((!account.IsNull() && !account.Document.IsNullOrWhiteSpace()) || account.IsNull()))
            {
                CheckEmailAndDocument(email, document, applicationStore, true);
            }

            if (!account.IsNull() && !account.Customer.IsNull())
            {
                account.Customer.HandlerToGet();
            }

            return(account);
        }
コード例 #7
0
        public DO.ResetSMSToken Generate(Customer customer, ApplicationStore applicationStore, string urlBack)
        {
            DO.ResetSMSToken token = null;

            var codeSMS = new Random().Next(222222, 999999).ToString();

            //Send SMS Token
            var phone      = customer.Mobile;
            var ZenviaCode = Guid.NewGuid();
            var tokenCode  = ZenviaCode.EncryptDES();

            if (phone.IsNull())
            {
                throw new ArgumentException("Telefone celular não encontrado");
            }

            smsTokenInfraService.SendSms(phone.DDD, phone.Number, string.Format(Config.ResetPasswordSMSMessage, codeSMS, applicationStore.Store.Name), ZenviaCode.AsString());

            token = new DO.ResetSMSToken()
            {
                PhoneNumber          = string.Format("{0}{1}", phone.DDD, phone.Number),
                Code                 = tokenCode,
                CodeSMS              = codeSMS,
                OwnerCode            = customer.Guid,
                UrlBack              = urlBack,
                ApplicationStoreCode = applicationStore.Code,
                ZenviaCode           = ZenviaCode
            };

            smsRepository.Add(token);

            return(token);
        }
コード例 #8
0
        public void Authenticate(Account account, ApplicationStore applicationStore, string password)
        {
            if (!account.IsNull() && account.Status && !account.Removed)
            {
                if (lockedUpMemberPolicy == null || (lockedUpMemberPolicy.Validate(account) && (applicationStore.IsNull() || lockedUpMemberPolicy.Validate(account, applicationStore))))
                {
                    if (!password.IsNullOrWhiteSpace() && account.Password.Equals(password.Encrypt()))
                    {
                        account.SuccessfullyLogin(lockedUpMemberPolicy, lockMemberPolicy);
                        Update(account);
                    }
                    else
                    {
                        account.WrongLoginAttempt(lockedUpMemberPolicy, lockMemberPolicy);
                        Update(account);

                        throw new ArgumentException("invalid_password");
                    }
                }
            }
            else
            {
                throw new ArgumentException("invalid_account");
            }
        }
コード例 #9
0
ファイル: PathMgr.cs プロジェクト: tah182/Comet
        public PathMgr(IPathSvc svc)
        {
            this.svc = svc;

            this.vendorPoints = (ApplicationStore<Dictionary<string, IList<Line>>>)HttpContext.Current.Application["gisFiber"];
            this.vendorNames = (ApplicationStore<Dictionary<string, FiberVendorDetails>>)HttpContext.Current.Application["gisVendorNames"];
            if (vendorNames == null)
                refresh();
        }
コード例 #10
0
ファイル: BuildingMgr.cs プロジェクト: tah182/Comet
 public BuildingMgr(IBuildingSvc svc)
 {
     this.svc = svc;
     this.sdpAssetList = (ApplicationStore<IList<IBuilding>>)HttpContext.Current.Application["sdpAsset"];
     this.entranceFacilityList = (ApplicationStore<IList<EntranceFacility>>)HttpContext.Current.Application["entranceFacility"];
     this.trendList = (ApplicationStore<IList<SDP_TREND>>)HttpContext.Current.Application["trendList"];
     if (this.sdpAssetList == null || !this.sdpAssetList.isValid() ||
         this.entranceFacilityList == null || !this.entranceFacilityList.isValid() ||
         this.trendList == null || !this.trendList.isValid())
             refresh();
 }
コード例 #11
0
ファイル: RequestMgr.cs プロジェクト: tah182/Comet
        public RequestMgr(IRequestSvc svc)
        {
            this.svc = svc;
            this.requestList = (ApplicationStore<IList<RequestView>>)HttpContext.Current.Application["Request"];
            this.elementStatusList = (ApplicationStore<IList<LookupSorted>>)HttpContext.Current.Application["ElementStatus"];
            this.requestStatusList = (ApplicationStore<IList<LookupSorted>>)HttpContext.Current.Application["RequestStatus"];
            this.projectStatusList = (ApplicationStore<IList<LookupSorted>>)HttpContext.Current.Application["ProjectStatus"];

            if (this.requestList == null || this.elementStatusList == null || this.requestStatusList == null || this.projectStatusList == null ||
                !this.requestList.isValid() || !this.elementStatusList.isValid() || !this.requestStatusList.isValid() || !this.projectStatusList.isValid())
                refresh();
        }
コード例 #12
0
ファイル: EmployeeMgr.cs プロジェクト: tah182/Comet
        public EmployeeMgr(IEmployeeSvc repository)
        {
            this.repository = repository;

            this.employeeList = (ApplicationStore<IList<Employee>>)HttpContext.Current.Application["Employee"];
            this.groupManagerList = (ApplicationStore<IList<GroupManager>>)HttpContext.Current.Application["GroupManager"];
            this.directorList = (ApplicationStore<IList<Director>>)HttpContext.Current.Application["Director"];

            if (employeeList == null || groupManagerList == null || directorList == null ||
                !employeeList.isValid() || !groupManagerList.isValid() || !directorList.isValid())
                refresh();
        }
コード例 #13
0
        public ActionResult ClientRegisteration(ClientViewModel userClient)
        {
            if (!ModelState.IsValid)
            {
                userClient.Cities = context.Cities.ToList();
                return(View(userClient));
            }
            ApplicationUser client = new ApplicationUser()
            {
                // remember to add gender
                Name         = userClient.Name,
                UserName     = userClient.Username,
                Gender       = userClient.Gender.ToString(),
                PasswordHash = userClient.Password,
                PhoneNumber  = userClient.Phone,
                Email        = userClient.Email
            };

            ApplicationDbContext DBContext = new ApplicationDbContext();
            ApplicationStore     store     = new ApplicationStore(DBContext);
            ApplicationManager   manager   = new ApplicationManager(store);
            IdentityResult       Result    = manager.CreateAsync(client, userClient.Password).Result;
            var RoleResult = manager.AddToRoleAsync(client.Id, "Client").Result;

            if (Result.Succeeded)
            {
                Client newClient = new Client()
                {
                    UserID  = client.Id,
                    Address = userClient.Address,
                    CityID  = userClient.CityID
                };
                context.Clients.Add(newClient);
                context.SaveChanges();
                IAuthenticationManager authentication          = HttpContext.GetOwinContext().Authentication;
                SignInManager <ApplicationUser, string> signIn = new SignInManager <ApplicationUser, string>(manager, authentication);
                signIn.SignIn(client, false, false);
                return(RedirectToAction("Index", "Home"));
            }

            string error = "";

            foreach (var err in Result.Errors)
            {
                error += err + " ";
            }
            ModelState.AddModelError("", error);
            return(View(userClient));
        }
コード例 #14
0
        public ApplicationStore Save(Application application, Store store, string[] jsAllowedOrigins)
        {
            var applicationStore = new ApplicationStore();

            applicationStore.Code             = Guid.NewGuid();
            applicationStore.Application      = application;
            applicationStore.Store            = store;
            applicationStore.Status           = true;
            applicationStore.ConfClient       = Guid.NewGuid();
            applicationStore.ConfSecret       = Guid.NewGuid().ToString().Substring(24);
            applicationStore.JSClient         = Guid.NewGuid();
            applicationStore.JSAllowedOrigins = !jsAllowedOrigins.IsNull() ? string.Join(",", jsAllowedOrigins) : string.Empty;

            return(applicationStoreRepository.Save(applicationStore));
        }
コード例 #15
0
ファイル: LookupMgr.cs プロジェクト: tah182/Comet
        public LookupMgr(IRequestSvc svc)
        {
            this.svc = svc;

            this.supportAreaList = (ApplicationStore<IList<SupportArea>>)HttpContext.Current.Application["SupportArea"];
            this.supportUnitList = (ApplicationStore<IList<ALookup>>)HttpContext.Current.Application["SupportUnit"];
            this.requestTypeList = (ApplicationStore<IList<LookupActive>>)HttpContext.Current.Application["RequestType"];
            this.projectTypeList = (ApplicationStore<IList<LookupActive>>)HttpContext.Current.Application["ProjectType"];
            this.requestCategoryList = (ApplicationStore<IList<LookupActive>>)HttpContext.Current.Application["RequestCategory"];
            this.valueDriverList = (ApplicationStore<IList<ALookup>>)HttpContext.Current.Application["ValueDriver"];
            this.programList = (ApplicationStore<IList<ALookup>>)HttpContext.Current.Application["Program"];

            if (this.supportAreaList == null || this.supportUnitList == null || this.requestTypeList == null || this.requestCategoryList == null || this.valueDriverList == null || this.programList == null ||
                !this.supportUnitList.isValid() || !this.supportUnitList.isValid() || !this.requestTypeList.isValid() || !this.requestCategoryList.isValid() || !this.valueDriverList.isValid() || !this.programList.isValid())
                refresh();
        }
コード例 #16
0
        public ApplicationStore Get(ApplicationStore applicationStore, Guid storeCode)
        {
            ApplicationStore _applicationStore;

            //get application on token
            if (applicationStore.Store.Code == storeCode)
            {
                _applicationStore = applicationStore;
            }
            else
            {
                _applicationStore = applicationStoreRepository.Get(applicationStore.Application.Code.Value, storeCode);
            }

            return(_applicationStore);
        }
コード例 #17
0
        public void Add(Account account, ApplicationStore applicationStore, Guid originStore, bool simplifiedCustomer = false)
        {
            if (applicationStore.IsNull())
            {
                throw new ArgumentException("Applicação inválida");
            }

            account.IsValid(simplifiedCustomer);

            account.SetPassword(account.Password, passwordPolicy);

            if (simplifiedCustomer || !account.Customer.IsNull())
            {
                var customer = account.Customer;
                customer.Password = account.Password;
                customer.Account  = account;

                if (!simplifiedCustomer && !account.Document.IsNullorEmpty())
                {
                    customerService.PrepareToAdd(customer, originStore);
                }
                else
                {
                    customerService.PrepareToAddSimplified(customer);
                }
            }

            account.SaveDate   = DateTime.Now;
            account.UpdateDate = DateTime.Now;

            var _account = accountRepository.Save(account);

            if (!account.CodeEmailTemplate.IsNull())
            {
                var resetPasswordTokenService = resetPasswordTokenFactory.GetResetPasswordTokenService(_account);
                SetConnection(resetPasswordTokenService);

                resetPasswordTokenService.lockedUpMemberPolicy = lockedUpMemberPolicy;

                var token = resetPasswordTokenService.GenerateResetPasswordToken(_account, applicationStore, "");

                var _tokenCode = token.Code.EncodeURIComponent();

                svcEmail.SendEmailUserCreatedByAccountAdminAsync(_account, _tokenCode, "");
            }
        }
コード例 #18
0
        private bool addAdminCenter(AdminClientViewModel newCenter, int centerID)
        {
            ApplicationUser admin = new ApplicationUser()
            {
                Name         = newCenter.AdminName,
                UserName     = newCenter.Username,
                PasswordHash = newCenter.Password,
                PhoneNumber  = newCenter.Phone,
                Email        = newCenter.Email
            };

            ApplicationDbContext DBContext = new ApplicationDbContext();
            ApplicationStore     store     = new ApplicationStore(DBContext);
            ApplicationManager   manager   = new ApplicationManager(store);
            IdentityResult       Result    = manager.CreateAsync(admin, newCenter.Password).Result;
            var RoleResult = manager.AddToRoleAsync(admin.Id, "CenterAdmin").Result;

            if (Result.Succeeded)
            {
                IAuthenticationManager authentication          = HttpContext.GetOwinContext().Authentication;
                SignInManager <ApplicationUser, string> signIn = new SignInManager <ApplicationUser, string>(manager, authentication);
                signIn.SignIn(admin, false, false);
                // add admin info to center admin table
                CenterAdmin centerAdmin = new CenterAdmin()
                {
                    UserID   = admin.Id,
                    NID      = newCenter.NID,
                    CenterID = centerID,

                    NiDImage = newCenter.NID,
                };
                context.CenterAdmins.Add(centerAdmin);
                context.SaveChanges();
                return(true);
            }
            else
            {
                string error = "";
                foreach (var err in Result.Errors)
                {
                    error += err + " ";
                }
                ModelState.AddModelError("", error);
                return(false);
            }
        }
コード例 #19
0
ファイル: SplashView.cs プロジェクト: ResaloliPT/HydroModTool
        public SplashView(IConfigurationService configurationService)
        {
            InitializeComponent();

            pictureBox2.Parent = this.pictureBox1;
            pictureBox2.BringToFront();

            label1.Parent = this.pictureBox1;
            label1.BringToFront();

            loadingLabel.Parent = this.pictureBox1;
            loadingLabel.BringToFront();

            loadingWorker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                loadingWorker.ReportProgress(1, new LoadingWorkerStage("Loading Configuration"));

                var config = configurationService.GetAsync().Result;

                ApplicationStore.RefreshStore(config).Wait();
            };

            loadingWorker.ProgressChanged += (sender, e) =>
            {
                loadingLabel.Text = ((LoadingWorkerStage)e.UserState) !.Phase;
            };
            loadingWorker.RunWorkerCompleted += (sender, e) =>
            {
                loadingLabel.Text = @"Starting App";

                splashTimer.Enabled = true;
                splashTimer.Start();
            };

            splashTimer.Tick += (sender, e) =>
            {
                splashTimer.Enabled = false;
                splashTimer.Stop();

                TimeOutEvent?.Invoke();
                Close();
            };

            loadingWorker.RunWorkerAsync();
        }
コード例 #20
0
        public IEnumerable <Account> Get(string login, ApplicationStore applicationStore, bool?status = null)
        {
            IEnumerable <Account> _result = null;

            _result = GetEmail(login);

            if (_result.Count() == 0)
            {
                _result = GetDocument(login);
            }

            if (_result.Count() == 0)
            {
                _result = GetLogin(login);
            }

            return(_result);
        }
コード例 #21
0
        /// <summary>
        /// Check if the specified client ID is valid.
        /// </summary>
        /// <param name="context">The authorization endpoint specific context.</param>
        /// <returns>A <see cref="Task{Application}"/> whose result represents the specified client ID specific application. </returns>
        /// <exception cref="ArgumentNullException">Specified <paramref name="context"/> is null.</exception>
        protected virtual async Task <Application> ValidateClientIdAsync(OAuthContext context)
        {
            Guard.ArgumentNotNull(context, nameof(context));
            var clientId = ((context as AuthorizationContext)?.ClientId)
                           ?? (context as TokenContext)?.ClientId;

            if (string.IsNullOrEmpty(clientId))
            {
                return(null);
            }
            var application = await ApplicationStore.GetByClientIdAsync(clientId);

            if (null == application)
            {
                context.Failed(OAuthErrors.UnauthorizedClient.UnregisteredApplication, clientId);
            }
            return(application);
        }
コード例 #22
0
        public bool Validate(Account account, ApplicationStore applicationStore, bool throwException = true)
        {
            bool valid = true;

            if (!account.BlacklistCollection.IsNull() && account.BlacklistCollection.Count > 0)
            {
                if (account.BlacklistCollection.Any(b => (b.StoreCode == null || b.StoreCode.IsEmpty()) && b.Blocked) || account.BlacklistCollection.Any(b => b.StoreCode == applicationStore.Store.Code && b.Blocked))
                {
                    valid = false;
                }

                if (throwException && !valid)
                {
                    throw new LockedUpMemberException(account, "member '{0}' is blocked.");
                }
            }

            return(valid);
        }
コード例 #23
0
 public void PrimeApplicationStore()
 {
     if (!File.Exists(ApplicationStoreFilePath))
     {
         ApplicationStore AppStore = new ApplicationStore();
         AppStore.App_id      = "28198d27-c475-4695-83d3-1f1f8256e01b";
         AppStore.App_secret  = "1c73a74b-45fc-4ee4-a400-15a398e46143";
         AppStore.App_Version = "1.0";
         AppStore.UserList    = new List <UserAccount>();
         try
         {
             XmlStoreHelper.ToXmlFile(AppStore, ApplicationStoreFilePath);
         }
         catch (Exception exec)
         {
             throw new FieldAccessException($"Unable to create file on prime at {ApplicationStoreFilePath} ", exec);
         }
     }
 }
コード例 #24
0
        private Account CreateConnect(IEnumerable <Account> accounts, ApplicationStore applicationStore, string password = "", bool isSave = false)
        {
            Account account = null;

            if (!accounts.IsNull() && accounts.Count() > 0)
            {
                for (int i = 0; i < accounts.Count(); i++)
                {
                    account = accounts.ElementAt(i);

                    if ((!password.IsNullOrWhiteSpace() && account.Password.Equals(password.Encrypt())) ||
                        (password.IsNullOrWhiteSpace() && applicationStore.Application.MemberType == Domain.Enums.MemberType.Consumer &&
                         (!account.Document.IsNullOrWhiteSpace() || !account.Customer.IsNull())))
                    {
                        //connect account to store
                        var role = roleRepository.GetByApplication(applicationStore.ApplicationCode, applicationStore.StoreCode);
                        if (!role.IsNull())
                        {
                            account.ConnectRole(role);
                        }

                        //connect account to store
                        var app = applicationStoreRepository.Get(applicationStore.Code);
                        account.ConnectApp(app);

                        break;
                    }
                    else if (account.AccountApplicationStoreCollection.Any(appSto => appSto.ApplicationStore.Application != null && appSto.ApplicationStore.Application.MemberType == MemberType.Merchant) && isSave)
                    {
                        throw new ArgumentException("E-mail já cadastrado");
                    }
                    else
                    {
                        account = null;
                    }
                }
            }

            return(account);
        }
コード例 #25
0
        public Account Get(string login, ApplicationStore applicationStore, string password = "")
        {
            Account account  = accPermissionService.Get(login, applicationStore).FirstOrDefault();
            Account _account = null;

            if (!password.IsNullOrWhiteSpace() && !account.IsNull() && !account.Password.Equals(password.Encrypt()))
            {
                _account = account;
                account  = null;
            }

            //dont has connect
            if (account.IsNull() &&
                (applicationStore.Application.MemberType == Domain.Enums.MemberType.Consumer || applicationStore.Application.Name.ToLower() == "mp-accounts"))
            {
                var accounts = accPermissionService.Get(login, applicationStore);

                account = CreateConnect(accounts, applicationStore, password);

                if (!password.IsNullOrWhiteSpace() && accounts.Count() > 0 && account.IsNull())
                {
                    accounts.ToList().ForEach(acc =>
                    {
                        if (acc.Code != _account.Code && lockedUpMemberPolicy.Validate(acc, false) && lockedUpMemberPolicy.Validate(acc, applicationStore, false))
                        {
                            acc.WrongLoginAttempt(lockedUpMemberPolicy, lockMemberPolicy);
                            Update(acc);
                        }
                    });
                }
            }

            if (account.IsNull() && !_account.IsNull())
            {
                account = _account;
            }

            return(account);
        }
コード例 #26
0
        public ActionResult AdminRegisteration(AdminRegisterationViewModel userAdmin)
        {
            if (!ModelState.IsValid)
            {
                return(View(userAdmin));
            }
            ApplicationUser admin = new ApplicationUser()
            {
                Name         = userAdmin.Name,
                UserName     = userAdmin.Username,
                Gender       = userAdmin.Gender.ToString(),
                PasswordHash = userAdmin.Password,
                PhoneNumber  = userAdmin.Phone,
                Email        = userAdmin.Email
            };

            ApplicationDbContext DBContext = new ApplicationDbContext();
            ApplicationStore     store     = new ApplicationStore(DBContext);
            ApplicationManager   manager   = new ApplicationManager(store);
            IdentityResult       Result    = manager.CreateAsync(admin, userAdmin.Password).Result;
            var RoleResult = manager.AddToRoleAsync(admin.Id, "Admin").Result;

            if (Result.Succeeded)
            {
                IAuthenticationManager authentication          = HttpContext.GetOwinContext().Authentication;
                SignInManager <ApplicationUser, string> signIn = new SignInManager <ApplicationUser, string>(manager, authentication);
                return(RedirectToAction("Index", "Home"));
            }

            string error = "";

            foreach (var err in Result.Errors)
            {
                error += err + " ";
            }
            ModelState.AddModelError("", error);
            return(View(userAdmin));
        }
コード例 #27
0
        public void Process()
        {
            var requisitions = requisitionRepository.GetStatusAndSetProcessing(RequisitionStatus.Pending);

            requisitions.ForEach(requisition =>
            {
                RequisitionStatus status;

                try
                {
                    var requisitionProcesssing = context.ResolveNamed <IRequisitionProcessingService>(requisition.RequisitionType.ToLower());

                    ApplicationStore appSto = null;

                    if (requisition.RequisitionType == RequisitionType.ImportInternalAccounts)
                    {
                        requisitionProcesssing.ImportCustomerToImportDb(requisition);
                        appSto = requisitionProcesssing.GetApplicationStore(requisition.Store.Code);
                    }

                    int skip          = 0;
                    object[] accounts = null;

                    do
                    {
                        if (!accounts.IsNull())
                        {
                            skip += accounts.Count() == Config.ProcessImportNumberRecordsPerCommit ? Config.ProcessImportNumberRecordsPerCommit : accounts.Count();
                        }

                        accounts = requisitionProcesssing.GetAccounts(requisition, skip, Config.ProcessImportNumberRecordsPerCommit);

                        Parallel.ForEach(accounts,
                                         new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = Config.ProcessImportMaxDegreeOfParallelism
                        },
                                         account =>
                        {
                            using (var scope = ((ILifetimeScope)context).BeginLifetimeScope())
                            {
                                var currentRequisitionProcesssing = scope.ResolveNamed <IRequisitionProcessingService>(requisition.RequisitionType.ToLower());

                                bool isValid = false;

                                using (var connection = scope.Resolve <IConnection>())
                                    using (var transacton = connection.BeginTransaction())
                                    {
                                        try
                                        {
                                            isValid = currentRequisitionProcesssing.SaveAccount(requisition, account, appSto, connection);

                                            if (isValid)
                                            {
                                                transacton.Commit();
                                            }
                                            else
                                            {
                                                transacton.Rollback();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            if (!ex.InnerException.IsNull() && !ex.InnerException.Message.IsNullorEmpty())
                                            {
                                                requisition.RequisitionErrors.Add(new RequisitionError()
                                                {
                                                    ErrorMessages = new List <string>()
                                                    {
                                                        ex.InnerException.ToString()
                                                    }
                                                });
                                            }
                                            else
                                            {
                                                requisition.RequisitionErrors.Add(new RequisitionError()
                                                {
                                                    ErrorMessages = new List <string>()
                                                    {
                                                        ex.ToString()
                                                    }
                                                });
                                            }

                                            transacton.Rollback();
                                        }
                                    }
                            }
                        });
                    }while (requisition.RequisitionType == RequisitionType.ImportInternalAccounts && !accounts.IsNull() && accounts.Count() > 0);

                    using (var transaction = Connection.BeginTransaction())
                    {
                        requisition.Store = storeRepository.Get(requisition.Store.Code);

                        requisitionRepository.Save(requisition);

                        if (requisition.RequisitionType == RequisitionType.ImportInternalAccounts)
                        {
                            requisitionProcesssing.ClearImportDb(requisition);
                        }
                    }
                }
                catch (Exception ex)
                {
                    requisition.RequisitionErrors.Add(new RequisitionError()
                    {
                        ErrorMessages = new List <string>()
                        {
                            "Erro desconhecido, tente importar novamente!",
                            ex.Message,
                            ex.StackTrace
                        }
                    });
                }

                using (var transaction = Connection.BeginTransaction())
                {
                    status = requisition.RequisitionErrors.Count > 0 ? RequisitionStatus.Failure : RequisitionStatus.Success;

                    requisitionService.UpdateStatus(requisition, status);
                }
            });
        }
コード例 #28
0
ファイル: PathMgr.cs プロジェクト: tah182/Comet
        public IList<Line> getPoints(string vendor, decimal bottomLeftLat, decimal bottomLeftLng, decimal topRightLat, decimal topRightLng, int zoom)
        {
            //double tolerance = Math.Pow(zoom, -(zoom / 5));

            IList<Line> coordinates;
            IList<Line> returnLine;
            coordinates = returnLine = new List<Line>();

            if (vendor.Equals("level3"))
                coordinates = this.svc.getPoints(vendor, bottomLeftLat, bottomLeftLng, topRightLat, topRightLng);
            else {
                if (vendorPoints != null && vendorPoints.Data != null)
                    vendorPoints.Data.TryGetValue(vendor, out coordinates);
                if (vendorPoints == null)
                    vendorPoints = new ApplicationStore<Dictionary<string, IList<Line>>>(MainFactory.getCacheExpiration(), new Dictionary<string, IList<Line>>());
                if (coordinates == null || coordinates.Count() < 1) {
                    coordinates = this.svc.getPoints(vendor, (decimal)26.4, (decimal)-132.1, (decimal)49.4, (decimal)-59.1);
                    if (!vendorPoints.Data.ContainsKey(vendor)) {
                        vendorPoints.Data.Add(vendor, coordinates);
                        HttpContext.Current.Application["gisFiber"] = vendorPoints;
                    }
                }
            }

            if (zoom <= 12) {
                foreach (Line line in coordinates) {
                    DouglasPeuckerReduction dpr = new DouglasPeuckerReduction(line.Coordinates);
                    if (!vendor.Equals("level3")) {             // if it is a GIS vendor, filter out unnecessary coordinates
                        if (!isOutsideBounds(line, bottomLeftLat, bottomLeftLng, topRightLat, topRightLng)) {
                            var l = new Line(line.Name, dpr.reduceLine(zoom));
                            l.Color = vendorNames.Data[line.Name].ColorHex;
                            returnLine.Add(l);
                        }
                    } else {
                        var l = new Line(line.Name, dpr.reduceLine(zoom));
                        l.Color = "#f00";
                        returnLine.Add(l);
                    }
                }
            } else {
                if (!vendor.Equals("level3")) {             // if it is a GIS vendor, filter out unnecessary coordinates
                    foreach (Line line in coordinates
                                                .Where(x =>
                                                    x.Coordinates.Any(y =>
                                                        y.Lat >= bottomLeftLat &&
                                                        y.Lat <= topRightLat &&
                                                        y.Lng >= bottomLeftLng &&
                                                        y.Lng <= topRightLng))) {
                        var l = new Line(line.Name, line.Coordinates);
                        l.Color = vendorNames.Data[line.Name].ColorHex;
                        returnLine.Add(l);
                    }
                } else {
                    foreach (Line line in coordinates) {
                        var l = new Line(line.Name, line.Coordinates);
                        l.Color = "#f00";
                        returnLine.Add(l);
                    }
                }
            }

            return returnLine;
        }
コード例 #29
0
ファイル: EmployeeMgr.cs プロジェクト: tah182/Comet
 public void refresh()
 {
     this.employeeList = new ApplicationStore<IList<Employee>>(MainFactory.getCacheExpiration(), this.repository.getAllEmployees().Cast<Employee>().ToList());
     HttpContext.Current.Application["Employee"] = employeeList;
     this.groupManagerList = new ApplicationStore<IList<GroupManager>>(MainFactory.getCacheExpiration(), this.repository.getAllGroupManagers().Cast<GroupManager>().ToList());
     HttpContext.Current.Application["GroupManager"] = groupManagerList;
     this.directorList = new ApplicationStore<IList<Director>>(MainFactory.getCacheExpiration(), this.repository.getAllDirectors().Cast<Director>().ToList());
     HttpContext.Current.Application["Director"] = directorList;
 }
コード例 #30
0
ファイル: PathMgr.cs プロジェクト: tah182/Comet
 public void refresh()
 {
     if (this.svc.GetType() == typeof(PathSvcImplGIS)) {
         this.vendorNames = new ApplicationStore<Dictionary<string, FiberVendorDetails>>(MainFactory.getCacheExpiration(), this.svc.getFiberVendors());
         HttpContext.Current.Application["gisVendorNames"] = vendorNames;
     }
 }
コード例 #31
0
        public bool SaveAccount(Requisition requisition, Object account, ApplicationStore applicationStore, IConnection connection)
        {
            var fileRequisition = requisition as FileRequisition;

            var line = (string)account;

            var  properties = line.Split(new char[] { '\t' });
            var  message    = new List <string>();
            bool isValid    = true;

            try
            {
                var result = customerImportFileInfraService.ValidCustomer(properties, fileRequisition);

                if (result.Item1)
                {
                    CustomerImport customer    = result.Item3;
                    var            clientValid = customer.isValid();

                    if (clientValid.Item1)
                    {
                        try
                        {
                            if (customer is CompanyImport)
                            {
                                var company = (CompanyImport)customer;
                            }
                            else
                            {
                                var person = (PersonImport)customer;
                            }
                        }
                        catch (Exception ex)
                        {
                            isValid = false;
                            message.Add(ex.Message);
                        }

                        if (isValid)
                        {
                            if (!IsMemberExists(customer))
                            {
                                customerImportRepository.Save(customer);
                            }
                            else
                            {
                                isValid = false;
                                message.Add("Usuário já existe");
                            }
                        }
                    }
                    else
                    {
                        isValid = false;
                        message.AddRange(clientValid.Item2);
                    }
                }
                else
                {
                    isValid = false;
                    message.AddRange(result.Item2);
                }
            }
            catch (Exception ex)
            {
                isValid = false;
                message.Add(string.Format("{0}", ex.TrimMessage()));
            }

            if (!isValid)
            {
                requisition.RequisitionErrors.Add(new RequisitionError()
                {
                    Code          = Guid.NewGuid(),
                    ErrorMessages = message,
                    Email         = properties.Count() > ConstantsFileImport.Email ? properties[ConstantsFileImport.Email] : string.Empty,
                    Name          = properties.Count() > ConstantsFileImport.FirstName ? properties[ConstantsFileImport.FirstName] : string.Empty
                });
            }

            return(isValid);
        }
コード例 #32
0
 public bool Authenticate(string clientId, string clientSecret, string reqOrigin, out string message, out ApplicationStore applicationStore)
 {
     return(applicationStoreService.Authenticate(clientId, clientSecret, reqOrigin, out message, out applicationStore));
 }
コード例 #33
0
ファイル: UserMgr.cs プロジェクト: tah182/Comet
 public void refresh()
 {
     this.userList = new ApplicationStore<IList<IUser>>(MainFactory.getCacheExpiration(), this.svc.getAllUsers());
     var temp = userList.Data.Where(x => x.AcknowledgedUpdateNotes).ToList();
     HttpContext.Current.Application["Users"] = userList;
 }
コード例 #34
0
ファイル: RequestMgr.cs プロジェクト: tah182/Comet
        public void refresh()
        {
            this.elementStatusList = new ApplicationStore<IList<LookupSorted>>(MainFactory.getCacheExpiration(), this.svc.getElementStatus());
            HttpContext.Current.Application.Lock();
            HttpContext.Current.Application["ElementStatus"] = this.elementStatusList;

            this.requestStatusList = new ApplicationStore<IList<LookupSorted>>(MainFactory.getCacheExpiration(), this.svc.getRequestStatus());
            HttpContext.Current.Application["RequestStatus"] = this.requestStatusList;

            this.projectStatusList = new ApplicationStore<IList<LookupSorted>>(MainFactory.getCacheExpiration(), this.svc.getProjectStatus());
            HttpContext.Current.Application["ProjectStatus"] = this.projectStatusList;

            List<RequestView> requests = new List<RequestView>();

            this.requestList = new ApplicationStore<IList<RequestView>>(MainFactory.getCacheExpiration(), new List<RequestView>());

            IList<ELEMENT> elements = this.svc.getElements();
            IList<NOTE> notes = this.svc.getNotes();
            IList<ProjectView> projects = new List<ProjectView>();
            foreach (PROJECT project in this.svc.getProjects())
                projects.Add(convertProject(project));
            foreach (REQUEST r in this.svc.getRequests()) {
                RequestView rv = convertRequest(r);
                this.requestList.Data.Add(rv);

                // pointer to parent project
                rv.Parent = r.PARENT_PROJECT_ID == null ? null : projects.Where(x => x.ID == r.PARENT_PROJECT_ID).FirstOrDefault();
                if (rv.Parent != null)
                    rv.Parent.RequestList.Add(rv);

                // pointer to child elements
                foreach (ELEMENT e in elements.Where(x => x.PARENT_REQUEST_ID == rv.ID)) {
                    ElementView ev = convertElement(e);
                    ev.Parent = rv;
                    rv.ElementList.Add(ev);

                    // pointer to notes
                    foreach (NOTE n in notes.Where(x => x.ELEMENT_ID == ev.ID)) {
                        Note nv = convertNote(n);
                        nv.Parent = ev;
                        ev.addNote(nv);
                    }
                }
            }
            HttpContext.Current.Application["Request"] = this.requestList;
            HttpContext.Current.Application.UnLock();
        }
コード例 #35
0
        public Account Get(Guid accountCode, ApplicationStore applicationStore, bool includeMetadata = false, bool includeRole = false, bool includeBlacklist = false, bool includeApplication = false)
        {
            IQueryable <Account> account = accPermissionRep.Get(accountCode, includeMetadata, includeRole, includeBlacklist, includeApplication);

            return(Get(account, applicationStore).FirstOrDefault());
        }
コード例 #36
0
        public Account Get(Guid accountCode, ApplicationStore applicationStore, bool includeMetadata = false, bool includeRole = false, bool includeBlacklist = false, bool includeApplication = false)
        {
            Account account = accPermissionService.Get(accountCode, applicationStore, includeMetadata: includeMetadata, includeRole: includeRole, includeBlacklist: includeBlacklist, includeApplication: includeApplication);

            return(account);
        }
コード例 #37
0
        public IEnumerable <Account> CheckEmailAndDocument(string email, string document, ApplicationStore applicationStore, bool throwException)
        {
            List <Account> accounts = accountRepository.Get(email, null, null).ToList();

            accounts.ForEach(account =>
            {
                if (account.Document != document && throwException)
                {
                    throw new ArgumentException("E-mail, CPF ou CNPJ já cadastrados com outros dados");
                }
            });

            if (!document.IsNullOrWhiteSpace())
            {
                var accountsDocument = accountRepository.Get(document, null, null).ToList();

                accountsDocument.ForEach(account =>
                {
                    if (account.Email != email && throwException)
                    {
                        throw new ArgumentException("E-mail, CPF ou CNPJ já cadastrados com outros dados");
                    }
                });

                if (accountsDocument.Count() > 0)
                {
                    accounts.AddRange(accountsDocument);
                }
            }

            return(accounts);
        }
コード例 #38
0
        public List <Account> Get(string login, ApplicationStore applicationStore, bool includeMetadata = false, bool includeRole = false, bool includeBlacklist = false, bool includeApplication = false)
        {
            IQueryable <Account> account = accPermissionRep.Get(login, includeMetadata: includeMetadata, includeRole: includeRole, includeBlacklist: includeBlacklist, includeApplication: includeApplication);

            return(Get(account, applicationStore));
        }
コード例 #39
0
ファイル: LookupMgr.cs プロジェクト: tah182/Comet
        public void refresh()
        {
            this.supportAreaList = new ApplicationStore<IList<SupportArea>>(MainFactory.getCacheExpiration(), this.svc.getSupportAreas().OrderBy(x => x.Text).ToList());
            this.supportUnitList = new ApplicationStore<IList<ALookup>>(MainFactory.getCacheExpiration(), this.svc.getSupportUnits().OrderBy(x => x.Text).ToList());
            this.requestTypeList = new ApplicationStore<IList<LookupActive>>(MainFactory.getCacheExpiration(), this.svc.getRequestTypes().OrderBy(x => x.Text).ToList());
            this.projectTypeList = new ApplicationStore<IList<LookupActive>>(MainFactory.getCacheExpiration(), this.svc.getProjectTypes().OrderBy(x => x.Text).ToList());
            this.requestCategoryList = new ApplicationStore<IList<LookupActive>>(MainFactory.getCacheExpiration(), this.svc.getRequestCategories().OrderBy(x => x.Text).ToList());
            this.valueDriverList = new ApplicationStore<IList<ALookup>>(MainFactory.getCacheExpiration(), this.svc.getValueDrivers().OrderBy(x => x.Text).ToList());
            this.programList = new ApplicationStore<IList<ALookup>>(MainFactory.getCacheExpiration(), this.svc.getPrograms().OrderBy(x => x.Text).ToList());

            HttpContext.Current.Application["SupportArea"] = supportAreaList;
            HttpContext.Current.Application["SupportUnit"] = supportUnitList;
            HttpContext.Current.Application["RequestType"] = requestTypeList;
            HttpContext.Current.Application["ProjectType"] = projectTypeList;
            HttpContext.Current.Application["RequestCategory"] = requestCategoryList;
            HttpContext.Current.Application["ValueDriver"] = valueDriverList;
            HttpContext.Current.Application["Program"] = programList;
        }
コード例 #40
0
ファイル: BuildingMgr.cs プロジェクト: tah182/Comet
        public void refresh()
        {
            this.sdpAssetList = new ApplicationStore<IList<IBuilding>>(MainFactory.getCacheExpiration(), this.svc.getBuildings());
            this.entranceFacilityList = new ApplicationStore<IList<EntranceFacility>>(MainFactory.getCacheExpiration(), this.svc.getEntranceFacilities());
            this.trendList = new ApplicationStore<IList<SDP_TREND>>(MainFactory.getCacheExpiration(), this.svc.getSDPTrend(TREND_WEEKS));

            HttpContext.Current.Application["sdpAsset"] = sdpAssetList;
            HttpContext.Current.Application["entranceFacility"] = entranceFacilityList;
            HttpContext.Current.Application["trendList"] = trendList;
            this.svc.close();
        }
コード例 #41
0
        public List <Account> Get(IQueryable <Account> account, ApplicationStore applicationStore)
        {
            List <Account> result = null;

            if (!account.IsNull())
            {
                if (applicationStore.Application.MemberType == MemberType.Consumer)
                {
                    var _accounts = account.ToList();

                    if (!_accounts.IsNull())
                    {
                        _accounts.ForEach(acc =>
                        {
                            if (lockedUp.Validate(acc, false) &&
                                acc.Status == true &&
                                acc.Removed == false &&
                                (!acc.Document.IsNullOrWhiteSpace() || !acc.Customer.IsNull()))
                            {
                                acc.ConnectApp(applicationStore);
                            }
                        });

                        result = _accounts;
                    }
                }
                else if (applicationStore.Application.AuthType == AuthType.Distributed)
                {
                    result = account.Where(a =>
                                           a.AccountRoles.Any(ar =>
                                                              ar.Status == true &&
                                                              ar.Role.Status == true &&
                                                              ar.Role.StoreCode == applicationStore.StoreCode && ar.Role.Store.Status == true &&
                                                              ar.Role.Permissions.Any(
                                                                  p =>
                                                                  p.Status == true &&
                                                                  p.Resource.ApplicationCode == applicationStore.ApplicationCode &&
                                                                  p.Resource.Application.Status == true
                                                                  )
                                                              )
                                           ).ToList();
                }
                else if (applicationStore.Store.IsMain)
                {
                    result = account.Where(a =>
                                           a.AccountRoles.Any(ar =>
                                                              ar.Status == true &&
                                                              ar.Role.Status == true &&
                                                              ar.Role.Store.Status == true &&
                                                              ar.Role.Permissions.Any(
                                                                  p =>
                                                                  p.Status == true &&
                                                                  p.Resource.ApplicationCode == applicationStore.ApplicationCode &&
                                                                  p.Resource.Application.Status == true
                                                                  )
                                                              )
                                           ).ToList();
                }
            }

            return(result);
        }
コード例 #42
0
ファイル: YourAppInitializer.cs プロジェクト: ElysiumLabs/Gem
 public YourAppInitializer(GemAppOptions appOptions, ApplicationStore applicationStore, ViewModelBaseServices viewModelBaseServices) : base(appOptions, applicationStore, viewModelBaseServices)
 {
 }
コード例 #43
0
 public ChatHub(ApplicationStore store, UserManager <IdentityUser> userManager)
 {
     _store       = store;
     _userManager = userManager;
 }