Ejemplo n.º 1
0
 void GenerateTestCrash(object sender, System.EventArgs e)
 {
     Crashes.GenerateTestCrash();
 }
Ejemplo n.º 2
0
        public void ChangeStoryView()
        {
            try
            {
                if (!Timerstory.Enabled)
                {
                    Timerstory.Enabled             = true;
                    Timerprogress.Enabled          = true;
                    StoriesProgressViewDisplay.Max = 100;
                }

                progrescount = 0;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
                {
                    StoriesProgressViewDisplay.SetProgress(progrescount, true);
                }
                else
                {
                    try
                    {
                        // For API < 24
                        StoriesProgressViewDisplay.Progress = progrescount;
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                }

                countstory++;
                CountStoryText.Text = (count - countstory).ToString();

                if (countstory <= count - 1)
                {
                    var dataStory = ListOfStories.FirstOrDefault();
                    if (dataStory.Key != null)
                    {
                        var type = IMethods.AttachmentFiles.Check_FileExtension(dataStory.Key);
                        if (type == "Video")
                        {
                            SetVideoStory(dataStory.Key, dataStory.Value);
                        }
                        else if (type == "Image")
                        {
                            SetImageStory(dataStory.Key, dataStory.Value);
                        }

                        ListOfStories.Remove(dataStory.Key);
                    }
                }
                else
                {
                    Finish();

                    Timerstory.Enabled = false;
                    Timerstory.Stop();

                    Timerprogress.Enabled = false;
                    Timerprogress.Stop();
                }
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
        }
Ejemplo n.º 3
0
 public UpdatePage()
 {
     try { InitializeComponent(); } catch (Exception ex) { Crashes.TrackError(ex); }
 }
Ejemplo n.º 4
0
    private void RenumberWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (!(e.Argument is WorkerParameters workerParameter))
        {
            return;
        }

        try
        {
            int currentEpisodeNumber = workerParameter.EpisodeNumberStart;

            for (int i = 0; i < workerParameter.SelectedEpisodes.Count; i++)
            {
                var episodeFilePath = workerParameter.SelectedEpisodes[i];

                string curDir = Path.GetDirectoryName(episodeFilePath);

                if (string.IsNullOrEmpty(curDir))
                {
                    WriteOutput("Could not find directory, skipping.", OutputMessageLevel.Error);
                    continue;
                }

                string curName = Path.GetFileName(episodeFilePath);

                if (string.IsNullOrEmpty(curName))
                {
                    WriteOutput("Could not find file, skipping.", OutputMessageLevel.Error);
                    continue;
                }

                // Using substring and Length so that user doesn't need an exact natch (e.g. episode number will be different for each selected episode, thus only one selection will get renamed... the exact match)
                var selectedText = curName.Substring(0, workerParameter.SelectedTextLength);

                // Get the show name to workaround not being able to select exact text
                var showName = Directory.GetParent(episodeFilePath)?.Parent?.Name;

                // Prefix the name name with the Show, then the season, then the episode number
                string newName = curName.Replace(selectedText, $"{showName} - S{workerParameter.SeasonNumber}E{currentEpisodeNumber:00} -", StringComparison.InvariantCulture);

                // If this is not a preview run, invoke the file rename
                if (!workerParameter.IsPreview)
                {
                    File.Move(episodeFilePath, Path.Combine(curDir, newName));
                }

                // Increment the episode number
                currentEpisodeNumber++;

                // Report progress
                var progressParameter = new WorkerProgress
                {
                    IsPreview       = workerParameter.IsPreview,
                    PercentComplete = i / workerParameter.SelectedEpisodes.Count * 100,
                    BusyMessage     = $"Completed: S{workerParameter.SeasonNumber}E{currentEpisodeNumber:00}...",
                    FileName        = newName
                };

                renumberWorker.ReportProgress(progressParameter.PercentComplete, progressParameter);
            }

            e.Result = new WorkerResult()
            {
                FinalMessage = $"Complete, renumbered {workerParameter.SelectedEpisodes.Count} episodes.",
                IsPreview    = workerParameter.IsPreview
            };
        }
        catch (Exception ex)
        {
            WriteOutput(ex.Message, OutputMessageLevel.Error);

            Crashes.TrackError(ex, new Dictionary <string, string>
            {
                { "Renumber Episode", "TV Show" }
            });
        }
    }
Ejemplo n.º 5
0
        /// <summary>
        /// Load all studies the current user is participating at.
        /// </summary>
        /// <returns>Returns a task as this is a async method.</returns>
        private async Task LoadStudies()
        {
            try
            {
                var documents = await CrossCloudFirestore.Current
                                .Instance
                                .GetCollection(QUser.CollectionPath)
                                .WhereEqualsTo("Email", this._user.Email)
                                .GetDocumentsAsync();

                IEnumerable <QUser> myModel = documents.ToObjects <QUser>();
                _user.ActiveStudies = myModel.First().ActiveStudies;
                _user.ActiveStudiesObjects.Clear();

                bool          userChanged = false;
                List <string> toDelete    = new List <string>();

                foreach (var study in _user.ActiveStudies)
                {
                    var studyDoc = await CrossCloudFirestore.Current
                                   .Instance
                                   .GetCollection(QStudy.CollectionPath)
                                   .GetDocument(study)
                                   .GetDocumentAsync();

                    QStudy temp = studyDoc.ToObject <QStudy>();

                    if (!temp.Team.Equals("System") && !(!(temp.EndDate < DateTime.Now) | (temp.EndDate == DateTime.MinValue)))
                    {
                        toDelete.Add(temp.Id);
                        userChanged = true;
                    }
                    else
                    {
                        if (temp.Team.Equals("System") && temp.Title.Equals("Add"))
                        {
                            temp.Command = new DelegateCommand(() =>
                            {
                                (Xamarin.Forms.Application.Current as App).GetNavigationService().NavigateAsync("FindAllStudiesView", null, null, false);
                            });
                        }
                        else
                        {
                            temp.Command = new DelegateCommand(() =>
                            {
                                var navigationParams = new NavigationParameters();
                                navigationParams.Add("study", temp);

                                (Xamarin.Forms.Application.Current as App).GetNavigationService().NavigateAsync("StudyDetailView", navigationParams, null, false);
                            });
                        }

                        var elementsDoc = await CrossCloudFirestore.Current
                                          .Instance
                                          .GetCollection(QStudy.CollectionPath + "/" + temp.Id + "/" + QElement.CollectionPath)
                                          .GetDocumentsAsync();

                        IEnumerable <QElement> elements = elementsDoc.ToObjects <QElement>();

                        if (elements.Count() > 0)
                        {
                            temp.Elements = new List <QElement>(elements.ToList());
                        }

                        _user.ActiveStudiesObjects.Add(temp);
                    }
                }

                await BlobCache.UserAccount.InsertObject("user", CurrentUser.Instance.User);

                if (userChanged)
                {
                    _user.ActiveStudies = _user.ActiveStudies.Except(toDelete).ToList();
                    Update("AciveStudies", _user.ActiveStudies);
                }
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
        }
 private void CrashWithTestException_Click(object sender, RoutedEventArgs e)
 {
     HandleOrThrow(() => Crashes.GenerateTestCrash());
 }
Ejemplo n.º 7
0
        public ReceivablesPageViewModel(INavigationService navigationService,
                                        IReceiptCashService receiptCashService,
                                        IDialogService dialogService,
                                        IProductService productService,
                                        IUserService userService,
                                        ITerminalService terminalService,
                                        IWareHousesService wareHousesService,
                                        IAccountingService accountingService

                                        ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "应收款";

            _receiptCashService = receiptCashService;

            //绑定数据
            this.Load = AmountReceivableGroupsLoader.Load(async() =>
            {
                var pending = new List <AmountReceivableGroupModel>();

                try
                {
                    //这里只取选择客户
                    int?terminalId     = Filter.TerminalId;
                    int businessUserId = Filter.BusinessUserId;
                    if (businessUserId == 0)
                    {
                        businessUserId = Settings.UserId;
                    }
                    DateTime?startTime = Filter.StartTime ?? null;
                    DateTime?endTime   = Filter.EndTime ?? null;

                    string billNumber = "";
                    string remark     = "";

                    var result = await _receiptCashService.GetOwecashBillsAsync(
                        businessUserId,
                        terminalId,
                        null,
                        billNumber,
                        remark,
                        startTime,
                        endTime,
                        0,
                        PageSize,
                        this.ForceRefresh,
                        new System.Threading.CancellationToken());

                    if (result != null)
                    {
                        foreach (IGrouping <int, BillSummaryModel> group in result.GroupBy(c => c.CustomerId))
                        {
                            var code = result.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerPointCode;
                            var name = result.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerName;
                            if (!string.IsNullOrEmpty(name))
                            {
                                pending.Add(new AmountReceivableGroupModel()
                                {
                                    CustomerId        = group.Key,
                                    CustomerName      = result.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerName,
                                    CustomerPointCode = code,
                                    Amount            = result.Where(c => c.CustomerId == group.Key)?.Sum(s => s.ArrearsAmount) ?? 0
                                });
                            }
                        }
                    }

                    if (pending.Any())
                    {
                        TotalAmount = pending.Sum(p => p.Amount);
                        BillItems   = new ObservableRangeCollection <AmountReceivableGroupModel>(pending);
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }

                return(pending);
            });


            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                int pageIdex = 0;
                if (BillItems.Count != 0)
                {
                    pageIdex = BillItems.Count / (PageSize == 0 ? 1 : PageSize);
                }

                if (PageCounter < pageIdex)
                {
                    PageCounter = pageIdex;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        try
                        {
                            int?terminalId     = Filter.TerminalId;
                            int businessUserId = Filter.BusinessUserId;
                            if (businessUserId == 0)
                            {
                                businessUserId = Settings.UserId;
                            }
                            DateTime?startTime = Filter.StartTime ?? null;
                            DateTime?endTime   = Filter.EndTime ?? null;

                            string billNumber = "";
                            string remark     = "";

                            var items = await _receiptCashService.GetOwecashBillsAsync(
                                businessUserId,
                                terminalId,
                                null,
                                billNumber,
                                remark,
                                startTime,
                                endTime,
                                pageIdex,
                                PageSize,
                                this.ForceRefresh,
                                new System.Threading.CancellationToken());

                            if (items != null)
                            {
                                var pending = new List <AmountReceivableGroupModel>();
                                foreach (IGrouping <int, BillSummaryModel> group in items.GroupBy(c => c.CustomerId))
                                {
                                    var code = items.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerPointCode;
                                    var name = items.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerName;
                                    if (!string.IsNullOrEmpty(name))
                                    {
                                        pending.Add(new AmountReceivableGroupModel()
                                        {
                                            CustomerId        = group.Key,
                                            CustomerName      = items.FirstOrDefault(c => c.CustomerId == group.Key)?.CustomerName,
                                            CustomerPointCode = code,
                                            Amount            = items.Where(c => c.CustomerId == group.Key)?.Sum(s => s.ArrearsAmount) ?? 0
                                        });
                                    }
                                }

                                foreach (var p in pending)
                                {
                                    if (BillItems.Where(s => s.CustomerId == p.CustomerId).Count() == 0)
                                    {
                                        BillItems.Add(p);
                                    }
                                }

                                if (pending.Count() == 0 || pending.Count() == BillItems.Count)
                                {
                                    ItemTreshold = -1;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex);
                            ItemTreshold = -1;
                        }
                    }
                }
            }, this.WhenAny(x => x.BillItems, x => x.GetValue().Count > 0));


            //选择转向收款单
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async x =>
            {
                await this.NavigateAsync("ReceiptBillPage", ("Terminaler",
                                                             new TerminalModel()
                {
                    Id = Selecter.CustomerId,
                    Name = Selecter.CustomerName
                }));
                Selecter = null;
            }).DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);
        }
