private async void romList_SelectionChanged_1(object sender, SelectionChangedEventArgs e) { ROMDBEntry entry = this.romList.SelectedItem as ROMDBEntry; if (entry == null) { return; } if (this.uploading) { MessageBox.Show(AppResources.BackupWaitForUpload, AppResources.ErrorCaption, MessageBoxButton.OK); this.romList.SelectedItem = null; return; } var indicator = new ProgressIndicator() { IsIndeterminate = true, IsVisible = true, Text = String.Format(AppResources.BackupUploadProgressText, entry.DisplayName) }; SystemTray.SetProgressIndicator(this, indicator); this.uploading = true; try { LiveConnectClient client = new LiveConnectClient(this.session); String folderID = await this.CreateExportFolder(client); IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication(); bool errors = false; foreach (var savestate in entry.Savestates) { String path = FileHandler.ROM_DIRECTORY + "/" + FileHandler.SAVE_DIRECTORY + "/" + savestate.FileName; try { using (IsolatedStorageFileStream fs = iso.OpenFile(path, System.IO.FileMode.Open)) { await client.UploadAsync(folderID, savestate.FileName, fs, OverwriteOption.Overwrite); } } catch (FileNotFoundException) { errors = true; } catch (LiveConnectException ex) { MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK); errors = true; } } String sramName = entry.FileName.Substring(0, entry.FileName.Length - 3) + "srm"; String sramPath = FileHandler.ROM_DIRECTORY + "/" + FileHandler.SAVE_DIRECTORY + "/" + sramName; try { if (iso.FileExists(sramPath)) { using (IsolatedStorageFileStream fs = iso.OpenFile(sramPath, FileMode.Open)) { await client.UploadAsync(folderID, sramName, fs, OverwriteOption.Overwrite); } } } catch (Exception) { errors = true; } if (errors) { MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK); } else { MessageBox.Show(AppResources.BackupUploadSuccessful); } } catch (NullReferenceException) { MessageBox.Show(AppResources.CreateBackupFolderError, AppResources.ErrorCaption, MessageBoxButton.OK); } catch (LiveConnectException) { MessageBox.Show(AppResources.SkyDriveInternetLost, AppResources.ErrorCaption, MessageBoxButton.OK); } finally { SystemTray.GetProgressIndicator(this).IsVisible = false; this.uploading = false; } }
private void HideProgressBar() { SystemTray.SetProgressIndicator(this, new ProgressIndicator { IsVisible = false, }); }
protected override void OnDoWork(DoWorkEventArgs e) { _log.Info("Automated processing worker started."); while (true) { _log.Info("Checking Master Request Queue for requests requiring automated processing."); SystemTray.UpdateNotificationIcon(IconType.IconBusy, "Processing Requests"); var reqs = from ns in Configuration.Instance.NetworkSettingCollection.NetWorkSettings.Cast <NetWorkSetting>().ToObservable() where ns.NetworkStatus == Util.ConnectionOKStatus let dmIds = ns.DataMartList // BMS: Note the ProcessAndNotUpload feature has been temporarilty disabled until we fix the processing around this feature .Where(dm => dm.AllowUnattendedOperation && (dm.NotifyOfNewQueries || /* dm.ProcessQueriesAndNotUpload || */ dm.ProcessQueriesAndUploadAutomatically)) .Select(dm => dm.DataMartId) .ToArray() where dmIds.Any() from list in DnsServiceManager.GetRequestList(ns, 0, Properties.Settings.Default.AutoProcessingBatchSize, new RequestFilter { Statuses = new [] { Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.Submitted }, DataMartIds = dmIds }, null, null) from rl in list.Segment.EmptyIfNull().ToObservable() where rl.AllowUnattendedProcessing from r in RequestCache.ForNetwork(ns).LoadRequest(rl.ID, rl.DataMartID) select new { Request = r, NetworkSetting = ns }; reqs .Do(r => { var request = r.Request; var datamartDescription = Configuration.Instance.GetDataMartDescription(request.NetworkId, request.DataMartId); var modelDescription = Configuration.Instance.GetModelDescription(request.NetworkId, request.DataMartId, request.Source.ModelID); var packageIdentifier = new Lpp.Dns.DTO.DataMartClient.RequestTypeIdentifier { Identifier = request.Source.RequestTypePackageIdentifier, Version = request.Source.AdapterPackageVersion }; if (!System.IO.File.Exists(System.IO.Path.Combine(Configuration.PackagesFolderPath, packageIdentifier.PackageName()))) { DnsServiceManager.DownloadPackage(r.NetworkSetting, packageIdentifier); } using (var domainManager = new DomainManger.DomainManager(Configuration.PackagesFolderPath)) { domainManager.Load(request.Source.RequestTypePackageIdentifier, request.Source.AdapterPackageVersion); IModelProcessor processor = domainManager.GetProcessor(modelDescription.ProcessorId); ProcessorManager.UpdateProcessorSettings(modelDescription, processor); if (processor is IEarlyInitializeModelProcessor) { ((IEarlyInitializeModelProcessor)processor).Initialize(modelDescription.ModelId, request.Documents.Select(d => new DocumentWithStream(d.ID, new Document(d.ID, d.Document.MimeType, d.Document.Name, d.Document.IsViewable, Convert.ToInt32(d.Document.Size), d.Document.Kind), new DocumentChunkStream(d.ID, r.NetworkSetting))).ToArray()); } if (processor != null && processor.ModelMetadata != null && processor.ModelMetadata.Capabilities != null && processor.ModelMetadata.Capabilities.ContainsKey("CanRunAndUpload") && !(bool)processor.ModelMetadata.Capabilities["CanRunAndUpload"]) { //can't be run, don't attempt autoprocessing return; } request.Processor = processor; if (request.RoutingStatus == Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.Submitted) { if (processor != null) { SystemTray.generate_notification(request, request.NetworkId); if (datamartDescription.NotifyOfNewQueries) { SystemTray.UpdateNotificationIcon(IconType.IconBusy, string.Format("Query Submitted by {0}", request.Source.Author.Username)); } else { processor.SetRequestProperties(request.Source.ID.ToString(), request.Properties); ProcessRequest(request); var statusCode = request.Processor.Status(request.Source.ID.ToString()).Code; if (datamartDescription.ProcessQueriesAndUploadAutomatically && (statusCode == RequestStatus.StatusCode.Complete || statusCode == RequestStatus.StatusCode.CompleteWithMessage)) { // Post process requests that are automatically uploaded processor.PostProcess(request.Source.ID.ToString()); // Increment counter _queriesProcessedCount++; SystemTray.update_notify_text(_queriesProcessedCount, request.DataMartName, request.NetworkId); UploadRequest(request); } } } } else if (request.RoutingStatus == Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.AwaitingResponseApproval) { if (datamartDescription.ProcessQueriesAndUploadAutomatically) { // Increment counter _queriesProcessedCount++; SystemTray.update_notify_text(_queriesProcessedCount, request.DataMartName, request.NetworkId); UploadRequest(request); } } } }) .LogExceptions(_log.Error) .Catch() .LastOrDefault(); SystemTray.UpdateNotificationIcon(IconType.IconDefault, null); Thread.Sleep(DMClient.Properties.Settings.Default.RefreshRate); } }
private void StartProcessingRequest(HubRequest request, IModelProcessor processor, DataMartDescription datamartDescription, DomainManger.DomainManager domainManager, Lib.Caching.DocumentCacheManager cache) { Action process = () => { processor.SetRequestProperties(request.Source.ID.ToString(), request.Properties); ProcessRequest(request); }; Action <Task> continuation = (completed) => { HubRequestStatus hubRequestStatus = null; var statusCode = request.Processor.Status(request.Source.ID.ToString()).Code; if (cache.Enabled) { Document[] responseDocuments = processor.Response(request.Source.ID.ToString()); cache.Add(responseDocuments.Select(doc => { System.IO.Stream data; processor.ResponseDocument(request.Source.ID.ToString(), doc.DocumentID, out data, doc.Size); Guid documentID; if (!Guid.TryParse(doc.DocumentID, out documentID)) { documentID = Utilities.DatabaseEx.NewGuid(); doc.DocumentID = documentID.ToString(); } return(new DocumentWithStream(documentID, doc, data)); })); } if (datamartDescription.ProcessQueriesAndNotUpload && (statusCode == RequestStatus.StatusCode.Complete || statusCode == RequestStatus.StatusCode.CompleteWithMessage)) { RequestStatuses.TryAdd(MakeKey(request), ProcessingStatus.PendingUpload); } else if (datamartDescription.ProcessQueriesAndUploadAutomatically && (statusCode == RequestStatus.StatusCode.Complete || statusCode == RequestStatus.StatusCode.CompleteWithMessage)) { // Post process requests that are automatically uploaded processor.PostProcess(request.Source.ID.ToString()); if (cache.Enabled) { cache.ClearCache(); Document[] responseDocuments = processor.Response(request.Source.ID.ToString()); cache.Add(responseDocuments.Select(doc => { System.IO.Stream data; processor.ResponseDocument(request.Source.ID.ToString(), doc.DocumentID, out data, doc.Size); Guid documentID; if (!Guid.TryParse(doc.DocumentID, out documentID)) { documentID = Utilities.DatabaseEx.NewGuid(); doc.DocumentID = documentID.ToString(); } return(new DocumentWithStream(documentID, doc, data)); })); } // Increment counter System.Threading.Interlocked.Increment(ref _queriesProcessedCount); statusCode = request.Processor.Status(request.Source.ID.ToString()).Code; if (statusCode == RequestStatus.StatusCode.Error) { hubRequestStatus = DnsServiceManager.ConvertModelRequestStatus(request.Processor.Status(request.Source.ID.ToString())); hubRequestStatus.Message = request.Processor.Status(request.Source.ID.ToString()).Message; } else if (statusCode == RequestStatus.StatusCode.Complete || statusCode == RequestStatus.StatusCode.CompleteWithMessage) { SystemTray.UpdateNotifyText(_queriesProcessedCount, request.DataMartName, request.NetworkId); try { UploadRequest(request, cache); statusCode = request.Processor.Status(request.Source.ID.ToString()).Code; hubRequestStatus = DnsServiceManager.ConvertModelRequestStatus(request.Processor.Status(request.Source.ID.ToString())); hubRequestStatus.Message = request.Processor.Status(request.Source.ID.ToString()).Message; } catch (Exception ex) { string message = string.Format("An error occurred while attempting unattended processing of the following query {0} (ID: {1}, DataMart: {2}, Network: {3})", request.Source.Identifier, request.Source.ID, request.DataMartName, request.NetworkName); Log.Error(message, ex); hubRequestStatus = new HubRequestStatus(Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.Failed, message); } } else { statusCode = request.Processor.Status(request.Source.ID.ToString()).Code; hubRequestStatus = DnsServiceManager.ConvertModelRequestStatus(request.Processor.Status(request.Source.ID.ToString())); hubRequestStatus.Message = request.Processor.Status(request.Source.ID.ToString()).Message; } DnsServiceManager.SetRequestStatus(request, hubRequestStatus, request.Properties, _networkSetting); Log.Info(string.Format("BackgroundProcess: Finished Processing / Uploading results for query {0} (RequestID: {3}, DataMart: {1}, Network: {2})", request.Source.Identifier, request.DataMartName, request.NetworkName, request.Source.ID)); if (statusCode == RequestStatus.StatusCode.Error || statusCode == RequestStatus.StatusCode.Complete || statusCode == RequestStatus.StatusCode.CompleteWithMessage || statusCode == RequestStatus.StatusCode.AwaitingResponseApproval) { //mark auto-processing complete in the status cache if the processing resulted in either an error or a completed status var key = MakeKey(request); if (RequestStatuses.ContainsKey(key)) { RequestStatuses[key] = ProcessingStatus.Complete; } } } }; RunTask(MakeKey(request), domainManager, process, continuation); }
void client_RequestCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { string json = e.Result; //Парсим и разбираем наш результат JObject jRes = JObject.Parse(json); //string access_token; //int expires_in; //int user_id; try { MyUserData.access_token = (string)jRes["access_token"]; MyUserData.user_id = (int)jRes["user_id"]; //access_token = (string)jRes["access_token"]; //expires_in = (int)jRes["expires_in"];//0, возможно не стоит собирать? //user_id = (int)jRes["user_id"]; //УСПЕХ! //Cохраняем данные в IsolateStorage, выводим тестовую инфу, завершаем прогрес бар, и переходим на диалоги settings["user_id"] = MyUserData.user_id; settings["access_token"] = MyUserData.access_token; #if SHOWDEBUGINFO MessageBox.Show("access_token = " + MyUserData.access_token + " user_id=" + MyUserData.user_id + "settings:" + (string)settings["access_token"]); #endif prog.IsVisible = false; prog.IsIndeterminate = false; //prog.Text = "Подождите..."; SystemTray.SetProgressIndicator(this, prog); NavigationService.Navigate(new Uri("/Pages/Conversation.xaml", UriKind.Relative)); } catch (Exception) {//Разбираем дальше. Смотрим есть ли капча string error; string captcha_sid; string captcha_img; try { error = (string)jRes["error"]; captcha_sid = (string)jRes["captcha_sid"]; captcha_img = (string)jRes["captcha_img"]; //Если понадобится капча //передаем данные о капче в окно, для составления повторного запроса //1.Построить интерфейс(для панорамы и стандартного) //2.Передать параметры в картинку и тп(сделать кнопки видимыми) //3.Сделать еще 1 кнопку для повторного отправления запроса(или эту перегрузить) //4.Оформить в ней новый запрос с данными } catch (Exception Error2) {//нет ни данных об успешной авторизации, ни данных о капче(ошибках) MessageBox.Show(Error2.Message); } } } else { MessageBox.Show("Error: " + e.Error); } }
public ConvSend() { InitializeComponent(); SystemTray.SetProgressIndicator(this, progress); }
public void CleanupAndExit() { SystemTray.Dispose(); Application.Exit(); Environment.Exit(0); }
public BikeStopPage() { InitializeComponent(); SystemTray.SetProgressIndicator(this, progressIndicator); }
private void btnSave_Click(System.Object sender, System.Windows.RoutedEventArgs e) { if (string.IsNullOrEmpty(this.txtUsername.Text)) { MessageBox.Show("Please input (Username)"); return; } if (string.IsNullOrEmpty(this.txtPassword.Password.ToString())) { MessageBox.Show("Please input (Password)"); return; } if (string.IsNullOrEmpty(this.txtConPassword.Password.ToString())) { MessageBox.Show("Please input (Confirm Username)"); return; } if (this.txtPassword.Password.ToString() != this.txtConPassword.Password.ToString()) { MessageBox.Show("Password Not Match!"); return; } if (string.IsNullOrEmpty(this.txtName.Text)) { MessageBox.Show("Please input (Name)"); return; } if (string.IsNullOrEmpty(this.txtTel.Text)) { MessageBox.Show("Please input (Tel)"); return; } if (string.IsNullOrEmpty(this.txtEmail.Text)) { MessageBox.Show("Please input (Email)"); return; } string url = "http://roboviper.besaba.com/imaginecup/json/saveData.php"; Uri uri = new Uri(url, UriKind.Absolute); StringBuilder postData = new StringBuilder(); postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtUsername.Text)); postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString())); postData.AppendFormat("&{0}={1}", "sName", HttpUtility.UrlEncode(this.txtName.Text)); postData.AppendFormat("&{0}={1}", "sTel", HttpUtility.UrlEncode(this.txtTel.Text)); postData.AppendFormat("&{0}={1}", "sEmail", HttpUtility.UrlEncode(this.txtEmail.Text)); WebClient client = default(WebClient); client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString(); client.UploadStringCompleted += client_UploadStringCompleted; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadStringAsync(uri, "POST", postData.ToString()); prog = new ProgressIndicator(); prog.IsIndeterminate = true; prog.IsVisible = true; prog.Text = "Loading...."; SystemTray.SetProgressIndicator(this, prog); }
private void CurrentViewModel_LongLoadingStopEvent(object sender, SimpleMvvmToolkit.NotificationEventArgs e) { SystemTray.SetProgressIndicator(this, null); SystemTray.SetIsVisible(this, systemTrayVisibleBck); }
void DetailsView_Loaded(object sender, RoutedEventArgs e) { string itemURL = ""; string randURI = ""; string title = ""; pi.IsIndeterminate = true; pi.IsVisible = true; SystemTray.SetProgressIndicator(this, pi); if (NavigationContext.QueryString.TryGetValue("title", out title)) { var story = StoryRepository.GetSingleStoryByTitle(title); if (story != null && !story.Details.Contains("[...")) { value = new PostRoot(); value.post = new Post(); value.post.title = story.Title; value.post.url = story.Link; ContentWebBrowser.NavigateToString(InjectedString(story.Details)); pi.IsVisible = false; var caption = story.Title.Split(new char[] { '.', '!', '?' }); tbCaption.Text = caption[0]; // Need some smarter trim here, for O.Henry for example if (caption.Length > 1) { tbCaptionAuthor.Text = value.post.title.Replace(caption[0], "").Trim(new char[] { '.', '!', '?' }); } return; } } wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_OpenReadCompleted); if (NavigationContext.QueryString.TryGetValue("item", out itemURL)) { itemURL = HttpUtility.UrlDecode(itemURL); try { wc.DownloadStringAsync(new Uri(itemURL + "?json=1")); } catch (Exception exception) { BugSenseHandler.Instance.LogError(exception); pi.IsVisible = false; } } if (NavigationContext.QueryString.TryGetValue("randURI", out randURI)) { try { string tURL = HttpUtility.UrlDecode(randURI); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(HttpUtility.UrlDecode(randURI))); request.Method = "HEAD"; request.AllowReadStreamBuffering = false; // Start the asynchronous request. request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } catch (Exception exception) { BugSenseHandler.Instance.LogError(exception); pi.IsVisible = false; } } }
private async void ApplicationBarActionButton_Click(object sender, EventArgs e) { PagePivot.Focus(); PendingOverlay.Visibility = Visibility.Visible; ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false; ApplicationBar.IsMenuEnabled = false; var progress = new ProgressIndicator { IsVisible = true, IsIndeterminate = true }; switch (_pivotState) { case State.Login: progress.Text = "Logging into Snapchat securely..."; SystemTray.SetProgressIndicator(this, progress); Tuple <TempEnumHolder.LoginStatus, Account> repsonse = await Functions.Login(TextUsername.Text, TextPassword.Password); switch (repsonse.Item1) { case TempEnumHolder.LoginStatus.InvalidCredentials: MessageBox.Show("Your username/password is incorrect.", "Invalid Credentials", MessageBoxButton.OK); break; case TempEnumHolder.LoginStatus.ServerError: MessageBox.Show("Unable to connect to server. Check your Internet Connection.", "Oops", MessageBoxButton.OK); break; case TempEnumHolder.LoginStatus.Success: // Tell User we be syncing progress.Text = "Syncing with Snapchat securely..."; SystemTray.SetProgressIndicator(this, progress); // Sync Other Shit Dictionary <string, Best> bests = await Functions.GetBests(repsonse.Item2.Friends, repsonse.Item2.UserName, repsonse.Item2.AuthToken); if (bests != null) { App.IsolatedStorage.UserAccount = repsonse.Item2; App.IsolatedStorage.FriendsBests = bests; // Navigate to Capture Page NavigationService.Navigate( Navigation.GenerateNavigateUri(Navigation.NavigationTarget.Capture)); } else { MessageBox.Show( "Unable to sync with Snapchat's servers. Check your internet connection and try logging in again.", "Syncing Error", MessageBoxButton.OK); } break; } break; case State.Register: progress.Text = "Registering your account with Snapchat securely..."; SystemTray.SetProgressIndicator(this, progress); MessageBox.Show("Haven't coded this yet", "nope.", MessageBoxButton.OK); break; } PendingOverlay.Visibility = Visibility.Collapsed; progress = new ProgressIndicator { IsVisible = false }; SystemTray.SetProgressIndicator(this, progress); ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true; ApplicationBar.IsMenuEnabled = true; }
/// <summary> /// Constructor. /// </summary> public MixesPage() { InitializeComponent(); DataContext = App.ViewModel; SystemTray.SetOpacity(this, 0.01); }
public ForumPost() { InitializeComponent(); SystemTray.SetProgressIndicator(this, progress); }
private async void Export_Click(object sender, EventArgs e) { if (fileList.CheckedItems.Count == 0) { MessageBox.Show(AppResources.ExportNoSelection); return; } //can only export 1 file if use cloudsix if (backupMedium == "cloudsix" && fileList.CheckedItems.Count > 1 && ZipCheckBox.IsChecked.Value == false) { MessageBox.Show(AppResources.CloudSixOneFileLimitText); return; } if (this.uploading) { MessageBox.Show(AppResources.BackupWaitForUpload, AppResources.ErrorCaption, MessageBoxButton.OK); return; } //zip file if users choose to do so if (ZipCheckBox.IsChecked.Value) { using (ZipFile zip = new ZipFile()) { using (var iso = IsolatedStorageFile.GetUserStoreForApplication()) { foreach (ExportFileItem file in fileList.CheckedItems) { IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open); zip.AddEntry(file.Name, fs); } MemoryStream stream = new MemoryStream(); zip.Save(stream); if (backupMedium == "cloudsix") { var saver = new CloudSixSaver(currentEntry.DisplayName + ".zip", stream); await saver.Launch(); } else if (backupMedium == "onedrive") { var indicator = SystemTray.GetProgressIndicator(this); indicator.IsIndeterminate = true; this.uploading = true; bool errors = false; try { LiveConnectClient client = new LiveConnectClient(this.session); String folderID = await CreateExportFolder(client); indicator.Text = String.Format(AppResources.UploadProgressText, currentEntry.DisplayName + ".zip"); stream.Seek(0, SeekOrigin.Begin); await client.UploadAsync(folderID, currentEntry.DisplayName + ".zip", stream, OverwriteOption.Overwrite); } catch (Exception ex) { MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK); errors = true; } this.uploading = false; if (errors) { MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK); } else { MessageBox.Show(AppResources.BackupUploadSuccessful); } #if GBC indicator.Text = AppResources.ApplicationTitle2; #else indicator.Text = AppResources.ApplicationTitle; #endif indicator.IsIndeterminate = false; } //end of if (backupMedium == "onedrive") stream.Close(); } } } else //does not use zip function { using (var iso = IsolatedStorageFile.GetUserStoreForApplication()) { if (backupMedium == "cloudsix") { ExportFileItem file = this.fileList.CheckedItems[0] as ExportFileItem; using (IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open)) { var saver = new CloudSixSaver(file.Name, fs); await saver.Launch(); } } else if (backupMedium == "onedrive") { var indicator = SystemTray.GetProgressIndicator(this); indicator.IsIndeterminate = true; this.uploading = true; bool errors = false; try { LiveConnectClient client = new LiveConnectClient(this.session); String folderID = await CreateExportFolder(client); foreach (ExportFileItem file in this.fileList.CheckedItems) { indicator.Text = String.Format(AppResources.UploadProgressText, file.Name); using (IsolatedStorageFileStream fs = iso.OpenFile(file.Path, System.IO.FileMode.Open)) { await client.UploadAsync(folderID, file.Name, fs, OverwriteOption.Overwrite); } } } catch (Exception ex) { MessageBox.Show(String.Format(AppResources.BackupErrorUpload, ex.Message), AppResources.ErrorCaption, MessageBoxButton.OK); errors = true; } this.uploading = false; if (errors) { MessageBox.Show(AppResources.BackupUploadUnsuccessful, AppResources.ErrorCaption, MessageBoxButton.OK); } else { MessageBox.Show(AppResources.BackupUploadSuccessful); } #if GBC indicator.Text = AppResources.ApplicationTitle2; #else indicator.Text = AppResources.ApplicationTitle; #endif indicator.IsIndeterminate = false; } } //IsolatedStorage } //using zip upload or not }
internal static async Task ImportSaveBySharedID(string fileID, string actualName, DependencyObject page) { //note: the file name obtained from fileID can be different from actualName if the file is obtained through cloudsix ROMDatabase db = ROMDatabase.Current; //check to make sure there is a rom with matching name ROMDBEntry entry = null; string extension = Path.GetExtension(actualName).ToLower(); if (extension == ".sgm") { entry = db.GetROMFromSavestateName(actualName); } else if (extension == ".sav") { entry = db.GetROMFromSRAMName(actualName); } if (entry == null) //no matching file name { MessageBox.Show(AppResources.NoMatchingNameText, AppResources.ErrorCaption, MessageBoxButton.OK); return; } //check to make sure format is right if (extension == ".sgm") { string slot = actualName.Substring(actualName.Length - 5, 1); int parsedSlot = 0; if (!int.TryParse(slot, out parsedSlot)) { MessageBox.Show(AppResources.ImportSavestateInvalidFormat, AppResources.ErrorCaption, MessageBoxButton.OK); return; } } //set status bar var indicator = SystemTray.GetProgressIndicator(page); indicator.IsIndeterminate = true; indicator.Text = String.Format(AppResources.ImportingProgressText, actualName); StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder romFolder = await localFolder.CreateFolderAsync(ROM_DIRECTORY, CreationCollisionOption.OpenIfExists); StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists); //if arrive here, entry cannot be null, we can copy the file IStorageFile file = null; if (extension == ".sgm") { file = await SharedStorageAccessManager.CopySharedFileAsync(saveFolder, Path.GetFileNameWithoutExtension(entry.FileName) + actualName.Substring(actualName.Length - 5), NameCollisionOption.ReplaceExisting, fileID); } else if (extension == ".sav") { file = await SharedStorageAccessManager.CopySharedFileAsync(saveFolder, Path.GetFileNameWithoutExtension(entry.FileName) + ".sav", NameCollisionOption.ReplaceExisting, fileID); entry.SuspendAutoLoadLastState = true; } //update database if (extension == ".sgm") { String number = actualName.Substring(actualName.Length - 5, 1); int slot = int.Parse(number); if (entry != null) //NULL = do nothing { SavestateEntry saveentry = db.SavestateEntryExisting(entry.FileName, slot); if (saveentry != null) { //delete entry db.RemoveSavestateFromDB(saveentry); } SavestateEntry ssEntry = new SavestateEntry() { ROM = entry, Savetime = DateTime.Now, Slot = slot, FileName = actualName }; db.Add(ssEntry); db.CommitChanges(); } } #if GBC indicator.Text = AppResources.ApplicationTitle2; #else indicator.Text = AppResources.ApplicationTitle; #endif indicator.IsIndeterminate = false; MessageBox.Show(String.Format(AppResources.ImportCompleteText, entry.DisplayName)); return; }
private ProgressIndicator GetIndicator() { return(SystemTray.GetProgressIndicator(page) ?? new ProgressIndicator()); }
// Constructor public MainPage() { InitializeComponent(); #region trial Check if (App.IsTrial == true) { // enable ads adControl.Visibility = System.Windows.Visibility.Visible; //adControl.IsAutoRefreshEnabled = true; adControl.IsEnabled = true; adControl.IsAutoCollapseEnabled = false; } else { // disables ads adControl.Visibility = System.Windows.Visibility.Collapsed; //adControl.IsAutoRefreshEnabled = false; adControl.IsEnabled = false; adControl.IsAutoCollapseEnabled = false; } #endregion OrientationChanged += new EventHandler <OrientationChangedEventArgs>(MainPage_OrientationChanged); // initially check PageOrientation po = this.Orientation; if (po == PageOrientation.Portrait || po == PageOrientation.PortraitDown || po == PageOrientation.PortraitUp) { // return pivot to original position MapHeight = 800; MainPivot.Margin = new Thickness(0, 125, 0, 0); AllPivot.Header = "all"; FreewayPivot.Header = "highways"; RoadPivot.Header = "roads"; // this.ApplicationBar.IsVisible = this.ApplicationBar.IsVisible; } else if (po == PageOrientation.Landscape || po == PageOrientation.LandscapeLeft || po == PageOrientation.LandscapeRight) { // hiding pivot header in landscape mode MapHeight = 480; MainPivot.Margin = new Thickness(0, 30, 0, 0); AllPivot.Header = ""; FreewayPivot.Header = ""; RoadPivot.Header = ""; // this.ApplicationBar.IsVisible = !this.ApplicationBar.IsVisible; } isolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings; // disable lock screen timer Microsoft.Phone.Shell.PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; // References: // http://weblogs.asp.net/scottgu/archive/2010/03/18/building-a-windows-phone-7-twitter-application-using-silverlight.aspx // http://msdn.microsoft.com/en-us/library/hh441726.aspx // http://json.codeplex.com // Bing Maps REST Services API Reference: http://msdn.microsoft.com/en-us/library/ff701722.aspx // Adding Tile Layers (overlays) http://msdn.microsoft.com/en-us/library/ee681902.aspx wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(REST_traffic); //wc.DownloadStringAsync(new Uri("http://dev.virtualearth.net/REST/v1/Traffic/Incidents/37,-105,45,-94?key=" + Id)); // caching Current_Location.CacheMode = new BitmapCache(); mMap.ZoomLevel = 10; //mMap.ZoomBarVisibility = System.Windows.Visibility.Visible; Current_Location.Style = (Style)(Application.Current.Resources["PushpinStyle"]); Current_Location.PositionOrigin = PositionOrigin.Center; MyPreviousLocation.X = 0; MyPreviousLocation.Y = 0; #region Progress Indicator SystemTray.SetIsVisible(this, true); SystemTray.SetOpacity(this, 0.5); SystemTray.SetBackgroundColor(this, Colors.Black); SystemTray.SetForegroundColor(this, Colors.White); prog = new ProgressIndicator(); prog.IsIndeterminate = true; prog.IsVisible = true; SystemTray.SetProgressIndicator(this, prog); #endregion }
public static async Task ImportSave(ImportFileItem item, DependencyObject page) { var indicator = SystemTray.GetProgressIndicator(page); indicator.IsIndeterminate = true; indicator.Text = String.Format(AppResources.ImportingProgressText, item.Name); try { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFolder romFolder = await folder.CreateFolderAsync(FileHandler.ROM_DIRECTORY, CreationCollisionOption.OpenIfExists); StorageFolder saveFolder = await romFolder.CreateFolderAsync(FileHandler.SAVE_DIRECTORY, CreationCollisionOption.OpenIfExists); ROMDatabase db = ROMDatabase.Current; if (item.Stream != null) { byte[] tmpBuf = new byte[32]; StorageFile destinationFile = null; ROMDBEntry entry = null; if (item.Type == SkyDriveItemType.SRAM) { entry = db.GetROMFromSRAMName(item.Name); if (entry != null) { entry.SuspendAutoLoadLastState = true; destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + ".srm", CreationCollisionOption.ReplaceExisting); } else { destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting); } } else if (item.Type == SkyDriveItemType.Savestate) { entry = db.GetROMFromSavestateName(item.Name); if (entry != null) { destinationFile = await saveFolder.CreateFileAsync(Path.GetFileNameWithoutExtension(entry.FileName) + item.Name.Substring(item.Name.Length - 4), CreationCollisionOption.ReplaceExisting); } else { destinationFile = await saveFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting); } } using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite)) using (DataWriter writer = new DataWriter(destStream)) { if (item.Stream.CanSeek) { item.Stream.Seek(0, SeekOrigin.Begin); } while (item.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0) { writer.WriteBytes(tmpBuf); } await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); } item.Downloading = false; if (item.Type == SkyDriveItemType.Savestate) { String number = item.Name.Substring(item.Name.Length - 1, 1); int slot = int.Parse(number); if (entry != null) //NULL = do nothing { SavestateEntry saveentry = db.SavestateEntryExisting(entry.FileName, slot); if (saveentry != null) { //delete entry db.RemoveSavestateFromDB(saveentry); } SavestateEntry ssEntry = new SavestateEntry() { ROM = entry, Savetime = DateTime.Now, Slot = slot, FileName = item.Name }; db.Add(ssEntry); db.CommitChanges(); } } MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name)); } else { MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Import error"), AppResources.ErrorCaption, MessageBoxButton.OK); } } catch (Exception ex) { MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK); } #if GBC indicator.Text = AppResources.ApplicationTitle2; #else indicator.Text = AppResources.ApplicationTitle; #endif indicator.IsIndeterminate = false; }
private async Task LoadFeed() { try { SystemTray.SetIsVisible(this, true); SystemTray.SetOpacity(this, 0); progress.IsVisible = true; string url = string.Format(FEED_URI, Keys.WP_CLIENT_ID); var httpClient = new HttpClient(new HttpClientHandler()); var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url)); request.Headers.Add("Authorization", "Bearer " + LoginService.SignInToken); request.Headers.Add("If-Modified-Since", DateTime.UtcNow.ToString("r")); HttpResponseMessage response = await httpClient.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var responseString = await response.Content.ReadAsStringAsync(); httpClient.Dispose(); JObject jobj = JObject.Parse(responseString); JArray jlist = (JArray)jobj["feed"]; var feedList = new List <FeedItem>(); foreach (JObject obj in jlist) { var item = new FeedItem(); string action = obj["action"] != null ? obj["action"].ToString() : ""; string type = obj["type"] != null ? obj["type"].ToString() : ""; string object_type = obj["object_type"] != null ? obj["object_type"].ToString() : ""; string object_key = obj["object_key"] != null ? obj["object_key"].ToString() : ""; string object_value = obj["object_value"] != null ? obj["object_value"].ToString() : ""; string image_url = obj["image_url"] != null ? obj["image_url"].ToString() : ""; string image_key = obj["image_key"] != null ? obj["image_key"].ToString() : ""; string main_description = obj["main_description"] != null ? obj["main_description"].ToString() : ""; string detail_description = obj["detail_description"] != null ? obj["detail_description"].ToString() : ""; string created_at = obj["created_at"] != null ? obj["created_at"].ToString() : null; string started_at = obj["started_at"] != null ? obj["started_at"].ToString() : null; string updated_at = obj["updated_at"] != null ? obj["updated_at"].ToString() : null; string id = obj["id"] != null ? obj["id"].ToString() : ""; int nbr_objects = obj["nbr_objects"] != null ? (int)obj["nbr_objects"] : 0; string user = obj["user"] != null ? obj["user"].ToString() : ""; bool open = obj["open"] != null ? (bool)obj["open"] : false; var dtcreated_at = created_at != null ? new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(created_at)) : DateTime.MinValue; var dtstarted_at = started_at != null ? new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(started_at)) : DateTime.MinValue; var dtupdated_at = updated_at != null ? new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(updated_at)) : DateTime.MinValue; item.Action = action; item.Type = type; item.ObjectType = object_type; item.ObjectKey = object_key; item.ObjectValue = object_value; item.ImageUrl = image_url; item.ImageKey = image_key; item.MainDescription = main_description; item.DetailDescription = detail_description; item.CreatedAt = dtcreated_at; item.StartedAt = started_at; item.UpdatedAt = updated_at; item.Id = id; item.NbrObjects = nbr_objects; item.User = user == LoginService.SignInEmail ? "You" : user; item.Open = open; item.FirstLine = item.User + " " + item.MainDescription; if (dtstarted_at.DayOfYear == DateTime.Now.DayOfYear && dtstarted_at.Year == DateTime.Now.Year) { item.SecondLine = "Today"; } else { item.SecondLine = dtstarted_at.ToShortDateString(); } if (dtstarted_at == DateTime.MinValue) { item.SecondLine = ""; } feedList.Add(item); } eventList.ItemsSource = feedList; App.EventListCache = feedList; App.FeedLastRefreshed = DateTime.Now; } else { //MessageBox.Show("An error occurred while getting your feed. Please try again.", "Error", MessageBoxButton.OK); } } catch (Exception ex) { //MessageBox.Show("An error occurred while getting your feed: " + ex.Message, "Error", MessageBoxButton.OK); } ShowHideList(App.EventListCache != null && App.EventListCache.Count > 0); SystemTray.SetIsVisible(this, false); progress.IsVisible = false; }
public static async Task ImportROM(ImportFileItem item, DependencyObject page) { var indicator = SystemTray.GetProgressIndicator(page); indicator.IsIndeterminate = true; indicator.Text = String.Format(AppResources.ImportingProgressText, item.Name); try { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFolder romFolder = await folder.CreateFolderAsync("roms", CreationCollisionOption.OpenIfExists); ROMDatabase db = ROMDatabase.Current; var romEntry = db.GetROM(item.Name); bool fileExisted = false; if (romEntry != null) { fileExisted = true; //MessageBox.Show(String.Format(AppResources.ROMAlreadyExistingError, item.Name), AppResources.ErrorCaption, MessageBoxButton.OK); //return; } if (item.Stream != null) { byte[] tmpBuf = new byte[32]; StorageFile destinationFile = await romFolder.CreateFileAsync(item.Name, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream destStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite)) using (DataWriter writer = new DataWriter(destStream)) { if (item.Stream.CanSeek) { item.Stream.Seek(0, SeekOrigin.Begin); } while (item.Stream.Read(tmpBuf, 0, tmpBuf.Length) != 0) { writer.WriteBytes(tmpBuf); } await writer.StoreAsync(); await writer.FlushAsync(); writer.DetachStream(); } item.Downloading = false; if (!fileExisted) { var entry = FileHandler.InsertNewDBEntry(destinationFile.Name); await FileHandler.FindExistingSavestatesForNewROM(entry); db.CommitChanges(); } //update voice command list await MainPage.UpdateGameListForVoiceCommand(); MessageBox.Show(String.Format(AppResources.DownloadCompleteText, item.Name)); } else { MessageBox.Show(String.Format(AppResources.DownloadErrorText, item.Name, "Import error"), AppResources.ErrorCaption, MessageBoxButton.OK); } } catch (Exception ex) { MessageBox.Show(ex.Message, AppResources.ErrorCaption, MessageBoxButton.OK); } #if GBC indicator.Text = AppResources.ApplicationTitle2; #else indicator.Text = AppResources.ApplicationTitle; #endif indicator.IsIndeterminate = false; }
public Form1() { InitializeComponent(); // check if the OpenHardwareMonitorLib assembly has the correct version if (Assembly.GetAssembly(typeof(Computer)).GetName().Version != Assembly.GetExecutingAssembly().GetName().Version) { MessageBox.Show( "The version of the file OpenHardwareMonitorLib.dll is incompatible.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } this.settings = new PersistentSettings(); this.settings.Load(Path.ChangeExtension( Application.ExecutablePath, ".config")); this.unitManager = new UnitManager(settings); // make sure the buffers used for double buffering are not disposed // after each draw call BufferedGraphicsManager.Current.MaximumBuffer = Screen.PrimaryScreen.Bounds.Size; // set the DockStyle here, to avoid conflicts with the MainMenu this.splitContainer.Dock = DockStyle.Fill; this.Font = SystemFonts.MessageBoxFont; treeView.Font = SystemFonts.MessageBoxFont; // Set the bounds immediately, so that our child components can be // properly placed. this.Bounds = new Rectangle { X = settings.GetValue("mainForm.Location.X", Location.X), Y = settings.GetValue("mainForm.Location.Y", Location.Y), Width = settings.GetValue("mainForm.Width", 470), Height = settings.GetValue("mainForm.Height", 640) }; plotPanel = new PlotPanel(settings, unitManager); plotPanel.Font = SystemFonts.MessageBoxFont; plotPanel.Dock = DockStyle.Fill; nodeCheckBox.IsVisibleValueNeeded += nodeCheckBox_IsVisibleValueNeeded; nodeTextBoxText.DrawText += nodeTextBoxText_DrawText; nodeTextBoxValue.DrawText += nodeTextBoxText_DrawText; nodeTextBoxMin.DrawText += nodeTextBoxText_DrawText; nodeTextBoxMax.DrawText += nodeTextBoxText_DrawText; nodeTextBoxText.EditorShowing += nodeTextBoxText_EditorShowing; foreach (TreeColumn column in treeView.Columns) { column.Width = Math.Max(20, Math.Min(400, settings.GetValue("treeView.Columns." + column.Header + ".Width", column.Width))); } treeModel = new TreeModel(); root = new Node(System.Environment.MachineName); root.Image = Utilities.EmbeddedResources.GetImage("computer.png"); treeModel.Nodes.Add(root); treeView.Model = treeModel; this.computer = new Computer(settings); systemTray = new SystemTray(computer, settings, unitManager); systemTray.HideShowCommand += hideShowClick; systemTray.ExitCommand += exitClick; int p = (int)Environment.OSVersion.Platform; if ((p == 4) || (p == 128)) { // Unix treeView.RowHeight = Math.Max(treeView.RowHeight, 18); splitContainer.BorderStyle = BorderStyle.None; splitContainer.Border3DStyle = Border3DStyle.Adjust; splitContainer.SplitterWidth = 4; treeView.BorderStyle = BorderStyle.Fixed3D; plotPanel.BorderStyle = BorderStyle.Fixed3D; gadgetMenuItem.Visible = false; minCloseMenuItem.Visible = false; minTrayMenuItem.Visible = false; startMinMenuItem.Visible = false; } else { // Windows treeView.RowHeight = Math.Max(treeView.Font.Height + 1, 18); gadget = new SensorGadget(computer, settings, unitManager); gadget.HideShowCommand += hideShowClick; wmiProvider = new WmiProvider(computer); } logger = new Logger(computer); plotColorPalette = new Color[13]; plotColorPalette[0] = Color.Blue; plotColorPalette[1] = Color.OrangeRed; plotColorPalette[2] = Color.Green; plotColorPalette[3] = Color.LightSeaGreen; plotColorPalette[4] = Color.Goldenrod; plotColorPalette[5] = Color.DarkViolet; plotColorPalette[6] = Color.YellowGreen; plotColorPalette[7] = Color.SaddleBrown; plotColorPalette[8] = Color.RoyalBlue; plotColorPalette[9] = Color.DeepPink; plotColorPalette[10] = Color.MediumSeaGreen; plotColorPalette[11] = Color.Olive; plotColorPalette[12] = Color.Firebrick; computer.HardwareAdded += new HardwareEventHandler(HardwareAdded); computer.HardwareRemoved += new HardwareEventHandler(HardwareRemoved); computer.Open(); timer.Enabled = true; showHiddenSensors = new UserOption("hiddenMenuItem", false, hiddenMenuItem, settings); showHiddenSensors.Changed += delegate(object sender, EventArgs e) { treeModel.ForceVisible = showHiddenSensors.Value; }; showValue = new UserOption("valueMenuItem", true, valueMenuItem, settings); showValue.Changed += delegate(object sender, EventArgs e) { treeView.Columns[1].IsVisible = showValue.Value; }; showMin = new UserOption("minMenuItem", false, minMenuItem, settings); showMin.Changed += delegate(object sender, EventArgs e) { treeView.Columns[2].IsVisible = showMin.Value; }; showMax = new UserOption("maxMenuItem", true, maxMenuItem, settings); showMax.Changed += delegate(object sender, EventArgs e) { treeView.Columns[3].IsVisible = showMax.Value; }; startMinimized = new UserOption("startMinMenuItem", false, startMinMenuItem, settings); minimizeToTray = new UserOption("minTrayMenuItem", true, minTrayMenuItem, settings); minimizeToTray.Changed += delegate(object sender, EventArgs e) { systemTray.IsMainIconEnabled = minimizeToTray.Value; }; minimizeOnClose = new UserOption("minCloseMenuItem", false, minCloseMenuItem, settings); autoStart = new UserOption(null, startupManager.Startup, startupMenuItem, settings); autoStart.Changed += delegate(object sender, EventArgs e) { try { startupManager.Startup = autoStart.Value; } catch (InvalidOperationException) { MessageBox.Show("Updating the auto-startup option failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); autoStart.Value = startupManager.Startup; } }; readMainboardSensors = new UserOption("mainboardMenuItem", true, mainboardMenuItem, settings); readMainboardSensors.Changed += delegate(object sender, EventArgs e) { computer.MainboardEnabled = readMainboardSensors.Value; }; readCpuSensors = new UserOption("cpuMenuItem", true, cpuMenuItem, settings); readCpuSensors.Changed += delegate(object sender, EventArgs e) { computer.CPUEnabled = readCpuSensors.Value; }; readRamSensors = new UserOption("ramMenuItem", true, ramMenuItem, settings); readRamSensors.Changed += delegate(object sender, EventArgs e) { computer.RAMEnabled = readRamSensors.Value; }; readGpuSensors = new UserOption("gpuMenuItem", true, gpuMenuItem, settings); readGpuSensors.Changed += delegate(object sender, EventArgs e) { computer.GPUEnabled = readGpuSensors.Value; }; readFanControllersSensors = new UserOption("fanControllerMenuItem", true, fanControllerMenuItem, settings); readFanControllersSensors.Changed += delegate(object sender, EventArgs e) { computer.FanControllerEnabled = readFanControllersSensors.Value; }; readHddSensors = new UserOption("hddMenuItem", true, hddMenuItem, settings); readHddSensors.Changed += delegate(object sender, EventArgs e) { computer.HDDEnabled = readHddSensors.Value; }; showGadget = new UserOption("gadgetMenuItem", false, gadgetMenuItem, settings); showGadget.Changed += delegate(object sender, EventArgs e) { if (gadget != null) { gadget.Visible = showGadget.Value; } }; celsiusMenuItem.Checked = unitManager.TemperatureUnit == TemperatureUnit.Celsius; fahrenheitMenuItem.Checked = !celsiusMenuItem.Checked; server = new HttpServer(root, this.settings.GetValue("listenerPort", 8085)); if (server.PlatformNotSupported) { webMenuItemSeparator.Visible = false; webMenuItem.Visible = false; } runWebServer = new UserOption("runWebServerMenuItem", false, runWebServerMenuItem, settings); runWebServer.Changed += delegate(object sender, EventArgs e) { if (runWebServer.Value) { server.StartHTTPListener(); } else { server.StopHTTPListener(); } }; logSensors = new UserOption("logSensorsMenuItem", false, logSensorsMenuItem, settings); loggingInterval = new UserRadioGroup("loggingInterval", 0, new[] { log1sMenuItem, log2sMenuItem, log5sMenuItem, log10sMenuItem, log30sMenuItem, log1minMenuItem, log2minMenuItem, log5minMenuItem, log10minMenuItem, log30minMenuItem, log1hMenuItem, log2hMenuItem, log6hMenuItem }, settings); loggingInterval.Changed += (sender, e) => { switch (loggingInterval.Value) { case 0: logger.LoggingInterval = new TimeSpan(0, 0, 1); break; case 1: logger.LoggingInterval = new TimeSpan(0, 0, 2); break; case 2: logger.LoggingInterval = new TimeSpan(0, 0, 5); break; case 3: logger.LoggingInterval = new TimeSpan(0, 0, 10); break; case 4: logger.LoggingInterval = new TimeSpan(0, 0, 30); break; case 5: logger.LoggingInterval = new TimeSpan(0, 1, 0); break; case 6: logger.LoggingInterval = new TimeSpan(0, 2, 0); break; case 7: logger.LoggingInterval = new TimeSpan(0, 5, 0); break; case 8: logger.LoggingInterval = new TimeSpan(0, 10, 0); break; case 9: logger.LoggingInterval = new TimeSpan(0, 30, 0); break; case 10: logger.LoggingInterval = new TimeSpan(1, 0, 0); break; case 11: logger.LoggingInterval = new TimeSpan(2, 0, 0); break; case 12: logger.LoggingInterval = new TimeSpan(6, 0, 0); break; } }; InitializePlotForm(); InitializeSplitter(); startupMenuItem.Visible = startupManager.IsAvailable; if (startMinMenuItem.Checked) { if (!minTrayMenuItem.Checked) { WindowState = FormWindowState.Minimized; Show(); } } else { Show(); } // Create a handle, otherwise calling Close() does not fire FormClosed IntPtr handle = Handle; // Make sure the settings are saved when the user logs off Microsoft.Win32.SystemEvents.SessionEnded += delegate { computer.Close(); SaveConfiguration(); if (runWebServer.Value) { server.Quit(); } }; }
public void Initialize() { SystemTray.ConfigureTray(_app.MainWindow); }
private void AutoProcess(KeyValuePair <string, HubRequest> input) { var request = input.Value; var datamartDescription = Configuration.Instance.GetDataMartDescription(request.NetworkId, request.DataMartId); if (datamartDescription.ProcessQueriesAndUploadAutomatically == false && datamartDescription.ProcessQueriesAndNotUpload == false) { //just notify, do not process string message = $"New query submitted and awaiting processing in { request.ProjectName } Project: { request.Source.Name } ({request.Source.Identifier})"; SystemTray.DisplayNewQueryNotificationToolTip(message); RequestStatuses.TryAdd(input.Key, ProcessingStatus.CannotRunAndUpload); return; } var modelDescription = Configuration.Instance.GetModelDescription(request.NetworkId, request.DataMartId, request.Source.ModelID); var packageIdentifier = new Lpp.Dns.DTO.DataMartClient.RequestTypeIdentifier { Identifier = request.Source.RequestTypePackageIdentifier, Version = request.Source.AdapterPackageVersion }; if (!System.IO.File.Exists(System.IO.Path.Combine(Configuration.PackagesFolderPath, packageIdentifier.PackageName()))) { DnsServiceManager.DownloadPackage(_networkSetting, packageIdentifier); } var domainManager = new DomainManger.DomainManager(Configuration.PackagesFolderPath); try { domainManager.Load(request.Source.RequestTypePackageIdentifier, request.Source.AdapterPackageVersion); IModelProcessor processor = domainManager.GetProcessor(modelDescription.ProcessorId); ProcessorManager.UpdateProcessorSettings(modelDescription, processor); processor.Settings.Add("NetworkId", request.NetworkId); Lib.Caching.DocumentCacheManager cache = new Lib.Caching.DocumentCacheManager(request.NetworkId, request.DataMartId, request.Source.ID, request.Source.Responses.Where(x => x.DataMartID == request.DataMartId).FirstOrDefault().ResponseID); //need to initialize before checking the capabilities and settings of the processor since they may change based on the type of request being sent. if (processor is IEarlyInitializeModelProcessor) { ((IEarlyInitializeModelProcessor)processor).Initialize(modelDescription.ModelId, request.Documents.Select(d => new DocumentWithStream(d.ID, new Document(d.ID, d.Document.MimeType, d.Document.Name, d.Document.IsViewable, Convert.ToInt32(d.Document.Size), d.Document.Kind), new DocumentChunkStream(d.ID, _networkSetting))).ToArray()); } if (processor != null && processor.ModelMetadata != null && processor.ModelMetadata.Capabilities != null && processor.ModelMetadata.Capabilities.ContainsKey("CanRunAndUpload") && !(bool)processor.ModelMetadata.Capabilities["CanRunAndUpload"]) { //can't be run, don't attempt autoprocessing RequestStatuses.TryAdd(input.Key, ProcessingStatus.CannotRunAndUpload); domainManager.Dispose(); return; } request.Processor = processor; if (cache.HasResponseDocuments == false && (request.RoutingStatus == Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.Submitted || request.RoutingStatus == DTO.DataMartClient.Enums.DMCRoutingStatus.Resubmitted)) { if (processor != null) { SystemTray.GenerateNotification(request, request.NetworkId); StartProcessingRequest(request, processor, datamartDescription, domainManager, cache); return; } } else if (request.RoutingStatus == Lpp.Dns.DTO.DataMartClient.Enums.DMCRoutingStatus.AwaitingResponseApproval) { if (datamartDescription.ProcessQueriesAndUploadAutomatically) { // Increment counter System.Threading.Interlocked.Increment(ref _queriesProcessedCount); SystemTray.UpdateNotifyText(_queriesProcessedCount, request.DataMartName, request.NetworkId); StartUploadingRequest(request, domainManager, cache); return; } } else if (cache.HasResponseDocuments) { RequestStatuses.TryAdd(input.Key, ProcessingStatus.PendingUpload); } domainManager.Dispose(); } catch (Exception ex) { Log.Error($"Error autoprocessing Request: { request.Source.Identifier }, DataMartId: { request.DataMartId }, NetworkId: {request.NetworkId}", ex); domainManager.Dispose(); throw; } }
public static void Hide() { SystemTray.SetProgressIndicator(UIElement, null); }
private void SearchCallback(IAsyncResult asynchronousResult) { try { HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult); using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(streamResponse)) { string result = reader.ReadToEnd(); Regex regexSearchResult = new Regex("<div class='searchresults'(?<data>[\\s\\S]*?)</ul>"); Match matchSearchResult = regexSearchResult.Match(result); if (matchSearchResult.Success) { string data = matchSearchResult.Groups["data"].Value; try { MatchCollection mc = _regexLatestEntry.Matches(data); int itemcounter = 0; foreach (Match m in mc) { itemcounter++; if (itemcounter % 2 == 0) { Thread.Sleep(20); } if (m.Value.Contains("#.")) { continue; } string title = HttpUtility.HtmlDecode(m.Groups["title"].Value); if (string.IsNullOrWhiteSpace(title) || !title.Contains(_searchContent)) { continue; } Entry en = new Entry { Href = HttpUtility.HtmlDecode(title.Replace(' ', '_')), Title = HttpUtility.HtmlDecode(title) }; Dispatcher.BeginInvoke(() => _listSearch.Add(en)); } Dispatcher.BeginInvoke(() => panorama.Focus()); } finally { Dispatcher.BeginInvoke(() => { tbTotal.Text = "共获得" + _listSearch.Count + "条搜索结果"; }); } } else { Dispatcher.BeginInvoke(() => { tbSearch.Text = "找不到和查询相匹配的结果。"; tbSearch.Visibility = Visibility.Visible; }); } } } Dispatcher.BeginInvoke(() => SystemTray.SetProgressIndicator(this, null)); } catch (Exception ex) { Debug.WriteLine("SearchCallback()出错:" + ex.Message); Dispatcher.BeginInvoke(() => { ProgressIndicator pi = new ProgressIndicator(); pi.Text = "搜索时出现错误"; pi.IsIndeterminate = false; pi.IsVisible = true; SystemTray.SetProgressIndicator(this, pi); }); } finally { Dispatcher.BeginInvoke(() => { rectSearch.Visibility = Visibility.Collapsed; tboxSearch.IsHitTestVisible = true; }); } }
private void ShowProgressIndicator(bool show) { SystemTray.GetProgressIndicator(this).IsVisible = show; }
/// <summary> /// Displays the progress indicator with the given message. /// </summary> /// <param name="message">The message to display.</param> private void ShowProgress(String message) { _progressIndicator.Text = message; _progressIndicator.IsVisible = true; SystemTray.SetProgressIndicator(this, _progressIndicator); }
public void CleanupAndExit() { SystemTray.Dispose(); Application.Exit(); }
/// <summary> /// Stops displaying progress indicator. /// </summary> private void HideProgress() { _progressIndicator.IsVisible = false; SystemTray.SetProgressIndicator(this, _progressIndicator); }
public virtual void setHideToSystemTray() { Console.WriteLine("setting up systemtray"); if (SystemTray.Supported) { Console.WriteLine("system tray supported"); tray = SystemTray.SystemTray; Image image = Toolkit.DefaultToolkit.getImage("wifi.png"); ActionListener exitListener = new ActionListenerAnonymousInnerClassHelper(this); PopupMenu popup = new PopupMenu(); MenuItem defaultItem = new MenuItem("Exit"); defaultItem.addActionListener(exitListener); popup.add(defaultItem); defaultItem = new MenuItem("Open"); defaultItem.addActionListener(new ActionListenerAnonymousInnerClassHelper2(this)); popup.add(defaultItem); trayIcon = new TrayIcon(image, "Wifi WebLogin", popup); trayIcon.ImageAutoSize = true; } else { Console.WriteLine("system tray not supported"); } trayIcon.addMouseListener(new MouseListenerAnonymousInnerClassHelper(this)); addWindowStateListener(new WindowStateListenerAnonymousInnerClassHelper(this)); IconImage = Toolkit.DefaultToolkit.getImage("wifi.png"); }