Beispiel #1
0
        public App()
        {
            UnhandledException += App_UnhandledException;

            InitializeComponent();

            RootFrame = new TransitionFrame();
            RootFrame.Navigated += RootFrame_Navigated;
            RootFrame.Obscured += RootFrame_Obscured;
            RootFrame.Unobscured += RootFrame_Unobscured;

            Settings = new AppSettings(IsolatedStorageSettings.ApplicationSettings);
            Storage = new AppStorage(IsolatedStorageSettings.ApplicationSettings);

            if (Storage.Signals == null)
            {
                Storage.Signals = new SignalCollection
                {
                    new MorseCodeSignal("SOS", "SOS", 3000),
                    new FlashSignal("Beacon", 100, 3000)
                };
            }

            if (Settings.DisableApplicationIdleDetection)
            {
                PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            }
        }
Beispiel #2
0
        private async void ExportAuths(object sender, RoutedEventArgs e)
        {
            Button Btn = ( Button )sender;

            Btn.IsEnabled = false;

            string Tag = ( string )Btn.Tag;

            IStorageFile ISF = await AppStorage.SaveFileAsync("wenku10 Auth", new List <string>() { ".xml" }, Tag);

            if (ISF == null)
            {
                Btn.IsEnabled = true;
                return;
            }

            try
            {
                using (Stream s = await ISF.OpenStreamForWriteAsync())
                {
                    await global::GR.Resources.Shared.Storage.GetStream(
                        Tag == "Keys"
                        ?AESMgr.SettingsFile
                        : TokMgr.SettingsFile
                        ).CopyToAsync(s);

                    await s.FlushAsync();
                }
            }
            catch (Exception)
            {
                // Failed to save file
            }

            Btn.IsEnabled = true;
        }
        private void CalcSavesAndSkills()
        {
            int i = 0;

            // Calculation of Saving Throws
            foreach (RelativePanel rp in rpSaves.Children.OfType <RelativePanel>())
            {
                if ((bool)rp.Children.OfType <CheckBox>().First().IsChecked)
                {
                    rp.Children.OfType <TextBox>().First().Text = (AppStorage.SelectedCharacter.Abimod[i] + AppStorage.GetProfiency()).ToString();
                    i++;
                }
                else
                {
                    rp.Children.OfType <TextBox>().First().Text = AppStorage.SelectedCharacter.Abimod[i].ToString();
                    i++;
                }
            }

            // Calculation of Skills
            foreach (RelativePanel rp in rpSkills.Children.OfType <RelativePanel>())
            {
                if ((bool)rp.Children.OfType <CheckBox>().First().IsChecked)
                {
                    rp.Children.OfType <TextBox>().First().Text = (GetAppropriateMod(rp.Children.OfType <TextBlock>().First()) + AppStorage.GetProfiency()).ToString();
                }
                else
                {
                    rp.Children.OfType <TextBox>().First().Text = GetAppropriateMod(rp.Children.OfType <TextBlock>().First()).ToString();
                }
            }
        }
        /// <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);
        }
 public MainPage()
 {
     this.InitializeComponent();
     InitializeCharacters();
     AppStorage.InitializeStorage();
 }
 public AppController(IConfiguration config)
 {
     _storage = new AppStorage(config);
 }
        private static async Task LogLineAsync(string line, LogLevels level = LogLevels.Debug)
        {
            if (!Enabled)
            {
                return;
            }

            if (!_initialized)
            {
                await Initialize();
            }

            if (_debuggerAttached)
            {
                Debug.WriteLine(line);
            }

            //don't write if not meeting minimum log level
            if (_currentLevel > level)
            {
                return;
            }

            if (!await threadblock.WaitAsync(100))
            {
                lock ( _deferredEntries )
                {
                    _deferredEntries.Add(line);
                }
                return;
            }
            try
            {
                List <string> list = null;
                lock ( _deferredEntries )
                {
                    if (_deferredEntries.Count > 0)
                    {
                        list = _deferredEntries.ToList();
                        _deferredEntries.Clear();
                    }
                }

                if (list != null)
                {
                    foreach (var l in list)
                    {
                        await AppStorage.AppendToFileAsync(_logFile, l);
                    }
                }

                await AppStorage.AppendToFileAsync(_logFile, line);
            }
            catch (Exception e)
            {
                throw new OperationCanceledException("Logging failed", e);
            }
            finally
            {
                threadblock.Release();
            }
        }
