示例#1
0
        public EditProfileViewModel(INavigationService navigationService,
                                    IUserService userService,
                                    IMediaPickerService mediaPickerService,
                                    ITestimonialsService testimonialsService) : base(navigationService)
        {
            this.userService         = userService;
            this.mediaPickerService  = mediaPickerService;
            this.testimonialsService = testimonialsService;

            SetTabs();

            Title = "Profile Edit";

            TabChangedCommand     = new Command(TabSelectedCommandExecute);
            SelectTopSkillCommand = new Command(SelectTopSkillCommandExecute);

            AddEducationCommand         = new Command(AddEducationCommandExecute);
            AddSkillCommand             = new Command(AddSkillCommandExecute);
            AddNewAccomplishmentCommand = new Command(AddNewAccomplishmentCommandExecute);
            AddConnectedWithCommand     = new Command(AddConnectedWithCommandExecute);
            AddPresentCompanyCommand    = new Command(AddPresentCompanyCommandExecute);
            AddPastCompanyCommand       = new Command(AddPastCompanyCommandExecute);
            AddExperienceCommand        = new Command(AddExperienceCommandExecute);
            AddCertificateCommand       = new Command(AddCertificateCommandExecute);
            ViewProfileCommand          = new Command(ViewProfileCommandExecute);
            ChangePhotoCommand          = new Command(ChangePhotoCommandExecute);
            AddNewTestimonialCommand    = new Command(AddNewTestimonialCommandExecute);
            SaveCommand = new Command(SaveCommandExecute);
            ViewAllTestimonialsCommand = new Command(ViewAllTestimonialsCommandExecute);
            SelectTestimonialCommand   = new Command(SelectTestimonialCommandExecute);

            InitUI();
        }
示例#2
0
 public MediaActionPopupViewModel(
     IProfileMediaService profileMediaService,
     IMediaPickerService mediaPickerService,
     IFileDTOBuilder fileDTOBuilder)
 {
     _profileMediaService = profileMediaService;
     _mediaPickerService  = mediaPickerService;
     _fileDTOBuilder      = fileDTOBuilder;
 }
示例#3
0
        public SignUpSecondViewModel(INavigationService navigationService,
                                     IAuthenticationService authenticationService,
                                     IMediaPickerService mediaPickerService) : base(navigationService)
        {
            this.authenticationService = authenticationService;
            this.mediaPickerService    = mediaPickerService;

            UploadPhotoCommand = new Command(UploadPhotoCommandExecute);
            ContinueCommand    = new Command(ContinueCommandExecute);
            BackCommand        = new Command(BackCommandExecute);
        }
        public ManageVideosViewModel(
            IMediaPickerService mediaPickerService,
            IProfileMediaService profileMediaService,
            IStateService stateService)
        {
            _mediaPickerService  = mediaPickerService;
            _profileMediaService = profileMediaService;
            _stateService        = stateService;

            IsAnyVideos = AddedVideos.Any();
        }
示例#5
0
 public PickAvatarPopupViewModelBase(
     IMediaPickerService mediaPickerService,
     IProfileService profileService,
     IIdentityUtilService identityUtilService,
     IProfileMediaService profileMediaService,
     IFileDTOBuilder fileDTOBuilder)
 {
     _mediaPickerService  = mediaPickerService;
     _profileService      = profileService;
     _identityUtilService = identityUtilService;
     _profileMediaService = profileMediaService;
     _fileDTOBuilder      = fileDTOBuilder;
 }
        public Restaurant_Card_Page1ViewModel(INavigationService navigationService,
                                              ICensusService censusService,
                                              IImageEditor imageEditor,
                                              IMediaPickerService mediaPickerService,
                                              IDialogService dialogService) : base(navigationService, dialogService)
        {
            _navigationService  = navigationService;
            _dialogService      = dialogService;
            _censusService      = censusService;
            _mediaPickerService = mediaPickerService;
            _imageEditor        = imageEditor;

            //普查步骤
            var steps = new Dictionary <int, string> {
                { 0, "基础信息" }, { 1, "经营信息" }, { 2, "销售信息" }
            };

            Steps = steps;
            Step  = 1;

            Title = "添加餐饮终端普查-基本信息";


            //
            GlobalSettings.EventDate = DateTime.Now;

            EndPointNumber_Tip    = "请定义终端编号";
            SaleRegion_Tip        = "请输入所在大区";
            SalesDepartment_Tip   = "请输入业务部";
            City_Tip              = "请确定你所在城市";
            DistrictOrCounty_Tip  = "请输入你所在区/县";
            CityOrTown_Tip        = "请输入城区/乡镇";
            EndPointStorsName_Tip = "请输入终端店名";
            EndPointTelphone_Tip  = "固话,填\"区号+号码\"(不加\"-\"),如0293248123";
            EndPointAddress_Tip   = "终端地址(详细街道/门牌号)";

            Restaurant = new Restaurant()
            {
                UserId    = Settings.UserId.ToString(),
                Latitude  = GlobalSettings.CurrtntCoordinate != null ? GlobalSettings.CurrtntCoordinate.Latitude : 0,
                Longitude = GlobalSettings.CurrtntCoordinate != null ? GlobalSettings.CurrtntCoordinate.Longitude : 0,
                Location  = GlobalSettings.CurrentAddComp != null ? GlobalSettings.CurrentAddComp.City : ""
            };

            BaseInfo = new RestaurantBaseInfo()
            {
                EndPointNumber  = string.Format("{0}_{1}", "CY", CommonHelper.GetTimeStamp(DateTime.Now, 13)),
                SaleRegion      = Settings.SaleRegion,
                SalesDepartment = Settings.SalesDepartment
            };
        }
        public ManagePicturesViewModel(
            IMediaPickerService mediaPickerService,
            IProfileMediaService profileMediaService,
            IFileDTOBuilder fileDTOBuilder,
            IStateService stateService)
        {
            _mediaPickerService  = mediaPickerService;
            _profileMediaService = profileMediaService;
            _fileDTOBuilder      = fileDTOBuilder;
            _stateService        = stateService;

            AddedPictures = new ObservableCollection <ProfileMediaDTO>();
            IsAnyPictures = AddedPictures.Any();
        }