Ejemplo n.º 8
0
 private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     Crashes.TrackError((Exception)e.ExceptionObject, new Dictionary <string, string> {
         ["location"] = "iOS"
     });
 }
Ejemplo n.º 9
0
 public static void Report(Exception exception)
 {
     Crashes.TrackError(exception);
 }
Ejemplo n.º 10
0
        //Event Delete
        private async void BtnDeleteOnClick(object sender, EventArgs e)
        {
            try
            {
                if (Chk_Delete.Checked)
                {
                    if (!IMethods.CheckConnectivity())
                    {
                        Toast.MakeText(this, GetText(Resource.String.Lbl_CheckYourInternetConnection),
                                       ToastLength.Short).Show();
                    }
                    else
                    {
                        var localdata = Classes.DataUserLoginList.FirstOrDefault(a => a.UserID == UserDetails.User_id);
                        if (localdata != null)
                        {
                            if (Txt_Password.Text == localdata.Password)
                            {
                                var(apiStatus, respond) = await Client.Global.Delete_User(Txt_Password.Text);

                                if (apiStatus == 200)
                                {
                                    if (respond is Update_Page_Data_Object result)
                                    {
                                        await API_Request.RemoveData("Delete");

                                        var dbDatabase = new SqLiteDatabase();
                                        var ss         = await dbDatabase.CheckTablesStatus();

                                        dbDatabase.Dispose();

                                        IMethods.DialogPopup.InvokeAndShowDialog(this,
                                                                                 GetText(Resource.String.Lbl_Deleted),
                                                                                 GetText(Resource.String.Lbl_Your_account_was_successfully_deleted),
                                                                                 GetText(Resource.String.Lbl_Ok));

                                        //wael change function to delete all data in app
                                        API_Request.Logout(this);
                                    }
                                }
                                else if (apiStatus == 400)
                                {
                                    if (respond is Error_Object error)
                                    {
                                        var errortext = error._errors.Error_text;
                                        //Toast.MakeText(this, errortext, ToastLength.Short).Show();

                                        if (errortext.Contains("Invalid or expired access_token"))
                                        {
                                            API_Request.Logout(this);
                                        }
                                    }
                                }
                                else if (apiStatus == 404)
                                {
                                    var error = respond.ToString();
                                    //Toast.MakeText(this, error, ToastLength.Short).Show();
                                }
                            }
                            else
                            {
                                IMethods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Warning),
                                                                         GetText(Resource.String.Lbl_Please_confirm_your_password),
                                                                         GetText(Resource.String.Lbl_Ok));
                            }
                        }
                    }
                }
                else
                {
                    IMethods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Warning),
                                                             GetText(Resource.String.Lbl_You_can_not_access_your_disapproval),
                                                             GetText(Resource.String.Lbl_Ok));
                }
            }
            catch (Exception exception)
            {
                Crashes.TrackError(exception);
            }
        }
Ejemplo n.º 11
0
 private void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
 {
     Crashes.TrackError(e.Exception, new Dictionary <string, string> {
         ["location"] = "iOS"
     });
 }
Ejemplo n.º 12
0
 public static void LogError(Exception ex, [CallerMemberName] string memberName = "UnknownMember", [CallerFilePath] string filePath = "Unknown.cs", [CallerLineNumber] int lineNum = 0)
 {
     Crashes.TrackError(ex, new Dictionary <string, string> {
         ["MemberName"] = memberName, ["FilePath"] = filePath, ["LineNumber"] = lineNum.ToString()
     });
 }
