Esempio n. 1
0
        private void ValidateTruck()
        {
            try
            {
                SplashScreenHelper.SetState(Resources.StringResources.StateValidateTruck);

                var mgrClient  = IoC.Instance.Resolve <IBaseManager <Client> >();
                var clientcode = GetClientCode();
                var client     = mgrClient.Get(clientcode, GetModeEnum.Partial);
                if (client == null)
                {
                    throw new DeveloperException("Can't find Client by key '{0}'.", clientcode);
                }

                if (string.IsNullOrEmpty(client.TruckCode_R))
                {
                    HasCriticalErrors = true;
                    _criticalErrorMessages.Add(string.Format(Resources.StringResources.TruckNotValidated,
                                                             GetClientCode()));
                }
                else
                {
                    WMSEnvironment.Instance.TruckCode = client.TruckCode_R;
                }
            }
            catch (Exception ex)
            {
                HasCriticalErrors = true;
                var msg = Resources.StringResources.TruckValidatedError;
                _criticalErrorMessages.Add(msg);
                ExceptionPolicy.Instance.HandleException(new OperationException(msg, ex), "RclBackgroundProcess");
            }
        }
Esempio n. 2
0
        public override void Run()
        {
            base.Run();

            var viewService             = Container.Resolve <IViewService>();
            var guaranteeExistViewModel = typeof(BPWorkflowListViewModel);

            foreach (var item in BLHelper.Registered)
            {
                // пытаемся найти ViewModel в стандартном namespace
                var assumeListViewModelName   = string.Format("{0}.{1}ListViewModel", guaranteeExistViewModel.Namespace, item.ObjectType.Name);
                var assumeTreeViewModelName   = string.Format("{0}.{1}TreeViewModel", guaranteeExistViewModel.Namespace, item.ObjectType.Name);
                var assumeObjectViewModelName = string.Format("{0}.{1}ViewModel", guaranteeExistViewModel.Namespace, item.ObjectType.Name);

                // если нет - берем базовый тип
                var listViewModelType = Type.GetType(assumeListViewModelName) ?? typeof(ObjectListViewModelBase <>).MakeGenericType(item.ObjectType);

                // для TreeView если нет - не берем базовый тип
                //var treeViewModelType = Type.GetType(assumeTreeViewModelName) ?? typeof(ObjectTreeViewModelBase<>).MakeGenericType(item.ObjectType);
                var treeViewModelType = Type.GetType(assumeTreeViewModelName);

                // если нет - берем базовый тип
                var objectViewModelType = Type.GetType(assumeObjectViewModelName) ?? typeof(ObjectViewModelBase <>).MakeGenericType(item.ObjectType);

                // регистриуем во viewservice
                viewService.Register(item.ObjectType.Name + ViewServiceRegisterSuffixListShow, listViewModelType);
                if (treeViewModelType != null)
                {
                    viewService.Register(item.ObjectType.Name + ViewServiceRegisterSuffixTreeShow, treeViewModelType);
                }

                // регистрируем в IoC
                var interfaceType = typeof(IListViewModel <>).MakeGenericType(item.ObjectType);
                IoC.Instance.Register(interfaceType, listViewModelType);

                var interfaceObjectType = typeof(IObjectViewModel <>).MakeGenericType(item.ObjectType);
                IoC.Instance.Register(interfaceObjectType, objectViewModelType);
            }

            viewService.Register("ARTMASSINPUT", typeof(ArtMassInputViewModel));
            viewService.Register(StringResources.Packing, typeof(IPackingViewModel));
            //viewService.Register("OPENWCL", typeof(OpenWclViewCommand));
            viewService.Register(StringResources.Chat, typeof(IChatViewModel));
            viewService.Register(MainViewModel.ShowMainMenuAction, typeof(MainMenuTreeViewModel));

            //Включаем кеширование wf
            BPWorkflowManager.SetObjectCachable(BatchcodeWorkflowCodes.ExecuteWorkflowCode);
            foreach (var wf in BatchcodeWorkflowCodes.WorkflowCodes)
            {
                BPWorkflowManager.SetObjectCachable(wf);
            }

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

            SplashScreenHelper.SetState(StringResources.LoadCustomization);
            MainViewModel.LoadCustomization();
            MainViewModel.ShowTree();
            MainViewModel.LoadDxAssemblies();
        }