示例#8
0
 public PickProfileAvatarPopupViewModel(
     IMediaPickerService mediaPickerService,
     IProfileService profileService,
     IIdentityUtilService identityUtilService,
     IProfileMediaService profileMediaService,
     IFileDTOBuilder fileDTOBuilder)
     : base(
         mediaPickerService,
         profileService,
         identityUtilService,
         profileMediaService,
         fileDTOBuilder)
 {
 }
示例#9
0
        public SettingsViewModel(
            IValidationObjectFactory validationObjectFactory,
            IMediaPickerService mediaPickerService,
            IProfileService profileService,
            IIdentityUtilService identityUtilService,
            IIdentityService identityService)
        {
            _validationObjectFactory = validationObjectFactory;
            _identityUtilService     = identityUtilService;
            _mediaPickerService      = mediaPickerService;
            _identityService         = identityService;
            _profileService          = profileService;

            switch (GlobalSettings.Instance.UserProfile.ProfileType)
            {
            case Models.DataItems.Autorization.ProfileType.Fan:
                SelfInformationViewModel = ViewModelLocator.Resolve <FanSelfInformationViewModel>();
                break;

            case Models.DataItems.Autorization.ProfileType.Player:
                SelfInformationViewModel = ViewModelLocator.Resolve <PlayerSelfInformationViewModel>();
                break;

            case Models.DataItems.Autorization.ProfileType.Parent:
                SelfInformationViewModel = ViewModelLocator.Resolve <ParentSelfInformationViewModel>();
                break;

            case Models.DataItems.Autorization.ProfileType.Organization:
                SelfInformationViewModel = ViewModelLocator.Resolve <OrganizationSelfInformationViewModel>();
                break;

            case Models.DataItems.Autorization.ProfileType.Coach:
                SelfInformationViewModel = ViewModelLocator.Resolve <CoachSelfInformationViewModel>();
                break;

            default:
                Debugger.Break();
                break;
            }
            SelfInformationViewModel?.InitializeAsync(this);

            PickAvatarPopupViewModel = ViewModelLocator.Resolve <PickProfileAvatarPopupViewModel>();
            PickAvatarPopupViewModel.InitializeAsync(this);

            ResetInputForm();

            IsImpersonateLogBackAvailable = (GlobalSettings.Instance.UserProfile.ImpersonateProfile != null);
            IsNestedPullToRefreshEnabled  = true;
        }
示例#10
0
 public SelfInformationBase(
     IValidationObjectFactory validationObjectFactory,
     IProfileService profileService,
     IMediaPickerService mediaPickerService,
     IFileDTOBuilder fileDTOBuilder,
     IIdentityUtilService identityUtilService,
     IProfileMediaService profileMediaService)
 {
     _validationObjectFactory = validationObjectFactory;
     _profileService          = profileService;
     _mediaPickerService      = mediaPickerService;
     _fileDTOBuilder          = fileDTOBuilder;
     _identityUtilService     = identityUtilService;
     _profileMediaService     = profileMediaService;
 }
        public EditPostPopupViewModel(IProfileMediaService profileMediaService,
                                      IMediaPickerService mediaPickerService,
                                      IValidationObjectFactory validationObjectFactory,
                                      IPostService postService,
                                      IFileDTOBuilder fileDTOBuilder,
                                      IMediaFactory mediaFactory)
        {
            _profileMediaService     = profileMediaService;
            _fileDTOBuilder          = fileDTOBuilder;
            _validationObjectFactory = validationObjectFactory;
            _postService             = postService;
            _mediaPickerService      = mediaPickerService;
            _mediaFactory            = mediaFactory;

            ResolveProfileInfo();
        }
 public PlayerSelfInformationViewModel(
     IValidationObjectFactory validationObjectFactory,
     IProfileService profileService,
     IMediaPickerService mediaPickerService,
     IFileDTOBuilder fileDTOBuilder,
     IIdentityUtilService identityUtilService,
     IProfileMediaService profileMediaService)
     : base(
         validationObjectFactory,
         profileService,
         mediaPickerService,
         fileDTOBuilder,
         identityUtilService,
         profileMediaService)
 {
     ResetInputForm();
 }
示例#13
0
        public ProfilePageViewModel(IProfileService profileService,
                                    IAuthenticationService authenticationService,
                                    IMediaPickerService mediaPickerService,
                                    INavigationService navigationService,
                                    ICacheManager cacheManager,
                                    IDialogService dialogService) : base(navigationService, dialogService)
        {
            _navigationService = navigationService;
            _dialogService     = dialogService;

            _profileService        = profileService;
            _authenticationService = authenticationService;
            _mediaPickerService    = mediaPickerService;
            _cacheManager          = cacheManager;

            Title = "个人资料";
        }
示例#14
0
        public CreateFeedViewModel(IProfileMediaService profileMediaService,
                                   IMediaFactory mediaFactory,
                                   IMediaPickerService mediaPickerService,
                                   IPostService postService,
                                   IValidationObjectFactory validationObjectFactory,
                                   IFileDTOBuilder fileDTOBuilder,
                                   IStateService stateService)
        {
            _profileMediaService     = profileMediaService;
            _mediaPickerService      = mediaPickerService;
            _postService             = postService;
            _validationObjectFactory = validationObjectFactory;
            _fileDTOBuilder          = fileDTOBuilder;
            _mediaFactory            = mediaFactory;
            _stateService            = stateService;

            IsAnyMedia = AttachedMedia.Any();
            ResetValidationObjects();
        }