Ejemplo n.º 13
0
        public async Task <User> Login(AuthDto authData)
        {
            try
            {
                var service = Mvx.IoCProvider.Resolve <IFirebaseService>();
                if (service != null)
                {
                    authData.DeviceToken = await service.CreateToken(Secrets.SenderId);
                }
            }
            catch (Exception e)
            {
                Crashes.TrackError(e, new Dictionary <string, string>());
                Console.WriteLine(e);
            }

            var json = JsonConvert.SerializeObject(authData);

            Debug.WriteLine(json);
            var response = await _httpClient.PostAsync(LoginUri, new StringContent(json, Encoding.UTF8, BaseService.ApplicationJson));

            var jsonString = await response.Content.ReadAsStringAsync();

            Debug.WriteLine(jsonString);

            if (string.IsNullOrEmpty(jsonString))
            {
                Error = "Нет ответа от сервера";
                return(null);
            }

            var data = JsonConvert.DeserializeObject <ResponseDto <UserDto> >(jsonString);

            if (response.IsSuccessStatusCode)
            {
                if (!data.Success)
                {
                    return(_mapper.Map <User>(data.Data));
                }

                var user     = _mapper.Map <User>(data.Data.Client);
                var userInfo = _mapper.Map <User>(data.Data.ClientInfo);

                userInfo.Role  = user.Role;
                userInfo.Uuid  = user.Uuid;
                userInfo.Email = user.Email ?? string.Empty;
                userInfo.Phone = user.Phone ?? string.Empty;
                userInfo.Name  = user.Name ?? string.Empty;
                userInfo.Login = user.Login ?? string.Empty;

                userInfo.AccessToken = new AccessToken
                {
                    Body = data.Data.Body,
                    Type = data.Data.Type
                };

                if (string.IsNullOrEmpty(userInfo.AccessToken.Body) && userInfo.Uuid != Guid.Empty)
                {
                    return(userInfo);
                }

                _userUuid = userInfo.Uuid;
                _userRepository.RemoveAll();
                _userRepository.Add(userInfo);

                _userIsAuthorized = true;
                TokenUpdated?.Invoke(this, EventArgs.Empty);

                return(userInfo);
            }

            if (data.ErrorDetails != null)
            {
                ErrorDetails = data.ErrorDetails;
            }

            Error = data.Error;
            return(null);
        }
Ejemplo n.º 14
0
        public async Task <User> AuthorizationAnExternalService(string email, string accessToken, ExternalAuthService authServiceType)
        {
            var request = new Dictionary <string, string>
            {
                { "email", email },
                { "access_token", accessToken },
            };

            switch (authServiceType)
            {
            case ExternalAuthService.Vk:
                request.Add("service", "vk");
                break;

            case ExternalAuthService.Facebook:
                request.Add("service", "facebook");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(authServiceType), authServiceType, null);
            }

            try
            {
                var service = Mvx.IoCProvider.Resolve <IFirebaseService>();
                if (service != null)
                {
                    var deviceToken = await service.CreateToken(Secrets.SenderId);

                    if (!string.IsNullOrWhiteSpace(deviceToken))
                    {
                        request.Add("device_token", deviceToken);
                    }
                }
            }
            catch (Exception e)
            {
                Crashes.TrackError(e, new Dictionary <string, string>());
                Console.WriteLine(e);
            }


            var response = await _httpClient.PostAsync(AuthorizationAnExternalServiceUri, new FormUrlEncodedContent(request));

            var jsonString = await response.Content.ReadAsStringAsync();

            Debug.WriteLine(jsonString);

            if (string.IsNullOrEmpty(jsonString))
            {
                Error = "Нет ответа от сервера";
                return(null);
            }

            var data = JsonConvert.DeserializeObject <ResponseDto <UserDto> >(jsonString);

            if (response.IsSuccessStatusCode)
            {
                if (!data.Success)
                {
                    return(_mapper.Map <User>(data.Data));
                }

                var user     = _mapper.Map <User>(data.Data.Client);
                var userInfo = _mapper.Map <User>(data.Data.ClientInfo);

                userInfo.Role  = user.Role;
                userInfo.Uuid  = user.Uuid;
                userInfo.Email = user.Email ?? string.Empty;
                userInfo.Phone = user.Phone ?? string.Empty;
                userInfo.Name  = user.Name ?? string.Empty;
                userInfo.Login = user.Login ?? string.Empty;

                userInfo.AccessToken = new AccessToken
                {
                    Body = data.Data.Body,
                    Type = data.Data.Type
                };

                if (string.IsNullOrEmpty(userInfo.AccessToken.Body) && userInfo.Uuid != Guid.Empty)
                {
                    return(userInfo);
                }

                _userUuid = userInfo.Uuid;
                _userRepository.Add(userInfo);
                TokenUpdated?.Invoke(this, EventArgs.Empty);
                return(userInfo);
            }

            if (data.ErrorDetails != null)
            {
                ErrorDetails = data.ErrorDetails;
            }

            Error = data.Error;
            return(null);
        }
