public MainViewModel() { SelectedIndex = -1; NoItemVisibility = Visibility.Collapsed; _dateTimer = new DispatcherTimer(); _dateTimer.Interval = TimeSpan.FromMilliseconds(1000); _dateTimer.Tick += (sender, e) => { CurrentDate = "今天:" + DateTime.Now.ToString(); }; _dateTimer.Start(); LoginVM = new LoginViewModel() { MainVM = this }; CurrentPlants = new ObservableCollection <Plant>(); if (ConfigHelper.IsLogin) { CurrentUser = new PlantSitterUser() { Email = LocalSettingHelper.GetValue("email"), }; var task1 = GetUserPlan(); var task2 = RefreshAllSensor(); } }
private async Task AddAllToDos() { foreach (var sche in MyToDos) { var result = await PostHelper.AddSchedule(LocalSettingHelper.GetValue("sid"), sche.Content, sche.IsDone? "1" : "0", SelectedCate.ToString()); } }
public static void SetupLang(string locale) { if (locale != null) { ApplicationLanguages.PrimaryLanguageOverride = locale; return; } if (LocalSettingHelper.HasValue("AppLang") == false) { var lang = GlobalizationPreferences.Languages[0]; if (lang.Contains("zh")) { ApplicationLanguages.PrimaryLanguageOverride = "zh-CN"; } else { ApplicationLanguages.PrimaryLanguageOverride = "en-US"; } LocalSettingHelper.AddValue("AppLang", ApplicationLanguages.PrimaryLanguageOverride); } else { ApplicationLanguages.PrimaryLanguageOverride = LocalSettingHelper.GetValue("AppLang"); } }
private void Grid_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) { if (_pointOriX < 10 && e.Delta.Translation.X > 10 && LocalSettingHelper.GetValue("EnableGesture") == "true") { SlideInStory.Begin(); HamburgerBtn.PlayHamInStory(); _isDrawerSlided = true; } }
/// <summary> /// 获得默认的参数 /// 将会返回带 UID AccessToken 的 /// </summary> /// <returns></returns> private static List <KeyValuePair <string, string> > GetDefaultParamWithAuthParam() { var param = new List <KeyValuePair <string, string> >(); param.Add(new KeyValuePair <string, string>("a", new Random().Next().ToString())); param.Add(new KeyValuePair <string, string>("uid", LocalSettingHelper.GetValue("uid"))); param.Add(new KeyValuePair <string, string>("access_token", LocalSettingHelper.GetValue("access_token"))); return(param); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); if (LocalSettingHelper.GetValue("EnableBackgroundTask") == "true") { BackgroundTaskHelper.RegisterBackgroundTask(DeviceKind.Windows); } Frame.BackStack.Clear(); }
public static string MakeFullUrlForPostReq(string baseUrl, bool withAuth) { StringBuilder sb = new StringBuilder(baseUrl); if (withAuth) { sb.Append("&uid=" + LocalSettingHelper.GetValue("uid")); sb.Append("&access_token=" + LocalSettingHelper.GetValue("access_token")); } return(sb.ToString()); }
public SettingsViewModel() { if (LocalSettingHelper.HasValue(SAVING_POSITION)) { var position = LocalSettingHelper.GetValue(SAVING_POSITION); SavingPositionPath = position; } else { SavingPositionPath = "\\Pictures\\MyerSplash"; } }
/// <summary> /// 进入 MainPage 会调用 /// </summary> /// <param name="param"></param> public async void Activate(object param) { TitleBarHelper.SetUpCateTitleBar(Enum.GetName(typeof(CateColors), SelectedCate)); if (param is LoginMode) { if (LOAD_ONCE) { return; } LOAD_ONCE = true; var mode = (LoginMode)param; switch (mode) { //已经登陆过的了 case LoginMode.Login: { CurrentUser.Email = LocalSettingHelper.GetValue("email"); ShowLoginBtnVisibility = Visibility.Collapsed; ShowAccountInfoVisibility = Visibility.Visible; //没有网络 if (App.IsNoNetwork) { await RestoreData(true); await Task.Delay(500); Messenger.Default.Send(new GenericMessage <string>(ResourcesHelper.GetString("NoNetworkHint")), MessengerTokens.ToastToken); } //有网络 else { Messenger.Default.Send(new GenericMessage <string>(ResourcesHelper.GetString("WelcomeBackHint")), MessengerTokens.ToastToken); await SyncAllToDos(); CurrentDisplayToDos = MyToDos; var resotreTask = RestoreData(false); } }; break; //处于离线模式 case LoginMode.OfflineMode: { ShowLoginBtnVisibility = Visibility.Visible; ShowAccountInfoVisibility = Visibility.Collapsed; var restoreTask = RestoreData(true); }; break; } } }
/// <summary> /// 从云端同步所有待办事项 /// </summary> /// <returns></returns> private async Task SyncAllToDos() { try { //没网络 if (App.IsNoNetwork) { //通知没有网络 Messenger.Default.Send(new GenericMessage <string>(ResourcesHelper.GetString("NoNetworkHint")), MessengerTokens.ToastToken); return; } //加载滚动条 IsLoading = Visibility.Visible; DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(3.2); timer.Tick += ((sendert, et) => { IsLoading = Visibility.Collapsed; }); timer.Start(); var result = await PostHelper.GetMySchedules(LocalSettingHelper.GetValue("sid")); if (!string.IsNullOrEmpty(result)) { //获得无序的待办事项 var scheduleWithoutOrder = ToDo.ParseJsonToObs(result); //获得顺序列表 var orders = await PostHelper.GetMyOrder(LocalSettingHelper.GetValue("sid")); //排序 MyToDos = ToDo.SetOrderByString(scheduleWithoutOrder, orders); ChangeDisplayCateList(SelectedCate); Messenger.Default.Send(new GenericMessage <string>(ResourcesHelper.GetString("SyncSuccessfully")), MessengerTokens.ToastToken); await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(MyToDos, SerializerFileNames.ToDoFileName, true); } //最后更新动态磁贴 Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); } }
public async Task DownloadFullImageAsync(CancellationToken token) { var url = GetSaveImageUrlFromSettings(); if (string.IsNullOrEmpty(url)) { return; } ToastService.SendToast("Downloading in background...", 2000); StorageFolder folder = null; if (LocalSettingHelper.HasValue(SettingsViewModel.SAVING_POSITION)) { var path = LocalSettingHelper.GetValue(SettingsViewModel.SAVING_POSITION); if (path == SettingsViewModel.DEFAULT_SAVING_POSITION) { folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("MyerSplash", CreationCollisionOption.OpenIfExists); } else { folder = await StorageFolder.GetFolderFromPathAsync(path); } } if (folder == null) { folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("MyerSplash", CreationCollisionOption.OpenIfExists); } var fileName = $"{Owner.Name} {CreateTimeString}"; var newFile = await folder.CreateFileAsync($"{fileName}.jpg", CreationCollisionOption.GenerateUniqueName); //backgroundDownloader.FailureToastNotification = ToastHelper.CreateToastNotification("Failed to download :-(", "You may cancel it. Otherwise please check your network."); _backgroundDownloader.SuccessToastNotification = ToastHelper.CreateToastNotification("Saved:D", $"You can find it in {folder.Path}."); var downloadOperation = _backgroundDownloader.CreateDownload(new Uri(url), newFile); var progress = new Progress <DownloadOperation>(); try { await downloadOperation.StartAsync().AsTask(token, progress); } catch (TaskCanceledException) { await downloadOperation.ResultFile.DeleteAsync(); downloadOperation = null; throw; } }
public static string MakeFullUrlForGetReq(string baseUrl, List <KeyValuePair <string, string> > paramList, bool withAuth) { StringBuilder sb = new StringBuilder(baseUrl); foreach (var item in paramList) { sb.Append(item.Key + "=" + item.Value + "&"); } if (withAuth) { sb.Append("&uid=" + LocalSettingHelper.GetValue("uid")); sb.Append("&access_token=" + LocalSettingHelper.GetValue("access_token")); } return(sb.ToString()); }
/// <summary> /// 初始化,还原列表等 /// 区分账户的各种状态:离线模式,没有网络,登录了有网络 /// </summary> /// <param name="args"></param> /// <returns></returns> private async Task HandleActive(LoginMode mode) { IsLoading = Visibility.Visible; await InitialCate(mode); //已经登陆过的了 if (mode != LoginMode.OfflineMode) { CurrentUser.Email = LocalSettingHelper.GetValue("email"); ShowLoginBtnVisibility = Visibility.Collapsed; ShowAccountInfoVisibility = Visibility.Visible; await RestoreData(); //没有网络 if (App.IsNoNetwork) { ToastService.SendToast(ResourcesHelper.GetResString("NoNetworkHint")); } //有网络 else { SelectedCate = 0; //从离线模式注册/登录的 if (mode == LoginMode.OfflineModeToLogin || mode == LoginMode.OfflineModeToRegister) { await AddAllOfflineToDos(); } await ReSendStagedToDos(); await SyncAllToDos(); CurrentDisplayToDos = AllToDos; } } //处于离线模式 else if (mode == LoginMode.OfflineMode) { ShowLoginBtnVisibility = Visibility.Visible; ShowAccountInfoVisibility = Visibility.Collapsed; await RestoreData(); } IsLoading = Visibility.Collapsed; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif var appView = ApplicationView.GetForCurrentView(); appView.SetPreferredMinSize(new Size(400, 700)); Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } Window.Current.Content = rootFrame; GlobalHelper.SetupLang(); if (LocalSettingHelper.HasValue("email")) { rootFrame.Navigate(typeof(MainPage), LoginMode.Login); } else if (LocalSettingHelper.GetValue("OfflineMode") == "true") { IsInOfflineMode = true; rootFrame.Navigate(typeof(MainPage), LoginMode.OfflineMode); } else { IsInOfflineMode = false; rootFrame.Navigate(typeof(StartPage)); } } Window.Current.Activate(); await UmengAnalytics.StartTrackAsync(UmengKey.UMENG_APP_KEY, "Marketplace"); }
public SettingPageViewModel() { ShowHint = Visibility.Collapsed; var lang = LocalSettingHelper.GetValue("AppLang"); if (lang.Contains("zh")) { CurrentLanguage = 1; } else { CurrentLanguage = 0; } InitialTileColors(); }
private void EnterBtn_Click(object sender, RoutedEventArgs e) { LocalSettingHelper.AddValue(App.Current.Resources["FeatureToken"] as string, "1"); if (LocalSettingHelper.HasValue("email")) { Frame.Navigate(typeof(MainPage), LoginMode.Login); } else if (LocalSettingHelper.GetValue("OfflineMode") == "true") { App.IsInOfflineMode = true; Frame.Navigate(typeof(MainPage), LoginMode.OfflineMode); } else { App.IsInOfflineMode = false; Frame.Navigate(typeof(StartPage)); } }
/// <summary> /// 完成待办事项 /// </summary> /// <param name="id">待办事项的ID</param> /// <returns></returns> private async Task CompleteTodo(string id) { try { var currentMemo = MyToDos.ElementAt(MyToDos.ToList().FindIndex(sch => { if (sch.ID == id) { return(true); } else { return(false); } })); currentMemo.IsDone = !currentMemo.IsDone; await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(MyToDos, "myschedules.sch", true); if (!App.isInOfflineMode) { var isDone = await PostHelper.FinishSchedule(id, currentMemo.IsDone? "1" : "0"); if (isDone) { await PostHelper.SetMyOrder(LocalSettingHelper.GetValue("sid"), ToDo.GetCurrentOrderString(MyToDos)); Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); } } else { Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); } } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); } }
public SettingPageViewModel() { ShowHint = Visibility.Collapsed; var lang = LocalSettingHelper.GetValue("AppLang"); if (lang.Contains("zh")) { CurrentLanguage = 1; } else { CurrentLanguage = 0; } EnableTile = LocalSettingHelper.GetValue("EnableTile") == "true" ? true : false; EnableBackgroundTask = LocalSettingHelper.GetValue("EnableBackgroundTask") == "true" ? true : false; EnableGesture = LocalSettingHelper.GetValue("EnableGesture") == "true" ? true : false; ShowKeyboard = LocalSettingHelper.GetValue("ShowKeyboard") == "true" ? true : false; IsAddToBottom = LocalSettingHelper.GetValue("AddMode") == "1" ? true : false; TransparentTile = LocalSettingHelper.GetValue("TransparentTile") == "true" ? true : false; }
/// <summary> /// 删除todo /// </summary> /// <param name="id">ID</param> /// <returns></returns> /// 先从列表删除,然后把列表内容都序列化保存,接着: /// 1.如果已经登陆的,尝试发送请求; /// 2.离线模式,不用管 private async Task DeleteToDo(string id) { try { var itemToDeleted = MyToDos.ToList().Find(s => { if (s.ID == id) { return(true); } else { return(false); } }); DeletedToDos.Add(itemToDeleted); await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(DeletedToDos, SerializerFileNames.DeletedFileName, true); MyToDos.Remove(itemToDeleted); UpdateDisplayList(SelectedCate); await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(MyToDos, SerializerFileNames.ToDoFileName, true); if (!App.isInOfflineMode) { var result = await PostHelper.DeleteSchedule(id); await PostHelper.SetMyOrder(LocalSettingHelper.GetValue("sid"), ToDo.GetCurrentOrderString(MyToDos)); } Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); } }
public LiveTileTemplate() { this.InitializeComponent(); Messenger.Default.Register <GenericMessage <ObservableCollection <ToDo> > >(this, MessengerTokens.UpdateTile, async schedules => { if (LocalSettingHelper.GetValue("EnableTile") == "false") { UpdateTileHelper.ClearAllSchedules(); return; } //if (LocalSettingHelper.GetValue("EnableBackgroundTask") == "true") //{ // UpdateNormalTile(schedules.Content); //} //else //{ // await UpdateCustomeTile(schedules.Content); //} await UpdateCustomeTile(schedules.Content); }); }
private async Task UpdateOrder() { var orderStr = ToDo.GetCurrentOrderString(MyToDos); await PostHelper.SetMyOrder(LocalSettingHelper.GetValue("sid"), orderStr); }
private async Task AddToDo() { //离线模式 if (App.isInOfflineMode || App.IsNoNetwork) { NewToDo.ID = Guid.NewGuid().ToString(); NewToDo.Category = this.SelectedCate; //0 for insert,1 for add if (LocalSettingHelper.GetValue("AddMode") == "0") { MyToDos.Insert(0, NewToDo); } else { MyToDos.Add(NewToDo); } await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(MyToDos, SerializerFileNames.ToDoFileName); Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); NewToDo = new ToDo(); IsLoading = Visibility.Collapsed; } else if (App.IsNoNetwork) { //TO DO: Store the schedule in SendingQueue } else { //在线模式 var result = await PostHelper.AddSchedule(LocalSettingHelper.GetValue("sid"), NewToDo.Content, "0", SelectedCate.ToString()); if (!string.IsNullOrEmpty(result)) { ToDo newSchedule = ToDo.ParseJsonTo(result); if (LocalSettingHelper.GetValue("AddMode") == "0") { MyToDos.Insert(0, newSchedule); UpdateDisplayList(SelectedCate); } else { MyToDos.Add(newSchedule); UpdateDisplayList(SelectedCate); } await PostHelper.SetMyOrder(LocalSettingHelper.GetValue("sid"), ToDo.GetCurrentOrderString(MyToDos)); NewToDo = new ToDo(); Messenger.Default.Send(new GenericMessage <ObservableCollection <ToDo> >(MyToDos), MessengerTokens.UpdateTile); IsLoading = Visibility.Collapsed; await SerializerHelper.SerializerToJson <ObservableCollection <ToDo> >(MyToDos, SerializerFileNames.ToDoFileName); } } }
public async static Task <bool> SetMyOrder(string sid, string order) { try { var param = new Dictionary <string, string>() { { "sid", sid }, { "order", order } }; HttpClient client = new HttpClient(); var messsage = await client.PostAsync(ScheduleSetOrderUri + "sid=" + LocalSettingHelper.GetValue("sid") + "&access_token=" + LocalSettingHelper.GetValue("access_token"), new FormUrlEncodedContent(param)); if (messsage.IsSuccessStatusCode) { var response = await messsage.Content.ReadAsStringAsync(); if (String.IsNullOrEmpty(response)) { return(false); } JObject job = JObject.Parse(response); if ((bool)job["isSuccessed"]) { return(true); } else { return(false); } } else { return(false); } } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); return(false); } }
public async static Task <string> GetMyOrder(string sid) { try { var param = new Dictionary <string, string>() { { "sid", sid } }; HttpClient client = new HttpClient(); var messsage = await client.PostAsync(ScheduleGetOrderUri + "sid=" + LocalSettingHelper.GetValue("sid") + "&access_token=" + LocalSettingHelper.GetValue("access_token"), new FormUrlEncodedContent(param)); if (messsage.IsSuccessStatusCode) { var response = await messsage.Content.ReadAsStringAsync(); if (String.IsNullOrEmpty(response)) { return(null); } JObject job = JObject.Parse(response); if ((bool)job["isSuccessed"]) { var orderString = (string)(((job["OrderList"] as JArray).First)["list_order"]); if (orderString != null) { return(orderString); } else { return(null); } } else { return(null); } } else { return(null); } } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); return(null); } }
/// <summary> /// 添加日程 /// </summary> /// <param name="sid">用户ID</param> /// <param name="content">内容</param> /// <param name="isdone">是否完成 0未完成 1完成</param> /// <returns>返回JSON数据</returns> public async static Task <string> AddSchedule(string sid, string content, string isdone, string cate) { try { var param = new Dictionary <string, string>() { { "sid", sid }, { "time", DateTime.Now.ToString() }, { "content", content }, { "isdone", isdone }, { "cate", cate } }; HttpClient client = new HttpClient(); var messsage = await client.PostAsync(ScheduleAddUri + "sid=" + LocalSettingHelper.GetValue("sid") + "&access_token=" + LocalSettingHelper.GetValue("access_token"), new FormUrlEncodedContent(param)); if (messsage.IsSuccessStatusCode) { var response = await messsage.Content.ReadAsStringAsync(); if (String.IsNullOrEmpty(response)) { return(null); } JObject job = JObject.Parse(response); if ((bool)job["isSuccessed"]) { return(response); } else { return(null); } } else { return(null); } } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); return(null); } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } Window.Current.Content = rootFrame; ConfigHelper.CheckConfig(); if (LocalSettingHelper.HasValue("AppLang") == false) { var lang = Windows.System.UserProfile.GlobalizationPreferences.Languages[0]; if (lang.Contains("zh")) { ApplicationLanguages.PrimaryLanguageOverride = "zh-CN"; } else { ApplicationLanguages.PrimaryLanguageOverride = "en-US"; } LocalSettingHelper.AddValue("AppLang", ApplicationLanguages.PrimaryLanguageOverride); } else { ApplicationLanguages.PrimaryLanguageOverride = LocalSettingHelper.GetValue("AppLang"); } if (LocalSettingHelper.HasValue("email")) { rootFrame.Navigate(typeof(MainPage), LoginMode.Login); } else if (LocalSettingHelper.GetValue("OfflineMode") == "true") { App.isInOfflineMode = true; rootFrame.Navigate(typeof(MainPage), LoginMode.OfflineMode); } else { App.isInOfflineMode = false; rootFrame.Navigate(typeof(StartPage)); } } // Ensure the current window is active Window.Current.Activate(); }
public async Task UpdateCustomeTile(ObservableCollection <ToDo> schedules) { try { if (LocalSettingHelper.GetValue("EnableTile") == "false") { UpdateTileHelper.ClearAllSchedules(); return; } CleanUpTileTemplate(); if (LocalSettingHelper.GetValue("TransparentTile") == "true") { backgrd1.Background = backgrd2.Background = backgrd3.Background = new SolidColorBrush(Colors.Transparent); } List <string> undoList = new List <string>(); foreach (var sche in schedules) { if (!sche.IsDone) { undoList.Add(sche.Content); } } Text0.Text = Text00.Text = undoList.ElementAtOrDefault(0) ?? ""; Text1.Text = Text01.Text = undoList.ElementAtOrDefault(1) ?? ""; Text2.Text = Text02.Text = undoList.ElementAtOrDefault(2) ?? ""; Text3.Text = Text03.Text = undoList.ElementAtOrDefault(3) ?? ""; Count1.Text = Count2.Text = Count3.Text = undoList.Count.ToString(); if (undoList.Count == 0) { Text0.Text = Text00.Text = "Enjoy your day ;-)"; } UpdateTileHelper.ClearAllSchedules(); if (undoList.Count <= 4) { await UpdateTileHelper.UpdatePersonalTile(WideGrid, MediumGrid, SmallGrid, false); } else { await UpdateTileHelper.UpdatePersonalTile(WideGrid, MediumGrid, SmallGrid, true); if (undoList.Count > 4) { Text0.Text = Text00.Text = undoList.ElementAtOrDefault(4) ?? ""; Text1.Text = Text01.Text = undoList.ElementAtOrDefault(5) ?? ""; Text2.Text = Text02.Text = undoList.ElementAtOrDefault(6) ?? ""; Text3.Text = Text03.Text = undoList.ElementAtOrDefault(7) ?? ""; await UpdateTileHelper.UpdatePersonalTile(WideGrid, MediumGrid, SmallGrid, true); } if (undoList.Count > 8) { Text0.Text = Text00.Text = undoList.ElementAtOrDefault(8) ?? ""; Text1.Text = Text01.Text = undoList.ElementAtOrDefault(9) ?? ""; Text2.Text = Text02.Text = undoList.ElementAtOrDefault(10) ?? ""; Text3.Text = Text03.Text = undoList.ElementAtOrDefault(11) ?? ""; await UpdateTileHelper.UpdatePersonalTile(WideGrid, MediumGrid, SmallGrid, true); } } } catch (Exception e) { var task = ExceptionHelper.WriteRecord(e); } }
/// <summary> /// 上传图片 /// </summary> /// <param name="fileData">包含图片信息的对象</param> /// <param name="imgKind">照片类型</param> /// <returns></returns> public async static Task <CommonRespMsg> UploadImageAsnyc(ButterFileToUpload fileData, UploadImageKind imgKind, CancellationToken ctoken) { var kindstr = "1:1"; if (fileData.ScaleKind == ScaleKind.Scale_3x4) { kindstr = "3:4"; } else if (fileData.ScaleKind == ScaleKind.Scale_4x3) { kindstr = "4:3"; } CommonRespMsg result = new CommonRespMsg(); try { using (var client = new HttpClient()) { Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("uid", LocalSettingHelper.GetValue("uid")); dic.Add("access_token", LocalSettingHelper.GetValue("access_token")); dic.Add("appkey", UrlHelper.APP_KEY); dic.Add("img_info", "{\"scale\":\"" + kindstr + "\"}"); dic.Add("ps", fileData.PsData); dic.Add("is_private", fileData.IsPrivate ? "1" : "0"); if (fileData.ActivityID != null) { dic.Add("activity_id", fileData.ActivityID); } if (fileData.OriginalImageID != -1) { dic.Add("ding_imgid", fileData.OriginalImageID.ToString()); } var resp = await client.PostAsync(new Uri(imgKind == UploadImageKind.Photo?UrlHelper.UploadImageUrl:UrlHelper.UploadAvatarUrl), new HttpFormUrlEncodedContent(dic)); var json = JsonObject.Parse(await resp.Content.ReadAsStringAsync()); var token = JsonParser.GetStringFromJsonObj(json, "token"); var key = JsonParser.GetStringFromJsonObj(json, "key"); Settings setting = new Settings(); ResumablePutExtra extra = new ResumablePutExtra(); ResumablePut rclient = new ResumablePut(setting, extra); extra.Notify += ((sendern, en) => { }); ctoken.ThrowIfCancellationRequested(); var ioresult = await Task.Run(async() => { ctoken.ThrowIfCancellationRequested(); return(await rclient.PutFile(token, fileData.File.Path, key, ctoken)); }); if (!ioresult.OK) { throw new APIException(int.Parse(ioresult.StatusCode.ToString()), ioresult.Exception.Message); } else { return(result); } } } catch (APIException) { result.IsSuccessful = false; return(result); } catch (OperationCanceledException) { throw; } catch (Exception ee) { var task = ExceptionHelper.WriteRecord(ee, nameof(CloudServices), nameof(UploadImageAsnyc)); var resultMsg = new CommonRespMsg() { IsSuccessful = false, ErrorMsg = ee.Message }; return(resultMsg); } }