示例#15
0
        public FeedbackComposerViewModel(IApplicationService applicationService, IImgurService imgurService,
                                         IMediaPickerService mediaPicker, IStatusIndicatorService statusIndicatorService, IAlertDialogService alertDialogService)
        {
            this.WhenAnyValue(x => x.IsFeature).Subscribe(x => Title = x ? "New Feature" : "Bug Report");

            SubmitCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Subject).Select(x => !string.IsNullOrEmpty(x)),
                async _ =>
            {
                if (string.IsNullOrEmpty(Subject))
                {
                    throw new ArgumentException(string.Format("You must provide a title for this {0}!", IsFeature ? "feature" : "bug"));
                }
                var labels       = await applicationService.Client.ExecuteAsync(applicationService.Client.Users[CodeHubOwner].Repositories[CodeHubName].Labels.GetAll());
                var createLabels = labels.Data.Where(x => string.Equals(x.Name, IsFeature ? "feature request" : "bug", StringComparison.OrdinalIgnoreCase)).Select(x => x.Name).Distinct();
                var request      = applicationService.Client.Users[CodeHubOwner].Repositories[CodeHubName].Issues.Create(Subject, Description, null, null, createLabels.ToArray());
                var createdIssue = await applicationService.Client.ExecuteAsync(request);
                _createdIssueSubject.OnNext(createdIssue.Data);
                DismissCommand.ExecuteIfCan();
            });

            PostToImgurCommand = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                var photo        = await mediaPicker.PickPhoto();
                var memoryStream = new MemoryStream();
                await photo.Save(Splat.CompressedBitmapFormat.Jpeg, 0.8f, memoryStream);
                using (statusIndicatorService.Activate("Uploading..."))
                {
                    var model = await imgurService.SendImage(memoryStream.ToArray());
                    if (model == null || model.Data == null || model.Data.Link == null)
                    {
                        throw new InvalidOperationException("Unable to upload to Imgur. Please try again later.");
                    }
                    return(model.Data.Link);
                }
            });

            PostToImgurCommand.ThrownExceptions
            .Where(x => !(x is TaskCanceledException))
            .Subscribe(x => alertDialogService.Alert("Upload Error", x.Message));
        }
示例#16
0
 public ProfileViewModel(IProfileService profileService, IAuthenticationService authenticationService, IMediaPickerService mediaPickerService)
 {
     _profileService        = profileService;
     _authenticationService = authenticationService;
     _mediaPickerService    = mediaPickerService;
 }