Beispiel #8
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();
            }
        }
        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>
        /// 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;
            }
        }
Beispiel #11
0
 public ForumController()
 {
     Storage = new AppStorage();
 }
Beispiel #12
0
        private void OpenKnxUiPrject()
        {
            Cursor = Cursors.WaitCursor;

            if (Saved == false)
            {
                var result = MessageBox.Show(ResourceMng.GetString("Message7"), ResourceMng.GetString("Message4"), MessageBoxButtons.YesNoCancel,
                                             MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

                if (DialogResult.Yes == result)
                {
                    SaveKnxUiProject(ProjectFile);
                    Cursor = Cursors.Default;
                    return;
                }
                else if (DialogResult.No == result)
                {
                }
                else if (DialogResult.Cancel == result)
                {
                    Cursor = Cursors.Default;
                    return;
                }
            }

            try
            {
                using (var ofd = new OpenFileDialog())
                {
                    ofd.InitialDirectory = MyCache.DefaultKnxProjectFolder;
                    ofd.Filter           = KnxFilter;
                    ofd.FilterIndex      = 1;
                    ofd.DefaultExt       = MyConst.KnxUiEditorFileExt;
                    ofd.RestoreDirectory = true;

                    if (ofd.ShowDialog(this) == DialogResult.OK)
                    {
                        // 新建项目文件夹
                        CreateProjectFolder();
                        var projectFile = ofd.FileName;
                        Debug.WriteLine(projectFile);
                        Debug.WriteLine(MyCache.ProjectFolder);

                        ZipHelper.UnZipDir(projectFile, MyCache.ProjectFolder, MyConst.MyKey);

                        var app = AppStorage.Load();

                        if (app != null)
                        {
                            // 导入所有节点
                            AppNode appNode = FrmMainHelp.ImportNode(app);
                            SetProjectOutline(appNode);

                            ProjectFile = ofd.FileName;
                            ShowProjectFile(ProjectFile);

                            //
                            //ToolBarStatus status = new ToolBarStatus { collapse = true, expand = true, searchBox = true, importKnx = true };
                            //SetButtonStatus(status);
                            SetToolStripButtonStatus(false);
                            SetToolStripButtonKNXAddrStatus(true);
                            SetToolStripButtonSaveStatus(true);

                            ResetParameter();
                            CreateCommandManager();
                            CloseAllTabPages();

                            Saved = true;
                        }
                        else
                        {
                            throw new ApplicationException(ResourceMng.GetString("Message8"));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = ResourceMng.GetString("Message8");
                MessageBox.Show(errorMsg, ResourceMng.GetString("Message6"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                Log.Error(errorMsg + LogHelper.Format(ex));
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Beispiel #13
0
        public RecordingsPresenter(Recordings view, Subscribe subscribe, ModelFactory modelFactory, AppStorage appStorage)
        {
            _view       = view;
            _subscribe  = subscribe;
            _appStorage = appStorage;

            recorder = new UserActionsRecorder(_subscribe, modelFactory);
            replier  = new Replier();

            Init();
        }
Beispiel #14
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;
        }
 private void SaveCall()
 {
     AppStorage.SaveData();
     navigationService.GoBackAsync();
 }
        /// <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++;
            }
        }
 public ModelFactory(AppStorage appStorage)
 {
     this.appStorage = appStorage;
 }
Beispiel #18
0
        /// <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;
            }
        }