Ejemplo n.º 1
0
 public void Init(OpenAPI api, AppDataService appDataService)
 {
     _api         = api;
     _chatAppData = new ChatAppData(appDataService);
     LoadChats();
     InitCleanup();
 }
Ejemplo n.º 2
0
 public DeleteAllDataCommand(AppDataService appDataService, RestartService restartService)
 {
     Ensure.NotNull(appDataService, "appDataService");
     Ensure.NotNull(restartService, "restartService");
     this.appDataService = appDataService;
     this.restartService = restartService;
 }
Ejemplo n.º 3
0
        protected override async Task ExecutePrimaryActionAsync()
        {
            await base.ExecutePrimaryActionAsync();

            foreach (ItemViewModel item in Items)
            {
                try
                {
                    await ApiClient.PostValidationAsync(ValidationSessionId, item.SampleItemId, Mapper.Map <ValidationCreateModel>(item));

                    item.Uploaded = true;

                    LocalValidation localValidation =
                        await AppDataService.GetLocalValidationByIdAsync(item.SampleItemId, ValidationSessionId);

                    localValidation.Uploaded = true;
                }
                catch (Exception e)
                {
                    // TODO: Notify user
                }
            }

            await AppDataService.SaveChangesAsync();
        }
Ejemplo n.º 4
0
        protected override async void OnNavigatedTo(NavigationEventArgs obj)
        {
            base.OnNavigatedTo(obj);
            rootPage = ((App)Application.Current).CurrentMain;
            if (obj.Parameter != null)
            {
                rootPage.UpdateTitle(ThoughtRecordListModel.Title);
                int thoughtRecordId = Convert.ToInt32(obj.Parameter);
                ViewModel = new ThoughtRecordDisplayModel(AppDataService.GetDatabase(Application.Current));
                await ViewModel.InitializeModel(thoughtRecordId);

                if (ViewModel.ThoughtRecord == null)
                {
                    NavigateWithBackStackRemoval(typeof(ThoughtRecordListPage));
                }
                else
                {
                    ViewModel.OnThoughtRecordDeleteRequested += ConfirmDeleteRequest;
                    ViewModel.OnThoughtRecordDeleted         += NavigatetoListPageAfterDelete;
                    ViewModel.OnThoughtRecordEditRequested   += NavigateToEditPage;
                    ViewModel.OnThoughtRecordChanged         += ScrollToTop;
                    rootPage.UpdateTitle(ThoughtRecordDisplayModel.Title);
                    rootPage.NavigateWithMenuUpdate(typeof(ThoughtRecordDisplayPage), thoughtRecordId);
                }
            }
            else
            {
                NavigateWithBackStackRemoval(typeof(ThoughtRecordListPage));
            }
        }
Ejemplo n.º 5
0
        protected async Task LoadLocalValidationsAsync(int validationSessionId)
        {
            List <LocalValidation> localValidations =
                (await AppDataService.GetLocalValidationsWhereNotUploadedByIdAsync(validationSessionId)).ToList();

            Mapper.Map(localValidations, Items);
        }
Ejemplo n.º 6
0
        // Your application's entry point. Here you can initialize your MVVM framework, DI
        // container, etc.
        private static void AppMain(Application app, string[] args)
        {
            DataGrid dg = new DataGrid();
            //RxApp.DefaultExceptionHandler = new MyCoolObservableExceptionHandler();

            var appData = new AppDataService().Load();
            var factory = new MainWindowDockFactory(appData);
            var layout  = factory.CreateLayout();

            factory.InitLayout(layout);

            var mainWindow = new MainWindow();

            mainWindow.DataContext = new MainWindowViewModel()
            {
                Factory = factory,
                Layout  = layout,
                Window  = mainWindow,
                AppData = appData
            };
            appData.MainWindow = mainWindow;
            app.Run(mainWindow);

            if (layout is IDock dock)
            {
                dock.Close();
            }
        }
