Beispiel #1
0
        protected override void DoHostInternal(object context)
        {
            if (_config == null)
            {
                throw new OperationException("Сервис не был сконфигурирован");
            }

            BLHelper.InitBL(dalType: DALType.Oracle);
            Authenticate();
            BLHelper.FillInitialCaches();

            CreateReportDirectoryIfNotExists();
            CreateArchiveDirectoryIfNotExists();

            if (!EPS.wmsEPS.Properties.Settings.Default.UseLocalReport)
            {
                Log.Info("CheckOut reports to local directory");
                var checkOut = new EpsCheckOut();
                checkOut.CheckOut();
            }

            var schedulerFactory = new StdSchedulerFactory();

            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.Start();

            AddProcessOutputQueueJob();

            Log.Info("EPSService started");
        }
        public void Setup()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);
//            BLHelper.RegisterServiceClient(Properties.Settings.Default.SessionId, Properties.Settings.Default.SDCL_Endpoint);
//            var auth = IoC.Instance.Resolve<IAuthenticationProvider>();
//            auth.Authenticate("DEBUG", "DEBUG");
        }
Beispiel #3
0
        public override void Run()
        {
            base.Run();

            // Настраиваем ImageSelector
            InitImageSelectorStrategies();

            // Настраиваем механизм сохранения настроек
            InitSaveRestoreStrategies();

            // Важно: стили нужно настраивать после отображения начальных форм. Иначе меню объектов не подхватит стиль
            InitDevexpress();

            LoadApplicationResource("/wmsMLC.DCL.Main;Component/Themes/Generic.xaml");

            // прогрузим инициализаторы DevExp
            //Убрал из-за ошибок при открытии Аналитики DevExpress 15.2.9
            //Не удалось привести тип объекта "DevExpress.Xpf.Bars.PopupMenuInfo" к типу "DevExpress.Xpf.Bars.PopupInfo`1[DevExpress.Xpf.Bars.PopupControlContainer]".
            //ImproveUIPerformance();

            //Подпишем кого надо на события
            BLHelper.SubscribeEvents();

            ConfigureNewDal();

            //Загрузим начальные кэши
            //BLHelper.FillInitialCaches();
        }
Beispiel #4
0
        private void InvoiceForm_Load(object sender, EventArgs e)
        {
            APCContext = new APCEntities();

            List <Project> projectList = BLProject.GetAllProject(APCContext);

            ddlProject.DataSource    = projectList;
            ddlProject.DisplayMember = "Name";
            ddlProject.ValueMember   = "Id";

            dgInvoiceProduct.AutoGenerateColumns = false;
            dgInvoiceProduct.DataSource          = createInvoiceProductTable();
            //dgInvoiceProduct.Columns.Remove("Name");
            //dgInvoiceProduct.Columns.Remove("Kurs");
            //dgInvoiceProduct.Columns.Remove("SubCon");

            DataGridViewComboBoxColumn colName = BLHelper.ReturnDataGridComboBoxColumn("Name", "Name", "Name", "Name");

            colName.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
            colName.DataSource   = APCContext.Category;

            DataGridViewComboBoxColumn colKurs = BLHelper.ReturnDataGridComboBoxColumn("Name", "Name", "Name", "Name");

            colName.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet;
            colKurs.DataSource   = APCContext.Kurs;

            DataGridViewCheckBoxColumn colSubCon = BLHelper.ReturnDataGridCBColumn("SubCon");

            //dgInvoiceProduct.Columns.Insert(0, colName);
            //dgInvoiceProduct.Columns.Insert(5, colKurs);
            dgInvoiceProduct.Columns.Add(colName);
            dgInvoiceProduct.Columns.Add(colKurs);
            dgInvoiceProduct.Columns.Add(colSubCon);
        }
        public virtual void Setup()
        {
            if (_initialized)
            {
                return;
            }

            //ConfigurationManager.AppSettings["BLToolkit.DefaultConfiguration"] = "DEV";

            IAuthenticationProvider auth;

            if (!IoC.Instance.TryResolve <IAuthenticationProvider>(out auth))
            {
                BLHelper.InitBL(dalType: DALType.Oracle);
            }

            //BLHelper.InitBL(dalType: DALType.Service);
            //BLHelper.RegisterServiceClient("Auto", ClientTypeCode.DCL, Properties.Settings.Default.SDCL_Endpoint);

            if (auth == null)
            {
                auth = IoC.Instance.Resolve <IAuthenticationProvider>();
            }
            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");

            //BLHelper.FillInitialCaches();

            _initialized = true;
        }