Esempio n. 3
0
        public void ValidateWorker()
        {
            SplashScreenHelper.SetState(Resources.StringResources.StateValidateWorker);
            if (WMSEnvironment.Instance.AuthenticatedUser == null)
            {
                HasCriticalErrors = true;
                _criticalErrorMessages.Add("User is null.");
                return;
            }

            // получим работника привязанного к пользователю
            WMSEnvironment.Instance.WorkerId = null;
            try
            {
                var currentUser = WMSEnvironment.Instance.AuthenticatedUser.GetSignature();
                using (var mgr = IoC.Instance.Resolve <IBaseManager <Worker> >())
                {
                    var filter  = string.Format("USERCODE_R = '{0}'", currentUser);
                    var workers = mgr.GetFiltered(filter).ToArray();
                    if (workers.Length == 1)
                    {
                        WMSEnvironment.Instance.WorkerId = workers[0].GetKey <decimal>();
                    }
                    else if (workers.Length > 1)
                    {
                        WMSEnvironment.Instance.WorkerId = SelectWorker(filter);
                    }

                    if (!WMSEnvironment.Instance.WorkerId.HasValue)
                    {
                        HasCriticalErrors = true;
                        _criticalErrorMessages.Add(string.Format(Resources.StringResources.WorkerNotValidated, currentUser));
                    }
                    else
                    {
                        // Запишем работника в сессию
                        if (!WMSEnvironment.Instance.SessionId.HasValue)
                        {
                            return;
                        }

                        using (var mgrSession = (IClientSessionManager)IoC.Instance.Resolve <IBaseManager <ClientSession> >())
                        {
                            mgrSession.UpdateWorker(WMSEnvironment.Instance.SessionId.Value, WMSEnvironment.Instance.WorkerId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HasCriticalErrors = true;
                var msg = Resources.StringResources.WorkerValidatedError;
                _criticalErrorMessages.Add(msg);
                ExceptionPolicy.Instance.HandleException(new OperationException(msg, ex), "RclBackgroundProcess");
            }
        }
Esempio n. 4
0
        protected override void OnStartup(StartupEventArgs e)
        {
            AppHelper.Init(ClientTypeCode.DCL.ToString());

#if !DEBUG
            CheckForUpdate();
#endif

            try
            {
                LocalizeDictionary.Instance.Culture = Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = Client.Properties.Settings.Default.Culture;
                SplashScreenHelper.Show(Thread.CurrentThread.CurrentCulture);
                SplashScreenHelper.SetState(DCL.Resources.StringResources.StateInitModules);

#if DEBUG
                // HACK: надоело по сто раз перегружаться
                SplashScreenHelper.SetState(DCL.Resources.StringResources.WaitServiceInit);
                //Thread.Sleep(10000);
#endif

                AppHelper.InitExceptionEngine(this);

                base.OnStartup(e);

                // стартуем "движок"
                var bootstrapper = new Bootstraper();
                bootstrapper.Run();

                // авторизуемся
                SplashScreenHelper.SetState(DCL.Resources.StringResources.StateAuthentication);
                AuthenticationHelper.AskCredentials = true;

                while (true)
                {
                    try
                    {
                        if (!Authenticate())
                        {
                            AppHelper.Log.Info("Exit from application. User was not Authenticated");
                            Environment.Exit(0);
                        }
                        else
                        {
                            // идем дальше
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is EndpointNotFoundException || ex.InnerException is General.CommunicationException)
                        {
                            if (
                                MessageBox.Show("Отсутствует связь с сервисом.\r\nПовторить попытку подключения?",
                                                "Соединение", MessageBoxButton.YesNo,
                                                MessageBoxImage.Question,
                                                MessageBoxResult.Yes) == MessageBoxResult.No)
                            {
                                AppHelper.Log.Info("Не удалось соединиться с сервисом");
                                Environment.Exit(0);
                            }
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                // запускаем модули
                SplashScreenHelper.SetState(DCL.Resources.StringResources.StateRunModules);
                bootstrapper.RunModules();

                // дополнительная проверка после общего запуска
                SplashScreenHelper.SetState(DCL.Resources.StringResources.StateRun);
                if (AuthenticationHelper.IsAuthenticated)
                {
                    AppHelper.Log.Debug("Show main form");
                    Current.MainWindow.Closed += MainWindow_Closed;
                    Current.MainWindow.UpdateLayout();
                    Current.MainWindow.Show();
                    SignalRHelper.TryConnectToServer();
                }
                else
                {
                    AppHelper.Log.Info("Exit from application. User Authentication was canceled");
                    Current.Shutdown();
                }

                SplashScreenHelper.Close();
            }
            catch (Exception ex)
            {
                SplashScreenHelper.Close();

                // обрабатываем ошибку
                if (!ExceptionPolicy.Instance.HandleException(ex, typeof(App)))
                {
                    throw;
                }

                // и безусловно выходим из приложения (без инициализации работать не можем)
                AppHelper.Log.Info("Exit from application. Exception was not handled");
                Environment.Exit(0);
            }
            finally
            {
                AppHelper.Log.Debug("Startup complete");
            }
        }
Esempio n. 5
0
        private const int MaxCountConnectionAttempt = 7; //Достаточно случайное число

        protected override void OnStartup(StartupEventArgs e)
        {
            AppHelper.Init(ClientTypeCode.RCL.ToString());

#if !DEBUG
            AppHelper.Log.Info("Проверка обновлений");

            bool isCantCopyToLocal;
            var  updateInfo = UpdateHelper.ReadUpdateInfo(Environment.CurrentDirectory, Client.Properties.Settings.Default.UpdateInfoFile, out isCantCopyToLocal);

            if (updateInfo == null)
            {
                MessageBox.Show(
                    "В данный момент выполняется обновление системы.\r\nПовторите попытку позже.", "ВНИМАНИЕ!", MessageBoxButton.OK, MessageBoxImage.Information);
                Shutdown();
                return;
            }
#endif

            try
            {
                CultureInfo.DefaultThreadCurrentCulture           =
                    LocalizeDictionary.Instance.Culture           =
                        Thread.CurrentThread.CurrentCulture       =
                            Thread.CurrentThread.CurrentUICulture = Client.Properties.Settings.Default.Culture;

                SplashScreenHelper.Show(Thread.CurrentThread.CurrentCulture);
                SplashScreenHelper.SetState(RCL.Resources.StringResources.StateInitModules);
                AppHelper.InitExceptionEngine(this);

                base.OnStartup(e);

                // стартуем "движок"
                var bootstrapper = new Bootstraper();
                bootstrapper.Run();

#if DEBUG
                SplashScreenHelper.SetState(RCL.Resources.StringResources.WaitServiceInit);
                Thread.Sleep(5000);
#endif

                // запускаем модули
                SplashScreenHelper.SetState(RCL.Resources.StringResources.StateRunModules);
                bootstrapper.RunModules();

                // авторизуемся
                SplashScreenHelper.SetState(RCL.Resources.StringResources.StateAuthentication);
                AuthenticationHelper.AskCredentials = true;

                var count = 0;
                while (true)
                {
                    try
                    {
                        if (!Authenticate())
                        {
                            AppHelper.Log.Info("Exit from application. User was not Authenticated.");
                            Environment.Exit(0);
                        }
                        else
                        {
                            // идем дальше
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is EndpointNotFoundException || ex.InnerException is CommunicationException)
                        {
                            if (count++ < MaxCountConnectionAttempt)
                            {
                                AppHelper.Log.Info(string.Format("Попытка соединения с сервисом {0}", count));
                            }
                            else
                            {
                                AppHelper.Log.Info("Не удалось соединиться с сервисом");
                                throw new DeveloperException("Превышено количество попыток соединения с сервером. Приложение будет закрыто.", ex);
                                //Environment.Exit(0);
                            }
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                // дополнительная проверка после общего запуска
                SplashScreenHelper.SetState(RCL.Resources.StringResources.StateRun);
                if (AuthenticationHelper.IsAuthenticated)
                {
                    AppHelper.Log.Debug("Show main form");
                    Current.MainWindow.Closed += MainWindow_Closed;
                    Current.MainWindow.UpdateLayout();
                    Current.MainWindow.Show();
                }
                else
                {
                    AppHelper.Log.Info("Exit from application. User Authentication was canceled");
                    Current.Shutdown();
                }
            }
            catch (Exception ex)
            {
                // обрабатываем ошибку
                if (!ExceptionPolicy.Instance.HandleException(ex, typeof(App)))
                {
                    throw;
                }

                // и безусловно выходим из приложения (без инициализации работать не можем)
                AppHelper.Log.Info("Exit from application. Exception was not handled");
                Environment.Exit(0);
            }
            finally
            {
                SplashScreenHelper.Close();
                AppHelper.Log.Debug("Startup complete");
            }
        }