示例#17
0
        public VisitStorePageViewModel(INavigationService navigationService,
                                       IProductService productService,
                                       ITerminalService terminalService,
                                       IUserService userService,
                                       IWareHousesService wareHousesService,
                                       IAccountingService accountingService,
                                       IMediaPickerService mediaPickerService,
                                       ILiteDbService <TrackingModel> conn,
                                       ILiteDbService <VisitStore> vsdb,
                                       IPermissionsService permissionsService,
                                       IDialogService dialogService) : base(navigationService,
                                                                            productService,
                                                                            terminalService,
                                                                            userService,
                                                                            wareHousesService,
                                                                            accountingService,
                                                                            dialogService)
        {
            _permissionsService = permissionsService;
            _mediaPickerService = mediaPickerService;

            _conn = conn;
            _vsdb = vsdb;

            Title = "拜访门店";

            httpClientHelper = new HttpClientHelper();

            this.SubmitText = "\uf017";

            this.Load = ReactiveCommand.Create(async() =>
            {
                try
                {
                    var check          = await CheckSignIn();
                    this.SignInEnabled = !check;

                    if (!string.IsNullOrWhiteSpace(Settings.DisplayPhotos))
                    {
                        var displayPhotos = JsonConvert.DeserializeObject <List <DisplayPhoto> >(Settings.DisplayPhotos);
                        if (displayPhotos != null)
                        {
                            this.Bill.DisplayPhotos = new ObservableCollection <DisplayPhoto>(displayPhotos);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(Settings.DoorheadPhotos))
                    {
                        var doorheadPhotos = JsonConvert.DeserializeObject <List <DoorheadPhoto> >(Settings.DoorheadPhotos);
                        if (doorheadPhotos != null)
                        {
                            this.Bill.DoorheadPhotos = new ObservableCollection <DoorheadPhoto>(doorheadPhotos);
                        }
                    }

                    //重新获取客户信息
                    if (Settings.LastSigninCoustmerId > 0)
                    {
                        var tt = await _terminalService.GetTerminalAsync(Settings.LastSigninCoustmerId);
                        if (tt != null)
                        {
                            this.Terminal     = tt;
                            Bill.TerminalId   = tt.Id;
                            Bill.TerminalName = tt.Name;
                        }
                    }


                    //有没签退信息时
                    if (this.OutVisitStore != null)
                    {
                        //刷新状态
                        Refresh(this.OutVisitStore);
                    }

                    //如果上次签到客户存在时
                    var terminalId = Settings.LastSigninCoustmerId > 0 ? Settings.LastSigninCoustmerId : Bill.TerminalId;
                    if (terminalId > 0)
                    {
                        //获取终端余额
                        _terminalService.Rx_GetTerminalBalance(terminalId, new CancellationToken())?.Subscribe((balance) =>
                        {
                            if (balance != null)
                            {
                                this.TBalance = balance;
                            }
                        }).DisposeWith(DeactivateWith);


                        //获取上次拜访信息
                        _terminalService.Rx_GetLastVisitStoreAsync(terminalId, Settings.UserId, new CancellationToken())?.Subscribe((result) =>
                        {
                            if (result != null && result.Id > 0)
                            {
                                try
                                {
                                    //上次签到时间
                                    if (result.SigninDateTime != null)
                                    {
                                        var seconds = (int)DateTime.Now.Subtract(result.SigninDateTime).TotalSeconds;
                                        var coms    = CommonHelper.ConvetToSeconds(seconds);

                                        if (!string.IsNullOrEmpty(coms))
                                        {
                                            this.Bill.LastSigninDateTimeName = coms;
                                        }
                                    }

                                    //上次采购时间
                                    if (result.LastPurchaseDate != null)
                                    {
                                        var seconds = (int)DateTime.Now.Subtract(result.LastPurchaseDate).TotalSeconds;
                                        var coms    = CommonHelper.ConvetToSeconds(seconds);
                                        if (!string.IsNullOrEmpty(coms))
                                        {
                                            this.Bill.LastPurchaseDateTimeName = coms;
                                        }
                                    }

                                    if (this.OutVisitStore == null && result.SigninDateTime != null)
                                    {
                                        this.Bill.SigninDateTime = result.SigninDateTime;
                                    }
                                }
                                catch (Exception) { }
                            }
                        }).DisposeWith(DeactivateWith);
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //历史记录选择
            this.HistoryCommand = ReactiveCommand.Create <object>(async e => await this.NavigateAsync($"{nameof(VisitRecordsPage)}", null));

            //到店签到
            this.OpenSignInCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                if (Bill.TerminalId == 0)
                {
                    await this.NavigateAsync("CurrentCustomerPage");
                    return(Unit.Default);
                }

                var loc = await _permissionsService.GetLocationConsent();
                if (loc != PermissionStatus.Granted)
                {
                    await _dialogService.ShowAlertAsync("你的位置服务没有开启,请打开GPS", "定位", "确定");
                    return(Unit.Default);
                }

                if (Bill.TerminalId == 0 || string.IsNullOrEmpty(Bill.TerminalName))
                {
                    this.Alert("未选择客户...");
                    return(Unit.Default);
                }

                if (IsFooterVisible)
                {
                    IsVisible  = true;
                    IsExpanded = true;
                    //载入位置
                    ReloadLocation();
                    IsFooterVisible = false;
                }
                else
                {
                    IsVisible       = false;
                    IsExpanded      = false;
                    IsFooterVisible = true;
                }

                return(Unit.Default);
            });

            //取消签到
            this.CancelSignIn = ReactiveCommand.Create(() =>
            {
                IsVisible       = false;
                IsExpanded      = false;
                IsFooterVisible = true;
            });

            //签到
            this.SignInCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    if (!IsFastClick())
                    {
                        return(Unit.Default);
                    }

                    bool continueTodo = true;
                    if (Terminal.CalcDistance() > 50)
                    {
                        continueTodo  = await UserDialogs.Instance.ConfirmAsync($"你确定要在{Terminal.Distance:#.00}米外签到吗?", "警告", cancelText: "不签到", okText: "继续签到");
                        Bill.Abnormal = true;
                        Bill.Distance = Math.Round(Terminal.Distance, 2);
                    }


                    var lat = GlobalSettings.Latitude ?? 0;
                    var lan = GlobalSettings.Longitude ?? 0;


                    if (!continueTodo)
                    {
                        return(Unit.Default);
                    }

                    //签到
                    Bill.Id                   = 0;
                    Bill.StoreId              = Settings.StoreId;
                    Bill.BusinessUserId       = Settings.UserId;
                    Bill.BusinessUserName     = Settings.UserRealName;
                    Bill.ChannelId            = Terminal.ChannelId;
                    Bill.DistrictId           = Terminal.DistrictId;
                    Bill.SigninDateTimeEnable = true;
                    Bill.SigninDateTime       = DateTime.Now;
                    Bill.SignOutDateTime      = DateTime.Now;
                    Bill.VisitTypeId          = 2;//计划内
                    Bill.SignTypeId           = 1;
                    Bill.SignType             = Enums.SignEnum.CheckIn;
                    Bill.Remark               = LocationAddress;

                    //获取坐标
                    Bill.Latitude  = lat;
                    Bill.Longitude = lan;

                    return(await SubmitAsync(Bill, _terminalService.SignInVisitStoreAsync, async(result) =>
                    {
                        if (!result.Success)
                        {
                            this.IsVisible = false;
                            this.IsExpanded = false;
                            this.IsFooterVisible = true;
                        }
                        else
                        {
                            if (result.Data is VisitStore data)
                            {
                                this.SignInEnabled = false;
                                this.SignOutEnabled = true;
                                this.OutVisitStore = null;

                                //drawer
                                this.IsVisible = false;
                                this.IsExpanded = false;
                                this.IsFooterVisible = true;

                                //记录下签到ID
                                Settings.LastSigninId = data.Id;
                                Settings.LastSigninCoustmerId = Bill.TerminalId;
                                Settings.LastSigninCoustmerName = Bill.TerminalName;

                                this.Bill.LastSigninDateTime = data.LastSigninDateTime;
                                this.Bill.LastPurchaseDateTime = data.LastPurchaseDateTime;

                                //添加签到记录
                                try
                                {
                                    Terminal.Id = Bill.TerminalId;
                                    Terminal.LastSigninDateTimeName = data.SigninDateTime.ToString();
                                    Terminal.SigninDateTime = data.SigninDateTime;
                                    await _terminalService.AddTerminal(Terminal);
                                }
                                catch (Exception) { }
                            }
                        }
                    }, goBack: false));
                }
                catch (Exception)
                {
                    this.IsVisible       = false;
                    this.IsExpanded      = false;
                    this.IsFooterVisible = true;

                    await ShowAlert(false, $"出错啦,内部异常!");
                    return(Unit.Default);
                }
            });

            //校准位置
            this.CorrectPositionCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    var lat = GlobalSettings.Latitude ?? 0;
                    var lan = GlobalSettings.Longitude ?? 0;

                    if (Terminal == null || Terminal.Id == 0)
                    {
                        await ShowAlert(false, $"无效操作!");
                        return;
                    }

                    if (lat != 0 && lan != 0)
                    {
                        var distance          = MapHelper.CalculateDistance(GlobalSettings.Latitude ?? 0, GlobalSettings.Longitude ?? 0, this.Terminal?.Location_Lat ?? 0, this.Terminal?.Location_Lng ?? 0);
                        Terminal.Location_Lat = GlobalSettings.Latitude;
                        Terminal.Location_Lng = GlobalSettings.Longitude;
                        Terminal.Distance     = distance;
                        await _terminalService.UpdateterminalAsync(Terminal.Id, GlobalSettings.Latitude ?? 0, GlobalSettings.Longitude ?? 0);
                    }

                    await ShowAlert(true, $"校准成功!");
                }
                catch (Exception)
                {
                    await ShowAlert(false, $"出错啦,内部异常!");
                }
            });

            //离店签退
            this.SignOutCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    int onStoreStopSeconds = 0;
                    double subtract        = DateTime.Now.Subtract(Bill?.SigninDateTime ?? DateTime.Now).TotalMinutes;
                    if (!string.IsNullOrEmpty(Settings.CompanySetting))
                    {
                        var companySetting = JsonConvert.DeserializeObject <CompanySettingModel>(Settings.CompanySetting);
                        if (companySetting != null)
                        {
                            onStoreStopSeconds = companySetting.OnStoreStopSeconds;
                        }
                    }

                    if (!SignOutEnabled)
                    {
                        this.Alert("还没签到哦!");
                        return(Unit.Default);
                    }

                    if (onStoreStopSeconds > 0 && subtract < onStoreStopSeconds)
                    {
                        this.Alert($"签退无效,拜访在店时间必须大于{onStoreStopSeconds}分钟");
                        return(Unit.Default);
                    }

                    if (Settings.LastSigninId == 0)
                    {
                        this.Alert("签退无效,无法确定记录");
                        return(Unit.Default);
                    }

                    if (Bill.TerminalId == 0 || string.IsNullOrEmpty(Bill.TerminalName))
                    {
                        this.Alert("选择客户");
                        return(Unit.Default);
                    }

                    if (Bill.DoorheadPhotos == null || Bill.DoorheadPhotos.Count == 0)
                    {
                        this.Alert("请拍摄门头照片");
                        return(Unit.Default);
                    }

                    if (Bill.DisplayPhotos == null || Bill.DisplayPhotos.Count == 0)
                    {
                        this.Alert("请拍摄陈列照片");
                        return(Unit.Default);
                    }

                    if (BillId > 0)
                    {
                        switch (BillType)
                        {
                        case BillTypeEnum.SaleReservationBill:
                            this.Bill.SaleReservationBillId = BillId;
                            this.Bill.SaleOrderAmount       = Amount;
                            break;

                        case BillTypeEnum.SaleBill:
                            this.Bill.SaleBillId = BillId;
                            this.Bill.SaleAmount = Amount;
                            break;

                        case BillTypeEnum.ReturnReservationBill:
                            this.Bill.ReturnReservationBillId = BillId;
                            this.Bill.ReturnOrderAmount       = Amount;
                            break;

                        case BillTypeEnum.ReturnBill:
                            this.Bill.ReturnBillId = BillId;
                            this.Bill.ReturnAmount = Amount;
                            break;
                        }
                    }

                    //签退
                    Bill.Id = Settings.LastSigninId;
                    Bill.SignOutDateTime = DateTime.Now;
                    Bill.SignTypeId      = 2;

                    await SubmitAsync(Bill, _terminalService.SignOutVisitStoreAsync, async(result) =>
                    {
                        if (result.Success)
                        {
                            this.SignOutEnabled            = false;
                            this.Bill.SigninDateTimeEnable = false;
                            this.OutVisitStore             = null;

                            Settings.LastSigninId           = 0;
                            Settings.LastSigninCoustmerId   = 0;
                            Settings.LastSigninCoustmerName = "";

                            Settings.DisplayPhotos  = "";
                            Settings.DoorheadPhotos = "";

                            //更新签到记录
                            try
                            {
                                Terminal.Id = Bill.TerminalId;
                                Terminal.SignOutDateTime = Bill.SignOutDateTime;
                                await _terminalService.UpdateTerminal(Terminal);
                            }catch (Exception) { }
                        }
                    });

                    await _navigationService.GoBackAsync();

                    return(Unit.Default);
                }
                catch (Exception)
                {
                    await ShowAlert(false, $"出错啦,内部异常!");
                    return(Unit.Default);
                }
            });

            //应用选择执行
            this.InvokeAppCommand = ReactiveCommand.CreateFromTask <string>(async(r) =>
            {
                try
                {
                    if (Settings.LastSigninId != 0 && Settings.LastSigninCoustmerId != 0)
                    {
                        await this.NavigateAsync(r.ToString(),
                                                 ("TerminalId", Bill.TerminalId),
                                                 ("TerminalName", Bill.TerminalName),
                                                 ("Reference", this.PageName));
                    }
                    else
                    {
                        await ShowAlert(false, "需要先签到后操作");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //拍照选择
            this.CameraPhotoCmd = ReactiveCommand.CreateFromTask <string>(async(r) =>
            {
                if (!IsFastClick())
                {
                    return;
                }

                if (this.SignInEnabled)
                {
                    this.Alert("还没有签到哦!");
                }
                else
                {
                    await this.NavigateAsync("CameraViewPage", ("TakeType", r));
                }
            });

            //删除门头照片
            this.RemoveStoragePathCommand = ReactiveCommand.Create <string>(async x =>
            {
                var ok = await _dialogService.ShowConfirmAsync("是否要删除该图片?", okText: "确定", cancelText: "取消");
                if (ok)
                {
                    var temp = this.Bill.DoorheadPhotos.FirstOrDefault(s => s.StoragePath == x);
                    if (temp != null)
                    {
                        this.Bill.DoorheadPhotos.Remove(temp);
                        Settings.DoorheadPhotos = JsonConvert.SerializeObject(this.Bill.DoorheadPhotos);
                    }
                }
            });

            //删除陈列照片
            this.RemoveDisplayPathCommand = ReactiveCommand.Create <string>(async x =>
            {
                var ok = await _dialogService.ShowConfirmAsync("是否要删除该图片?", okText: "确定", cancelText: "取消");
                if (ok)
                {
                    var temp = this.Bill.DisplayPhotos.FirstOrDefault(s => s.DisplayPath == x);
                    if (temp != null)
                    {
                        this.Bill.DisplayPhotos.Remove(temp);
                        Settings.DisplayPhotos = JsonConvert.SerializeObject(this.Bill.DisplayPhotos);
                    }
                }
            });

            //定位
            this.OrientationCmd = ReactiveCommand.Create(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    ReloadLocation();
                });
            });

            //预览照片
            this.WhenAnyValue(x => x.DoorheadPhotoSelecter)
            .Throttle(TimeSpan.FromMilliseconds(200))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                var images = new List <string> {
                    item.StoragePath
                };
                await this.NavigateAsync("ImageViewerPage", ("ImageInfos", images));
                DoorheadPhotoSelecter = null;
            }).DisposeWith(DeactivateWith);

            this.WhenAnyValue(x => x.DisplayPhotoSelecter)
            .Throttle(TimeSpan.FromMilliseconds(200))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                var images = new List <string> {
                    item.DisplayPath
                };
                await this.NavigateAsync("ImageViewerPage", ("ImageInfos", images));
                DisplayPhotoSelecter = null;
            }).DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);


            //拍照上传
            MessageBus
            .Current
            .Listen <byte[]?>(string.Format(Constants.CAMERA_KEY, "DoorheadPhotos"))
            .Subscribe(bit =>
            {
                if (bit != null && bit.Length > 0)
                {
                    UploadPhotograph((u) =>
                    {
                        var photo = new DoorheadPhoto
                        {
                            StoragePath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + ""
                        };
                        this.Bill.DoorheadPhotos.Add(photo);
                        Settings.DoorheadPhotos = JsonConvert.SerializeObject(this.Bill.DoorheadPhotos);
                    }, new MemoryStream(bit));
                }
            }).DisposeWith(DeactivateWith);


            MessageBus
            .Current
            .Listen <byte[]?>(string.Format(Constants.CAMERA_KEY, "DisplayPhotos"))
            .Subscribe(bit =>
            {
                if (bit != null && bit.Length > 0)
                {
                    UploadPhotograph((u) =>
                    {
                        var photo = new DisplayPhoto
                        {
                            DisplayPath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + ""
                        };
                        this.Bill.DisplayPhotos.Add(photo);
                        Settings.DisplayPhotos = JsonConvert.SerializeObject(this.Bill.DisplayPhotos);
                    }, new MemoryStream(bit));
                }
            }).DisposeWith(DeactivateWith);

            this.Load.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.HistoryCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.OpenSignInCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CancelSignIn.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.SignInCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CorrectPositionCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.SignOutCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.InvokeAppCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CameraPhotoCmd.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.RemoveStoragePathCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.RemoveDisplayPathCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.OrientationCmd.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
        }