Beispiel #6
0
        protected override void DoHostInternal(object context)
        {
            // выставим среду, если указана
            var env = Context.Get(ConfigBase.EnvironmentParam);

            ConfigurationManager.AppSettings["BLToolkit.DefaultConfiguration"] = string.IsNullOrEmpty(env) ? "DEV" : env;

            // явно инициализируем Oracle - чтобы не было ни каких накладок
            BLHelper.InitBL(dalType: DALType.Oracle);

            // аутентифицируемся
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate(ConfigurationManager.AppSettings["Login"], ConfigurationManager.AppSettings["Password"]);

            // запрашиваем данные сразу
            BLHelper.FillInitialCaches();

            FreeScheduler();
            _scheduler = new EpsScheduler();

            FreeTimer();
            _timer = new Timer(Tick);

            _date0 = DateTime.Now;
            Log.Info("Service was initialized");

            _timer.Change(0, _timerPeriod); // стартуем сразу, а потом через период
            Log.Info("Service was started");
        }
Beispiel #7
0
        public void Test()
        {
            var mgr = CreateManager() as IUserManager;

            BLHelper.FillInitialCaches();
            var res = mgr.GetUserRights("DEBUG");
        }
Beispiel #8
0
        public void Setup()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate(Login, "DEBUG");
        }
Beispiel #9
0
        public void Setup()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");
        }
Beispiel #10
0
        protected void Application_Start()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate(Settings.Default.ServiceUserName, Settings.Default.ServicePassword);

            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
        public virtual void Setup()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);
            //            BLHelper.InitBL(dalType: DALType.Service);
            //            BLHelper.RegisterServiceClient("Auto", "net.tcp://localhost:8035/wmsSDCLService");
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");
            // тестируем валидацию - ValidatorFactory вместо EmptyValidatorFactory
            IoC.Instance.Register <IValidatorFactory, ValidatorFactory>(LifeTime.Singleton);
        }
Beispiel #12
0
        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            Log.Debug("Start configure Main");

            //Настраиваем Business Layer (Пока тут)
            BLHelper.InitBL(new IoCConfigurationContext {
                ExternalContainer = Container
            }, DALType.Service);

            //Регистрируем клиента для сервиса
            var clienttypecode = Settings.Default.ClientType.To(ClientTypeCode.None);

            if (clienttypecode == ClientTypeCode.None)
            {
                throw new DeveloperException("ClientType '{0}' is undefined.", clienttypecode);
            }
            BLHelper.RegisterServiceClient(Settings.Default.SessionId, clienttypecode, Settings.Default.SDCL_Endpoint);

            // подписываемся на обработку ошибок
            ExceptionPolicy.Instance.ExceptionOccure += OnExceptionOccure;

            // регистрируем Shell
            Container.RegisterType <Shell>(new ContainerControlledLifetimeManager()).RegisterType <IShell, Shell>();

            // отрабатываем PRISM
            //var shell = (DependencyObject)Container.Resolve<IShell>();
            //RegionManager.SetRegionManager(shell, Container.Resolve<IRegionManager>());

            Log.Debug("50% configure Main");

            // регистрируем сервисы
            Container.RegisterType <IViewService, ViewService>(new ContainerControlledLifetimeManager());

            // регистрируем помощника по SQL (когда появися MS SQL нужно будет подменить)
            Container.RegisterType <ISqlExpressionHelper, SqlExpressionHelper>(new ContainerControlledLifetimeManager());

            // регистрируем главную форму
            Container.RegisterInstance(typeof(MainView), Container.Resolve <MainView>(), new ContainerControlledLifetimeManager());

            // стартуем Caliburn
            var caliburnBootstrapper = new CaliburnBootstrapper(Container);

            caliburnBootstrapper.Start();

            // регистрируем главный регион
            //var regionManager = Container.Resolve<IRegionManager>();
            //regionManager.AddToRegion(RegionNames.MainRegion, Container.Resolve<MainView>());

            IoC.Instance.Register <IAuthenticationViewModel, AuthenticationViewModel>();

            Log.Debug("End configure Main");
        }