Ejemplo n.º 7
0
        public void ApplyChanges(ChangesApplying changesApplying)
        {
            // Догрузить changesApplying.
            DataService.LoadObject(changesApplying);

            // Прочитаем из бд входящие изменения.
            // Выберем только те, которые еще не применены
            Message[] changes = DataService.LoadObjects();

            foreach (var message in changes)
            {
                // Указать messageBuilder-у распаковать изменения и получить объекты.
                // На данном этапе MessageBuilder должен знать, в какие именно объекты он должен распаковывать изменения.
                // Если он не ссылается на объекты целевого приложения, то какие-то "шаблоны" объектов может выдавать сам ChangesApplier.
                // Поэтому получаем объект package - пакет и набор ObjectChangePackage.
                var package = messageBuilder.GetChangesPackage(message);

                foreach (var objectChangePackage in package.ObjectChangePackages)
                {
                    // Создадим объект с типом, указанным в ObjectChangePackages.
                    var obj = Activator.CreateInstance(Type.GetType(objectChangePackage.type));
                    // Затем надо достать изменения и применить их к объекту.
                    obj = messageBuilder.FillObject(obj, objectChangePackage);

                    // Выполнить обновление объекта в БД приложения.
                    AppDataService.UpdateObject(obj);

                    // Todo подумать над откатом изменений, транзакционностью.
                    // Первый вариант, если классы объекты не аудируются, перед обновлением объекта читать изменяемые атрибуты этого объекта из БД приложения (если он там есть),
                    // а при ошибке - откатывать все успшные изменения.
                    // Второй вариант, если целевые классы аудируются, то откатывать изменения на дату начала применения изменений с помощью аудита.
                }
            }
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            ILog log = LogManager.GetLogger(typeof(Program));

            try
            {
                log.Info(LogFormat.Message("", "Application_start", LogStatus.Success, ""));

                MultiLanguageManager.SetDefaultLabelsDictionary <DSW.Localisation.Labels.Dictionary>();
                MultiLanguageManager.SetDefaultMessageDictionary <DSW.Localisation.Messages.Dictionary>();

                if (SingleInstanceApplication.IsExist())
                {
                    FormUtility.EnableTaskBar(false);
                    FormUtility.EnableTaskBar(true);

                    MessageUtility.DisplayErrorMsg(MultiLanguageManager.Messages.GetString(DSW.Localisation.Messages.Dictionary.Common.HT_COM_MS029),
                                                   MultiLanguageManager.Messages.GetString(DSW.Localisation.Messages.Dictionary.Common.HT_COM_CAP001));

                    log.Info(LogFormat.Message("", "Application_end", LogStatus.Failed, DSW.Localisation.Messages.Dictionary.Common.HT_COM_MS029));

                    Application.Exit();

                    return;
                }

                FormUtility.EnableTaskBar(false);

                AppDataService.SetSettingApiAddress(Setting.ApiAddress);

                var appModule       = new AppModule();
                var mvvmApplication = new MvvmApplication(appModule);

                mvvmApplication.Run <StocktakeNewView>();

                FormUtility.EnableTaskBar(true);

                log.Info(LogFormat.Message("", "Application_end", LogStatus.Success, ""));

                LogManager.Shutdown();
            }
            catch (Exception ex)
            {
                log.Info(LogFormat.Message("", "Application_end", LogStatus.Failed, ex.Message + Environment.NewLine + ex.StackTrace));

                LogManager.Shutdown();

                FormUtility.EnableTaskBar(false);
                FormUtility.EnableTaskBar(true);

                MessageUtility.DisplayErrorMsg(ex.Message,
                                               MultiLanguageManager.Messages.GetString(DSW.Localisation.Messages.Dictionary.Common.HT_COM_CAP001));

                Application.Exit();
            }
        }
        protected override async Task PrimaryActionButtonTappedAsync()
        {
            await base.PrimaryActionButtonTappedAsync();

            await AppDataService.AddLocalValidationAsync(Mapper.Map <LocalValidation>(this));

            // TODO: Localization
            NotificationService.Notify("Validation saved locally.");
            await NavigationService.GoBackAsync();
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage  = ((App)(Application.Current)).CurrentMain;
            ViewModel = new ThoughtRecordListModel(AppDataService.GetDatabase(Application.Current));
            rootPage.UpdateTitle(ThoughtRecordListModel.Title);
            rootPage.NavigateWithMenuUpdate(this.GetType());
            await InitializeViewModel();

            base.OnNavigatedTo(e);
        }