Ejemplo n.º 15
0
        public SaleOrderSummeryPageViewModel(INavigationService navigationService,
                                             IGlobalService globalService,
                                             IDialogService dialogService,
                                             IAllocationService allocationService,
                                             IAdvanceReceiptService advanceReceiptService,
                                             IReceiptCashService receiptCashService,
                                             ICostContractService costContractService,
                                             ICostExpenditureService costExpenditureService,
                                             IInventoryService inventoryService,
                                             IPurchaseBillService purchaseBillService,
                                             IReturnReservationBillService returnReservationBillService,
                                             IReturnBillService returnBillService,
                                             ISaleReservationBillService saleReservationBillService,
                                             ISaleBillService saleBillService
                                             ) : base(navigationService, globalService, allocationService, advanceReceiptService, receiptCashService, costContractService, costExpenditureService, inventoryService, purchaseBillService, returnReservationBillService, returnBillService, saleReservationBillService, saleBillService, dialogService)
        {
            Title = "销售订单";

            this.BillType = BillTypeEnum.SaleReservationBill;


            //加载数据
            this.Load = ReactiveCommand.Create(async() =>
            {
                //重载时排它
                ItemTreshold = 1;
                PageCounter  = 0;

                try
                {
                    int?terminalId     = Filter.TerminalId;
                    int?businessUserId = Filter.BusinessUserId;
                    DateTime?startTime = Filter.StartTime;
                    DateTime?endTime   = Filter.EndTime;
                    string billNumber  = Filter.SerchKey;
                    int?makeuserId     = Settings.UserId;

                    if (businessUserId.HasValue && businessUserId > 0)
                    {
                        makeuserId = 0;
                    }

                    string terminalName = "";
                    int?deliveryUserId  = 0;
                    int?wareHouseId     = 0;
                    string remark       = "";
                    int?districtId      = 0;
                    //获取已审核
                    bool?auditedStatus     = true;
                    bool?sortByAuditedTime = null;
                    bool?showReverse       = null;
                    bool?showReturn        = null;
                    bool?alreadyChange     = null;

                    //清除列表
                    Bills?.Clear();

                    var items = await _saleReservationBillService.GetSaleReservationBillsAsync(makeuserId, terminalId, terminalName, businessUserId, deliveryUserId, billNumber, wareHouseId, remark, districtId, startTime, endTime, auditedStatus, sortByAuditedTime, showReverse, showReturn, alreadyChange, 0, PageSize, this.ForceRefresh, new System.Threading.CancellationToken());

                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            if (Bills.Count(s => s.Id == item.Id) == 0)
                            {
                                Bills.Add(item);
                            }
                        }

                        foreach (var s in Bills)
                        {
                            s.IsLast = !(Bills.LastOrDefault()?.BillNumber == s.BillNumber);
                        }

                        if (Bills.Count > 0)
                        {
                            this.Bills = new ObservableRangeCollection <SaleReservationBillModel>(Bills);
                        }
                        UpdateTitle();
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                int pageIdex = 0;
                if (Bills?.Count != 0)
                {
                    pageIdex = Bills.Count / (PageSize == 0 ? 1 : PageSize);
                }

                if (PageCounter < pageIdex)
                {
                    PageCounter = pageIdex;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        try
                        {
                            int?terminalId     = Filter.TerminalId;
                            int?businessUserId = Filter.BusinessUserId;
                            DateTime?startTime = Filter.StartTime;
                            DateTime?endTime   = Filter.EndTime;
                            string billNumber  = Filter.SerchKey;

                            int?makeuserId      = Settings.UserId;
                            string terminalName = "";
                            int?deliveryUserId  = 0;
                            int?wareHouseId     = 0;
                            string remark       = "";
                            int?districtId      = 0;
                            //获取已审核
                            bool?auditedStatus     = true;
                            bool?sortByAuditedTime = null;
                            bool?showReverse       = null;
                            bool?showReturn        = null;
                            bool?alreadyChange     = null;

                            var items = await _saleReservationBillService.GetSaleReservationBillsAsync(makeuserId, terminalId, terminalName, businessUserId, deliveryUserId, billNumber, wareHouseId, remark, districtId, startTime, endTime, auditedStatus, sortByAuditedTime, showReverse, showReturn, alreadyChange, pageIdex, PageSize, this.ForceRefresh, new System.Threading.CancellationToken());

                            if (items != null)
                            {
                                foreach (var item in items)
                                {
                                    if (Bills.Count(s => s.Id == item.Id) == 0)
                                    {
                                        Bills.Add(item);
                                    }
                                }

                                if (items.Count() == 0)
                                {
                                    ItemTreshold = -1;
                                }

                                foreach (var s in Bills)
                                {
                                    s.IsLast = !(Bills.LastOrDefault()?.BillNumber == s.BillNumber);
                                }
                                UpdateTitle();
                            }
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex);
                        }
                    }
                }
            }, this.WhenAny(x => x.Bills, x => x.GetValue().Count > 0));

            //选择单据
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async x =>
            {
                if (x != null)
                {
                    await NavigateAsync(nameof(SaleOrderBillPage), ("Bill", x));
                }
                this.Selecter = null;
            }).DisposeWith(DeactivateWith);

            //菜单选择
            this.SubscribeMenus((x) =>
            {
                //获取当前UTC时间
                DateTime dtime = DateTime.Now;
                switch (x)
                {
                case MenuEnum.TODAY:
                    {
                        Filter.StartTime = DateTime.Parse(dtime.ToString("yyyy-MM-dd 00:00:00"));
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.YESTDAY:
                    {
                        Filter.StartTime = dtime.AddDays(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.OTHER:
                    {
                        SelectDateRang();
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.SUBMIT30:
                    {
                        Filter.StartTime = dtime.AddMonths(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.CLEARHISTORY:    //清空一个月历史单据
                    {
                        ClearHistory(() => _globalService.UpdateHistoryBillStatusAsync((int)this.BillType));
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;
                }
            }, string.Format(Constants.MENU_KEY, 0));


            this.BindBusyCommand(Load);
        }
Ejemplo n.º 16
0
 private void OnCrashButtonClicked(object sender, EventArgs e)
 {
     Crashes.GenerateTestCrash();
     throw new Exception("Crash Button Tapped");
 }
 private void CrashesEnabled_Checked(object sender, RoutedEventArgs e)
 {
     CrashesEnabled.IsEnabled = AppCenterEnabled.IsChecked.Value;
     Crashes.SetEnabledAsync(CrashesEnabled.IsChecked.Value).Wait();
 }
Ejemplo n.º 18
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad();
     Crashes.GenerateTestCrash();
     // Perform any additional setup after loading the view, typically from a nib.
 }
Ejemplo n.º 19
0
        public static void LogException(Exception ex)
        {
            ExceptionLogged?.Invoke(ex);

            // Getting exception Data
            Dictionary <string, string?> properties  = new();
            List <ErrorAttachmentLog>    attachments = new();

            foreach (DictionaryEntry de in ex.Data)
            {
                if (de.Value is ErrorAttachmentLog attachment)
                {
                    attachments.Add(attachment);
                    continue;
                }
                properties.Add(de.Key.ToString() !, de.Value?.ToString());
            }
            if (ex.InnerException != null)
            {
                attachments.Add(ErrorAttachmentLog.AttachmentWithText(ex.InnerException.ToString(), "InnerException.txt"));
            }

            // Special cases for certain exception types
            if (ex is WebException webEx)
            {
                if (Connectivity.NetworkAccess == NetworkAccess.None)
                {
                    // No Internet caused WebException, nothing to log here
                    return;
                }

                // WebException happens for external reasons, and shouldn't be treated as an exception.
                // But just in case it is logged as Event

                if (webEx.Status != 0 && webEx.Status != WebExceptionStatus.UnknownError)
                {
                    properties.Add("Status", webEx.Status.ToString());
                }
                if (webEx.InnerException != null)
                {
                    properties.Add("InnerException", webEx.InnerException.GetType().FullName);
                }
                properties.Add("Message", ex.Message);

                Analytics.TrackEvent("WebException", properties);
                return;
            }
            else if (ex is CistException cistEx)
            {
                // CistException happens for external reasons, and shouldn't be treated as an exception

                if (!properties.ContainsKey("Status"))
                {
                    properties.Add("Status", cistEx.Status.ToString());
                }

                Analytics.TrackEvent("CistException", properties);
                return;
            }
            else if (ex is MoodleException moodleEx)
            {
                // MoodleException happens for external reasons, and shouldn't be treated as an exception

                properties.Add("ErrorCode", moodleEx.ErrorCode);
                properties.Add("Message", moodleEx.Message);

                Analytics.TrackEvent("MoodleException", properties);
                return;
            }
            else if (ex is IOException && ex.Message.StartsWith("Disk full."))
            {
                return;
            }

            // Logging exception
            Crashes.TrackError(ex, properties, attachments.ToArray());
        }
 public void Error(Exception exception)
 {
     Crashes.TrackError(exception);
 }
Ejemplo n.º 21
0
    private async void UpdateFileNameButton_Click(object sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(OriginalTextBox_Renaming.Text))
        {
            WriteOutput("No text selected, aborting file name update.", OutputMessageLevel.Error);
            return;
        }
        else
        {
            WriteOutput("Renaming operation starting...", OutputMessageLevel.Warning);
        }

        // variables for background thread access
        var selectedItems   = EpisodesListBox.SelectedItems.Cast <string>().ToList();
        var selectedText    = OriginalTextBox_Renaming.Text;
        var replacementText = ReplacementTextBox.Text;

        LocalBusyIndicator.IsBusy          = true;
        LocalBusyIndicator.Visibility      = Visibility.Visible;
        LocalBusyIndicator.BusyContent     = "updating file names...";
        LocalBusyIndicator.IsIndeterminate = false;
        LocalBusyIndicator.ProgressValue   = 0;

        await Task.Run(() =>
        {
            try
            {
                for (int i = 0; i < selectedItems.Count; i++)
                {
                    var episodeFilePath = selectedItems[i];

                    // Need to separate name and path in order to prefix the file name
                    string curDir = Path.GetDirectoryName((string)episodeFilePath);

                    if (string.IsNullOrEmpty(curDir))
                    {
                        WriteOutput("Could not find directory, skipping.", OutputMessageLevel.Error);
                        continue;
                    }

                    string curName = Path.GetFileName((string)episodeFilePath);

                    if (string.IsNullOrEmpty(curName))
                    {
                        WriteOutput("Could not find file, skipping.", OutputMessageLevel.Error);
                        continue;
                    }

                    // Replace the selected text with the new text (support empty replacement to remove text)
                    string newName = curName.Replace(selectedText, replacementText, StringComparison.InvariantCulture);

                    // Rename the file
                    File.Move(episodeFilePath, Path.Combine(curDir, newName));

                    // Need to dispatch back to UI thread, variables to avoid access to modified closure problem
                    var progressComplete = i / selectedItems.Count * 100;
                    var progressText     = $"Renaming - '{selectedText}' to '{replacementText}'...";

                    Dispatcher.Invoke(() =>
                    {
                        LocalBusyIndicator.ProgressValue = progressComplete;
                        LocalBusyIndicator.BusyContent   = $"Completed {progressText}...";
                    });
                }

                WriteOutput("Renaming operation complete!", OutputMessageLevel.Success);
            }
            catch (Exception ex)
            {
                WriteOutput(ex.Message, OutputMessageLevel.Error);

                Crashes.TrackError(ex, new Dictionary <string, string>
                {
                    { "Rename Episode", "TV Show" }
                });
            }
        }).ConfigureAwait(true);

        RefreshEpisodesList();

        Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Episode Renaming Complete", new Dictionary <string, string>
        {
            { "Total Episodes", episodes.Count.ToString(CultureInfo.InvariantCulture) },
            { "Episodes Renamed", EpisodesListBox.SelectedItems.Count.ToString(CultureInfo.InvariantCulture) }
        });

        LocalBusyIndicator.BusyContent   = "";
        LocalBusyIndicator.IsBusy        = false;
        LocalBusyIndicator.Visibility    = Visibility.Collapsed;
        LocalBusyIndicator.ProgressValue = 0;
    }
Ejemplo n.º 22
0
        public async Task StartFresh()
        {
            try
            {
                Debug.WriteLine($"{nameof(PushClient)}: Starting fresh.");
                if (_loopGroup != null)
                {
                    await Shutdown();
                }
                _loopGroup = new SingleThreadEventLoop();

                var connectPacket = new FbnsConnectPacket
                {
                    Payload = await PayloadProcessor.BuildPayload(ConnectionData)
                };

                Socket = new StreamSocket();
                Socket.Control.KeepAlive = true;
                Socket.Control.NoDelay   = true;
                if (await RequestBackgroundAccess())
                {
                    try
                    {
                        Socket.EnableTransferOwnership(_socketActivityTask.TaskId, SocketActivityConnectedStandbyAction.Wake);
                    }
                    catch (Exception connectedStandby)
                    {
                        Debug.WriteLine(connectedStandby);
                        Debug.WriteLine($"{nameof(PushClient)}: Connected standby not available.");
                        try
                        {
                            Socket.EnableTransferOwnership(_socketActivityTask.TaskId, SocketActivityConnectedStandbyAction.DoNotWake);
                        }
                        catch (Exception e)
                        {
#if !DEBUG
                            Crashes.TrackError(e);
#endif
                            Debug.WriteLine(e);
                            Debug.WriteLine($"{nameof(PushClient)}: Failed to transfer socket completely!");
                            await Shutdown().ConfigureAwait(false);

                            return;
                        }
                    }
                }

                await Socket.ConnectAsync(new HostName(HOST_NAME), "443", SocketProtectionLevel.Tls12);

                var streamSocketChannel = new StreamSocketChannel(Socket);
                streamSocketChannel.Pipeline.AddLast(new FbnsPacketEncoder(), new FbnsPacketDecoder(), this);

                await _loopGroup.RegisterAsync(streamSocketChannel).ConfigureAwait(false);

                await streamSocketChannel.WriteAndFlushAsync(connectPacket).ConfigureAwait(false);
            }
            catch (Exception e)
            {
#if !DEBUG
                Crashes.TrackError(e);
#endif
                await Shutdown().ConfigureAwait(false);
            }
        }
Ejemplo n.º 23
0
    private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            WriteOutput("Opening folder picker...", OutputMessageLevel.Normal);

            LocalBusyIndicator.IsBusy          = true;
            LocalBusyIndicator.Visibility      = Visibility.Visible;
            LocalBusyIndicator.BusyContent     = "opening folder...";
            LocalBusyIndicator.IsIndeterminate = true;

            if (!string.IsNullOrEmpty(Properties.Settings.Default.LastFolder))
            {
                // Need to bump up one level from the last folder location
                var topDirectoryInfo = Directory.GetParent(Properties.Settings.Default.LastFolder);

                openFolderDialog.InitialDirectory = topDirectoryInfo.FullName;

                WriteOutput("Starting at saved folder.", OutputMessageLevel.Normal);
            }
            else
            {
                WriteOutput("No saved folder, starting at root.", OutputMessageLevel.Warning);
            }

            openFolderDialog.ShowDialog();

            if (openFolderDialog.DialogResult != true)
            {
                WriteOutput("Canceled folder selection.", OutputMessageLevel.Normal);
                return;
            }
            else
            {
                Properties.Settings.Default.LastFolder = openFolderDialog.FileName;
                Properties.Settings.Default.Save();
            }

            Reset();

            LocalBusyIndicator.BusyContent = "searching for seasons...";

            var seasonsResult = Directory.EnumerateDirectories(openFolderDialog.FileName).ToList();

            seasons.Clear();

            foreach (var season in seasonsResult)
            {
                seasons.Add(season);

                LocalBusyIndicator.BusyContent = $"added {season}";
            }

            if (seasons.Count == 0)
            {
                WriteOutput("No seasons detected, make sure there are subfolders with season number.", OutputMessageLevel.Warning);
            }
            else if (seasons.Count == 1)
            {
                WriteOutput($"Opened '{Path.GetFileName(openFolderDialog.FileName)}' ({seasons.Count} season).", OutputMessageLevel.Success);
            }
            else
            {
                WriteOutput($"Opened '{Path.GetFileName(openFolderDialog.FileName)}' ({seasons.Count} seasons).", OutputMessageLevel.Success);
            }

            Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Video Folder Opened", new Dictionary <string, string>
            {
                { "Seasons", seasons.Count.ToString(CultureInfo.InvariantCulture) }
            });
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            WriteOutput(ex.Message, OutputMessageLevel.Error);

            Crashes.TrackError(ex, new Dictionary <string, string>
            {
                { "Folder Open", "TV Show" }
            });
        }
        finally
        {
            LocalBusyIndicator.BusyContent     = "";
            LocalBusyIndicator.IsBusy          = false;
            LocalBusyIndicator.Visibility      = Visibility.Collapsed;
            LocalBusyIndicator.IsIndeterminate = false;
        }
    }