Beispiel #13
0
        public async Task <bool> RegisterByPhoneNumber(string phoneNumber)
        {
            try
            {
                var AuthenticationCode = BLHelper.GenerateRandomNumber(1000, 9999).ToString();
                var smsResult          = BLHelper.SendSMS(phoneNumber, "کد چهار رقمی احراز هویت :" + "\n" + AuthenticationCode);

                //if (smsResult == 10) //Delivered
                //{
                //    //1   در صف ارسال قرار دارد.
                //    //2   زمان بندی شده(ارسال در تاریخ معین).
                //    //4   ارسال شده به مخابرات.
                //    //5   ارسال شده به مخابرات(همانند وضعیت 4)
                //    //6   خطا در ارسال پیام که توسط سر شماره پیش می آید و به معنی عدم رسیدن پیامک می باشد(Failed)
                //    //10  رسیده به گیرنده(Delivered)
                //    //11  نرسیده به گیرنده ،این وضعیت به دلایلی از جمله خاموش یا خارج از دسترس بودن گیرنده اتفاق می افتد(Undelivered)
                //    //13  ارسال پیام از سمت کاربر لغو شده یا در ارسال آن مشکلی پیش آمده که هزینه آن به حساب برگشت داده میشود.
                //    //14  بلاک شده است،عدم تمایل گیرنده به دریافت پیامک از خطوط تبلیغاتی که هزینه آن به حساب برگشت داده میشود
                //    //100 شناسه پیامک نامعتبر است.(به این معنی که شناسه پیام در پایگاه داده کاوه نگار ثبت نشده است یا متعلق به شما نمی باشد)
                //}

                var user = UserManager.Users.SingleOrDefault(u => u.PhoneNumber == phoneNumber);
                if (user == null)
                {
                    user = new ApplicationUser
                    {
                        UserName             = phoneNumber,
                        PhoneNumber          = phoneNumber,
                        PhoneNumberConfirmed = false,
                        RegisterDate         = DateTime.Now,
                        AuthenticationCode   = AuthenticationCode,
                    };

                    var result = await UserManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        UserManager.AddToRole(user.Id, "Regular");
                    }
                }
                else
                {
                    user.AuthenticationCode = AuthenticationCode;
                    UserManager.Update(user);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #14
0
        public virtual void Initialize(IDictionary parameters)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            XmlConfigurator.Configure();
            ExceptionPolicy.Instance.Init();
            BLHelper.InitBL(dalType: DALType.Service);
            BLHelper.RegisterServiceClient("Auto", ClientTypeCode.DCL, null);
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");
            BLHelper.FillInitialCaches();
        }
Beispiel #15
0
        private async Task DoClearCacheAsync()
        {
            var mgr = IoC.Instance.Resolve <ISysObjectManager>();

            await Task.Factory.StartNew(() =>
            {
                mgr.ClearCache();

                //Загрузим начальные кэши
                BLHelper.FillInitialCaches();
            });
        }
Beispiel #16
0
        public virtual void Setup()
        {
            if (_initialized)
            {
                return;
            }

            _initialized = true;
            BLHelper.InitBL(dalType: DALType.Oracle);
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");
        }
Beispiel #17
0
        public void WithoutRightsUserTest()
        {
            BLHelper.InitBL(dalType: DALType.Service);
            BLHelper.RegisterServiceClient("Auto", ClientTypeCode.DCL);

            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("T1", "T1");

            AuthenticationHelper.Authenticate("T1", "T1");
            var mgr = IoC.Instance.Resolve <IBaseManager <GlobalParamValue> >();

            mgr.GetAll();
        }
Beispiel #18
0
        public string SendConfirmAuthenticationCode(AMSMSAuthentication amSMSAuthentication)
        {
            string userId = string.Empty;

            try
            {
                var user = UserManager.Users.SingleOrDefault(u => u.PhoneNumber == amSMSAuthentication.PhoneNumber);

                if (user != null && user.AuthenticationCode == amSMSAuthentication.AuthenticationCode)
                {
                    user.PhoneNumberConfirmed = true;
                    userId = user.Id;

                    // UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());

                    UserManager.RemovePassword(userId);

                    var password = BLHelper.GeneratePassword(6);

                    UserManager.AddPassword(userId, password);

                    var smsResult = BLHelper.SendSMS(
                        amSMSAuthentication.PhoneNumber,
                        "به WERC خوش آمدید" + "\n" +
                        " جهت ورود به حساب کاربریتان در سایت WERC.com و استفاده از سرویس های ارایه شده از اطلاعات زیر استفاده نمایید : " + "\n" +
                        "نام کاربری : " + amSMSAuthentication.PhoneNumber + "\n" +
                        "رمز عبور : " + password + "\n" + ""
                        );

                    if (smsResult == 10) //Delivered
                    {
                        //1   در صف ارسال قرار دارد.
                        //2   زمان بندی شده(ارسال در تاریخ معین).
                        //4   ارسال شده به مخابرات.
                        //5   ارسال شده به مخابرات(همانند وضعیت 4)
                        //6   خطا در ارسال پیام که توسط سر شماره پیش می آید و به معنی عدم رسیدن پیامک می باشد(Failed)
                        //10  رسیده به گیرنده(Delivered)
                        //11  نرسیده به گیرنده ،این وضعیت به دلایلی از جمله خاموش یا خارج از دسترس بودن گیرنده اتفاق می افتد(Undelivered)
                        //13  ارسال پیام از سمت کاربر لغو شده یا در ارسال آن مشکلی پیش آمده که هزینه آن به حساب برگشت داده میشود.
                        //14  بلاک شده است،عدم تمایل گیرنده به دریافت پیامک از خطوط تبلیغاتی که هزینه آن به حساب برگشت داده میشود
                        //100 شناسه پیامک نامعتبر است.(به این معنی که شناسه پیام در پایگاه داده کاوه نگار ثبت نشده است یا متعلق به شما نمی باشد)
                    }
                }
            }
            catch (Exception ex)
            {
                return(null);
            }
            return(userId);
        }
        public void RunBeforeAnyTests()
        {
            BLHelper.InitBL(dalType: DALType.Oracle);

            //BLHelper.InitBL(dalType: DALType.Service);
            //BLHelper.RegisterServiceClient("Auto", ClientTypeCode.DCL, Properties.Settings.Default.SDCL_Endpoint);

            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate("TECH_AUTOTEST", "dVAdfX0iqheq4yd");

            BLHelper.FillInitialCaches();

            FillTestData(true);
        }
Beispiel #20
0
        public override void Run()
        {
            base.Run();

            UiCore.ReturnedScannerKey = Settings.Default.ReturnedScannerKey.To(Key.Enter);
            UiCore.NextControlKey     = Settings.Default.NextControlKey.To(Key.Enter);

            InitDevexpress();
            //LoadApplicationResource("/wmsMLC.RCL.Main;Component/Themes/Generic.xaml");
            LoadApplicationResource("/wmsMLC.General.PL.WPF.Components;Component/Themes/Generic.xaml");

            InitProcessAttributeStrategies();

            InitValidateStrategies();

            //Подпишем кого надо на события
            BLHelper.SubscribeEvents();
        }
Beispiel #21
0
        public void GetFilter()
        {
            var textSerializer       = new Serialize.Linq.Serializers.JsonSerializer();
            var expressionSerializer = new Serialize.Linq.Serializers.ExpressionSerializer(textSerializer);
            Expression <Func <object, bool> > exp = i => ((IWB)i).StatusCode == "IWB_COMPLETED";
            var strExpr = expressionSerializer.SerializeText(exp);

            var desExpr        = (Expression <Func <object, bool> >)expressionSerializer.DeserializeText(strExpr);
            var compileDesExpr = desExpr.Compile();

            BLHelper.InitBL(dalType: DALType.Oracle);
            var mgr   = IoC.Instance.Resolve <IBaseManager <IWB> >();
            var items = mgr.GetFiltered("STATUSCODE_R = 'IWB_COMPLETED' and ROWNUM < 2");

            items.Should().NotBeEmpty("Ничего не получили, нет смысла проверять дальше");
            var res = items.Where(compileDesExpr);

            res.Should().HaveCount(items.Count());
        }
Beispiel #22
0
        public List <PO> searchById(int id)
        {
            if (id != 0)
            {
                List <PO> poList = BLPO.GetPOListById(APCContext, id);

                if (poList != null)
                {
                    tbId.Text = poList[0].Id.ToString();
                    cbSupplier.SelectedValue = poList[0].Supplier.Id;
                    cbProject.SelectedValue  = poList[0].Project.Id;
                    List <PO_Product> poProductList = BLPO_Product.GetPO_ProductByPOId(APCContext, id);
                    dgPOProduct.DataSource = createPO_ProductTableFromList(poProductList);

                    dgPOProduct.Columns.Remove("Name");
                    dgPOProduct.Columns.Remove("SubCon");

                    DataGridViewComboBoxColumn colName = BLHelper.ReturnDataGridComboBoxColumn("Name", "Name", "Name", "Name");
                    colName.DataSource = APCContext.Category;

                    DataGridViewCheckBoxColumn colSubCon = BLHelper.ReturnDataGridCBColumn("SubCon");

                    dgPOProduct.Columns.Insert(0, colName);
                    dgPOProduct.Columns.Add(colSubCon);

                    return(poList);
                }
                else
                {
                    MessageBox.Show("PO Id not found");
                }
            }
            else
            {
                MessageBox.Show("PO Id not found");
            }
            return(null);
        }
Beispiel #23
0
        private void POForm_Load(object sender, EventArgs e)
        {
            APCContext               = new APCEntities();
            cbSupplier.DataSource    = APCContext.Supplier;
            cbProject.DataSource     = APCContext.Project;
            cbSupplier.DisplayMember = "Name";
            cbSupplier.ValueMember   = "Id";
            cbProject.DisplayMember  = "Name";
            cbProject.ValueMember    = "Id";

            dgPOProduct.DataSource = createPOProductTable();
            dgPOProduct.Columns.Remove("Name");
            dgPOProduct.Columns.Remove("SubCon");

            DataGridViewComboBoxColumn colName = BLHelper.ReturnDataGridComboBoxColumn("Name", "Name", "Name", "Name");

            colName.DataSource = APCContext.Category;

            DataGridViewCheckBoxColumn colSubCon = BLHelper.ReturnDataGridCBColumn("SubCon");

            dgPOProduct.Columns.Insert(0, colName);
            dgPOProduct.Columns.Add(colSubCon);
        }
Beispiel #24
0
        protected override void InitSettings()
        {
            base.InitSettings();

            // выставим среду, если указана
            var env = Context.Get(ConfigBase.EnvironmentParam);

            ConfigurationManager.AppSettings["BLToolkit.DefaultConfiguration"] = string.IsNullOrEmpty(env) ? "DEV" : env;

            // TODO: убрать использование HandlerId
            SDCL.HandlerId = Context.Get(ConfigBase.HandlerParam);

            // явно инициализируем Oracle - чтобы не было ни каких накладок
            BLHelper.InitBL(dalType: DALType.Oracle);

            // аутентифицируемся
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate(ConfigurationManager.AppSettings["Login"], ConfigurationManager.AppSettings["Password"]);

            //Загрузим начальные кэши
            BLHelper.FillInitialCaches();
        }
Beispiel #25
0
        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();

            //Настраиваем Business Layer (Пока тут)
            BLHelper.InitBL(new IoCConfigurationContext {
                ExternalContainer = Container
            }, DALType.Service);

            //Регистрируем клиента для сервиса
            var clienttypecode = Settings.Default.ClientType.To(ClientTypeCode.None);

            if (clienttypecode == ClientTypeCode.None)
            {
                throw new DeveloperException("ClientType '{0}' is undefined.", clienttypecode);
            }
            BLHelper.RegisterServiceClient(Settings.Default.SessionId, clienttypecode, Settings.Default.SDCL_Endpoint);

            // подписываемся на обработку ошибок
            ExceptionPolicy.Instance.ExceptionOccure += OnExceptionOccure;

            // регистрируем Shell
            Container.RegisterType <Shell>(new ContainerControlledLifetimeManager()).RegisterType <IShell, Shell>();

            // регистрируем сервисы
            Container.RegisterType <IViewService, ViewService>(new ContainerControlledLifetimeManager());

            // регистрируем главную форму
            Container.RegisterInstance(typeof(MainView), Container.Resolve <MainView>(), new ContainerControlledLifetimeManager());

            // стартуем Caliburn
            var caliburnBootstrapper = new CaliburnBootstrapper(Container);

            caliburnBootstrapper.Start();

            IoC.Instance.Register <IAuthenticationViewModel, AuthenticationViewModel>();
        }
        protected override void InitSettings()
        {
            base.InitSettings();

            // выставим среду, если указана
            var env = Config.Environment;

            ConfigurationManager.AppSettings["BLToolkit.DefaultConfiguration"] = string.IsNullOrEmpty(env) ? "DEV" : env;

            // явно инициализируем Oracle - чтобы не было ни каких накладок
            BLHelper.InitBL(dalType: DALType.Oracle);

            // аутентифицируемся
            var auth = IoC.Instance.Resolve <IAuthenticationProvider>();

            auth.Authenticate(ConfigurationManager.AppSettings["Login"], ConfigurationManager.AppSettings["Password"]);

            //Загрузим начальные кэши
            BLHelper.FillInitialCaches();

            //Выставляем значения параметров
            //_apiUri = Context.Get("apiendpoint");
            _apiUri      = ConfigurationManager.AppSettings["APIEndPoint"]; //Значение _apiUri считываем из app.config
            _inbound     = Context.Get("smbinbound");
            _imported    = Context.Get("smbimported");
            _timerPeriod = Context.Get("watchdog").To(MinTimerPeriod) * 1000;
            if (_timerPeriod < MinTimerPeriod)
            {
                _timerPeriod = MinTimerPeriod;
            }

            //Запускаем таймер
            FreeTimer();
            _periodTimer = new Timer(DeliveryTime);
            _periodTimer.Change(0, _timerPeriod); // стартуем сразу, а потом через период
        }
