Exemple #1
0
        public string SaveCommission(CommissionRate cr, int userId)
        {
            if (db.CommissionRate.Where(c => c.id != cr.id && c.end_date > cr.begin_date && c.begin_date < cr.end_date && c.product_type == cr.product_type).Count() > 0)
            {
                return("此时间段与之前设置的时间段有重叠,保存失败");
            }
            try {
                if (cr.id != 0)
                {
                    //更新,将旧的删除
                    CommissionRate existed = db.CommissionRate.Single(c => c.id == cr.id);
                    BackupData     bd      = new BackupData();
                    bd.user_id        = userId;
                    bd.sys_no         = "佣金率维护";
                    bd.op_date        = DateTime.Now;
                    bd.main_data      = SomeUtils.ModelToString <CommissionRate>(existed);
                    bd.secondary_data = SomeUtils.ModelsToString <CommissionRateDetail>(existed.CommissionRateDetail.ToList());
                    db.BackupData.InsertOnSubmit(bd);

                    db.CommissionRateDetail.DeleteAllOnSubmit(existed.CommissionRateDetail);
                    db.CommissionRate.DeleteOnSubmit(existed);
                }

                db.CommissionRate.InsertOnSubmit(cr);
                db.SubmitChanges();
            }
            catch (Exception ex) {
                return(ex.Message);
            }

            return("");
        }
Exemple #2
0
        /// <summary>
        /// Generates the sample data.
        /// </summary>
        /// <returns>A set of Design-Time <see cref="BackupData"/> sample data.</returns>
        public BackupData GenerateSampleData()
        {
            if (this.classData == null)
            {
                /*// Das ist Model Stuff
                 * string str = string.Empty;
                 * using (
                 *  Stream stream =
                 *      typeof(DesignDataProvider).Assembly.GetManifestResourceStream(
                 *          "Jedzia.BackBock.ViewModel.Design.Data.BackupData01.xml"))
                 * {
                 *  TextReader txr = new StreamReader(stream);
                 *  str = txr.ReadToEnd();
                 * }
                 * classData = BackupData.Deserialize(str);*/
                this.classData = new BackupData {
                    DatasetGroup = "Main", DatasetName = "Daily"
                };

                this.classData.BackupItem.Add(
                    new BackupItemType
                {
                    ItemGroup = "Standard",
                    IsEnabled = true,
                    ItemName  = "All from Temp, exclude *.msi;B* "
                });
            }

            return(this.classData);
        }