Ejemplo n.º 11
0
        private async Task DeleteActivity()
        {
            if (_calenderEvent?.Data != null)
            {
                var res = await AppDataService.RemovePlotActivityAsync(_calenderEvent?.Data);

                if (res)
                {
                    IsActivityInfoShown = false;
                }
            }
        }
Ejemplo n.º 12
0
        private async void SetupHome()
        {
            var tok = AppDataService.LoadLocalSetting(Settings.apiKey);

            if (tok is null)
            {
                await DataService.LoginTemp();
            }
            await LoadIdeas();
            await LoadCategoriesAsync();
            await LoadCollections();
        }
        // TODO: Disable primary action button until data is loaded
        protected override async Task ExecutePrimaryActionAsync()
        {
            await base.ExecutePrimaryActionAsync();

            if (await AppDataService.TryGetValidationSessionByIdAsync(ViewModel.Id) == null)
            {
                await AppDataService.AddValidationSessionAsync(Mapper.Map <ValidationSessionDetailViewModel, ValidationSession>(ViewModel));
            }

            await PermissionService.CheckAndRequestPermissionIfRequiredAsync(Permission.Location)
            .ContinueIfTrueWith(() =>
            {
                Helper.RunOnMainThreadIfRequired(() => { NavigationService.NavigateToMapAsync(ViewModel.Id, ViewModel.Name); });
            });
        }
        protected override async Task InitializeOnceAsync(INavigationParameters parameters)
        {
            await base.InitializeOnceAsync(parameters);

            Title = (string)parameters["name"];
            ValidationSessionId = (int)parameters["id"];

            ValidationSession validationSession = await AppDataService.TryGetValidationSessionByIdAsync((int)parameters["id"]);

            if (validationSession != null)
            {
                ViewModel   = Mapper.Map <ValidationSessionDetailViewModel>(validationSession);
                ShowLoading = false;
            }
        }
Ejemplo n.º 15
0
        protected override async Task InitializeOnceAsync(INavigationParameters parameters)
        {
            await base.InitializeOnceAsync(parameters);

            ValidationSessionId = (int)parameters["validationSessionId"];
            SampleItemId        = (int)parameters["sampleItemId"];

            // TODO: Localization
            Title = $"Sample #{SampleItemId}";

            SampleItem sampleItem = await AppDataService.GetSampleItemByIdAsync(SampleItemId, ValidationSessionId);

            ValidationMethod = sampleItem.ValidationSession.ValidationMethod;
            LegendItem       = Mapper.Map <ItemViewModel>(sampleItem.LegendItem);
            Mapper.Map(sampleItem.ValidationSession.LegendItems, LegendItems);
        }
Ejemplo n.º 16
0
 public SnaBaseController(
     ApplicationDbContext context,
     IConfiguration configuration,
     RoleManager <IdentityRole> roleManager,
     IAmazonSimpleEmailService client,
     UserManager <IdentityUser> userManager,
     SignInManager <IdentityUser> signInManager
     )
 {
     _configuration     = configuration;
     _roleManager       = roleManager;
     _userManager       = userManager;
     _context           = context;
     _signInManager     = signInManager;
     _AuthMessageSender = new AuthMessageSender(client, _configuration);
     _appData           = new AppDataService(_configuration);
 }
Ejemplo n.º 17
0
        public static void SyncList(Guid listId)
        {
            var configProvider = new AppConfigService();
            var mappingSetting = configProvider.GetMappingByList(listId.ToString());

            if (mappingSetting == null)
            {
                return;
            }
            var dataProvider = new AppDataService();
            {
                var list      = SPContext.Current.SPList(listId);
                var listitems = list.ListItems(mappingSetting.Key,
                                               String.Join("$", mappingSetting.ListMappingFields.Select(item => item.ItemName).ToList()), true);

                dataProvider.SaveRows(mappingSetting, listitems);
            }
        }