示例#18
0
        public FeedbackPageViewModel(INavigationService navigationService,


                                     IDialogService dialogService,
                                     IFeedbackService feedbackService,
                                     IMediaPickerService mediaPickerService
                                     ) : base(navigationService, dialogService)
        {
            _feedbackService    = feedbackService;
            _mediaPickerService = mediaPickerService;


            Title = "问题反馈";
            this.TextCounterTxt = "0/500";
            this.Contacts       = Settings.UserEmall ?? (Settings.UserMobile ?? Settings.UserRealName);

            this.WhenAnyValue(x => x.IssueDescribe)
            .Skip(1)
            .Where(x => x != null)
            .Select(x =>
            {
                if (!string.IsNullOrEmpty(x))
                {
                    return($"{x.Length}/500");
                }
                else
                {
                    return($"0/500");
                }
            }).Subscribe(x => { this.TextCounterTxt = x; }).DisposeWith(DeactivateWith);


            this.TextChangedCommand = ReactiveCommand.Create <string>((e) =>
            {
                if (IssueDescribe.Length > 500)
                {
                    IsEnabled = false;
                    _dialogService.ShortAlert("字数超过限制!");
                }
                else
                {
                    IsEnabled = true;
                }
            });

            //验证
            var valid_Describe  = this.ValidationRule(x => x.IssueDescribe, _isDefined, "请先输入内容");
            var valid_Contracts = this.ValidationRule(x => x.Contacts, _isDefined, "请先输入联系方式");
            var valid_Photos    = this.ValidationRule(x => x.DisplayPhotos.Count, _isZero, "请先上传截图");
            var canExcute       = this.WhenAnyValue(x => x.DisplayPhotos.Count).Select(x => x <= 4).Do(x => { if (!x)
                                                                                                              {
                                                                                                                  this.Alert("最多只能五张哦!");
                                                                                                              }
                                                                                                       });

            //提交
            this.SubmitCommand = ReactiveCommand.CreateFromTask <object>(async e =>
            {
                try
                {
                    if (!valid_Describe.IsValid)
                    {
                        this.Alert(valid_Describe.Message[0]); return;
                    }
                    if (!valid_Contracts.IsValid)
                    {
                        this.Alert(valid_Contracts.Message[0]); return;
                    }
                    if (!valid_Photos.IsValid)
                    {
                        this.Alert(valid_Photos.Message[0]); return;
                    }

                    var feedback = new FeedBack
                    {
                        FeedbackTyoe  = this.SelectedSegment,
                        IssueDescribe = this.IssueDescribe,
                        Contacts      = this.Contacts,
                        CreatedOnUtc  = DateTime.Now
                    };

                    if (DisplayPhotos != null && DisplayPhotos.Count > 0)
                    {
                        switch (DisplayPhotos.Count)
                        {
                        case 1:
                            feedback.Screenshot1 = DisplayPhotos[0] == null ? "" : DisplayPhotos[0].DisplayPath;
                            break;

                        case 2:
                            feedback.Screenshot1 = DisplayPhotos[0] == null ? "" : DisplayPhotos[0].DisplayPath;
                            feedback.Screenshot2 = DisplayPhotos[1] == null ? "" : DisplayPhotos[1].DisplayPath;
                            break;

                        case 3:
                            feedback.Screenshot1 = DisplayPhotos[0] == null ? "" : DisplayPhotos[0].DisplayPath;
                            feedback.Screenshot2 = DisplayPhotos[1] == null ? "" : DisplayPhotos[1].DisplayPath;
                            feedback.Screenshot3 = DisplayPhotos[2] == null ? "" : DisplayPhotos[2].DisplayPath;
                            break;

                        case 4:
                            feedback.Screenshot1 = DisplayPhotos[0] == null ? "" : DisplayPhotos[0].DisplayPath;
                            feedback.Screenshot2 = DisplayPhotos[1] == null ? "" : DisplayPhotos[1].DisplayPath;
                            feedback.Screenshot3 = DisplayPhotos[2] == null ? "" : DisplayPhotos[2].DisplayPath;
                            feedback.Screenshot4 = DisplayPhotos[3] == null ? "" : DisplayPhotos[3].DisplayPath;
                            break;

                        case 5:
                            feedback.Screenshot1 = DisplayPhotos[0] == null ? "" : DisplayPhotos[0].DisplayPath;
                            feedback.Screenshot2 = DisplayPhotos[1] == null ? "" : DisplayPhotos[1].DisplayPath;
                            feedback.Screenshot3 = DisplayPhotos[2] == null ? "" : DisplayPhotos[2].DisplayPath;
                            feedback.Screenshot4 = DisplayPhotos[3] == null ? "" : DisplayPhotos[3].DisplayPath;
                            feedback.Screenshot5 = DisplayPhotos[4] == null ? "" : DisplayPhotos[4].DisplayPath;
                            break;
                        }
                    }

                    await SubmitAsync(feedback, _feedbackService.CreateOrUpdateAsync, (result) =>
                    {
                        if (result.Success)
                        {
                            this.IssueDescribe   = "";
                            this.SelectedSegment = 0;
                            this.Contacts        = "";
                        }
                    });
                }
                catch (Exception)
                {
                    await ShowAlert(false, $"出错啦,内部异常!");
                    return;
                }
            });

            //拍照选择
            this.CameraPhotoCmd = ReactiveCommand.CreateFromTask <string>(async(r) =>
            {
                try
                {
                    //var resultMedia = await CrossDiaglogKit.Current.GetMediaResultAsync("请选择", "");

                    //if (resultMedia != null)
                    //{
                    //    //上传图片
                    //    using (UserDialogs.Instance.Loading("上传中..."))
                    //    {
                    //        byte[] base64Stream = Convert.FromBase64String(resultMedia.ToString());

                    //        Stream resultStream = null;

                    //        //裁切图片481X480
                    //        using (var imageEditor = await _mediaPickerService.CreateImageAsync(base64Stream))
                    //        {
                    //            imageEditor.Resize(480, 480);
                    //            resultStream = CommonHelper.BytesToStream(imageEditor.ToJpeg());
                    //        }

                    //        if (resultStream == null)
                    //        {
                    //            return;
                    //        }

                    //        var content = new MultipartFormDataContent
                    //                {
                    //                     { new StreamContent(resultStream), "\"file\"", $"\"{Settings.UserId}_feedBack.jpg\"" }
                    //                };

                    //        using (var httpClient = new HttpClient())
                    //        {
                    //            var uploadServiceBaseAddress = $"{GlobalSettings.FileCenterEndpoint}document/reomte/fileupload/HRXHJS";
                    //            var httpResponseMessage = await httpClient.PostAsync(uploadServiceBaseAddress, content);
                    //            var result = await httpResponseMessage.Content.ReadAsStringAsync();
                    //            var uploadResult = new UploadResult();

                    //            try
                    //            {
                    //                if (!string.IsNullOrEmpty(result))
                    //                {
                    //                    uploadResult = JsonConvert.DeserializeObject<UploadResult>(result);
                    //                }
                    //            }
                    //            catch (Exception)
                    //            {
                    //                uploadResult = null;
                    //            }
                    //            finally
                    //            {
                    //                if (httpResponseMessage != null)
                    //                    httpResponseMessage.Dispose();
                    //            }

                    //            if (uploadResult != null)
                    //            {
                    //                var displayPhoto = new DisplayPhoto
                    //                {
                    //                    DisplayPath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + uploadResult.Id + ""
                    //                };

                    //                DisplayPhotos.Add(displayPhoto);
                    //            }
                    //        }

                    //        if (resultStream != null)
                    //            resultStream.Dispose();
                    //    };
                    //}
                }
                catch (Exception)
                {
                    await _dialogService.ShowAlertAsync("上传失败,服务器错误!", "提示", "取消");
                }
            }, canExcute);

            //删除
            this.RemoveCommand = ReactiveCommand.Create <string>(async x =>
            {
                var ok = await _dialogService.ShowConfirmAsync("是否要删除该图片?", okText: "确定", cancelText: "取消");
                if (ok)
                {
                    var temp = DisplayPhotos.FirstOrDefault(c => c.DisplayPath == x);
                    if (temp != null)
                    {
                        DisplayPhotos.Remove(temp);
                    }
                }
            });
        }