Exemple #3
0
        private async Task <BackupData> GetBackupData()
        {
            BackupData backupData = null;

            RestoreListPickerItem selectedItem = RestorePicker.SelectedItem as RestoreListPickerItem;

            if (selectedItem != null && selectedItem.Value1 != null)
            {
                // Stáhnutí souboru
                string data = await LiveConnectHelper.DownloadAsync(selectedItem.Value1.Id);

                if (data != null)
                {
                    try
                    {
                        backupData = JsonConvert.DeserializeObject <BackupData>(data, new JsonSerializerSettings());
                    }
                    catch
                    {
                        backupData = null;
                    }
                }
            }

            return(backupData);
        }
        /// <summary>
        /// Discards changes since the last <see cref="IEditableObject.BeginEdit()"/> call.
        /// </summary>
        void IEditableObject.CancelEdit()
        {
            if (_backup == null)
            {
                Log.Debug("IEditableObject is not in edit state");
                return;
            }

            CancelEditCompletedEventArgs cancelEditCompletedEventArgs;
            var eventArgs = new CancelEditEventArgs(this);

            _cancelEditingEvent.SafeInvoke(this, eventArgs);
            OnCancelEdit(eventArgs);

            if (eventArgs.Cancel)
            {
                Log.Info("IEditableObject.CancelEdit is canceled by the event args");
                cancelEditCompletedEventArgs = new CancelEditCompletedEventArgs(true);
                _cancelEditingCompletedEvent.SafeInvoke(this, cancelEditCompletedEventArgs);
                OnCancelEditCompleted(cancelEditCompletedEventArgs);
                return;
            }

            Log.Debug("IEditableObject.CancelEdit");

            _backup.RestoreBackup();
            _backup = null;

            cancelEditCompletedEventArgs = new CancelEditCompletedEventArgs(false);
            _cancelEditingCompletedEvent.SafeInvoke(this, cancelEditCompletedEventArgs);
            OnCancelEditCompleted(cancelEditCompletedEventArgs);
        }
        /// <summary>
        /// 뒤로 가기 처리를 합니다.
        /// </summary>
        public bool Back(Intent context = null)
        {
            /// 화면 전환중일 경우에는 무시합니다.
            if (!isDone)
            {
                return(false);
            }

            /// 게임 모드에 따라 다르게 처리해야 합니다.
            /// TODO: 인게임 중일 경우 일시 정지 처리를 해야 합니다.
            if ((GameManager.playing && !GameManager.instance.isNewReplayPlaying) || GameManager.paused)
            {
                return(false);
            }

            if (sceneHistory.Count == 0)
            {
                return(false);
            }

            restoreScene = sceneHistory.Pop();
            if (restoreScene == null)
            {
                return(false);
            }

#if UNITY_EDITOR
            Debug.Log(string.Format("[SCENE] BACK: {0}", restoreScene.sceneName));
#endif
            var scene = sceneTable.GetScene(restoreScene.sceneName);
            SceneChangeContext = context;
            Change(scene);
            return(true);
        }
        /// <summary>
        /// Generates the sample data.
        /// </summary>
        /// <returns>A set of Design-Time <see cref="BackupData"/> sample data.</returns>
        public BackupData GenerateSampleData()
        {
            if (this.classData == null)
            {
                /*// Das ist Model Stuff
                string str = string.Empty;
                using (
                    Stream stream =
                        typeof(DesignDataProvider).Assembly.GetManifestResourceStream(
                            "Jedzia.BackBock.ViewModel.Design.Data.BackupData01.xml"))
                {
                    TextReader txr = new StreamReader(stream);
                    str = txr.ReadToEnd();
                }
                classData = BackupData.Deserialize(str);*/
                this.classData = new BackupData { DatasetGroup = "Main", DatasetName = "Daily" };

                this.classData.BackupItem.Add(
                    new BackupItemType
                        {
                            ItemGroup = "Standard",
                            IsEnabled = true,
                            ItemName = "All from Temp, exclude *.msi;B* "
                        });
            }

            return this.classData;
        }
        public async static Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", Route = Consts.Backups.ApiRouteBase + "/{version}/{id}")] HttpRequestMessage req,
                                                                string version,
                                                                string id,
                                                                [Table(Consts.Backups.TableStorageName, "{version}", "{id}")] BackupData backupData,
                                                                TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            if (backupData == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound));
            }

            var storageService = ServicesProvider.GetStorageService();
            var blob           = await storageService.GetCloudBlobReferenceAsync(Consts.Backups.BackupsBlobContainerName, $"{version}_{id}");

            var text = await blob.DownloadTextAsync();

            var formatter    = ServicesProvider.GetDataFormatter();
            var formatResult = formatter.FormatInitialData(text, backupData.DataFormat);

            return(formatResult.Formatted ?
                   req.CreateResponse(HttpStatusCode.OK, formatResult.FormattedObject, backupData.DataFormat) :
                   req.CreateResponse(HttpStatusCode.OK, text, backupData.DataFormat));
        }
Exemple #8
0
        private async Task ImportHistory(BackupData backupData, IDictionary <int, DAL.SupportTeam> teamMap, IDictionary <int, DAL.UserPhoneNumber> phoneNumberMap)
        {
            var teamHist = await db.ForwardingStates.GroupBy(s => s.TeamId,
                                                             (id, states) => new
            {
                TeamId = id, Min = states.Select(s => s.When).Min(), Max = states.Select(s => s.When).Max()
            }).ToDictionaryAsync(x => x.TeamId);

            foreach (var entry in backupData.History)
            {
                var team = teamMap[entry.TeamId];
                if (teamHist.TryGetValue(team.Id, out var hist))
                {
                    // Skip history update within known history
                    if (entry.When >= hist.Min && entry.When <= hist.Max)
                    {
                        continue;
                    }
                }

                DAL.UserPhoneNumber detected = null;
                if (entry.DetectedPhoneNumberId.HasValue)
                {
                    detected = phoneNumberMap[entry.DetectedPhoneNumberId.Value];
                }

                db.ForwardingStates.Add(new()
                {
                    Team                = team,
                    RawPhoneNumber      = entry.RawPhoneNumber,
                    DetectedPhoneNumber = detected,
                    When                = entry.When
                });
            }
        }
Exemple #9
0
        private async Task ImportSchedule(BackupData backupData, IDictionary <int, DAL.SupportTeam> teamMap,
                                          IDictionary <int, DAL.UserPhoneNumber> phoneNumberMap)
        {
            var teamLatest = await db.ScheduledForwards.GroupBy(s => s.TeamId,
                                                                (id, states) => new
            {
                TeamId = id, Latest = states.Select(s => s.When).Max()
            }).ToDictionaryAsync(x => x.TeamId, x => x.Latest);

            foreach (var entry in backupData.Schedule)
            {
                var team = teamMap[entry.TeamId];
                if (teamLatest.TryGetValue(team.Id, out var latest))
                {
                    // Skip schedule update within known schedule
                    if (entry.When <= latest)
                    {
                        continue;
                    }
                }

                db.ScheduledForwards.Add(new()
                {
                    Team = team, PhoneNumber = phoneNumberMap[entry.UserPhoneNumberId], When = entry.When
                });
            }
        }
Exemple #10
0
        public void SetUp()
        {
            BackupData backupData = new BackupData();

            backupData.DatasetName = "My Data Set";
            target = new BackupDataViewModel(backupData);
        }