Ejemplo n.º 24
0
        protected override async void ChannelRead0(IChannelHandlerContext ctx, Packet msg)
        {
            try
            {
                _context = ctx; // Save context for manual Ping later
                switch (msg.PacketType)
                {
                case PacketType.CONNACK:
                    Debug.WriteLine($"{nameof(PushClient)}:\tCONNACK received.");
                    ConnectionData.UpdateAuth(((FbnsConnAckPacket)msg).Authentication);
                    RegisterMqttClient(ctx);
                    break;

                case PacketType.PUBLISH:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPUBLISH received.");
                    var publishPacket = (PublishPacket)msg;
                    if (publishPacket.QualityOfService == QualityOfService.AtLeastOnce)
                    {
                        await ctx.WriteAndFlushAsync(PubAckPacket.InResponseTo(publishPacket));
                    }

                    var payload = DecompressPayload(publishPacket.Payload);
                    var json    = Encoding.UTF8.GetString(payload);
                    Debug.WriteLine($"{nameof(PushClient)}:\tMQTT json: {json}");
                    switch (Enum.Parse(typeof(TopicIds), publishPacket.TopicName))
                    {
                    case TopicIds.Message:
                        var message = JsonConvert.DeserializeObject <PushReceivedEventArgs>(json);
                        message.Json = json;
                        OnMessageReceived(message);
                        break;

                    case TopicIds.RegResp:
                        OnRegisterResponse(json);
                        try
                        {
                            await _context.Executor.Schedule(KeepAliveLoop,
                                                             TimeSpan.FromSeconds(KEEP_ALIVE - 60));
                        }
                        catch (TaskCanceledException)
                        {
                            // pass
                        }

                        break;

                    default:
                        Debug.WriteLine($"Unknown topic received: {publishPacket.TopicName}", "Warning");
                        break;
                    }

                    break;

                case PacketType.PUBACK:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPUBACK received.");
                    _waitingForPubAck = false;
                    break;

                // todo: PingResp never arrives even though data was received. Decoder problem?
                case PacketType.PINGRESP:
                    Debug.WriteLine($"{nameof(PushClient)}:\tPINGRESP received.");
                    break;

                default:
                    throw new NotSupportedException($"Packet type {msg.PacketType} is not supported.");
                }
            }
            catch (Exception e)
            {
                // Something went wrong with Push client. Shutting down.
#if !DEBUG
                Crashes.TrackError(e);
#endif
                await Shutdown().ConfigureAwait(false);
            }
        }