Ejemplo n.º 18
0
        protected override async Task ExecutePrimaryActionAsync()
        {
            await base.ExecutePrimaryActionAsync();

            if (ShowPrimaryAction)
            {
                // TODO: Block Navigation
                await NavigationService.NavigateAsync(nameof(ValidationSessionOverviewPage));
            }
            else
            {
                foreach (ItemViewModel itemViewModel in Items.Where(x => x.IsChecked).ToList())
                {
                    await AppDataService.TryRemoveValidationSessionAsync(itemViewModel.Id);

                    Items.Remove(itemViewModel);
                }
            }
        }
Ejemplo n.º 19
0
        public string GetDataSource(string iiid)
        {
            var result     = SearchService.GetMetadata(GetSearchMetadataRequest(iiid));
            var dataId     = result.DataId;
            var dataSource = string.Empty;
            var showType   = result.ShowType;

            if (string.Equals(showType, "image", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(showType, "pdf", StringComparison.OrdinalIgnoreCase))
            {
                dataSource = GetFullAPIUrl(dataId);
            }
            else
            {
                var pageData = (AppDataService.Get(dataId) as PKS.WebAPI.Models.IndexAppData);
                var content  = pageData.Content;
                dataSource = Convert.ToString(content);
            }
            return(SerializeObject(new { iiid = iiid, showtype = showType, createddate = result.GetValueBy(MetadataConsts.CreatedDate), title = result.Title, author = result.Author, Abstract = result.Abstract, dataSource = dataSource }));
        }
Ejemplo n.º 20
0
        public static List <Tuple <int, ExpandoObject> > SourceContent(string source, string key, string fields, int type, List <Tuple <string, string> > whereCriteria = null)
        {
            List <Tuple <int, ExpandoObject> > itemCollection = null;

            switch (type)
            {
            case (int)LookupSourceType.SpList:
            {
                itemCollection = SPContext.Current.SPList(source.ToGuid()).ListItemsByCriteria(key, fields, false, whereCriteria);
                break;
            }

            case (int)LookupSourceType.Table:
            case (int)LookupSourceType.Query:
            {
                itemCollection = new AppDataService().TableContent(source, key, fields, whereCriteria);
                break;
            }
            }
            return(itemCollection);
        }
Ejemplo n.º 21
0
        protected async Task LoadValidationSessionsAsync()
        {
            if (await ApiAuthentication.IsAuthenticatedAsync())
            {
                await AppDataService.EnsureUserExistsAsync();
            }

            IEnumerable <ValidationSession> validationSessions = await AppDataService.GetValidationSessionsAsync();

            Items = new ObservableCollection <ItemViewModel>(Mapper.Map <IEnumerable <ItemViewModel> >(validationSessions)).OnPropertyChanged(
                (sender, args) =>
            {
                OnPropertyChanged(nameof(ShowInstructions));
                OnPropertyChanged(nameof(ShowList));

                ShowPrimaryAction = !Items.Any(x => x.IsChecked);
            })
                    .OnChildrenPropertyChanged((sender, args) => { ShowPrimaryAction = !Items.Any(x => x.IsChecked); });

            Items.ForEach(x => { x.ItemTapped += ItemTapped; });
        }
Ejemplo n.º 22
0
 public override void ItemUpdated(SPItemEventProperties properties)
 {
     base.ItemUpdated(properties);
     try
     {
         var configProvider = new AppConfigService(properties.Web);
         var mappingSetting = configProvider.GetMappingByList(properties.ListId.ToString());
         if (mappingSetting == null)
         {
             return;
         }
         var dataProvider = new AppDataService(properties.Web);
         {
             dataProvider.SaveRow(mappingSetting, properties.ListItem.ToSyncObject(mappingSetting));
         }
     }
     catch (Exception ex)
     {
         LogHelper.Instance.ErrorULS("ItemUpdated error", ex);
     }
 }
Ejemplo n.º 23
0
 public override void ItemDeleting(SPItemEventProperties properties)
 {
     base.ItemDeleting(properties);
     try
     {
         var configProvider = new AppConfigService(properties.Web);
         var mappingSetting = configProvider.GetMappingByList(properties.ListId.ToString());
         if (mappingSetting == null)
         {
             return;
         }
         var dataProvider = new AppDataService(properties.Web);
         {
             dataProvider.Delete(mappingSetting.TableName, mappingSetting.Key, properties.ListItemId);
         }
     }
     catch (Exception ex)
     {
         LogHelper.Instance.ErrorULS("ItemDeleting error", ex);
     }
 }
Ejemplo n.º 24
0
        protected override async Task InitializeAsync(INavigationParameters parameters)
        {
            await base.InitializeAsync(parameters);

            IEnumerable <LocalValidation> localValidations =
                (await AppDataService.GetLocalValidationsWhereNotUploadedByIdAsync(ValidationSessionId)).ToList();

            foreach (SamplePointViewModel samplePointViewModel in SamplePointsViewModel.Points)
            {
                if (localValidations.Any(x => x.SampleItem.Id == samplePointViewModel.Id))
                {
                    samplePointViewModel.Selected    = false;
                    samplePointViewModel.IsValidated = true;

                    if (ReferenceEquals(SelectedPoint, samplePointViewModel))
                    {
                        SelectedPoint = null;
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public async Task <TokenSeguridad> Autenticar(string usuario, string password)
        {
            var data = new
            {
                NombreUsuario         = usuario,
                Password              = password,
                ClaimResourceName     = "app_movil",
                ParametrosAdicionales = "Version:" + ParametrosSistema.AppVersion
            };
            var token = await _ds.RealizarPeticionApi <TokenSeguridad>("Autenticar", TipoPeticionApi.Post, data);

            if (token != null && !String.IsNullOrEmpty(token.access_token))
            {
                _ds = new AppDataService(token.access_token);
                //se guardan las credenciales de forma segura
                this.GuardarCredencialesUsuario(token.userName, password, null, null, token.access_token);

                //Se obtiene información del usuario
                Usuario infoUsuario = await this.SeleccionarUsuario(token.userName);

                if (infoUsuario != null)
                {
                    this.GuardarCredencialesUsuario(token.userName, password, infoUsuario.NumeroIdentificacion.ToString(), infoUsuario.NombreUsuario, token.access_token);
                    //se consultan y guardan los permisos del usuario
                    List <PermisoAplicacion> permisos = new List <PermisoAplicacion>();
                    permisos = await this.ObtenerPermisosUsuario();

                    string jsonPermisos = Newtonsoft.Json.JsonConvert.SerializeObject(permisos);
                    this.GuardarPermisosUsuario(jsonPermisos);

                    //Se resetea la variable estatica de permisos
                    ParametrosSistema.PermisosUsuarioAlmacenado = null;
                }
                else
                {
                    token = null;
                }
            }
            return(token);
        }
        protected override void OnNavigatedTo(NavigationEventArgs obj)
        {
            rootPage = (Application.Current as App).CurrentMain;
            int thoughtRecordId = Convert.ToInt32(obj.Parameter);

            if (thoughtRecordId != 0)
            {
                ViewModel = new ThoughtRecordEditModel(thoughtRecordId, AppDataService.GetDatabase(Application.Current));
            }
            else
            {
                ViewModel = new ThoughtRecordEditModel(AppDataService.GetDatabase(Application.Current));
            }
            rootPage.UpdateTitle(ViewModel.Title);
            ViewModel.OnThoughtRecordSaving           += ShowProgressRing;
            ViewModel.OnThoughtRecordSaved            += HideProgressRing;
            ViewModel.OnNewThoughtRecordOverwriteRisk += PromptToSave;
            ViewModel.OnNewThoughtRecordCreated       += UpdateMainMenu;
            this.Unloaded += ThoughtRecordEditPage_Unloaded;
            rootPage.NavigateWithMenuUpdate(this.GetType(), thoughtRecordId);
            base.OnNavigatedTo(obj);
        }
Ejemplo n.º 27
0
 private void InitializeCommands()
 {
     LoginTempCommand = new RelayCommand(async() =>
     {
         var u       = await DataService.LoginTemp();
         CurrentUser = u.user;
     });
     GetIdeasCommand = new RelayCommand(async() => await LoadIdeas());
     IdeaTapCommand  = new RelayCommand <ItemClickEventArgs>(async args =>
     {
         var clickedItem = args.ClickedItem as DJIdea;
         try
         {
             if (clickedItem.type == "listing")
             {
                 App.ViewModelLocator.Listing.CurrentListing = clickedItem.listing;
                 NavigationService.NavigateTo(typeof(ListingViewModel).FullName);
             }
             else if (clickedItem.type == "story")
             {
                 App.ViewModelLocator.Story.CurrentStory = await DataService.LoadStory(clickedItem.story.id);
                 NavigationService.NavigateTo(typeof(StoryViewModel).FullName);
             }
         }
         catch (Exception ex)
         {
             await new MessageDialog(ex.Message).ShowAsync();
         }
     });
     HamburgerClickCommand = new RelayCommand(async() =>
     {
         await AppDataService.SaveRemoteSettings();
         if (true)
         {
             var test  = await AppDataService.LoadRemoteSettings();
             TestValue = test.test_value;
         }
     });
 }
Ejemplo n.º 28
0
        private dynamic GetConfig(string iiid, string dataid, bool fromUrl)
        {
            var result = SearchService.GetMetadata(GetSearchMetadataRequest(iiid));

            var dataSource = GetFullAPIUrl(dataid);

            if (!fromUrl)
            {
                var content = (AppDataService.Get(dataid) as PKS.WebAPI.Models.IndexAppData).Content;
                dataSource = Convert.ToString(content);
            }
            dynamic data = new ExpandoObject();

            data.userid      = PKSUser.Identity.Id;
            data.iiid        = iiid;
            data.showtype    = result.ShowType;
            data.dataid      = result.DataId;
            data.createddate = result.GetValueBy(MetadataConsts.CreatedDate);
            data.title       = result.Title;
            data.author      = result.Author;
            data.Abstract    = result.Abstract;
            data.dataSource  = dataSource;
            return(data);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 下载
        /// </summary>
        /// <returns></returns>
        public bool DownloadFile(string iiid, string dataid)
        {
            var usercenterService = GetService <UserCenterService>();

            usercenterService.AddDownLoad(PKSUser.Identity.Id.ToInt32(), iiid);

            try
            {
                DownloadRequest downloadRequest = new DownloadRequest();
                downloadRequest.DataId   = dataid;
                downloadRequest.Source   = true;
                downloadRequest.Download = true;

                var    response = AppDataService.Download(downloadRequest);
                byte[] bytes    = new byte[(int)response.Content.Length];
                response.Content.Read(bytes, 0, bytes.Length);
                response.Content.Close();
                Response.ContentType = response.ContentType;
                //Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(response.FileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Disposition", "attachment;  filename=" + response.FileName);
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
            catch (Exception e)
            {
                string content = "下载失败:\r\n" + e.Message;
                byte[] bytes   = Encoding.UTF8.GetBytes(content);
                Response.ContentType = "text/plain";
                Response.AddHeader("Content-Disposition", "attachment;  filename=error.txt");
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();
            }
            return(true);
        }
Ejemplo n.º 30
0
        private void OnClick_btAssign(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(tbAssignNumber.Text))
            {
                MessageBox.Show("계약번호를 입력하여 주세요.");
            }
            else
            {
                string filename = AppDataService.GetFilePath("ISA.AssignNumber.txt");
                File.WriteAllText(filename, tbAssignNumber.Text);

                AssignService.AssignNumber = tbAssignNumber.Text;
                AssignService.DataIn();
                List <AssignModel> assigns = AssignService.Data;
                foreach (AssignModel assign in assigns)
                {
                    tbAssignNumber.Text     = assign.AssignNumber;
                    tbBizName.Text          = assign.BizName;
                    tbUserContact.Text      = assign.UserContact;
                    tbUserName.Text         = assign.UserName;
                    tbUserOrganization.Text = assign.UserOrganization;
                }
            }
        }