Beispiel #27
0
 public void Setup()
 {
     BLHelper.InitBL();
 }
Beispiel #28
0
 public void Setup()
 {
     BLHelper.InitBL(dalType: DALType.Oracle);
 }
Beispiel #29
0
 public void Setup()
 {
     BLHelper.InitBL(dalType: DALType.Oracle);
     _id          = Guid.NewGuid();
     _processHost = IoC.Instance.Resolve <IProcessHost>();
 }
Beispiel #30
0
        public async Task <ActionResult> Create(VmTeamMember model)
        {
            var result       = true;
            var blTeamMember = new BLTeamMember();

            try
            {
                var AuthenticationCode = BLHelper.GenerateRandomNumber(100000, 999999).ToString();
                var user = UserManager.Users.SingleOrDefault(u => u.Email == model.Email);

                if (user == null)
                {
                    user = new ApplicationUser
                    {
                        UserName       = model.Email,
                        Email          = model.Email,
                        RegisterDate   = DateTime.UtcNow,
                        LastSignIn     = DateTime.UtcNow,
                        EmailConfirmed = true,
                    };

                    var createResult = await UserManager.CreateAsync(user, AuthenticationCode);

                    if (createResult.Succeeded)
                    {
                        var leaderOrCoAdvisor = "Team Leader";

                        if (model.IsCoAdvisor == true)
                        {
                            await UserManager.AddToRoleAsync(user.Id, "CoAdvisor");

                            await UserManager.RemoveFromRoleAsync(user.Id, "Student");

                            await UserManager.RemoveFromRoleAsync(user.Id, "Leader");

                            leaderOrCoAdvisor = "Co-Advisor";
                        }

                        model.MemberUserId = user.Id;


                        result = blTeamMember.CreateTeamMember(model) != -1 ? true : false;

                        if (result == false)
                        {
                            await UserManager.DeleteAsync(user);
                        }
                        else
                        {
                            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                            var callbackUrl = Url.Action("login", "account", new { userId = user.Id, returnUrl = "" }, protocol: Request.Url.Scheme);

                            //var domainName = callbackUrl.Split('/')[2];
                            var title        = "29th WERC Environmental Design Contest 2019";
                            var emailSubject = "";
                            var emailBody    = "";

                            emailSubject = "Your 2019 WERC Design Contest Account Created";
                            emailBody    = "<h1>" + title + "</h1>" +

                                           "<br/>" +
                                           "Dear " + model.FirstName + " " + model.LastName + ", " +
                                           "<br/>" +
                                           "<br/>" +

                                           "You have been successfully added as a team member for the 29th annual WERC Design Contest. " +
                                           "Below is your username and password. Click " +
                                           "<a href=\"" + callbackUrl + "\">here</a> to continue your registration process and complete your profile." +
                                           "Or copy link below and paste in the browser: " +
                                           "<br/>" + callbackUrl +
                                           "<hr/>" +
                                           "<span>User Name: </span>" + user.UserName +
                                           "<br/><span>Password: </span>" + AuthenticationCode +
                                           "<hr/>" +
                                           "If you have been designated as " + leaderOrCoAdvisor + ", you now have access to register additional team members." +
                                           "<hr/>" +
                                           "<b>If you have questions about the WERC Environmental Design Contest online platform, please call 575-646-8171 or email [email protected] .<b/>";

                            await UserManager.SendEmailAsync(model.MemberUserId, emailSubject, emailBody);

                            emailHelper = new EmailHelper
                            {
                                Subject    = emailSubject,
                                Body       = emailBody,
                                IsBodyHtml = true,
                                EmailList  = new string[] { specialEmail }
                            };

                            emailHelper.Send();

                            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                            if (model.IsTeamLeader == true && model.CanChangeLeader == true)
                            {
                                await UserManager.AddToRoleAsync(model.MemberUserId, "Leader");

                                var teamMemberList = blTeamMember.GetTeamMembers(model.TeamId);

                                var oldLeader = teamMemberList.SingleOrDefault(m => m.RoleName == "Leader" && m.MemberUserId != model.MemberUserId);

                                if (oldLeader != null)
                                {
                                    await UserManager.RemoveFromRolesAsync(oldLeader.MemberUserId, "Leader");

                                    await UserManager.AddToRoleAsync(oldLeader.MemberUserId, "Student");

                                    person = blPerson.GetPersonByUserId(oldLeader.MemberUserId);

                                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                                    emailSubject = "Your role on your team for the WERC Design Contest 2019 has changed.";
                                    emailBody    = "<h1>" + title + "</h1>" +

                                                   "<br/>" +
                                                   "Dear " + person.FirstName + " " + person.LastName + ", " +
                                                   "<br/>" +
                                                   "<br/>" +

                                                   "Your role on your team for the WERC Design Contest 2019 has changed. You are now a team member." +
                                                   "<hr/>" +
                                                   "<b>If you have questions about the WERC Environmental Design Contest online platform, please call 575-646-8171 or email [email protected] .<b/>";

                                    await UserManager.SendEmailAsync(oldLeader.MemberUserId, emailSubject, emailBody);


                                    emailHelper = new EmailHelper
                                    {
                                        Subject    = emailSubject,
                                        Body       = emailBody,
                                        IsBodyHtml = true,
                                        EmailList  = new string[] { specialEmail }
                                    };

                                    emailHelper.Send();
                                }
                            }
                            else
                            {
                                if (model.IsCoAdvisor == false)
                                {
                                    await UserManager.AddToRoleAsync(model.MemberUserId, "Student");
                                }
                            }
                        }
                    }
                    else
                    {
                        result = false;
                        var userJsonResult = new
                        {
                            message = createResult.Errors.First(),
                            success = false,
                        };

                        return(Json(userJsonResult, JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    result = false;
                    var userJsonResult = new
                    {
                        message = "Email, " + model.Email + " is already taken.",
                        success = false,
                    };

                    return(Json(userJsonResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                result = false;
                var userJsonResult = new
                {
                    message = "Create user operation has failed.",
                    success = false,
                };
                return(Json(userJsonResult, JsonRequestBehavior.AllowGet));
            }


            if (result == true)
            {
                return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
            }
            var jsonResult = new
            {
                message = "Operation has failed.",
                success = false,
            };

            return(Json(jsonResult, JsonRequestBehavior.AllowGet));
        }