Exemple #11
0
        public static async Task <bool> Backup(string fileName = null)
        {
            // Získání id složky
            string folderId = await LiveConnectHelper.SearchFolderIdAsync(BackupFolderName);

            if (folderId == null)
            {
                folderId = await LiveConnectHelper.CreateFolderAsync(LiveConnectHelper.Root, BackupFolderName);
            }

            // Nahrajeme soubor a získáme jeho id
            string fileId = null;

            if (folderId != null)
            {
                // Vytvoření dat
                BackupData backupData = new BackupData();
                backupData.Version  = App.VersionString;
                backupData.Created  = DateTime.UtcNow;
                backupData.Settings = Settings.Current;
                backupData.Tasks    = App.Tasks.Tasks;
#if DEBUG
                Formatting formatting = Formatting.Indented;
#else
                Formatting formatting = Formatting.None;
#endif
                string json = JsonConvert.SerializeObject(backupData, formatting);

                // Nahrání
                fileName = string.Format("{0}{1}", fileName ?? DateTime.Now.ToFileName(), BackupFileExtension);
                fileId   = await LiveConnectHelper.UploadAsync(folderId, fileName, json);
            }

            return(fileId != null);
        }
        public EditBackupItemViewModel(INavigationService navigationService, BackupData backupData, Func <Type, ILogger> loggerFactory) : base(navigationService)
        {
            Title = "Edit";

            _logger = loggerFactory(typeof(EditBackupItemViewModel));

            _backupData = backupData;
        }
 void IEditableObject.CancelEdit()
 {
     if (inTxn)
     {
         this.backupData = backupDataBackup;
         inTxn           = false;
     }
 }
 // Implements IEditableObject
 void IEditableObject.BeginEdit()
 {
     if (!inTxn)
     {
         this.backupDataBackup = backupData;
         inTxn = true;
     }
 }