Ejemplo n.º 25
0
        //Function add data story
        public void AddDataStory()
        {
            try
            {
                ListOfStories.Clear();
                if (_Story_Data != null)
                {
                    IMethods.Set_TextViewIcon("1", BackIcon, IonIcons_Fonts.AndroidArrowBack);
                    IMethods.Load_Image_From_Url(UserProfileImage, _Story_Data.user_data.avatar);

                    User_ID  = _Story_Data.user_id;
                    Story_ID = _Story_Data.id;

                    usernameText.Text = _Story_Data.user_data.name;
                    Txt_LastSeen.Text = _Story_Data.expire;

                    //Successfully read
                    _Story_Data.Profile_indicator = Settings.Story_Read_Color;

                    //Set show or not icon delete
                    DeleteStory_Icon.Visibility = _Story_Data.is_owner ? ViewStates.Visible : ViewStates.Invisible;

                    var getStory = Classes.StoryList.FirstOrDefault(a => a.Value == User_ID);
                    if (getStory.Value != null)
                    {
                        count = getStory.Key.Count;

                        foreach (var story in getStory.Key)
                        {
                            string storyAbout = "";

                            if (!string.IsNullOrEmpty(_Story_Data.description))
                            {
                                storyAbout = _Story_Data.description;
                            }
                            else if (!string.IsNullOrEmpty(_Story_Data.title))
                            {
                                storyAbout = _Story_Data.title;
                            }

                            //image and video
                            if (!story.thumbnail.Contains("avatar"))
                            {
                                string[] data = new string[] { story.id, storyAbout };
                                ListOfStories?.Add(story.thumbnail, data);
                            }

                            if (story.images?.Count > 0)
                            {
                                for (int i = 0; i < story.images?.Count; i++)
                                {
                                    string[] data = new string[] { story.id, storyAbout };
                                    ListOfStories.Add(story.images[i].filename, data);
                                }
                            }

                            if (story.videos?.Count > 0)
                            {
                                for (int i = 0; i < story.videos?.Count; i++)
                                {
                                    string[] data = new string[] { story.id, storyAbout };
                                    ListOfStories.Add(story.videos[i].filename, data);
                                }
                            }
                        }
                    }
                    count = ListOfStories.Count;
                    CountStoryText.Text = count.ToString();
                }

                Timerstory          = new Timer();
                Timerstory.Interval = 6000;
                Timerstory.Elapsed += Timerstory_Elapsed;
                Timerstory.Start();

                Timerprogress          = new Timer();
                Timerprogress.Interval = 60;
                Timerprogress.Elapsed += Timerprogress_Elapsed;
                Timerprogress.Start();
                progrescount = 0;

                countstory = -1; // starts the list from the first url

                RunOnUiThread(ChangeStoryView);
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
        }
Ejemplo n.º 26
0
        async void RunMBaaSAsync(object sender, EventArgs e)
        {
            try
            {
                userInfo = await Auth.SignInAsync();

                if (userInfo.AccountId != null)
                {
                    Application.Current.Properties[AccountId] = userInfo.AccountId;
                    SignInInformationButton.Text = "User authenticated";
                }
                AppCenterLog.Info(App.LogTag, "Auth.SignInAsync succeeded accountId=" + userInfo.AccountId);
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Auth scenario failed", ex);
                Crashes.TrackError(ex);
            }
            try
            {
                var list = await Data.ListAsync <CustomDocument>(DefaultPartitions.UserDocuments);

                foreach (var doc in list)
                {
                    AppCenterLog.Info(App.LogTag, "List result=" + JsonConvert.SerializeObject(doc));
                }
                var document = list.CurrentPage.Items.First();
                AppCenterLog.Info(App.LogTag, "List first result=" + JsonConvert.SerializeObject(document));
                document = await Data.DeleteAsync <CustomDocument>(document.Id, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Delete result=" + JsonConvert.SerializeObject(document));
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Data list/delete first scenario failed", ex);
                Crashes.TrackError(ex);
            }
            try
            {
                var objectCollection = new List <Uri>();
                objectCollection.Add(new Uri("http://google.com/"));
                objectCollection.Add(new Uri("http://microsoft.com/"));
                objectCollection.Add(new Uri("http://facebook.com/"));
                var primitiveCollection = new List <int>();
                primitiveCollection.Add(1);
                primitiveCollection.Add(2);
                primitiveCollection.Add(3);
                var dict = new Dictionary <string, Uri>();
                dict.Add("key1", new Uri("http://google.com/"));
                dict.Add("key2", new Uri("http://microsoft.com/"));
                dict.Add("key3", new Uri("http://facebook.com/"));
                var customDoc = new CustomDocument
                {
                    Id                 = Guid.NewGuid(),
                    TimeStamp          = DateTime.UtcNow,
                    SomeNumber         = 123,
                    SomeObject         = dict,
                    SomePrimitiveArray = new int[] { 1, 2, 3 },
                    SomeObjectArray    = new CustomDocument[] {
                        new CustomDocument {
                            Id                      = Guid.NewGuid(),
                            TimeStamp               = DateTime.UtcNow,
                            SomeNumber              = 123,
                            SomeObject              = dict,
                            SomePrimitiveArray      = new int[] { 1, 2, 3 },
                            SomeObjectCollection    = objectCollection,
                            SomePrimitiveCollection = primitiveCollection
                        }
                    },
                    SomeObjectCollection    = objectCollection,
                    SomePrimitiveCollection = primitiveCollection,
                    Custom = new CustomDocument
                    {
                        Id                      = Guid.NewGuid(),
                        TimeStamp               = DateTime.UtcNow,
                        SomeNumber              = 123,
                        SomeObject              = dict,
                        SomePrimitiveArray      = new int[] { 1, 2, 3 },
                        SomeObjectCollection    = objectCollection,
                        SomePrimitiveCollection = primitiveCollection
                    }
                };
                var id       = customDoc.Id.ToString();
                var document = await Data.ReplaceAsync(id, customDoc, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Replace result=" + JsonConvert.SerializeObject(document));
                document = await Data.ReadAsync <CustomDocument>(id, DefaultPartitions.UserDocuments);

                AppCenterLog.Info(App.LogTag, "Read result=" + JsonConvert.SerializeObject(document));
            }
            catch (Exception ex)
            {
                AppCenterLog.Error(App.LogTag, "Data person scenario failed", ex);
                Crashes.TrackError(ex);
            }
        }
Ejemplo n.º 27
0
        public void SetImageStory(string url, string[] data)
        {
            try
            {
                if (imagstoryDisplay.Visibility == ViewStates.Gone)
                {
                    imagstoryDisplay.Visibility = ViewStates.Visible;
                }

                if (data?.Length > 0)
                {
                    Story_ID            = data[0];
                    storyaboutText.Text = data[1];
                }

                if (videoView.Visibility == ViewStates.Visible)
                {
                    videoView.Visibility = ViewStates.Gone;
                }

                Timerstory.Enabled    = false;
                Timerprogress.Enabled = false;

                LoadingProgressBarview.Visibility = ViewStates.Visible;

                if (url.Contains("http"))
                {
                    var Filename  = url.Split('/').Last();
                    var filePath  = Path.Combine(IMethods.IPath.FolderDcimStory);
                    var MediaFile = filePath + "/" + Filename;

                    if (File.Exists(MediaFile))
                    {
                        Timerstory.Enabled    = true;
                        Timerprogress.Enabled = true;

                        LoadingProgressBarview.Visibility = ViewStates.Gone;

                        var file = Uri.FromFile(new Java.IO.File(MediaFile));

                        var ImageTrancform = ImageService.Instance.LoadFile(file.Path);
                        ImageTrancform.DownSampleMode(InterpolationMode.Medium);
                        ImageTrancform.FadeAnimation(false);
                        ImageTrancform.Retry(3, 3000);
                        ImageTrancform.WithCache(CacheType.All);
                        ImageTrancform.Into(imagstoryDisplay);
                    }
                    else
                    {
                        var WebClient = new WebClient();

                        WebClient.DownloadDataAsync(new System.Uri(url));
                        WebClient.DownloadDataCompleted += (s, e) =>
                        {
                            try
                            {
                                if (!Directory.Exists(filePath))
                                {
                                    Directory.CreateDirectory(filePath);
                                }

                                File.WriteAllBytes(MediaFile, e.Result);

                                var file = Uri.FromFile(new Java.IO.File(MediaFile));

                                var ImageTrancform = ImageService.Instance.LoadFile(file.Path);
                                ImageTrancform.DownSampleMode(InterpolationMode.Medium);
                                ImageTrancform.FadeAnimation(false);
                                ImageTrancform.Retry(3, 3000);
                                ImageTrancform.WithCache(CacheType.All);
                                ImageTrancform.Into(imagstoryDisplay);

                                Timerstory.Enabled    = true;
                                Timerprogress.Enabled = true;

                                LoadingProgressBarview.Visibility = ViewStates.Gone;
                            }
                            catch (Exception ex)
                            {
                                Crashes.TrackError(ex);
                            }

                            var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                            mediaScanIntent.SetData(Uri.FromFile(new Java.IO.File(MediaFile)));
                            Application.Context.SendBroadcast(mediaScanIntent);
                        };
                    }
                }
                else
                {
                    Timerstory.Enabled    = true;
                    Timerprogress.Enabled = true;

                    LoadingProgressBarview.Visibility = ViewStates.Gone;

                    var file = Uri.FromFile(new Java.IO.File(url));

                    var ImageTrancform = ImageService.Instance.LoadFile(file.Path);
                    ImageTrancform.DownSampleMode(InterpolationMode.Medium);
                    ImageTrancform.FadeAnimation(false);
                    ImageTrancform.Retry(3, 3000);
                    ImageTrancform.WithCache(CacheType.All);
                    ImageTrancform.Into(imagstoryDisplay);
                }
            }
            catch (Exception e)
            {
                Crashes.TrackError(e);
            }
        }
Ejemplo n.º 28
0
        public SalePageViewModel(INavigationService navigationService,
                                 IGlobalService globalService,
                                 IDialogService dialogService,
                                 IAllocationService allocationService,
                                 IAdvanceReceiptService advanceReceiptService,
                                 IReceiptCashService receiptCashService,
                                 ICostContractService costContractService,
                                 ICostExpenditureService costExpenditureService,
                                 IInventoryService inventoryService,
                                 IPurchaseBillService purchaseBillService,
                                 IReturnReservationBillService returnReservationBillService,
                                 IReturnBillService returnBillService,
                                 ISaleReservationBillService saleReservationBillService,
                                 ISaleBillService saleBillService
                                 ) : base(navigationService, globalService, allocationService, advanceReceiptService, receiptCashService, costContractService, costExpenditureService, inventoryService, purchaseBillService, returnReservationBillService, returnBillService, saleReservationBillService, saleBillService, dialogService)
        {
            Title    = "销售单据";
            PageSize = 30;

            this.BillType = BillTypeEnum.SaleBill;

            this.Load = ReactiveCommand.Create(async() =>
            {
                ItemTreshold = 1;
                PageCounter  = 0;

                try
                {
                    Bills?.Clear();
                    int?terminalId     = Filter.TerminalId;
                    int?businessUserId = Filter.BusinessUserId;
                    string billNumber  = Filter.SerchKey;
                    //DateTime? startTime = DateTime.Now.AddMonths(-1);
                    //DateTime? endTime = DateTime.Now;
                    DateTime?startTime = Filter.StartTime ?? DateTime.Now;
                    DateTime?endTime   = Filter.EndTime ?? DateTime.Now;

                    int?makeuserId = Settings.UserId;

                    if (businessUserId == Settings.UserId)
                    {
                        businessUserId = 0;
                    }

                    int?wareHouseId     = 0;
                    string terminalName = "";
                    string remark       = "";
                    int?districtId      = 0;
                    int?deliveryUserId  = 0;
                    //获取未审核
                    bool?auditedStatus     = false;
                    bool?sortByAuditedTime = null;
                    bool?showReverse       = null;
                    bool?showReturn        = null;
                    bool?handleStatus      = null;
                    int?paymentMethodType  = 0;
                    int?billSourceType     = 0;

                    var pending = new List <SaleBillModel>();

                    var result = await _saleBillService.GetSalebillsAsync(makeuserId, terminalId, terminalName, businessUserId, districtId, deliveryUserId, wareHouseId, billNumber, remark, startTime, endTime, auditedStatus, sortByAuditedTime, showReverse, showReturn,
                                                                          paymentMethodType,
                                                                          billSourceType,
                                                                          handleStatus,
                                                                          null,
                                                                          0,
                                                                          PageSize, this.ForceRefresh, new System.Threading.CancellationToken());

                    if (result != null)
                    {
                        pending = result?.Select(s =>
                        {
                            var sm    = s;
                            sm.IsLast = !(result.LastOrDefault()?.BillNumber == s.BillNumber);
                            return(sm);
                        }).ToList();
                    }

                    if (pending.Any())
                    {
                        Bills = new System.Collections.ObjectModel.ObservableCollection <SaleBillModel>(pending);
                    }

                    UpdateTitle();
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });


            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                int pageIdex = 0;
                if (Bills?.Count != 0)
                {
                    pageIdex = Bills.Count / (PageSize == 0 ? 1 : PageSize);
                }

                if (PageCounter < pageIdex)
                {
                    PageCounter = pageIdex;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        try
                        {
                            int?terminalId     = Filter.TerminalId;
                            int?businessUserId = Filter.BusinessUserId;
                            DateTime?startTime = Filter.StartTime ?? DateTime.Now;
                            DateTime?endTime   = Filter.EndTime ?? DateTime.Now;
                            string billNumber  = Filter.SerchKey;

                            int?makeuserId = Settings.UserId;
                            if (businessUserId.HasValue && businessUserId > 0)
                            {
                                makeuserId = 0;
                            }

                            int?wareHouseId     = 0;
                            string terminalName = "";
                            string remark       = "";
                            int?districtId      = 0;
                            int?deliveryUserId  = 0;
                            //获取已审核
                            bool?auditedStatus     = false;
                            bool?sortByAuditedTime = null;
                            bool?showReverse       = null;
                            bool?showReturn        = null;
                            bool?handleStatus      = null;
                            int?paymentMethodType  = 0;
                            int?billSourceType     = 0;

                            //清除列表
                            //Bills.Clear();

                            var items = await _saleBillService.GetSalebillsAsync(makeuserId, terminalId, terminalName, businessUserId, districtId, deliveryUserId, wareHouseId, billNumber, remark, startTime, endTime, auditedStatus, sortByAuditedTime, showReverse, showReturn, paymentMethodType, billSourceType, handleStatus, null, pageIdex, PageSize, this.ForceRefresh, new System.Threading.CancellationToken());

                            if (items != null)
                            {
                                foreach (var item in items)
                                {
                                    if (Bills.Count(s => s.Id == item.Id) == 0)
                                    {
                                        Bills.Add(item);
                                    }
                                }

                                foreach (var s in Bills)
                                {
                                    s.IsLast = !(Bills.LastOrDefault()?.BillNumber == s.BillNumber);
                                }
                            }
                            UpdateTitle();
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex);
                        }
                    }
                }
            }, this.WhenAny(x => x.Bills, x => x.GetValue().Count > 0));
            //选择单据
            this.SelectedCommand = ReactiveCommand.Create <SaleBillModel>(async x =>
            {
                //已提交
                if (x != null)
                {
                    await NavigateAsync(nameof(SaleBillPage), ("Bill", x), ("IsSubmitBill", true));
                }
            });


            //菜单选择
            this.SubscribeMenus((x) =>
            {
                //获取当前UTC时间
                DateTime dtime = DateTime.Now;
                switch (x)
                {
                case MenuEnum.TODAY:
                    {
                        Filter.StartTime = DateTime.Parse(dtime.ToString("yyyy-MM-dd 00:00:00"));
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.YESTDAY:
                    {
                        Filter.StartTime = dtime.AddDays(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.OTHER:
                    {
                        SelectDateRang();
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case MenuEnum.SUBMIT30:
                    {
                        Filter.StartTime = dtime.AddMonths(-1);
                        Filter.EndTime   = dtime;
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;

                case Enums.MenuEnum.CLEARHISTORY:    //清空一个月历史单据
                    {
                        ClearHistory(() => _globalService.UpdateHistoryBillStatusAsync((int)this.BillType));
                        ((ICommand)Load)?.Execute(null);
                    }
                    break;
                }
            }, string.Format(Constants.MENU_VIEW_KEY, 1));


            this.BindBusyCommand(Load);
        }
Ejemplo n.º 29
0
        private async Task ActivateAsync(IActivatedEventArgs e)
        {
            bool rootFrameCreated = false;

            if (!(Window.Current.Content is Frame rootFrame))
            {
                rootFrame = CreateRootFrame(e);
                Window.Current.Content = rootFrame;
                rootFrameCreated       = true;

                ThemeSettingsService.Initialize();
                EditorSettingsService.Initialize();
            }

            var appLaunchSettings = new Dictionary <string, string>()
            {
                { "OSArchitecture", SystemInformation.OperatingSystemArchitecture.ToString() },
                { "OSVersion", $"{SystemInformation.OperatingSystemVersion.Major}.{SystemInformation.OperatingSystemVersion.Minor}.{SystemInformation.OperatingSystemVersion.Build}" },
                { "UseWindowsTheme", ThemeSettingsService.UseWindowsTheme.ToString() },
                { "ThemeMode", ThemeSettingsService.ThemeMode.ToString() },
                { "UseWindowsAccentColor", ThemeSettingsService.UseWindowsAccentColor.ToString() },
                { "AppBackgroundTintOpacity", $"{(int) (ThemeSettingsService.AppBackgroundPanelTintOpacity * 10.0) * 10}" },
                { "ShowStatusBar", EditorSettingsService.ShowStatusBar.ToString() },
                { "EditorDefaultLineEnding", EditorSettingsService.EditorDefaultLineEnding.ToString() },
                { "EditorDefaultEncoding", EncodingUtility.GetEncodingName(EditorSettingsService.EditorDefaultEncoding) },
                { "EditorDefaultTabIndents", EditorSettingsService.EditorDefaultTabIndents.ToString() },
                { "EditorDefaultDecoding", EditorSettingsService.EditorDefaultDecoding == null ? "Auto" : EncodingUtility.GetEncodingName(EditorSettingsService.EditorDefaultDecoding) },
                { "EditorFontFamily", EditorSettingsService.EditorFontFamily },
                { "EditorFontSize", EditorSettingsService.EditorFontSize.ToString() },
                { "IsSessionSnapshotEnabled", EditorSettingsService.IsSessionSnapshotEnabled.ToString() },
                { "IsShadowWindow", (!IsFirstInstance && !IsGameBarWidget).ToString() },
                { "IsGameBarWidget", IsGameBarWidget.ToString() },
                { "AlwaysOpenNewWindow", EditorSettingsService.AlwaysOpenNewWindow.ToString() },
                { "IsHighlightMisspelledWordsEnabled", EditorSettingsService.IsHighlightMisspelledWordsEnabled.ToString() },
                { "DisplayLineHighlighter", EditorSettingsService.EditorDisplayLineHighlighter.ToString() },
                { "DisplayLineNumbers", EditorSettingsService.EditorDisplayLineNumbers.ToString() },
                { "EditorDefaultSearchEngine", EditorSettingsService.EditorDefaultSearchEngine.ToString() }
            };

            LoggingService.LogInfo($"[{nameof(App)}] Launch settings: \n{string.Join("\n", appLaunchSettings.Select(x => x.Key + "=" + x.Value).ToArray())}.");
            Analytics.TrackEvent("AppLaunch_Settings", appLaunchSettings);

            try
            {
                await ActivationService.ActivateAsync(rootFrame, e);
            }
            catch (Exception ex)
            {
                var diagnosticInfo = new Dictionary <string, string>()
                {
                    { "Message", ex?.Message },
                    { "Exception", ex?.ToString() },
                };
                Analytics.TrackEvent("AppFailedToActivate", diagnosticInfo);
                Crashes.TrackError(ex, diagnosticInfo);
                throw;
            }

            if (rootFrameCreated)
            {
                ExtendViewIntoTitleBar();
                Window.Current.Activate();
            }
        }
Ejemplo n.º 30
0
        public HotSalesRankingPageViewModel(INavigationService navigationService,
                                            IProductService productService,
                                            IReportingService reportingService,
                                            IDialogService dialogService
                                            ) : base(navigationService,
                                                     productService,
                                                     reportingService,
                                                     dialogService)
        {
            Title = "热销排行榜";

            this.PageType = Enums.ChartPageEnum.HotSalesRanking_Template;

            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                if (item != null)
                {
                    var start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
                    await this.NavigateAsync("SaleDetailPage", ("ProductId", item.ProductId), ("TotalSumNetAmount", item.TotalSumNetAmount), ("TotalSumReturnAmount", item.TotalSumReturnAmount), ("ProductName", item.ProductName), ("Reference", PageName), ("BusinessUserId", Filter.BusinessUserId), ("StartTime", Filter.StartTime ?? start), ("EndTime", Filter.EndTime ?? DateTime.Now));
                }

                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);


            this.Load = ReactiveCommand.CreateFromTask(() => Task.Run(async() =>
            {
                try
                {
                    var rankings       = new List <HotSaleRanking>();
                    int?terminalId     = Filter.TerminalId;
                    int?businessUserId = Filter.BusinessUserId;
                    int?brandId        = Filter.BrandId;
                    int?categoryId     = Filter.CatagoryId;
                    DateTime?startTime = Filter.StartTime ?? DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
                    DateTime?endTime   = Filter.EndTime ?? DateTime.Now;

                    //初始化
                    var result = await _reportingService.GetHotSaleRankingAsync(terminalId,
                                                                                businessUserId,
                                                                                brandId,
                                                                                categoryId,
                                                                                startTime.Value,
                                                                                endTime.Value,
                                                                                this.ForceRefresh,
                                                                                new System.Threading.CancellationToken());

                    if (result != null)
                    {
                        RefreshData(result.ToList());
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            }));

            //绑定页面菜单
            BindFilterDateMenus(true);

            this.BindBusyCommand(Load);
        }