private void btnDeletePartner_Click(object sender, EventArgs e) { if (dgPartners.SelectedRows.Count == 0) { MessageBox.Show("Please select a partner to delete."); } else { var rowToDelete = dgPartners.SelectedRows[0]; int id = Convert.ToInt32(rowToDelete.Cells[0].Value); string orgName = (string)rowToDelete.Cells[2].Value; if (MessageBox.Show("Are you sure you want to delete " + orgName + "? This does not delete this partner from your MyJohnDeere account. Previously downloaded files will not be deleted.", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes) { using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { //delete all recent files var files = p.SourceFiles.FindMatching(f => f.OrganizationId == id).ToList(); files.ForEach(f => p.SourceFiles.Delete(f)); var org = p.Organizations.FindSingle(f => f.Id == id); p.Organizations.Delete(org); p.SaveChanges(); } dgPartners.Rows.Remove(rowToDelete); } } }
private async Task loadPartnerGrid() { showLoadingMessage("Loading partner data"); IEnumerable <Organization> orgs = null; dgPartners.Rows.Clear(); await Task.Run(() => { //load partners using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { orgs = p.Organizations.GetAll(); } }); foreach (var org in orgs) { DataGridViewRow row = new DataGridViewRow(); dgPartners.Rows.Add(org.Id.ToString(), (!string.IsNullOrEmpty(org.RemoteID) ? org.RemoteID.ToString() : "PENDING"), org.Name, org.Email, (org.PermissionGranted) ? "Granted" : "Not Granted", org.SharedFiles.ToString(), "MyJohnDeere"); } }
private bool ValidateEmail() { bool result = true; Regex expression = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"); if (chkRequestPermission.Checked == false && string.IsNullOrEmpty(tbEmail.Text.Trim())) { result = true; } else if (string.IsNullOrEmpty(tbEmail.Text)) { formErrorProvider.SetError(tbEmail, "Email is required."); result = false; } else if (!expression.IsMatch(tbEmail.Text.Trim())) { formErrorProvider.SetError(tbEmail, "Email is not valid."); result = false; } else { using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { var existingOrg = p.Organizations.FindSingle(o => o.Email == tbEmail.Text && o.Id != orgId); if (existingOrg != null) { formErrorProvider.SetError(tbEmail, "A partner with this email has already been added."); result = false; } } } return(result); }
/// <summary> /// Saves the currently selected settings to the database /// </summary> public void SaveCurrentSettings() { //save settings using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { dp.Settings.UpdateSettingWithKey(SettingKeyType.DownloadFolderKey, SelectedDownloadFolder); dp.Settings.UpdateSettingWithKey(SettingKeyType.DownloadFrequencyTypeKey, ((int)IntervalType).ToString()); dp.Settings.UpdateSettingWithKey(SettingKeyType.HourlyDownloadTimeKey, HourlyDownloadInterval.ToString()); dp.Settings.UpdateSettingWithKey(SettingKeyType.DailyDownloadTimeKey, DailyDownloadTime.ToString()); dp.SaveChanges(); } //make sure checkbox value is saved var shortcutFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "CottonHarvestFileDownloadUtility.lnk"); if (chkStartup.Checked) { if (!System.IO.File.Exists(shortcutFile)) { createShortcut(); } } else { if (System.IO.File.Exists(shortcutFile)) { System.IO.File.Delete(shortcutFile); } } }
/// <summary> /// Asynchronously loads the recent files grid /// </summary> /// <returns></returns> private async Task LoadRecentFilesAsync() { await Task.Run(() => { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { recentFiles.Clear(); recentFiles = dp.OutputFiles.GetRecentFiles(); } }); this.Invoke((MethodInvoker) delegate { dgRecentFiles.Rows.Clear(); dgRecentFiles.ShowCellToolTips = true; foreach (var file in recentFiles) { string shortName = ".." + file.Filename.Substring(file.Filename.LastIndexOf("\\")); var row = new DataGridViewRow(); DataGridViewTextBoxCell c1 = new DataGridViewTextBoxCell(); DataGridViewLinkCell c2 = new DataGridViewLinkCell(); c1.Value = file.SourceFile.Organization.Name; c2.Value = shortName; c2.ToolTipText = file.Filename; row.Cells.Add(c1); row.Cells.Add(c2); dgRecentFiles.Rows.Add(row); } }); }
/// <summary> /// Runs a simple check to verify connectivity to remote API /// </summary> /// <returns></returns> private async Task checkConnection() { bool connected = false; lblStatusValue.Text = "Checking connection..."; await Task.Run(async() => { System.Threading.Thread.Sleep(1500); using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { //if we have credentials test connection connected = ((await remoteDataRepository.TestConnection()) != string.Empty); } }); this.Invoke((MethodInvoker) delegate { if (connected) { lblStatusValue.Text = "Connected"; lblStatusValue.ForeColor = Color.Green; } else { lblStatusValue.Text = "Not Connected"; lblStatusValue.ForeColor = Color.Red; } }); }
private void SetDownloadFolderLabel() { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { lblDownloadFolderValue.Text = dp.Settings.GetDownloadFolder().TrimEnd('\\') + "\\"; } }
private bool ValidateOrganization() { bool result = true; if (string.IsNullOrEmpty(tbOrganization.Text)) { result = false; formErrorProvider.SetError(tbOrganization, "Organization name is required."); } else { using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { var existingOrg = p.Organizations.FindSingle(o => o.Name == tbOrganization.Text && o.Id != orgId); if (existingOrg != null) { formErrorProvider.SetError(tbOrganization, "A partner with this name has already been added."); result = false; } } } return(result); }
public static bool IsTokenExpired() { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { var expiresAt = dp.Settings.GetAccessTokenExpiresUTC(); expiresAt = expiresAt.AddMinutes(-10); return(DateTime.UtcNow > expiresAt); } }
private void initRemoteRepo() { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { accessToken = dp.Settings.GetAsString(SettingKeyType.JDAccessToken); refreshToken = dp.Settings.GetAsString(SettingKeyType.JDRefreshToken); } remoteDataRepository.Initialize(AppConfig.JohnDeereApiUrl, AppConfig.JohnDeereWellKnownUrl, RemoteProviderType.OAuthProvider, DataHelper.SaveNewToken, DataHelper.IsTokenExpired, AppConfig.AppId, AppConfig.AppSecret, accessToken, refreshToken); }
public static void SaveNewToken(Token token) { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { dp.Settings.UpsertSettingWithKey(SettingKeyType.JDAccessToken, token.access_token); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDAccessTokenExpires, DateTime.UtcNow.AddSeconds(token.expires_in).ToString()); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDRefreshToken, token.refresh_token); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDCredentialDateTime, DateTime.UtcNow.ToString()); dp.SaveChanges(); } }
private async Task <HttpResponseMessage> SecuredApiGetRequest(string url) { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { var client = new HttpClient(); var tokenSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.JDAccessToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.deere.axiom.v3+json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenSetting.Value}"); return(await client.GetAsync(url)); } }
private void btnChangeFolder_Click(object sender, EventArgs e) { if (folderDialog.ShowDialog() == DialogResult.OK) { //downloadSettingsControl.SelectedDownloadFolder = folderDialog.SelectedPath; lblDownloadFolderValue.Text = folderDialog.SelectedPath; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { dp.Settings.UpdateSettingWithKey(SettingKeyType.DownloadFolderKey, folderDialog.SelectedPath.TrimEnd('\\')); dp.SaveChanges(); } } }
/// <summary> /// Loads settings data and initializes UI /// </summary> /// <returns></returns> public async Task LoadDataAsync() { loading = true; Setting downloadFolderSetting = null; Setting downloadFrequencyTypeSetting = null; Setting hourlyDownloadTimeSetting = null; Setting dailyDownloadTimeSetting = null; chkStartup.Checked = false; var shortcutFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "CottonHarvestFileDownloadUtility.lnk"); chkStartup.Checked = System.IO.File.Exists(shortcutFile); await Task.Run(() => { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { downloadFolderSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.DownloadFolderKey); downloadFrequencyTypeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.DownloadFrequencyTypeKey); hourlyDownloadTimeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.HourlyDownloadTimeKey); dailyDownloadTimeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.DailyDownloadTimeKey); } }); if (downloadFolderSetting != null) { SelectedDownloadFolder = downloadFolderSetting.Value; } if (downloadFrequencyTypeSetting != null) { cboDownloadType.SelectedIndex = int.Parse(downloadFrequencyTypeSetting.Value); } if (hourlyDownloadTimeSetting != null) { hourPicker.Value = decimal.Parse(hourlyDownloadTimeSetting.Value); } if (dailyDownloadTimeSetting != null) { timePicker.Value = DateTime.Parse(dailyDownloadTimeSetting.Value); } SetPanelVisibility(); loading = false; }
private void btnViewFiles_Click(object sender, EventArgs e) { string folder = ""; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { folder = dp.Settings.GetDownloadFolder(); } if (!string.IsNullOrEmpty(folder) && System.IO.Directory.Exists(folder)) { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = folder, UseShellExecute = true, Verb = "open" }); } }
private async void btnEdit_Click(object sender, EventArgs e) { await partnerForm.SetRemoteRepository(remoteDataRepository); if (dgPartners.SelectedRows.Count == 0) { MessageBox.Show("Please select a partner to edit."); } else { var selectedRow = dgPartners.SelectedRows[0]; int id = Convert.ToInt32(selectedRow.Cells[0].Value); using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { //delete all recent files var org = p.Organizations.FindSingle(f => f.Id == id); partnerForm.ShowEdit(org); } } }
private async void Main_Load(object sender, EventArgs e) { _loading = true; try { string arguments = "Application loading with arguments: "; foreach (var s in Environment.GetCommandLineArgs()) { arguments += s + " "; } Logger.Log("INFO", arguments); Logger.Log("INFO", "Main_Load"); this.WindowState = FormWindowState.Minimized; initRemoteRepo(); downloadSettingsControl.AutoSaveChanges = true; string downloadFolderSetting = ""; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { downloadFolderSetting = dp.Settings.GetDownloadFolder(); } if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(refreshToken) || string.IsNullOrEmpty(downloadFolderSetting)) { Logger.Log("INFO", "Launching setup form"); setupForm = new FirstLaunchForm(); focusApplication(); if (setupForm.ShowDialog() == DialogResult.OK) { activitySummaryControl.SetStatusMessage("Connected", Color.Green); await activitySummaryControl.Initialize(remoteDataRepository, false); setupForm = null; focusApplication(); } else { Application.Exit(); } } else { await activitySummaryControl.Initialize(remoteDataRepository, true); var args = Environment.GetCommandLineArgs(); //if started from startup then minimize if (args.Length >= 2 && args[1] == "-minimized") { Logger.Log("INFO", "Starting minimized"); this.WindowState = FormWindowState.Minimized; this.Hide(); } else { Logger.Log("INFO", "Starting normal"); this.WindowState = FormWindowState.Normal; } } } catch (Exception exc) { MessageBox.Show(exc.Message); Application.Exit(); } _loading = false; }
/// <summary> /// Initiates the update of local partnerships and then downloads files for /// relevant partners /// </summary> /// <returns></returns> private async Task executeDownload() { DateTime startTime = DateTime.Now; if (!downloadRunning) { Logger.Log("INFO", "Starting download"); downloadRunning = true; extractErrors = 0; //kick off process to download all files List <Partner> results = null; string message = ""; ImportPartnerResult importResult = new ImportPartnerResult(); //first check for new partner relationships this.Invoke((MethodInvoker) delegate { lblStatusValue.Text = "Getting download information..."; lblStatusValue.ForeColor = Color.Green; }); await Task.Run(async() => { try { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { //save last download time at beginning so another download doesn't start if //process takes longer dp.Settings.UpdateSettingWithKey(SettingKeyType.LastDownload, startTime.ToString()); dp.SaveChanges(); } //TODO: NEED A WAY TO PROPAGATE MESSAGE BACK TO SCREEN importResult = await DataHelper.ImportPartners(results, remoteDataRepository, false); } catch (Exception exc) { extractErrors++; Logger.Log(exc); } }); await Task.Run(async() => { try { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { downloadFolder = dp.Settings.GetDownloadFolder().TrimEnd('\\') + "\\"; downloadFolder += "temp\\"; //clean up previous download attempt if (System.IO.Directory.Exists(downloadFolder)) { System.IO.Directory.Delete(downloadFolder, true); } int fileCountOld = dp.OutputFiles.FileCount(); batchNumber = dp.SourceFiles.GetNextBatchNumber(); var orgIds = dp.Organizations.GetAll().Select(o => o.RemoteID).ToArray(); var fileIds = dp.SourceFiles.GetFileIds(); List <OrgFileETag> savedETags = new List <OrgFileETag>(); var orgs = dp.Organizations.GetAll(); foreach (var o in orgs) { savedETags.Add(new OrgFileETag { OrgId = o.RemoteID, CreatedDate = o.FilesETagDate, Tag = o.FilesETag }); } Logger.Log("INFO", "Start download all files."); var updatedETags = await remoteDataRepository.DownloadOrganizationFiles(savedETags, downloadFolder, orgIds, fileIds, FileDownloaded, DownloadProgress, FileDownloadError); Logger.Log("INFO", "Finished download all files."); //update organization record with new file eTags foreach (var o in orgs) { var tag = updatedETags.SingleOrDefault(t => t.OrgId == o.RemoteID); if (tag != null) { o.FilesETag = tag.Tag; o.FilesETagDate = tag.CreatedDate; } } dp.SaveChanges(); int fileCountNew = dp.OutputFiles.FileCount(); Logger.Log("INFO", "Old file count: " + fileCountOld.ToString()); Logger.Log("INFO", "New file count: " + fileCountNew.ToString()); if (System.IO.Directory.Exists(downloadFolder)) { System.IO.Directory.Delete(downloadFolder, true); } if (fileCountNew > fileCountOld) { OnNewFilesDownloaded(new EventArgs()); } } } catch (Exception exc) { extractErrors++; Logger.Log(exc); } }); await LoadRecentFilesAsync(); this.Invoke((MethodInvoker) delegate { lblNextDownloadValue.Text = "--"; if (extractErrors > 0) { lblStatusValue.Text = "Completed with errors at " + DateTime.Now.ToString(); lblStatusValue.ForeColor = Color.Red; } else { lblStatusValue.Text = "Completed successfully at " + DateTime.Now.ToString(); lblStatusValue.ForeColor = Color.Green; } }); downloadRunning = false; } }
/// <summary> /// This helper method handles the import of partners. /// </summary> /// <param name="results">List of partners retrieved from remote data source</param> /// <param name="displayMessage">Error message if any</param> /// <param name="remoteDataRepository">repository instance to access the remote datasource</param> /// <param name="addNew"></param> /// <returns></returns> public static async Task <ImportPartnerResult> ImportPartners(List <Partner> results, IRemoteDataRepository remoteDataRepository, bool addNew) { results = null; ImportPartnerResult result = new ImportPartnerResult(); try { using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { var orgIds = dp.Organizations.GetAll().Select(o => o.RemoteID).ToArray(); //passing null for eTags results in only total file count being fetched //instead of downloading files when filing the partner object tree results = await remoteDataRepository.FetchAllPartners(null, (addNew)?null : orgIds); } } catch (Exception fetchExc) { result.Message = "An error occurred fetching partner data."; Logger.Log("MESSAGE", result.Message); Logger.Log(fetchExc); result.Status = ImportStatus.REMOTE_FETCH_ERROR; return(result); } if (results == null || results.Count() == 0) { result.Message = "No partners found."; result.Status = ImportStatus.REMOTE_FETCH_ERROR; return(result); } using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { try { foreach (var p in dp.Organizations.GetAll()) { if (string.IsNullOrEmpty(p.RemoteID) && !string.IsNullOrEmpty(p.PartnerLink)) { p.RemoteID = await remoteDataRepository.GetRemoteIDFromPartnerLink(p.PartnerLink); dp.Organizations.Update(p); } } dp.SaveChanges(); } catch (Exception exc) { result.Message = "An error occurred checking status of pending partner invitations."; Logger.Log("MESSAGE", result.Message); Logger.Log(exc); result.Status = ImportStatus.REMOTE_FETCH_ERROR; return(result); } try { foreach (var p in results) { Organization existingOrg = null; var matches = dp.Organizations.FindMatching(x => x.RemoteID == p.Id); if (matches.Count() > 0) { existingOrg = matches.ToArray()[0]; } if (existingOrg == null) //try to find a matching partnership link { existingOrg = dp.Organizations.FindSingle(x => x.PartnerLink == p.PartnershipLink); } if (existingOrg == null) //only import new partners { if (addNew) { Organization newOrg = new Organization(); newOrg.Name = p.Name; newOrg.Created = DateTime.Now; newOrg.DataSourceId = 1; newOrg.RemoteID = p.Id; newOrg.MyLinkedOrgId = p.MyLinkedOrgId; newOrg.SharedFiles = p.SharedFileCount; newOrg.PermissionGranted = p.PermissionGranted; newOrg.FilesETag = ""; newOrg.FilesETagDate = DateTime.Now; dp.Organizations.Add(newOrg); } } else { existingOrg.RemoteID = p.Id; existingOrg.MyLinkedOrgId = p.MyLinkedOrgId; existingOrg.SharedFiles = p.SharedFileCount; existingOrg.PermissionGranted = p.PermissionGranted; dp.Organizations.Update(existingOrg); } } dp.SaveChanges(); } catch (Exception exc) { result.Message = "An error occurred saving partners. " + exc.Message; Logger.Log("MESSAGE", result.Message); Logger.Log(exc); result.Status = ImportStatus.SAVE_ERROR; return(result); } } result.Status = ImportStatus.SUCCESS; result.Message = ""; return(result); }
/// <summary> /// Callback method that is called when a file is successfully downloaded. This /// method extracts the ZIP file and produces the final output file. /// </summary> /// <param name="result"></param> private void FileDownloaded(FileDownloadedResult result) { try { if (result.Filename.ToLower().Trim().EndsWith(".zip")) { Logger.Log("INFO", string.Format("Extracting {0}", result.Filename)); ZipFile.ExtractToDirectory(result.Filename, downloadFolder + result.OrganizationID + "-" + result.FileIdentifier.ToString()); System.IO.File.Delete(result.Filename); FileLocator locator = new FileLocator(downloadFolder + result.OrganizationID + "-" + result.FileIdentifier.ToString()); var filenames = locator.FindHIDFiles(); using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { int oldLineCount = 0; Organization org = dp.Organizations.FindSingle(x => x.RemoteID == result.OrganizationID); int currentFileCount = 1; foreach (var filename in filenames) { //instantiate parser which will read file CSVFileParser parser = new CSVFileParser(filename); //if no data in file then no reason to do anything if (!string.IsNullOrEmpty(parser.FirstLineText) && parser.LineCount > 1 && !string.IsNullOrWhiteSpace(parser.MachineID)) { //look to see if we have read another file with the same data appearing at the start of the file //new files may get uploaded that are really the same data with additional modules //appended. var files = dp.SourceFiles.FindMatching(x => x.FirstLineText == parser.FirstLineText && org.Id == x.OrganizationId); SourceFile file = null; //get source file that had the highest line count if (files != null && files.Count() > 0) { file = files.OrderByDescending(x => x.LineCount).ToList()[0]; } var shortName = filename.Replace(downloadFolder, ""); OutputFile outputFile = new OutputFile(); outputFile.Filename = downloadFolder.Replace("\\temp", "") + parser.MachineID.ToUpper().Trim() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss_fff") + ".TXT"; outputFile.Created = DateTime.Now; oldLineCount = 0; if (file != null) { oldLineCount = file.LineCount; } //add a record for this file id - file will not be downloaded in //subsequent downloads SourceFile newFile = new SourceFile(); newFile.BatchNumber = batchNumber; newFile.FileIdentifer = result.FileIdentifier; newFile.SourceFilename = shortName; newFile.FirstDownload = DateTime.Now; newFile.LastDownload = DateTime.Now; newFile.OrganizationId = org.Id; newFile.LineCount = parser.LineCount; newFile.FirstLineText = parser.FirstLineText.ToLower().Trim(); if (parser.LineCount > oldLineCount) { newFile.OutputFiles.Add(outputFile); parser.WriteFile(outputFile.Filename, oldLineCount); } dp.SourceFiles.Add(newFile); dp.SaveChanges(); currentFileCount++; } else { Logger.Log("WARNING", "Empty file downloaded ignoring."); } } } } } catch (Exception exc) { Logger.Log(exc); extractErrors++; } }
private async void btnSave_Click(object sender, EventArgs e) { btnSave.Enabled = false; string partnerLink = string.Empty; string requestingOrgId = (string)cboMyOrg.SelectedValue; if (ValidateForm()) { //try to initiate permission request if (chkRequestPermission.Checked) { //await Task.Run(async () => //{ try { partnerLink = await remoteRepository.RequestPartnerPermission(tbEmail.Text.Trim(), requestingOrgId); } catch (Exception exc) { Logger.Log(exc); partnerLink = string.Empty; } //}); if (string.IsNullOrEmpty(partnerLink)) { MessageBox.Show("Unable to initiate partner request. Check your network connection."); return; } } using (IUnitOfWorkDataProvider p = AppStorage.GetUnitOfWorkDataProvider()) { Organization org = new Organization(); if (orgId == 0) { //initiate contact request org.RemoteID = string.Empty; org.PartnerLink = partnerLink; org.Created = DateTime.Now; org.PermissionGranted = false; org.FilesETag = ""; org.FilesETagDate = DateTime.Now; p.Organizations.Add(org); } else { org = p.Organizations.FindSingle(o => o.Id == orgId); org.Updated = DateTime.Now; p.Organizations.Update(org); } org.Email = tbEmail.Text.Trim(); org.Name = tbOrganization.Text.Trim(); org.DataSourceId = 1; p.SaveChanges(); } this.DialogResult = DialogResult.OK; this.Close(); } }
private async Task ExchangeCodeForToken(string code) { //now what do we do with the code - we need to exchange it for tokens Dictionary <string, object> oAuthMetadata = await GetOAuthMetadata(AppConfig.JohnDeereWellKnownUrl); string tokenEndpoint = oAuthMetadata["token_endpoint"].ToString(); var queryParameters = new Dictionary <string, string>(); queryParameters.Add("grant_type", "authorization_code"); queryParameters.Add("code", code); queryParameters.Add("redirect_uri", "cottonutil://localhost/callback"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("authorization", $"Basic {GetBase64EncodedClientCredentials()}"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint) { Content = new FormUrlEncodedContent(queryParameters) }; HttpResponseMessage response = await client.SendAsync(request); var responseContent = await response.Content.ReadAsStringAsync(); Token accessToken = JsonConvert.DeserializeObject <Token>(responseContent); //need to save access token info using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { dp.Settings.UpsertSettingWithKey(SettingKeyType.JDAccessToken, accessToken.access_token); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDAccessTokenExpires, DateTime.UtcNow.AddSeconds(accessToken.expires_in).ToString()); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDRefreshToken, accessToken.refresh_token); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDCredentialDateTime, DateTime.UtcNow.ToString()); dp.SaveChanges(); } string organizationAccessUrl = await NeedsOrganizationAccess(); //if we received an organizationsAccessUrl we need to open a browser for user to give permission //once completed browser will redirect to the call back if (organizationAccessUrl != null) { ClearAuthResponseText(); ProcessStartInfo sInfo = new ProcessStartInfo(organizationAccessUrl); Process.Start(sInfo); } else { if (openProcess != null && !openProcess.HasExited) { openProcess.CloseMainWindow(); if (this.ParentForm != null) { this.ParentForm.Focus(); } } verifyConnection(); } }
private async void verifyConnection() { string accessToken = ""; string refreshToken = ""; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { accessToken = dp.Settings.GetAsString(SettingKeyType.JDAccessToken); refreshToken = dp.Settings.GetAsString(SettingKeyType.JDRefreshToken); remoteDataRepository.SetAuthData(accessToken, refreshToken); } string newUserID = ""; lblLoadingMessage.Text = "Verifying connection"; await Task.Run(async() => { System.Threading.Thread.Sleep(1000); newUserID = await remoteDataRepository.TestConnection(); }); pnlLoading.Visible = false; if (!string.IsNullOrEmpty(newUserID)) { if (newUserID != _currentUserId && !_firstRun) //switched accounts { if (MessageBox.Show("You have switched to a different account. This will reset all application data. Are you sure you want to continue?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) { pnlConnectionSettingsConnected.Visible = true; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = false; _currentUserId = newUserID; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { //remove all organizations saved dp.Organizations.DeleteAll(); //save updated token and secret dp.Settings.UpsertSettingWithKey(SettingKeyType.JDAccessToken, accessToken); dp.Settings.UpsertSettingWithKey(SettingKeyType.JDRefreshToken, refreshToken); dp.Settings.UpsertSettingWithKey(SettingKeyType.LastUserID, _currentUserId); dp.SaveChanges(); } this.OnConnectionComplete(new EventArgs()); } else { //reset auth token back to original remoteDataRepository.SetAuthData(accessToken, refreshToken); pnlConnectionSettingsConnected.Visible = true; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = false; this.OnConnectionComplete(new EventArgs()); } } else { //handle same user just save new secret and token _currentUserId = newUserID; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { dp.Settings.UpdateSettingWithKey(SettingKeyType.JDAccessToken, accessToken); dp.Settings.UpdateSettingWithKey(SettingKeyType.JDRefreshToken, refreshToken); dp.Settings.UpsertSettingWithKey(SettingKeyType.LastUserID, _currentUserId); dp.SaveChanges(); } pnlConnectionSettingsConnected.Visible = true; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = false; this.OnConnectionComplete(new EventArgs()); } remoteDataRepository.EmptyAllCacheItems(); } else { MessageBox.Show("Unable to establish connection. Verify you have a network connection."); pnlConnectionSettingsVerifyCode.Visible = true; } pnlLoading.Visible = false; }
private async void timerControl_Tick(object sender, EventArgs e) { timerControl.Enabled = false; try { Setting downloadFrequencyTypeSetting = null; Setting hourlyDownloadTimeSetting = null; Setting dailyDownloadTimeSetting = null; Setting lastDownloadSetting = null; DateTime?lastDownload = null; DateTime?nextDownloadTime = null; await Task.Run(async() => { Logger.CleanUp(); using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { downloadFrequencyTypeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.DownloadFrequencyTypeKey); hourlyDownloadTimeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.HourlyDownloadTimeKey); dailyDownloadTimeSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.DailyDownloadTimeKey); lastDownloadSetting = dp.Settings.FindSingle(x => x.Key == SettingKeyType.LastDownload); if (lastDownloadSetting != null) { lastDownload = DateTime.Parse(lastDownloadSetting.Value); } else { lastDownload = DateTime.Now; dp.Settings.UpdateSettingWithKey(SettingKeyType.LastDownload, lastDownload.ToString()); } if (downloadFrequencyTypeSetting != null) { DownloadIntervalType IntervalType = (DownloadIntervalType)int.Parse(downloadFrequencyTypeSetting.Value); if (IntervalType == DownloadIntervalType.HourlyIntervals) { if (hourlyDownloadTimeSetting != null) { int hours = int.Parse(hourlyDownloadTimeSetting.Value); nextDownloadTime = lastDownload.Value.AddHours(hours); if (lastDownload.Value.AddHours(hours) <= DateTime.Now) { await executeDownload(); } } } else //must be time of day download type { if (dailyDownloadTimeSetting != null) { DateTime dailyDownloadTime = DateTime.Parse(dailyDownloadTimeSetting.Value); DateTime current = DateTime.Now; nextDownloadTime = new DateTime(current.Year, current.Month, current.Day, dailyDownloadTime.Hour, dailyDownloadTime.Minute, 0); if (nextDownloadTime < current) { nextDownloadTime = nextDownloadTime.Value.AddDays(1); } if (current.Hour == dailyDownloadTime.Hour && current.Minute == dailyDownloadTime.Minute) { await executeDownload(); } } } } } }); if (nextDownloadTime.HasValue) { lblNextDownloadValue.Text = nextDownloadTime.ToString(); } else { lblNextDownloadValue.Text = "--"; } } catch (Exception exc) { Logger.Log(exc); } timerControl.Enabled = true; }
/// <summary> /// Checks for a connection and initializes UI for connections /// </summary> /// <returns></returns> public async Task LoadDataAsync() { if (!_loading || _firstRun) { _loading = true; lblPermissions.Visible = false; btnConnections.Visible = false; using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { _currentUserId = dp.Settings.GetAsString(SettingKeyType.LastUserID); } remoteDataRepository.Initialize(AppConfig.JohnDeereApiUrl, AppConfig.JohnDeereWellKnownUrl, RemoteProviderType.OAuthProvider, DataHelper.SaveNewToken, DataHelper.IsTokenExpired, AppConfig.AppId, AppConfig.AppSecret, string.Empty, string.Empty); btnExit.Visible = _showExitButton; if (_firstRun) { pnlConnectionSettingsConnected.Visible = false; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = true; pnlNoNetwork.Visible = false; return; } pnlConnectionSettingsConnected.Visible = false; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = false; pnlNoNetwork.Visible = false; pnlLoading.Visible = true; lblLoadingMessage.Text = "Checking for connection"; bool connected = false; bool noNetwork = false; await Task.Run(async() => { System.Threading.Thread.Sleep(1000); //check network state if (!NetworkHelper.HasInternetConnection("https://google.com")) { connected = false; noNetwork = true; } else { //we have a network connection so verify we can connect to John Deere using (IUnitOfWorkDataProvider dp = AppStorage.GetUnitOfWorkDataProvider()) { var accessToken = dp.Settings.GetAsString(SettingKeyType.JDAccessToken); var refreshToken = dp.Settings.GetAsString(SettingKeyType.JDRefreshToken); var deereCredentialDate = dp.Settings.GetLastJohnDeereLoginDateTime(); var accessTokenExpires = dp.Settings.GetAccessTokenExpiresUTC(); //if we have an access token and refresh token and we last logged in within the last 360 days //we should have at a minimum a valid refresh token if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(refreshToken) && (deereCredentialDate.HasValue && deereCredentialDate.Value.AddDays(360) >= DateTime.UtcNow)) { try { remoteDataRepository.SetAuthData(accessToken, refreshToken); _currentUserId = await remoteDataRepository.TestConnection(); if (_currentUserId != string.Empty) { connected = true; } } catch (Exception exc) { Logger.Log(exc); connected = false; } } } } }); pnlLoading.Visible = false; if (noNetwork == false) { pnlConnectionSettingsConnected.Visible = connected; pnlConnectionSettingsLinkAccount.Visible = !connected; pnlConnectionSettingsVerifyCode.Visible = false; pnlNoNetwork.Visible = false; if (connected) { await showPermissionButtonIfNeeded(); } } else { pnlConnectionSettingsConnected.Visible = false; pnlConnectionSettingsLinkAccount.Visible = false; pnlConnectionSettingsVerifyCode.Visible = false; pnlNoNetwork.Visible = true; } _loading = false; } }