Exemple #15
0
        public override string SaveBill(System.Web.Mvc.FormCollection fc, UserInfo user)
        {
            bill = new ChBill();
            SomeUtils.SetFieldValueToModel(fc, bill);
            List <ChBillDetail> details = JsonConvert.DeserializeObject <List <ChBillDetail> >(fc.Get("ch_bill_details"));

            bill.ChBillDetail.AddRange(details);

            try {
                //保存送货地址信息
                var dInfos = new OtherSv().GetDeliveryInfo(bill.customer_no)
                             .Where(d => d.deliveryUnit == bill.delivery_unit && d.attn == bill.delivery_attn &&
                                    d.addr == bill.delivery_addr && d.phone == bill.delivery_phone).Count();
                if (dInfos == 0)
                {
                    var info = new CustomerDeliveryInfo()
                    {
                        customer_name   = bill.customer_name,
                        customer_number = bill.customer_no,
                        delivery_unit   = bill.delivery_unit,
                        addr            = bill.delivery_addr,
                        attn            = bill.delivery_attn,
                        phone           = bill.delivery_phone,
                        op_date         = DateTime.Now,
                        op_name         = user.realName
                    };
                    db.CustomerDeliveryInfo.InsertOnSubmit(info);
                }

                var existsed = db.ChBill.Where(c => c.sys_no == bill.sys_no).ToList();
                if (existsed.Count() > 0)
                {
                    //备份旧单
                    BackupData bd = new BackupData();
                    bd.sys_no         = bill.sys_no;
                    bd.op_date        = DateTime.Now;
                    bd.user_id        = user.userId;
                    bd.main_data      = SomeUtils.ModelToString <ChBill>(existsed.First());
                    bd.secondary_data = SomeUtils.ModelsToString <ChBillDetail>(existsed.First().ChBillDetail.ToList());
                    db.BackupData.InsertOnSubmit(bd);

                    //删掉旧单
                    db.ChBillDetail.DeleteAllOnSubmit(existsed.First().ChBillDetail);
                    db.ChBill.DeleteAllOnSubmit(existsed);
                }
                bill.bill_date = DateTime.Now;
                bill.user_id   = user.userId;

                db.ChBill.InsertOnSubmit(bill);
                db.ChBillDetail.InsertAllOnSubmit(bill.ChBillDetail);
                db.SubmitChanges();
            }
            catch (Exception ex) {
                return(ex.Message);
            }

            return("");
        }
 public static BackupData FromDTO(this DTO.BackupData source)
 {
     var h = new BackupData();
     h.DatasetGroup = source.DatasetGroup;
     h.DatasetName = source.DatasetName;
     if (source.BackupItem != null)
         h.BackupItem = source.BackupItem.Select(wld => wld.FromDTO()).ToList();
     return h;
 }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", "put", Route = Consts.Backups.ApiRouteBase + "/{version}/{id}")] HttpRequestMessage req,
            string version,
            string id,
            [Table(Consts.Backups.TableStorageName, "{version}", "{id}")] BackupKey backupKey,
            [Table(Consts.Backups.TableStorageName)] CloudTable table,
            TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            var createdNew = false;

            if (backupKey == null)
            {
                createdNew = true;
                backupKey  = new BackupKey
                {
                    PartitionKey = version,
                    RowKey       = id,
                    Id           = Guid.NewGuid()
                };

                var insert = TableOperation.Insert(backupKey);
                await table.ExecuteAsync(insert);
            }

            var retreiveData     = TableOperation.Retrieve <BackupData>(version, id);
            var backupDataResult = await table.ExecuteAsync(retreiveData);

            var backupData = backupDataResult.Result as BackupData;

            if (backupData == null)
            {
                backupData = new BackupData();
            }

            backupData.BackupVersion = Consts.Backups.BackupVersion;
            backupData.DataFormat    = req.Content.Headers.ContentType.MediaType;
            backupData.Data          = await req.Content.ReadAsStringAsync();

            backupData.LastSaveUTCTime = DateTime.UtcNow;

            log.Info($"Saving read data: {backupData.Data}");

            var storageService = ServicesProvider.GetStorageService();
            var blob           = await storageService.GetCloudBlobReferenceAsync(Consts.Backups.BackupsBlobContainerName, $"{version}_{id}");

            blob.Properties.ContentType = req.Content.Headers.ContentType.MediaType;
            await blob.UploadTextAsync(backupData.Data);

            backupData.Data = blob.Uri.ToString();

            var update       = TableOperation.InsertOrReplace(backupData);
            var updateResult = await table.ExecuteAsync(update);

            return(req.CreateResponse(createdNew ? HttpStatusCode.Created : HttpStatusCode.Accepted));
        }
        /// <summary>
        /// 현재 씬을 백업하지 않고, 씬을 이동합니다.
        /// </summary>
        /// <param name="sceneName"></param>
        /// <param name="it"></param
        public void Penetration(string sceneName, Intent it)
        {
            if (isDone == false)
            {
#if DEBUG
                Debug.LogError("화면 전환 중 요청이 들어와 무시합니다.");
#endif
                return;
            }

            var scene = sceneTable.GetScene(sceneName);
            if (scene == null)
            {
#if UNITY_EDITOR
                Debug.Log(string.Format("[SCENE] No Exist: {0}", sceneName));
#endif
                return;
            }

            /// 현재 선택된 화면일 경우 화면 전환 무시
            string currentScene = sceneData.name;
            if (string.IsNullOrEmpty(currentScene) == false)
            {
                bool found = currentScene.Equals(sceneName);
                if (found)
                {
#if UNITY_EDITOR
                    Debug.Log(string.Format("[SCENE] Screen Duplication: {0}", scene));
#endif
                    return;
                }
            }

            /// 이동할 씬이 메인 화면이라면 뒤로 가기 정보를 초기화합니다.
            if (scene.resetBackup == true)
            {
                ResetBackup();
                if (TOP_MENU_NAMES.Any(t => t.Equals(scene.name, StringComparison.OrdinalIgnoreCase)))
                {
                    ResetBackup();
                    BackupData backup = new BackupData();

                    backup.sceneName = "Menu";
                    backup.ui        = UIManager.instance.Backup();
                    backup.gameMode  = GameModeManager.instance.Backup();
                    sceneHistory.Push(backup);
                }
            }

            SceneChangeContext = it;

#if UNITY_EDITOR
            Debug.Log(string.Format("[SCENE] Penetration: {0}", sceneName));
#endif
            Change(scene);
        }
 void IBackup.Backup(BackupData data)
 {
     data.Push(this._args);
     data.Push(this._error);
     data.Push(this._isDisposed);
     data.Push(this._results);
     data.Push(this._tracker);
     data.Push(this.OverrideDisplayName);
     data.Push(this.Comment);
 }
 void IBackup.Restore(BackupData data)
 {
     data.Pull(ref this._args);
     data.Pull(ref this._error);
     data.Pull(ref this._isDisposed);
     data.Pull(ref this._results);
     data.Pull(ref this._tracker);
     this.OverrideDisplayName = data.Pull <string>();
     this.Comment             = data.Pull <string>();
 }
Exemple #21
0
        public ActionResult <GlobalStructureList> ReadStructuresDB([FromBody] BackupData aSelectBackupDir)
        {
            var BackupGlobalStructureList = new ConfigurationManager <GlobalStructureList>();

            BackupGlobalStructureList.ConfigFilename = Path.Combine(
                BackupManager.BackupDir, aSelectBackupDir.backup,
                @"Saves\Games", Path.GetFileName(EmpyrionConfiguration.SaveGamePath), @"Mods\EWA\DB\GlobalStructureList.json");
            BackupGlobalStructureList.Load();

            return(BackupGlobalStructureList.Current);
        }