示例#19
0
        //public Task<IPickedMediaFromGallery> TakePhotoOrVideoAsync() =>
        //    Task<IPickedMediaFromGallery>.Run(() => {
        //        PickedMediaFromGallery pickedMediaResult = new PickedMediaFromGallery();

        //        try {
        //            UIViewController topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
        //            while (topController.PresentedViewController != null) {
        //                topController = topController.PresentedViewController;
        //            }

        //            UIAlertController actionSheet = UIAlertController.Create("Make a choise", "Take Image or Video with:", UIAlertControllerStyle.ActionSheet);

        //            ///
        //            /// Use photo camera action
        //            ///
        //            actionSheet.AddAction(UIAlertAction.Create("Camera", UIAlertActionStyle.Default, (action) => {
        //                if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
        //                    UIImagePickerController imagePicker = new UIImagePickerController();
        //                    imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
        //                    imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera);

        //                    imagePicker.FinishedPickingMedia += (sender, args) => {
        //                        if (args?.OriginalImage != null) {
        //                            ///
        //                            /// Figure out how much to scale down by
        //                            ///
        //                            int inSampleSize = GetInSampleSize(args.OriginalImage.Size.Width, args.OriginalImage.Size.Height);

        //                            UIImage originalImage = args.OriginalImage.Scale(new CGSize(args.OriginalImage.Size.Width / inSampleSize, args.OriginalImage.Size.Height / inSampleSize));
        //                            string imageBase64 = originalImage.AsJPEG().GetBase64EncodedString(NSDataBase64EncodingOptions.EndLineWithLineFeed);

        //                            pickedMediaResult.Completion = true;
        //                            pickedMediaResult.DataBase64 = imageBase64;
        //                            pickedMediaResult.DataThumbnailBase64 = imageBase64;
        //                            pickedMediaResult.MimeType = ProfileMediaService.IMAGE_MEDIA_TYPE;
        //                        }

        //                        topController.DismissModalViewController(true);
        //                    };

        //                    imagePicker.Canceled += (sender, args) => {
        //                        topController.DismissModalViewController(true);
        //                        pickedMediaResult.Completion = true;
        //                    };

        //                    topController.PresentModalViewController(imagePicker, true);
        //                }
        //                else {
        //                    UIAlertController alert = UIAlertController.Create("Warning", "Your device don't have camera", UIAlertControllerStyle.Alert);
        //                    alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (alertAction) => {
        //                        pickedMediaResult.Completion = false;
        //                        pickedMediaResult.ErrorMessage = _TAKE_IMAGE_COMMON_ERROR;
        //                    }));

        //                    topController.PresentViewController(alert, true, null);
        //                }
        //            }));

        //            ///
        //            /// Use photo camera action
        //            ///
        //            //actionSheet.AddAction(UIAlertAction.Create("Video camera", UIAlertActionStyle.Default, (action) => {
        //            //    if (UIVide.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
        //            //        UIImagePickerController imagePicker = new UIImagePickerController();
        //            //        imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
        //            //        imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera);

        //            //        imagePicker.FinishedPickingMedia += (sender, args) => {
        //            //            if (args?.OriginalImage != null) {
        //            //                ///
        //            //                /// Figure out how much to scale down by
        //            //                ///
        //            //                int inSampleSize = GetInSampleSize(args.OriginalImage.Size.Width, args.OriginalImage.Size.Height);

        //            //                UIImage originalImage = args.OriginalImage.Scale(new CGSize(args.OriginalImage.Size.Width / inSampleSize, args.OriginalImage.Size.Height / inSampleSize));
        //            //                string imageBase64 = originalImage.AsJPEG().GetBase64EncodedString(NSDataBase64EncodingOptions.EndLineWithLineFeed);

        //            //                pickedMediaResult.Completion = true;
        //            //                pickedMediaResult.DataBase64 = imageBase64;
        //            //                pickedMediaResult.DataThumbnailBase64 = imageBase64;
        //            //                pickedMediaResult.MimeType = ProfileMediaService.IMAGE_MEDIA_TYPE;
        //            //            }

        //            //            topController.DismissModalViewController(true);
        //            //        };

        //            //        imagePicker.Canceled += (sender, args) => {
        //            //            topController.DismissModalViewController(true);
        //            //            pickedMediaResult.Completion = true;
        //            //        };

        //            //        topController.PresentModalViewController(imagePicker, true);
        //            //    }
        //            //    else {
        //            //        UIAlertController alert = UIAlertController.Create("Warning", "Your device don't have camera", UIAlertControllerStyle.Alert);
        //            //        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (alertAction) => {
        //            //            pickedMediaResult.Completion = false;
        //            //            pickedMediaResult.ErrorMessage = _TAKE_IMAGE_COMMON_ERROR;
        //            //        }));

        //            //        topController.PresentViewController(alert, true, null);
        //            //    }
        //            //}));
        //        }
        //        catch (Exception exc) {
        //            pickedMediaResult.Completion = false;
        //            pickedMediaResult.Exception = exc;
        //            pickedMediaResult.ErrorMessage = _TAKE_MEDIA_COMMON_ERROR;
        //        }

        //        return (IPickedMediaFromGallery)pickedMediaResult;
        //    });

        public Task <IPickedMediaFromGallery> TakePhotoOrVideoAsync()
        {
            _takeVideoOrImageTaskCompletion = new TaskCompletionSource <IPickedMediaFromGallery>();

            try {
                UIViewController topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                while (topController.PresentedViewController != null)
                {
                    topController = topController.PresentedViewController;
                }

                IMediaPickerService mediaPickerService = ViewModelLocator.Resolve <IMediaPickerService>();

                UIAlertController actionSheet = UIAlertController.Create("Make a choise", "Take Image or Video with:", UIAlertControllerStyle.ActionSheet);

                ///
                /// Use photo camera action
                ///
                actionSheet.AddAction(UIAlertAction.Create("Camera", UIAlertActionStyle.Default, async(action) => {
                    if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
                    {
                        try {
                            MediaFile mediaFile = await mediaPickerService.TakePhotoAsync();

                            if (mediaFile != null)
                            {
                                string base64 = await mediaPickerService.ParseStreamToBase64(mediaFile.GetStream());
                                _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                                {
                                    Completion = true, DataBase64 = base64, MimeType = ProfileMediaService.IMAGE_MEDIA_TYPE, DataThumbnailBase64 = base64
                                });
                                mediaFile.Dispose();
                            }
                            else
                            {
                                _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                                {
                                    Completion = true
                                });
                            }
                        }
                        catch (Exception exc) {
                            _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                            {
                                ErrorMessage = _TAKE_IMAGE_COMMON_ERROR, Exception = exc
                            });
                        }

                        topController.DismissModalViewController(true);
                    }
                    else
                    {
                        UIAlertController alert = UIAlertController.Create("Warning", "Your device don't have camera", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (alertAction) => _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                        {
                            ErrorMessage = _TAKE_IMAGE_COMMON_ERROR
                        })));

                        topController.PresentViewController(alert, true, null);
                    }
                }));

                ///
                /// Use photo camera action
                ///
                actionSheet.AddAction(UIAlertAction.Create("Video camera", UIAlertActionStyle.Default, async(action) => {
                    if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
                    {
                        try {
                            MediaFile mediaFile = await mediaPickerService.TakeVideoAsync();

                            if (mediaFile != null)
                            {
                                string thumbnailBase64 = await mediaPickerService.ParseStreamToBase64(GetThumbnail(mediaFile.Path));
                                string base64          = await mediaPickerService.ParseStreamToBase64(mediaFile.GetStream());

                                _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                                {
                                    Completion = true, DataBase64 = base64, MimeType = ProfileMediaService.VIDEO_MEDIA_TYPE, DataThumbnailBase64 = thumbnailBase64
                                });

                                mediaFile.Dispose();
                            }
                            else
                            {
                                _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                                {
                                    Completion = true
                                });
                            }
                        }
                        catch (Exception exc) {
                            _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                            {
                                ErrorMessage = _TAKE_IMAGE_COMMON_ERROR, Exception = exc
                            });
                        }

                        topController.DismissModalViewController(true);
                    }
                    else
                    {
                        UIAlertController alert = UIAlertController.Create("Warning", "Your device don't have camera", UIAlertControllerStyle.Alert);
                        alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, (alertAction) => _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                        {
                            ErrorMessage = _TAKE_IMAGE_COMMON_ERROR
                        })));

                        topController.PresentViewController(alert, true, null);
                    }
                }));

                topController.PresentViewController(actionSheet, true, null);
            }
            catch (Exception exc) {
                _takeVideoOrImageTaskCompletion.SetResult(new PickedMediaFromGallery()
                {
                    Exception = exc, ErrorMessage = _TAKE_VIDEO_COMMON_ERROR
                });
            }

            return(_takeVideoOrImageTaskCompletion.Task);
        }
示例#20
0
 public FileDTOBuilder(IMediaPickerService mediaPickerService)
 {
     _mediaPickerService = mediaPickerService;
 }