private void cmdOK_Click(object sender, RoutedEventArgs e) { try { var hash = PNEncryptor.GetHashString(txtEnterPwrd.Password.Trim()); var hashCheck = (m_Mode == PasswordDlgMode.DeleteMain || m_Mode == PasswordDlgMode.LoginMain) ? PNStatic.Settings.Protection.PasswordString : m_Hash; if (hash != null) { if (hash != hashCheck) { var message = PNLang.Instance.GetMessageText("pwrd_not_match", "Invalid password"); PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Error); txtEnterPwrd.Focus(); txtEnterPwrd.SelectAll(); return; } } if (m_Mode == PasswordDlgMode.DeleteMain || m_Mode == PasswordDlgMode.DeleteGroup || m_Mode == PasswordDlgMode.DeleteNote) { if (PasswordDeleted != null) { PasswordDeleted(this, new EventArgs()); } } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex); } }
private void cmdOK_Click(object sender, RoutedEventArgs e) { try { if (txtEnterPwrd.Password != txtConfirmPwrd.Password) { var message = PNLang.Instance.GetMessageText("pwrd_not_identical", "Both password strings should be identical. Please, check the spelling."); PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); txtEnterPwrd.Focus(); txtEnterPwrd.SelectAll(); return; } string hash = PNEncryptor.GetHashString(txtEnterPwrd.Password.Trim()); if (hash != null) { if (PasswordChanged != null) { PasswordChanged(this, new PasswordChangedEventArgs(hash)); } } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex); } }
private void DlgSmtp_Loaded(object sender, RoutedEventArgs e) { try { PNLang.Instance.ApplyControlLanguage(this); if (_Mode == AddEditMode.Edit) { Title = PNLang.Instance.GetCaptionText("smtp_edit", "Edit SMTP client"); txtSmtpHost.Text = _Client.HostName; txtSmtpAddress.Text = _Client.SenderAddress; txtSmtpDisplayName.Text = _Client.DisplayName; txtSmtpPort.Text = _Client.Port.ToString(CultureInfo.InvariantCulture); using (var encryptor = new PNEncryptor(PNKeys.ENC_KEY)) { txtSmtpPassword.Password = encryptor.DecryptString(_Client.Password); } cmdOK.IsEnabled = true; } else { Title = PNLang.Instance.GetCaptionText("smtp_new", "New SMTP client"); } txtSmtpHost.SelectAll(); txtSmtpHost.Focus(); } catch (Exception ex) { PNStatic.LogException(ex); } }
private void cmdOK_Click(object sender, RoutedEventArgs e) { try { var hostNameType = Uri.CheckHostName(txtSmtpHost.Text.Trim()); if (hostNameType == UriHostNameType.Unknown) { PNMessageBox.Show(PNLang.Instance.GetMessageText("invalid_host", "Invalid host name"), PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); txtSmtpHost.SelectAll(); txtSmtpHost.Focus(); return; } var rg = new Regex(PNStrings.MAIL_PATTERN, RegexOptions.IgnoreCase); var match = rg.Match(txtSmtpAddress.Text.Trim()); if (!match.Success) { PNMessageBox.Show(PNLang.Instance.GetMessageText("invalid_email", "Invalid e-mail address"), PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); txtSmtpAddress.SelectAll(); txtSmtpAddress.Focus(); return; } if (txtSmtpPort.Text.Trim().StartsWith("0") || Convert.ToInt32(txtSmtpPort.Text.Trim()) > 65535) { PNMessageBox.Show(PNLang.Instance.GetMessageText("invalid_port", "Invalid port number"), PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); txtSmtpPort.SelectAll(); txtSmtpPort.Focus(); return; } _Client.HostName = txtSmtpHost.Text.Trim(); _Client.SenderAddress = txtSmtpAddress.Text.Trim(); using (var encryptor = new PNEncryptor(PNKeys.ENC_KEY)) { _Client.Password = encryptor.EncryptString(txtSmtpPassword.Password); } _Client.Port = Convert.ToInt32(txtSmtpPort.Text.Trim()); _Client.DisplayName = txtSmtpDisplayName.Text.Trim().Length > 0 ? txtSmtpDisplayName.Text.Trim() : _Client.SenderAddress; if (SmtpChanged != null) { var ev = new SmtpChangedEventArgs(_Client, _Mode); SmtpChanged(this, ev); if (!ev.Accepted) { txtSmtpAddress.SelectAll(); txtSmtpAddress.Focus(); return; } } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex); } }
private void cmdOK_Click(object sender, RoutedEventArgs e) { try { using (var enc = new PNEncryptor(txtKey.Text.Trim())) { _Note.Dialog.Edit.Text = _Mode == ScrambleMode.Scramble ? enc.EncryptStringWithTrim(_Note.Dialog.Edit.Text.Trim()) : enc.DecryptStringWithTrim(_Note.Dialog.Edit.Text); } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex, false); PNMessageBox.Show(this, PNLang.Instance.GetMessageText("pwrd_not_match", "Invalid password"), PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Error); } }
internal static void LoadNoteFile(RichTextBox edit, string originalPath) { try { if (PNStatic.Settings.Protection.PasswordString.Length == 0 || !PNStatic.Settings.Protection.StoreAsEncrypted) { edit.LoadFile(originalPath, RichTextBoxStreamType.RichText); } else { if (originalPath != null) { var tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(originalPath)); File.Copy(originalPath, tempPath, true); using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.DecryptTextFile(tempPath); } edit.LoadFile(tempPath, RichTextBoxStreamType.RichText); File.Delete(tempPath); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void LoadNoteFile(System.Windows.Controls.RichTextBox edit, string originalPath) { try { if (PNStatic.Settings.Protection.PasswordString.Length == 0 || !PNStatic.Settings.Protection.StoreAsEncrypted) { var textRange = new TextRange(edit.Document.ContentStart, edit.Document.ContentEnd); using (var fileStream = new FileStream(originalPath, FileMode.OpenOrCreate)) { textRange.Load(fileStream, DataFormats.Rtf); } } else { if (originalPath != null) { var tempPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(originalPath)); File.Copy(originalPath, tempPath, true); using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.DecryptTextFile(tempPath); } var textRange = new TextRange(edit.Document.ContentStart, edit.Document.ContentEnd); using (var fileStream = new FileStream(tempPath, FileMode.OpenOrCreate)) { textRange.Load(fileStream, DataFormats.Rtf); } File.Delete(tempPath); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteFile(RichTextBox edit, string path) { try { edit.SaveFile(path, RichTextBoxStreamType.RichText); if (PNStatic.Settings.Protection.PasswordString.Length > 0 && PNStatic.Settings.Protection.StoreAsEncrypted) { using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.EncryptTextFile(path); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
private void sendMail() { try { Cursor = Cursors.Wait; string password; using (var encryptor = new PNEncryptor(PNKeys.ENC_KEY)) { password = encryptor.DecryptString(_Client.Password); } var smtp = new SmtpClient(_Client.HostName, _Client.Port) { EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(_Client.SenderAddress, password), Timeout = 20000 }; using ( var message = new MailMessage { Body = txtSmtpBody.Text.Trim(), Subject = txtSmtpSubject.Text.Trim() }) { message.From = new MailAddress(_Client.SenderAddress, _Client.DisplayName); var recipients = txtSmtpRecipients.Text.Trim() .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var ma in recipients.Select(r => resolveName(r.Trim())).Where(ma => ma != null)) { message.To.Add(ma); } if (_Attachment != null) { var ext = ""; var extension = Path.GetExtension(_Attachment.First()); if (extension != null) { ext = extension.ToUpper(); } var mt = ext.EndsWith("PNOTE") ? MediaTypeNames.Application.Rtf : (ext.EndsWith("ZIP") ? MediaTypeNames.Application.Zip : MediaTypeNames.Application.Octet); foreach (var s in _Attachment) { message.Attachments.Add(new Attachment(s, mt)); } } var attempts = 0; while (attempts < 5) { try { smtp.Send(message); break; } catch (SmtpException smtex) { if (smtex.Message.Contains("The operation has timed out")) { PNStatic.LogException(smtex, false); attempts++; } else { PNStatic.LogException(smtex, false); var sb = new StringBuilder(PNLang.Instance.GetMessageText("send_error_1", "An error occurred during note(s) sending.")); sb.AppendLine(); sb.Append(PNLang.Instance.GetMessageText("send_error_2", "Please, refer to log file for details.")); var baloon = new Baloon(BaloonMode.Error) {BaloonText = sb.ToString()}; PNStatic.FormMain.ntfPN.ShowCustomBalloon(baloon, PopupAnimation.Slide, 10000); return; } } } } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex); } finally { Cursor = Cursors.Arrow; } }
private void receiveNote(string data) { try { var temp = data.Split(PNStrings.END_OF_ADDRESS); var receivedFrom = PNStatic.Contacts.ContactNameByComputerName(temp[0]); var addresses = Dns.GetHostAddresses(temp[0]); // because we are on intranet, sender's ip which is equal to ourself ip is most probably ip of our computer var recIp = (addresses.Any(ip => ip.Equals(PNSingleton.Instance.IpAddress))) ? PNSingleton.Instance.IpAddress : addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork); var sb = new StringBuilder(); _ReceivedNotes = new List<string>(); var rawData = temp[1].Split(PNStrings.END_OF_NOTE); //rawData[rawData.Length - 1] = rawData[rawData.Length - 1].Substring(0, rawData[rawData.Length - 1].IndexOf(PNStrings.END_OF_FILE)); for (var i = 0; i < rawData.Length - 1; i++) { temp = rawData[i].Split(PNStrings.END_OF_TEXT); var nc = new NoteConverter(); var note = (PNote)nc.ConvertFromString(temp[1]); if (note == null) continue; note.ID = DateTime.Now.ToString("yyMMddHHmmssfff"); //note.NoteLocation = new Point(0, 0); note.GroupID = (int)SpecialGroups.Incoming; note.PrevGroupID = note.GroupID; note.SentReceived = SendReceiveStatus.Received; note.DateReceived = DateTime.Now; note.ReceivedFrom = receivedFrom; note.ReceivedIp = recIp != null ? recIp.ToString() : ""; note.NoteLocation = new Point( (Screen.GetWorkingArea(new System.Drawing.Point((int)Left, (int)Top)).Width - note.NoteSize.Width) / 2, (Screen.GetWorkingArea(new System.Drawing.Point((int)Left, (int)Top)).Height - note.NoteSize.Height) / 2); if (PNStatic.Settings.Network.ReceivedOnTop) { note.Topmost = true; } _ReceivedNotes.Add(note.ID); sb.Append(note.Name); sb.Append(";"); //sb.AppendLine(); if (!PNStatic.Settings.Network.ShowAfterArrive) { note.Visible = false; } var path = Path.Combine(PNPaths.Instance.DataDir, note.ID) + PNStrings.NOTE_EXTENSION; using (var sw = new StreamWriter(path, false)) { sw.Write(temp[0]); } if (PNStatic.Settings.Protection.PasswordString.Length > 0 && PNStatic.Settings.Protection.StoreAsEncrypted) { using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.EncryptTextFile(path); } } if (note.Visible) { note.Dialog = new WndNote(note, note.ID, NewNoteMode.Identificator); note.Dialog.Show(); } PNStatic.Notes.Add(note); if (NewNoteCreated != null) { NewNoteCreated(this, new NewNoteCreatedEventArgs(note)); } subscribeToNoteEvents(note); // save received note PNNotesOperations.SaveNewNote(note); PNNotesOperations.SaveNoteTags(note); if (note.Schedule != null) { PNNotesOperations.SaveNoteSchedule(note); } note.Changed = false; } if (!PNStatic.Settings.Network.NoSoundOnArrive) { PNSound.PlayMailSound(); } if (!PNStatic.Settings.Network.NoNotificationOnArrive) { var sbb = new StringBuilder(PNLang.Instance.GetCaptionText("received", "New notes received")); sbb.Append(": "); sbb.Append(sb); if (sbb.Length > 1) sbb.Length -= 1; sbb.AppendLine(); sbb.Append(PNLang.Instance.GetMessageText("sender", "Sender:")); sbb.Append(" "); sbb.Append(receivedFrom); var baloon = new Baloon(BaloonMode.NoteReceived); if (PNStatic.Settings.Network.ShowReceivedOnClick || PNStatic.Settings.Network.ShowIncomingOnClick) { baloon.BaloonLink = sbb.ToString(); } else { baloon.BaloonText = sbb.ToString(); } baloon.BaloonLinkClicked += baloon_BaloonLinkClicked; ntfPN.ShowCustomBalloon(baloon, PopupAnimation.Slide, 10000); } if (NotesReceived != null) { NotesReceived(this, new EventArgs()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static List <Tuple <string, string> > GetGoogleContacts() { var list = new List <Tuple <string, string> >(); try { using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var update = false; using (var t = oData.FillDataTable("SELECT * FROM SERVICES WHERE APP_NAME = 'PNContactsLoader'")) { if (t.Rows.Count == 0) { return(list); } var row = t.Rows[0]; using (var enc = new PNEncryptor(PNKeys.ENC_KEY)) { var gc = new GContacts(Convert.ToString(row["CLIENT_ID"]), enc.DecryptString(Convert.ToString(row["CLIENT_SECRET"])), Convert.ToString(row["APP_NAME"])); if (!PNData.IsDBNull(row["ACCESS_TOKEN"])) { gc.AccessToken = enc.DecryptString(Convert.ToString(row["ACCESS_TOKEN"])); } if (!PNData.IsDBNull(row["REFRESH_TOKEN"])) { gc.RefreshToken = enc.DecryptString(Convert.ToString(row["REFRESH_TOKEN"])); } if (!PNData.IsDBNull(row["TOKEN_EXPIRY"])) { var expDate = Convert.ToDateTime(Convert.ToString(row["TOKEN_EXPIRY"])); if (expDate <= DateTime.Now && !string.IsNullOrWhiteSpace(gc.RefreshToken) && !string.IsNullOrWhiteSpace(gc.AccessToken)) { if (!string.IsNullOrWhiteSpace(gc.RefreshToken)) { update = gc.RefreshAccessToken(); } if (!update) { update = gc.Authenticate(); } if (!update) { return(list); } } } if (string.IsNullOrWhiteSpace(gc.AccessToken)) { update = gc.Authenticate(); } while (true) { try { list = gc.GetContacts(); if (update) { var sb = new StringBuilder("UPDATE SERVICES SET ACCESS_TOKEN = '"); sb.Append(enc.EncryptString(gc.AccessToken)); sb.Append("', REFRESH_TOKEN = '"); sb.Append(enc.EncryptString(gc.RefreshToken)); sb.Append("', TOKEN_EXPIRY = '"); sb.Append(gc.TokenExpiry.ToString("dd MMM yyyy HH:mm:ss")); sb.Append("' WHERE APP_NAME = 'PNContactsLoader'"); oData.Execute(sb.ToString()); } break; } catch (PNContactsException pnex) { if (pnex.AdditionalInfo.ToUpper().Contains("UNAUTHORIZED")) { if (!string.IsNullOrWhiteSpace(gc.RefreshToken)) { update = gc.RefreshAccessToken(); } if (update) { continue; } update = gc.Authenticate(); if (update) { continue; } PNStatic.LogException(pnex); break; } PNStatic.LogException(pnex); break; } catch (Exception ex) { PNStatic.LogException(ex); break; } } } } } return(list); } catch (Exception ex) { PNStatic.LogException(ex); return(list); } }
internal static void DecryptAllNotes(string passwordString) { try { var files = new DirectoryInfo(PNPaths.Instance.DataDir).GetFiles("*" + PNStrings.NOTE_EXTENSION); using (var pne = new PNEncryptor(passwordString)) { foreach (var f in files) { pne.DecryptTextFile(f.FullName); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal bool SendNotesViaNetwork(List<PNote> notes, PNContact cn) { try { var sb = new StringBuilder(); foreach (var note in notes) { if (PNStatic.Settings.Protection.PromptForPassword) if (!PNNotesOperations.LogIntoNoteOrGroup(note)) continue; string text, tempPath = ""; var newNote = false; var nc = new NoteConverter(); // decrypt note file to temp file if note is encrypted var path = Path.Combine(PNPaths.Instance.DataDir, note.ID); path += PNStrings.NOTE_EXTENSION; // save note first if (note.Dialog != null && note.Changed) { if (note.FromDB) { if (PNStatic.Settings.Network.SaveBeforeSending) { note.Dialog.ApplySaveNote(false); } } else { path = Path.Combine(Path.GetTempPath(), note.ID); path += PNStrings.NOTE_EXTENSION; note.Dialog.Edit.SaveFile(path, RichTextBoxStreamType.RichText); newNote = true; } } if (PNStatic.Settings.Protection.PasswordString.Length > 0 && PNStatic.Settings.Protection.StoreAsEncrypted && !newNote) { var fileName = Path.GetFileName(path); if (string.IsNullOrEmpty(fileName)) continue; tempPath = Path.Combine(Path.GetTempPath(), fileName); File.Copy(path, tempPath, true); using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.DecryptTextFile(tempPath); } path = tempPath; } // read note file content using (var sr = new StreamReader(path)) { text = sr.ReadToEnd(); } // remove temp file if (tempPath != "") { File.Delete(tempPath); } //remove temporary file created for new note if (newNote) { File.Delete(path); } sb.Append(text); sb.Append(PNStrings.END_OF_TEXT); sb.Append(nc.ConvertToString(note)); sb.Append(PNStrings.END_OF_NOTE); } if (sb.Length <= 0) return false; string ipAddress; if (!cn.UseComputerName || !string.IsNullOrEmpty(cn.IpAddress)) { ipAddress = cn.IpAddress; } else { IPHostEntry ipHostInfo; try { ipHostInfo = Dns.GetHostEntry(cn.ComputerName); } catch (SocketException) { var msg = PNLang.Instance.GetMessageText("host_unknown", "Computer %PLACEHOLDER1% cannot be found on network"); msg = msg.Replace(PNStrings.PLACEHOLDER1, cn.ComputerName); PNMessageBox.Show(msg, PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Error); return false; } var address = ipHostInfo.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork); if (address == null) return false; ipAddress = address.ToString(); } //check whether contact's computer is on network if (PNConnections.CheckContactConnection(ipAddress) == ContactConnection.Disconnected) { var msg = PNLang.Instance.GetMessageText("contact_disconnected", "Computer of contact %PLACEHOLDER1% is not connected to network"); PNMessageBox.Show(msg.Replace("%PLACEHOLDER1%", cn.Name), PNStrings.PROG_NAME, MessageBoxButton.OK); return false; } var clientRunner = new PNWCFClientRunner(); clientRunner.PNDataError += WCFClient_PNDataError; clientRunner.NotesSent += WCFClient_NotesSent; if (ipAddress == PNSingleton.Instance.IpAddress.ToString()) //we are on intranet, so most probably this is the same computer { Task.Factory.StartNew(() => clientRunner.SendNotes(cn.Name, PNSingleton.Instance.IpAddress.ToString(), sb.ToString(), PNStatic.Settings.Network.ExchangePort.ToString(CultureInfo.InvariantCulture), notes)); //var t = new Thread(() => clientRunner.SendNotes(cn.Name, ipAddress.ToString(), sb.ToString(), PNStatic.Settings.Network.ExchangePort.ToString(CultureInfo.InvariantCulture), notes)); //t.Start(); return true; } else { return clientRunner.SendNotes(cn.Name, ipAddress, sb.ToString(), PNStatic.Settings.Network.ExchangePort.ToString(CultureInfo.InvariantCulture), notes); } } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
private void restoreFromFullBackup() { var hash = ""; try { var ofd = new OpenFileDialog { Title = PNLang.Instance.GetCaptionText("resture_full_backup", "Restore from full backup") }; var sb = new StringBuilder(); sb.Append(PNLang.Instance.GetCaptionText("full_backup_filter", "PNotes full backup files")); sb.Append(" ("); sb.Append("*" + PNStrings.FULL_BACK_EXTENSION); sb.Append(")|"); sb.Append("*" + PNStrings.FULL_BACK_EXTENSION); ofd.Filter = sb.ToString(); ofd.Multiselect = false; if (!ofd.ShowDialog(this).Value) { return; } var packageFile = ofd.FileName; var message = PNLang.Instance.GetMessageText("full_restore_warning", "ATTENTION! All existing notes will ber removed and replaced by notes from backup copy. Continue?"); if ( PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.YesNo, MessageBoxImage.Exclamation) == MessageBoxResult.No) { return; } // store existing files for possible crash if (Directory.Exists(PNPaths.Instance.TempDir)) { Directory.Delete(PNPaths.Instance.TempDir, true); } Directory.CreateDirectory(PNPaths.Instance.TempDir); var di = new DirectoryInfo(PNPaths.Instance.DataDir); var files = di.GetFiles("*" + PNStrings.NOTE_EXTENSION); string path; foreach (var f in files) { path = Path.Combine(PNPaths.Instance.TempDir, f.Name); File.Move(f.FullName, path); } var fi = new FileInfo(PNPaths.Instance.DBPath); path = Path.Combine(PNPaths.Instance.TempDir, fi.Name); File.Move(fi.FullName, path); // start reading package using (var package = Package.Open(packageFile, FileMode.Open, FileAccess.Read)) { // build parameters file URI var uriData = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), new Uri("data.xml", UriKind.Relative)); // get parameters file var documentPart = package.GetPart(uriData); // load XDocument var xdoc = XDocument.Load(documentPart.GetStream(), LoadOptions.None); if (xdoc.Root != null) { var xhash = xdoc.Root.Element("hash"); if (xhash != null) { hash = xhash.Value; } } foreach (var prs in package.GetRelationships()) { var noteExtracted = false; var uriDocumentTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), prs.TargetUri); documentPart = package.GetPart(uriDocumentTarget); if (prs.RelationshipType.EndsWith(PNStrings.NOTE_EXTENSION)) { path = Path.Combine(PNPaths.Instance.DataDir, prs.RelationshipType); noteExtracted = true; } else { path = Path.Combine(PNPaths.Instance.DataDir, prs.RelationshipType); } extractPackagePart(documentPart.GetStream(), path); if (!noteExtracted) continue; // check whether note has been added to backup as encrypted if (hash != "") { // decrypt note using (var pne = new PNEncryptor(hash)) { pne.DecryptTextFile(path); } } // check whether note should be encrypted if (!PNStatic.Settings.Protection.StoreAsEncrypted) continue; // encrypt note using (var pne = new PNEncryptor(PNStatic.Settings.Protection.PasswordString)) { pne.EncryptTextFile(path); } } } reloadNotes(); message = PNLang.Instance.GetMessageText("full_restore_complete", "Restoration from full backup copy completed successfully"); PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { PNStatic.LogException(ex); if (Directory.Exists(PNPaths.Instance.TempDir)) { getFilesBack(PNPaths.Instance.TempDir); } } finally { if (Directory.Exists(PNPaths.Instance.TempDir)) { Directory.Delete(PNPaths.Instance.TempDir, true); } } }
internal static List<Tuple<string, string>> GetGoogleContacts() { var list = new List<Tuple<string, string>>(); try { using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var update = false; using (var t = oData.FillDataTable("SELECT * FROM SERVICES WHERE APP_NAME = 'PNContactsLoader'")) { if (t.Rows.Count == 0) return list; var row = t.Rows[0]; using (var enc = new PNEncryptor(PNKeys.ENC_KEY)) { var gc = new GContacts(Convert.ToString(row["CLIENT_ID"]), enc.DecryptString(Convert.ToString(row["CLIENT_SECRET"])), Convert.ToString(row["APP_NAME"])); if (!PNData.IsDBNull(row["ACCESS_TOKEN"])) gc.AccessToken = enc.DecryptString(Convert.ToString(row["ACCESS_TOKEN"])); if (!PNData.IsDBNull(row["REFRESH_TOKEN"])) gc.RefreshToken = enc.DecryptString(Convert.ToString(row["REFRESH_TOKEN"])); if (!PNData.IsDBNull(row["TOKEN_EXPIRY"])) { var expDate = Convert.ToDateTime(Convert.ToString(row["TOKEN_EXPIRY"])); if (expDate <= DateTime.Now && !string.IsNullOrWhiteSpace(gc.RefreshToken) && !string.IsNullOrWhiteSpace(gc.AccessToken)) { if (!string.IsNullOrWhiteSpace(gc.RefreshToken)) update = gc.RefreshAccessToken(); if (!update) update = gc.Authenticate(); if (!update) return list; } } if (string.IsNullOrWhiteSpace(gc.AccessToken)) update = gc.Authenticate(); while (true) { try { list = gc.GetContacts(); if (update) { var sb = new StringBuilder("UPDATE SERVICES SET ACCESS_TOKEN = '"); sb.Append(enc.EncryptString(gc.AccessToken)); sb.Append("', REFRESH_TOKEN = '"); sb.Append(enc.EncryptString(gc.RefreshToken)); sb.Append("', TOKEN_EXPIRY = '"); sb.Append(gc.TokenExpiry.ToString("dd MMM yyyy HH:mm:ss")); sb.Append("' WHERE APP_NAME = 'PNContactsLoader'"); oData.Execute(sb.ToString()); } break; } catch (PNContactsException pnex) { if (pnex.AdditionalInfo.ToUpper().Contains("UNAUTHORIZED")) { if (!string.IsNullOrWhiteSpace(gc.RefreshToken)) update = gc.RefreshAccessToken(); if (update) continue; update = gc.Authenticate(); if (update) continue; PNStatic.LogException(pnex); break; } PNStatic.LogException(pnex); break; } catch (Exception ex) { PNStatic.LogException(ex); break; } } } } } return list; } catch (Exception ex) { PNStatic.LogException(ex); return list; } }
private void sendMail() { try { Cursor = Cursors.Wait; string password; using (var encryptor = new PNEncryptor(PNKeys.ENC_KEY)) { password = encryptor.DecryptString(_Client.Password); } var smtp = new SmtpClient(_Client.HostName, _Client.Port) { EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(_Client.SenderAddress, password), Timeout = 20000 }; using ( var message = new MailMessage { Body = txtSmtpBody.Text.Trim(), Subject = txtSmtpSubject.Text.Trim() }) { message.From = new MailAddress(_Client.SenderAddress, _Client.DisplayName); var recipients = txtSmtpRecipients.Text.Trim() .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var ma in recipients.Select(r => resolveName(r.Trim())).Where(ma => ma != null)) { message.To.Add(ma); } if (_Attachment != null) { var ext = ""; var extension = Path.GetExtension(_Attachment.First()); if (extension != null) { ext = extension.ToUpper(); } var mt = ext.EndsWith("PNOTE") ? MediaTypeNames.Application.Rtf : (ext.EndsWith("ZIP") ? MediaTypeNames.Application.Zip : MediaTypeNames.Application.Octet); foreach (var s in _Attachment) { message.Attachments.Add(new Attachment(s, mt)); } } var attempts = 0; while (attempts < 5) { try { smtp.Send(message); break; } catch (SmtpException smtex) { if (smtex.Message.Contains("The operation has timed out")) { PNStatic.LogException(smtex, false); attempts++; } else { PNStatic.LogException(smtex, false); var sb = new StringBuilder(PNLang.Instance.GetMessageText("send_error_1", "An error occurred during note(s) sending.")); sb.AppendLine(); sb.Append(PNLang.Instance.GetMessageText("send_error_2", "Please, refer to log file for details.")); var baloon = new Baloon(BaloonMode.Error) { BaloonText = sb.ToString() }; PNStatic.FormMain.ntfPN.ShowCustomBalloon(baloon, PopupAnimation.Slide, 10000); return; } } } } DialogResult = true; } catch (Exception ex) { PNStatic.LogException(ex); } finally { Cursor = Cursors.Arrow; } }