Exemple #22
0
        public ActionResult <string[]> ReadPlayfields([FromBody] BackupData aSelectBackupDir)
        {
            var TemplatesPath = Path.Combine(
                BackupManager.BackupDir, aSelectBackupDir.backup,
                @"Saves\Games", Path.GetFileName(EmpyrionConfiguration.SaveGamePath), @"Templates");

            return(Directory
                   .EnumerateDirectories(TemplatesPath)
                   .Select(D => Path.GetFileName(D))
                   .ToArray());
        }
Exemple #23
0
        /// <summary>
        /// Saves the specified <see cref="BackupData"/> to disk.
        /// </summary>
        /// <param name="data">The data to save.</param>
        /// <param name="filename">The path to the stored <see cref="BackupData"/> on disk.</param>
        /// <param name="user">The requesting user with permissions.</param>
        /// <param name="parameters">Optional specified parameters. Can be <c>null</c>.</param>
        public void Save(BackupData data, string filename, IPrincipal user, StringDictionary parameters)
        {
            // use the
            var repo     = this.repositories.First(x => x.RepositoryType == BackupRepositoryType.FileSystemProvider);
            var fileRepo = (BackupDataFsRepository)repo;

            // var repo = repositories.OfType<BackupDataFsRepository>().First();
            fileRepo.SaveBackupData(data.ToDTO(), filename, parameters);

            // throw new NotImplementedException();
        }
 public BackupItemViewModel(INavigationService navigationService, Func <Lua> luaCreator, IEventAggregator eventAggregator, Func <Type, ILogger> loggerFactory, IContainer container, BackupData backupData) : base(navigationService)
 {
     _logger                = loggerFactory(typeof(BackupItemViewModel));
     _luaCreator            = luaCreator;
     _eventAggregator       = eventAggregator;
     _container             = container;
     _backupData            = backupData;
     BackupCommand          = new AsyncCommand(BackupAsync);
     OpenSourceCommand      = new Command(OpenSource);
     OpenDestinationCommand = new Command(OpenDestination);
 }
Exemple #25
0
        public string DeleteDR(int billId, bool alsoDeleteBox, int userId, string userName)
        {
            var dr      = db.DRBills.Where(d => d.bill_id == billId).FirstOrDefault();
            var details = db.DRBillDetails.Where(d => d.bill_id == billId).ToList();

            if (dr == null)
            {
                throw new Exception("此申请单不存在,可能已被删除");
            }
            if (!new string[] { "未提交", "已拒绝" }.Contains(dr.p_status))
            {
                throw new Exception("当前申请单状态是:" + dr.p_status + ",不能删除");
            }

            string deleteInfo = dr.bill_no + ":";

            //先备份
            var backup = new BackupData();

            backup.account   = dr.account;
            backup.user_id   = userId;
            backup.user_name = userName;
            backup.op_date   = DateTime.Now;
            backup.bill_no   = dr.bill_no;
            backup.head      = JsonConvert.SerializeObject(dr);
            backup.details   = JsonConvert.SerializeObject(details);
            db.BackupData.InsertOnSubmit(backup);

            //删除单据
            db.DRBills.DeleteOnSubmit(dr);
            db.DRBillDetails.DeleteAllOnSubmit(details);

            //删除关联箱子
            foreach (var box in db.OuterBoxes.Where(o => o.bill_id == billId))
            {
                if (alsoDeleteBox)
                {
                    deleteInfo += new BoxSv().RemoveOuterBox(box.outer_box_id) + ";";
                    //int outerBoxId = box.outer_box_id;
                    //db.OuterBoxes.DeleteOnSubmit(box);
                    //db.OuterBoxPOs.DeleteAllOnSubmit(db.OuterBoxPOs.Where(p => p.out_box_id == outerBoxId));
                    //db.OuterBoxesDetail.DeleteAllOnSubmit(db.OuterBoxesDetail.Where(d => d.outer_box_id == outerBoxId));
                    //db.InneBoxes.DeleteAllOnSubmit(db.InneBoxes.Where(i => i.outer_box_id == outerBoxId));
                    //db.InnerBoxesDetail.DeleteAllOnSubmit(db.InnerBoxesDetail.Where(i => i.outer_box_id == outerBoxId));
                }
                else
                {
                    box.bill_id = null;
                }
            }
            db.SubmitChanges();
            return(deleteInfo);
        }
Exemple #26
0
        public static BackupData FromDTO(this DTO.BackupData source)
        {
            var h = new BackupData();

            h.DatasetGroup = source.DatasetGroup;
            h.DatasetName  = source.DatasetName;
            if (source.BackupItem != null)
            {
                h.BackupItem = source.BackupItem.Select(wld => wld.FromDTO()).ToList();
            }
            return(h);
        }
