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);
                }
            }
        }
示例#2
0
        /// <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);
                }
            }
        }
 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 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>
        /// 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);
        }
示例#6
0
        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();
            }
        }
        /// <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++;
            }
        }
        /// <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;
            }
        }
示例#9
0
        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;
        }
示例#10
0
        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();
            }
        }