Exemple #27
0
        public static DTO.BackupData ToDTO(this BackupData source)
        {
            var h = new DTO.BackupData();

            h.DatasetGroup = source.DatasetGroup;
            h.DatasetName  = source.DatasetName;
            if (source.BackupItem != null)
            {
                h.BackupItem = source.BackupItem.ConvertAll(wld => wld.ToDTO()).ToArray();
            }
            return(h);
        }
        private async void Load()
        {
            try
            {
                await InitIoCContainerAsync();

                await BackupData.Init();

                baseDataFetcher = IoCManager.Resolve <IBaseDataFetcher>();

                var networkAccessStatus = IoCManager.Resolve <INetworkAccessChecker>().GetNetworkAccessStatus();

                if (networkAccessStatus != NetworkAccessStatus.NoAccess)
                {
                    await CheckForUpdatedDatabase();
                }
                else
                {
                    errorTitle   = Strings.LoadingPageViewModel_BaseData_DownloadFailed_Title;
                    errorMessage = Strings.LoadingPageViewModel_BaseData_DatabaseUpToDateCheckFailed;
                }

                if (!isDatabaseUpToDate)
                {
                    if (networkAccessStatus == NetworkAccessStatus.MobileAccess && Settings.WifiOnly)
                    {
                        actionOnUiThread = AskUserDownloadDataViaMobile;
                        // if the app is not sleeping ask the user whether to download via mobile otherwise wait for wake up
                        if (!isSleeping)
                        {
                            Device.BeginInvokeOnMainThread(actionOnUiThread);
                        }

                        return;
                    }

                    await UpdateDatabase();
                }

                await AchievementManager.UpdateServerAndLocalState();
            }
            catch (Exception e)
            {
                // Catch all exceptions happening on startup cause otherwise the loading page will be shown indefinitely
                // This should only happen during development
                errorMessage = null;
                errorTitle   = null;
                Debug.WriteLine(e);
            }

            LoadCacheAndStart();
        }
Exemple #29
0
        public override string SaveBill(System.Web.Mvc.FormCollection fc, UserInfo user)
        {
            bill = new Sale_eo_bill();
            SomeUtils.SetFieldValueToModel(fc, bill);
            bill.Sale_eo_bill_detail.AddRange(JsonConvert.DeserializeObject <List <Sale_eo_bill_detail> >(fc.Get("details")));

            if (string.IsNullOrEmpty(bill.clerk_no))
            {
                return("营业员请输入厂牌或姓名然后按回车键搜索后,在列表中选择");
            }

            try {
                var existedBill = db.Sale_eo_bill.Where(s => s.sys_no == bill.sys_no).FirstOrDefault();
                if (existedBill != null)
                {
                    bill.applier_id   = existedBill.applier_id;
                    bill.applier_name = existedBill.applier_name;
                    bill.apply_time   = existedBill.apply_time;

                    //备份
                    JsonSerializerSettings js = new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    };
                    BackupData bd = new BackupData();
                    bd.op_date        = DateTime.Now;
                    bd.sys_no         = existedBill.sys_no;
                    bd.user_id        = user.userId;
                    bd.main_data      = JsonConvert.SerializeObject(existedBill, js);
                    bd.secondary_data = JsonConvert.SerializeObject(existedBill.Sale_eo_bill_detail, js);
                    db.BackupData.InsertOnSubmit(bd);

                    //删除
                    db.Sale_eo_bill_detail.DeleteAllOnSubmit(existedBill.Sale_eo_bill_detail);
                    db.Sale_eo_bill.DeleteOnSubmit(existedBill);
                }
                else
                {
                    bill.applier_id   = user.userId;
                    bill.applier_name = user.realName;
                    bill.apply_time   = DateTime.Now;
                }

                db.Sale_eo_bill.InsertOnSubmit(bill);
                db.Sale_eo_bill_detail.InsertAllOnSubmit(bill.Sale_eo_bill_detail);
                db.SubmitChanges();
            }
            catch (Exception ex) {
                return(ex.Message);
            }
            return("");
        }
        private void Backup()
        {
            BackupData backup = new BackupData();

            backup.sceneName = sceneData.name;
            backup.ui        = UIManager.instance.Backup();
            backup.gameMode  = GameModeManager.instance.Backup();

            sceneHistory.Push(backup);
#if UNITY_EDITOR
            Debug.Log("[SCENE] Scene Backup");
#endif
        }
Exemple #31
0
        public void BackupDataViewModelConstructorTest()
        {
            BackupData          backupData = null; // TODO: Initialize to an appropriate value
            BackupDataViewModel target     = new BackupDataViewModel(backupData);
            // Todo: Guard checks for initialization arguments.

            /*AssertEx.IsNull(target.DatasetName);
             * string expected = "A new name.";
             * string actual;
             * target.DatasetName = expected;
             * actual = target.DatasetName;
             * Assert.AreEqual(expected, actual);*/
        }
        private async Task UpdateAchievements()
        {
            await BackupData.WaitForInitAsync();

            Achievements.Clear();
            if (IsLoggedIn) //current user is logged in to the server
            {
                try
                {
                    var newlyUnlocked = await IoCManager.Resolve <IAchievementFetcher>().UpdateAchievements();

                    AchievementNotification.QueueAchievementNotifications(newlyUnlocked);

                    var achievementCounter = 0;
                    var unlockedCounter    = 0;
                    foreach (var achievement in DbManager.DataAccess.Achievements().GetAchievements())
                    {
                        Achievements.Add(AchievementViewModel.CreateFrom(achievement));

                        if (achievement.IsUnlocked)
                        {
                            unlockedCounter++;
                        }

                        achievementCounter++;
                    }

                    Score            = $"{Strings.AchievementsScreenView_Score} {AppSharedData.CurrentAchievementsScore()}";
                    AchievementCount = $"{unlockedCounter + "/" + achievementCounter}{Strings.AchievementsScreenView_Achievement_Count}";
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);

                    if ((((WebException)e.InnerException).Response as HttpWebResponse)?.StatusCode == HttpStatusCode.InternalServerError)
                    {
                        await IoCManager.Resolve <INavigationService>()
                        .DisplayAlert(Strings.Alert_Server_Error_Title,
                                      Strings.Alert_Server_Error_Description,
                                      Strings.Alert_Confirm);
                    }
                    else
                    {
                        await IoCManager.Resolve <INavigationService>()
                        .DisplayAlert(Strings.Alert_Network_Error_Title,
                                      Strings.Alert_Network_Error_Description,
                                      Strings.Alert_Confirm);
                    }
                }
            }
        }
 /// <summary>
 /// Opens a new set of Backup Data from the specified file name.
 /// </summary>
 /// <param name="path">The full path to the backup data file on disk.</param>
 internal void OpenFile(string path)
 {
     // Todo: switch this to this.dataprovider.Load( ... );
     //this.Data2 = ModelLoader.LoadBackupData(path);
     this.Data2 = dataprovider.Load(path, new MyPrincipal(), null);
     Data = new BackupDataViewModel(this.Data2);
     //this.mainWindow.Designer.DataContext = bdvm;
 }
Exemple #34
0
        /// <summary>
        /// Saves the specified <see cref="BackupData"/> to disk.
        /// </summary>
        /// <param name="data">The data to save.</param>
        /// <param name="filename">The path to the stored <see cref="BackupData"/> on disk.</param>
        /// <param name="user">The requesting user with permissions.</param>
        /// <param name="parameters">Optional specified parameters. Can be <c>null</c>.</param>
        public void Save(BackupData data, string filename, IPrincipal user, StringDictionary parameters)
        {
            // use the
            var repo = this.repositories.First(x => x.RepositoryType == BackupRepositoryType.FileSystemProvider);
            var fileRepo = (BackupDataFsRepository)repo;

            // var repo = repositories.OfType<BackupDataFsRepository>().First();
            fileRepo.SaveBackupData(data.ToDTO(), filename, parameters);

            // throw new NotImplementedException();
        }
        void InitIfNeeded()
        {
            if (s_Styles == null)
                s_Styles = new Styles ();

            if (_backupData == null)
                _backupData = new BackupData();

            // Reconstruct state after domain reloading
            if (_textView == null && !string.IsNullOrEmpty(_filePath))
            {
                OpenFile (_filePath);
                _textView.Document.Caret.SetPosition(_backupData.caretRow, _backupData.caretColumn);
                _textView.ScrollOffset = _backupData.scrollOffset;
                _textView.SelectionAnchor = new Position((int)_backupData.selectionAnchor.y, (int)_backupData.selectionAnchor.x);
            }
        }
 public DTO.BackupData ConvertToDTO(BackupData source)
 {
     return source.ToDTO();
 }
        /// <summary>
        /// Discards changes since the last <see cref="IEditableObject.BeginEdit()"/> call.
        /// </summary>
        void IEditableObject.CancelEdit()
        {
            CancelEditCompletedEventArgs cancelEditCompletedEventArgs;
            var eventArgs = new CancelEditEventArgs(this);
            _cancelEditingEvent.SafeInvoke(this, eventArgs);
            OnCancelEdit(eventArgs);

            if (eventArgs.Cancel)
            {
                Log.Info("IEditableObject.CancelEdit is canceled by the event args");
                cancelEditCompletedEventArgs = new CancelEditCompletedEventArgs(true);
                _cancelEditingCompletedEvent.SafeInvoke(this, cancelEditCompletedEventArgs);
                OnCancelEditCompleted(cancelEditCompletedEventArgs);
                return;
            }

            if (_backup == null)
            {
                cancelEditCompletedEventArgs = new CancelEditCompletedEventArgs(true);
                _cancelEditingCompletedEvent.SafeInvoke(this, cancelEditCompletedEventArgs);
                OnCancelEditCompleted(cancelEditCompletedEventArgs);
                return;
            }

            Log.Debug("IEditableObject.CancelEdit");

            _backup.RestoreBackup();
            _backup = null;

            cancelEditCompletedEventArgs = new CancelEditCompletedEventArgs(false);
            _cancelEditingCompletedEvent.SafeInvoke(this, cancelEditCompletedEventArgs);
            OnCancelEditCompleted(cancelEditCompletedEventArgs);
        }
        private BackupDataViewModel GetSampleData()
        {
            //System.Diagnostics.Debugger.Launch();

            //MessageBox.Show("Before MainWindowViewModel GetSampleData");
            //string connection = null;
            /*if (dataprovider.ServiceType == BackupRepositoryType.FileSystemProvider)
            {
                var startupPath = applicationContext.Settings.GetStartupDataFile();
                connection = startupPath;
            }*/
            // this.Data2 = dataprovider.GetBackupData(new MyPrincipal());
            // this.Data2 = dataprovider.GetBackupData(connection, new MyPrincipal(), null);

            // load static => this is the sample data. BackupRepositoryType.FileSystemProvider is
            // "load from file" and BackupRepositoryType.Database from a database.
            this.Data2 = dataprovider.GetBackupData(BackupRepositoryType.Static, new MyPrincipal(), null);
            //MessageBox.Show("After MainWindowViewModel GetSampleData");
            return new BackupDataViewModel(this.Data2);
        }
 /// <summary>
 /// Saves the specified <see cref="BackupData"/> to disk.
 /// </summary>
 /// <param name="data">The data to save.</param>
 /// <param name="filename">The path to the stored <see cref="BackupData"/> on disk.</param>
 /// <param name="user">The requesting user with permissions.</param>
 /// <param name="parameters">Optional specified parameters. Can be <c>null</c>.</param>
 public void Save(BackupData data, string filename, IPrincipal user, StringDictionary parameters)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Pushes changes since the last <see cref="IEditableObject.BeginEdit()"/> call.
        /// </summary>
        void IEditableObject.EndEdit()
        {
            if (_backup == null)
            {
                return;
            }

            var eventArgs = new EndEditEventArgs(this);
            _endEditingEvent.SafeInvoke(this, eventArgs);
            OnEndEdit(eventArgs);

            if (eventArgs.Cancel)
            {
                Log.Info("IEditableObject.EndEdit is canceled by the event args");
                return;
            }

            Log.Debug("IEditableObject.EndEdit");

            _backup = null;
        }
        /// <summary>
        /// Begins an edit on an object.
        /// </summary>
        void IEditableObject.BeginEdit()
        {
            var eventArgs = new BeginEditEventArgs(this);
            _beginEditingEvent.SafeInvoke(this, eventArgs);
            OnBeginEdit(eventArgs);

            if (_backup != null)
            {
                return;
            }

            if (eventArgs.Cancel)
            {
                Log.Info("IEditableObject.BeginEdit is canceled by the event args");
                return;
            }

            Log.Debug("IEditableObject.BeginEdit");

            _backup = new BackupData(this);
        }
Exemple #42
0
        private void GetLawyersDataBtn_Click(object sender, System.EventArgs e)
        {
            ShowState.Text = "备份操作开始......";
            ShowState.Refresh();

            BackupData BKData = new BackupData(WebName.Text, UserID.Text, PSWord.Text);
            BKData.ShowState = ShowState;
            BKData.StateBar = PBLine;

            if (DownCardNo.Checked)
            {
                BKData.BKLawyersInfo(LawyerPhoto.Checked);
                MessageBox.Show("完成律师资料/照片的本地备份...");
            }

            if (DownLessonInfo.Checked)
            {
                BKData.BKLessonsInfo();
                Thread.Sleep(2000);
                InitSKClassID(false, OldLessonType.Checked);

                MessageBox.Show("完成课程资料的本地备份...");
            }
        }
Exemple #43
0
        private void UploadBtn_Click(object sender, System.EventArgs e)
        {
            ShowState.Text = "上传操作开始......";
            ShowState.Refresh();

            BackupData BKData = new BackupData(WebName.Text, UserID.Text, PSWord.Text);
            BKData.ShowState = ShowState;
            BKData.StateBar = PBLine;

            int RecsNum = BKData.UploadSKRecs();

            AutoExportNum.Text = (Convert.ToInt16(AutoExportNum.Text) + RecsNum).ToString();
            MessageBox.Show(string.Format("完成 {0} 条记录的上传......", RecsNum));
        }
 public void SetUp()
 {
     BackupData backupData = new BackupData();
     backupData.DatasetName = "My Data Set";
     target = new BackupDataViewModel(backupData);
 }
Exemple #45
0
        public void AutoSKRecsExport()
        {
            BackupData BKData = new BackupData(WebName.Text, UserID.Text, PSWord.Text);
            BKData.ShowState = ShowState;
            BKData.StateBar = PBLine;

            while (true)
            {
                int RecsNum = BKData.UploadSKRecs();
                AutoExportNum.Text = (Convert.ToInt16(AutoExportNum.Text) + RecsNum).ToString();

                Thread.Sleep(6000);
            }
        }