//todo private bool exchangeData(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, string id, Dictionary <string, List <_FieldData> > tablesData) { try { //todo if (!exchangeNotes(dataSrc, dataDest, id, tablesData.FirstOrDefault(td => td.Key == "NOTES"))) { return(false); } if (!exchangeCustomNotesSettings(dataSrc, dataDest, id, tablesData.FirstOrDefault(td => td.Key == "CUSTOM_NOTES_SETTINGS"))) { return(false); } if (!exchangeLinkedNotes(dataSrc, dataDest, id, tablesData.FirstOrDefault(td => td.Key == "LINKED_NOTES"))) { return(false); } if (!exchangeNotesSchedule(dataSrc, dataDest, id, tablesData.FirstOrDefault(td => td.Key == "NOTES_SCHEDULE"))) { return(false); } if (!exchangeNotesTags(dataSrc, dataDest, id, tablesData.FirstOrDefault(td => td.Key == "NOTES_TAGS"))) { return(false); } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
private string saveReplace() { try { var str = cboReplace.Text.Trim(); if (cboReplace.Items.Contains(str)) { return(str); } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder(); sb.Append("UPDATE FIND_REPLACE SET REPLACE = '"); sb.Append(str); foreach (string s in cboReplace.Items) { sb.Append(","); sb.Append(s); } sb.Append("'"); oData.Execute(sb.ToString()); cboReplace.Items.Insert(0, str); } return(str); } catch (Exception ex) { PNStatic.LogException(ex); return(""); } }
private bool executeTransaction(SQLiteDataObject oData, string sqlQuery) { var inTrans = false; try { inTrans = oData.BeginTransaction(); if (!inTrans) { return(false); } oData.ExecuteInTransaction(sqlQuery); oData.CommitTransaction(); inTrans = false; return(true); } catch (Exception ex) { if (inTrans) { oData.RollbackTransaction(); } PNStatic.LogException(ex); return(false); } }
private void DlgSearchReplace_Loaded(object sender, RoutedEventArgs e) { try { PNLang.Instance.ApplyControlLanguage(this); if (_Mode == SearchReplace.Search) { Title = PNLang.Instance.GetCaptionText("dlg_search_find", "Find"); lblReplace.Visibility = cboReplace.Visibility = cmdReplace.Visibility = cmdReplaceAll.Visibility = Visibility.Collapsed; } else { Title = PNLang.Instance.GetCaptionText("dlg_search_replace", "Replace"); } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable("SELECT FIND, REPLACE FROM FIND_REPLACE")) { if (t.Rows.Count > 0) { if (!PNData.IsDBNull(t.Rows[0]["FIND"])) { var values = (Convert.ToString(t.Rows[0]["FIND"])).Split(','); foreach (var s in values) { cboFind.Items.Add(s); } } if (!PNData.IsDBNull(t.Rows[0]["REPLACE"])) { var values = (Convert.ToString(t.Rows[0]["REPLACE"])).Split(','); foreach (var s in values) { cboReplace.Items.Add(s); } } } } } cboFind.Text = _Edit.SelectionLength > 0 ? _Edit.SelectedText : PNStatic.FindString; cboReplace.Text = PNStatic.ReplaceString; chkRegExp.IsChecked = PNStatic.SearchMode == SearchMode.RegularExp; cboFind.Focus(); } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveExitFlag(int flag) { try { using (var oData = new SQLiteDataObject(SettingsConnectionString)) { var sqlQuery = "UPDATE CONFIG SET EXIT_FLAG = " + flag.ToString(PNStatic.CultureInvariant); oData.Execute(sqlQuery); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal bool restoreTriggers(string dbPath) { try { var connSrc = "data source = " + dbPath; using (var src = new SQLiteDataObject(connSrc)) { src.Execute(PNStrings.CREATE_TRIGGERS); } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
private List <string> deletedIDs(SQLiteDataObject oData) { var list = new List <string>(); try { using (var t = oData.FillDataTable("SELECT ID FROM NOTES WHERE GROUP_ID = " + (int)SpecialGroups.RecycleBin)) { list.AddRange(from DataRow r in t.Rows select(string) r["ID"]); } return(list); } catch (Exception ex) { PNStatic.LogException(ex); return(list); } }
internal static void CompactDatabases() { try { using (var oData = new SQLiteDataObject(SettingsConnectionString)) { oData.CompactDatabase(); } using (var oData = new SQLiteDataObject(ConnectionString)) { oData.CompactDatabase(); } } catch (Exception ex) { PNStatic.LogException(ex); } }
private void DlgSearchInNotes_Loaded(object sender, RoutedEventArgs e) { try { applyLanguage(); PNStatic.FormMain.LanguageChanged += FormMain_LanguageChanged; PNStatic.FormMain.NoteBooleanChanged += FormMain_NoteBooleanChanged; PNStatic.FormMain.NoteNameChanged += FormMain_NoteNameChanged; PNStatic.FormMain.NoteScheduleChanged += FormMain_NoteScheduleChanged; using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable("SELECT FIND, REPLACE FROM FIND_REPLACE")) { if (t.Rows.Count <= 0) { return; } if (!PNData.IsDBNull(t.Rows[0]["FIND"])) { var values = Convert.ToString(t.Rows[0]["FIND"]).Split(','); foreach (var s in values) { cboFind.Items.Add(s); } } if (!PNData.IsDBNull(t.Rows[0]["REPLACE"])) { var values = Convert.ToString(t.Rows[0]["REPLACE"]).Split(','); foreach (var s in values) { cboReplace.Items.Add(s); } } } } tvwResults.ItemsSource = _FoundItems; setSettings(); cboFind.Focus(); } catch (Exception ex) { PNStatic.LogException(ex); } }
private bool insertToNotesSchedule(SQLiteDataObject dataDest, DataRow r, KeyValuePair <string, List <_FieldData> > tableData) { try { var sb = new StringBuilder(); sb.Append("DELETE FROM NOTES_SCHEDULE WHERE NOTE_ID = '"); sb.Append(r["NOTE_ID"]); sb.Append("'; "); sb.Append(createInsert(r, tableData)); return(executeTransaction(dataDest, sb.ToString())); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
internal static void CheckAndApplyNewMenusOrder(ContextMenu ctm) { try { var sb = new StringBuilder("SELECT COUNT(MENU_NAME) FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(ctm.Name); sb.Append("' AND ORDER_ORIGINAL <> ORDER_NEW"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var obj = oData.GetScalar(sb.ToString()); if (obj != null && !PNData.IsDBNull(obj) && Convert.ToInt32(obj) > 0) RearrangeMenus(ctm); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void CheckAndApplyNewMenusOrder(ContextMenu ctm) { try { var sb = new StringBuilder("SELECT COUNT(MENU_NAME) FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(ctm.Name); sb.Append("' AND ORDER_ORIGINAL <> ORDER_NEW"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var obj = oData.GetScalar(sb.ToString()); if (obj != null && !PNData.IsDBNull(obj) && Convert.ToInt32(obj) > 0) { RearrangeMenus(ctm); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
private bool exchangeCustomNotesSettings(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, string id, KeyValuePair <string, List <_FieldData> > tableData) { try { using (var t1 = dataSrc.FillDataTable("SELECT * FROM CUSTOM_NOTES_SETTINGS WHERE NOTE_ID = '" + id + "'")) { using (var t2 = dataDest.FillDataTable("SELECT * FROM CUSTOM_NOTES_SETTINGS WHERE NOTE_ID = '" + id + "'")) { if (t1.Rows.Count > 0 && t2.Rows.Count > 0) { var d1 = Convert.ToInt64(t1.Rows[0]["UPD_DATE"]); var d2 = Convert.ToInt64(t2.Rows[0]["UPD_DATE"]); if (d1 > d2) { return(insertToCustomNotesSettings(dataDest, t1.Rows[0], tableData)); } if (d2 > d1) { return(insertToCustomNotesSettings(dataSrc, t2.Rows[0], tableData)); } } else if (t1.Rows.Count > 0) { return(insertToCustomNotesSettings(dataDest, t1.Rows[0], tableData)); } else if (t2.Rows.Count > 0) { return(insertToCustomNotesSettings(dataSrc, t2.Rows[0], tableData)); } } } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
//todo private bool exchangeNotes(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, string id, KeyValuePair<string, List<_FieldData>> tableData) { try { using (var t1 = dataSrc.FillDataTable("SELECT * FROM NOTES WHERE ID = '" + id + "'")) { using (var t2 = dataDest.FillDataTable("SELECT * FROM NOTES WHERE ID = '" + id + "'")) { if (t1.Rows.Count > 0 && t2.Rows.Count > 0) { var d1 = Convert.ToInt64(t1.Rows[0]["UPD_DATE"]); var d2 = Convert.ToInt64(t2.Rows[0]["UPD_DATE"]); if (d1 > d2) { return insertToNotes(dataDest, t1.Rows[0], tableData); } if (d2 > d1) { return insertToNotes(dataSrc, t2.Rows[0], tableData); } } else if (t1.Rows.Count > 0) { return insertToNotes(dataDest, t1.Rows[0], tableData); } else if (t2.Rows.Count > 0) { return insertToNotes(dataSrc, t2.Rows[0], tableData); } } } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
private void DlgSearchInNotes_Loaded(object sender, RoutedEventArgs e) { try { applyLanguage(); PNStatic.FormMain.LanguageChanged += FormMain_LanguageChanged; PNStatic.FormMain.NoteBooleanChanged += FormMain_NoteBooleanChanged; PNStatic.FormMain.NoteNameChanged += FormMain_NoteNameChanged; PNStatic.FormMain.NoteScheduleChanged += FormMain_NoteScheduleChanged; using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable("SELECT FIND, REPLACE FROM FIND_REPLACE")) { if (t.Rows.Count <= 0) return; if (!PNData.IsDBNull(t.Rows[0]["FIND"])) { var values = Convert.ToString(t.Rows[0]["FIND"]).Split(','); foreach (var s in values) cboFind.Items.Add(s); } if (!PNData.IsDBNull(t.Rows[0]["REPLACE"])) { var values = Convert.ToString(t.Rows[0]["REPLACE"]).Split(','); foreach (var s in values) cboReplace.Items.Add(s); } } } tvwResults.ItemsSource = _FoundItems; setSettings(); cboFind.Focus(); } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void RearrangeMenus(ContextMenu ctm) { try { var tableList = new List <Tuple <string, string, int> >(); var tempMenus = new List <Control>(); var sb = new StringBuilder("SELECT MENU_NAME, IFNULL(PARENT_NAME, '') AS PARENT_NAME, ORDER_NEW FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(ctm.Name); sb.Append("' ORDER BY ORDER_NEW"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable(sb.ToString())) { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_NEW"]))); tempMenus.AddRange(ctm.Items.Cast <Control>()); ctm.Items.Clear(); foreach ( var tm in tableList.Where(tb => tb.Item2 == "") .Select(tp => tempMenus.FirstOrDefault(m => m.Name == tp.Item1)) .Where(tm => tm != null)) { ctm.Items.Add(tm); addSubitem(tableList, tm); } } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void RearrangeMenus(ContextMenu ctm) { try { var tableList = new List<Tuple<string, string, int>>(); var tempMenus = new List<Control>(); var sb = new StringBuilder("SELECT MENU_NAME, IFNULL(PARENT_NAME, '') AS PARENT_NAME, ORDER_NEW FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(ctm.Name); sb.Append("' ORDER BY ORDER_NEW"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable(sb.ToString())) { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_NEW"]))); tempMenus.AddRange(ctm.Items.Cast<Control>()); ctm.Items.Clear(); foreach ( var tm in tableList.Where(tb => tb.Item2 == "") .Select(tp => tempMenus.FirstOrDefault(m => m.Name == tp.Item1)) .Where(tm => tm != null)) { ctm.Items.Add(tm); addSubitem(tableList, tm); } } } } catch (Exception ex) { PNStatic.LogException(ex); } }
private void clearSearchHistory() { try { var message = PNLang.Instance.GetMessageText("clear_search_history", "Clear search history?"); if (PNMessageBox.Show(message, PNStrings.PROG_NAME, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) { return; } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute("UPDATE FIND_REPLACE SET FIND = NULL, REPLACE = NULL"); cboFind.Items.Clear(); cboReplace.Items.Clear(); cboFind.Text = ""; cboReplace.Text = ""; } } catch (Exception ex) { PNStatic.LogException(ex); } }
private bool exchangeNotesTags(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, string id, KeyValuePair <string, List <_FieldData> > tableData) { try { using (var t1 = dataSrc.FillDataTable("SELECT * FROM NOTES_TAGS WHERE NOTE_ID = '" + id + "'")) { using (var t2 = dataDest.FillDataTable("SELECT * FROM NOTES_TAGS WHERE NOTE_ID = '" + id + "'")) { if (t1.Rows.Count > 0 && t2.Rows.Count > 0) { var t = t1.Clone(); foreach (DataRow r1 in t1.Rows) { if (t.AsEnumerable().All(r => (string)r["TAG"] != (string)r1["TAG"])) { t.Rows.Add(r1.ItemArray); } } foreach (DataRow r2 in t2.Rows) { if (t.AsEnumerable().All(r => (string)r["TAG"] != (string)r2["TAG"])) { t.Rows.Add(r2.ItemArray); } } foreach (DataRow r in t.Rows) { if (!insertToNotesTags(dataDest, r, tableData)) { return(false); } if (!insertToNotesTags(dataSrc, r, tableData)) { return(false); } } } else if (t1.Rows.Count > 0) { if (t1.Rows.Cast <DataRow>().Any(r => !insertToNotesTags(dataDest, r, tableData))) { return(false); } } else if (t2.Rows.Count > 0) { if (t2.Rows.Cast <DataRow>().Any(r => !insertToNotesTags(dataSrc, r, tableData))) { return(false); } } } } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
private void DlgSearchReplace_Loaded(object sender, RoutedEventArgs e) { try { PNLang.Instance.ApplyControlLanguage(this); if (_Mode == SearchReplace.Search) { Title = PNLang.Instance.GetCaptionText("dlg_search_find", "Find"); lblReplace.Visibility = cboReplace.Visibility = cmdReplace.Visibility = cmdReplaceAll.Visibility = Visibility.Collapsed; } else { Title = PNLang.Instance.GetCaptionText("dlg_search_replace", "Replace"); } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable("SELECT FIND, REPLACE FROM FIND_REPLACE")) { if (t.Rows.Count > 0) { if (!PNData.IsDBNull(t.Rows[0]["FIND"])) { var values = (Convert.ToString(t.Rows[0]["FIND"])).Split(','); foreach (var s in values) cboFind.Items.Add(s); } if (!PNData.IsDBNull(t.Rows[0]["REPLACE"])) { var values = (Convert.ToString(t.Rows[0]["REPLACE"])).Split(','); foreach (var s in values) cboReplace.Items.Add(s); } } } } cboFind.Text = _Edit.SelectionLength > 0 ? _Edit.SelectedText : PNStatic.FindString; cboReplace.Text = PNStatic.ReplaceString; chkRegExp.IsChecked = PNStatic.SearchMode == SearchMode.RegularExp; cboFind.Focus(); } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNotePin(PNote note) { try { if (note.FromDB) { var sb = new StringBuilder(); sb.Append("UPDATE NOTES SET PINNED = "); sb.Append(Convert.ToInt32(note.Pinned)); sb.Append(", PIN_CLASS = '"); sb.Append(note.PinClass); sb.Append("', PIN_TEXT = '"); sb.Append(note.PinText); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteSize(PNote note, Size size, System.Drawing.Size editSize) { try { note.NoteSize = size; note.EditSize = editSize; if (note.FromDB) { var sc = new SizeConverter(); var scd = new System.Drawing.SizeConverter(); var sb = new StringBuilder(); sb.Append("UPDATE NOTES SET SIZE = '"); sb.Append(sc.ConvertToString(null, PNStatic.CultureInvariant, note.NoteSize)); sb.Append("', EDIT_SIZE = '"); sb.Append(scd.ConvertToString(null, PNStatic.CultureInvariant, note.EditSize)); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteSkinless(PNote note) { try { var cr = new ColorConverter(); var lfc = new WPFFontConverter(); var sb = new StringBuilder(); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { if (isNotePresentedInCustomSettings(note)) { sb.Append("UPDATE CUSTOM_NOTES_SETTINGS SET BACK_COLOR = "); if (note.Skinless != null) { sb.Append("'"); sb.Append(cr.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.BackColor)); sb.Append("'"); } else { sb.Append("NULL"); } sb.Append(", CAPTION_FONT_COLOR = "); if (note.Skinless != null) { sb.Append("'"); sb.Append(cr.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionColor)); sb.Append("'"); } else { sb.Append("NULL"); } sb.Append(", CAPTION_FONT = "); if (note.Skinless != null) { sb.Append("'"); sb.Append(lfc.ConvertToString(note.Skinless.CaptionFont)); sb.Append("'"); } else { sb.Append("NULL"); } sb.Append(" WHERE NOTE_ID = '"); sb.Append(note.ID); sb.Append("'"); } else { sb.Append("INSERT INTO CUSTOM_NOTES_SETTINGS (NOTE_ID, BACK_COLOR, CAPTION_FONT_COLOR, CAPTION_FONT) VALUES("); if (note.Skinless != null) { sb.Append("'"); sb.Append(note.ID); sb.Append("', '"); sb.Append(cr.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.BackColor)); sb.Append("', '"); sb.Append(cr.ConvertToString(null, PNStatic.CultureInvariant, note.Skinless.CaptionColor)); sb.Append("', '"); sb.Append(lfc.ConvertToString(note.Skinless.CaptionFont)); sb.Append("')"); } else { sb.Append("'"); sb.Append(note.ID); sb.Append("', NULL, NULL, NULL)"); } } oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void RemoveCustomNotesSettings(string id) { try { using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder("DELETE FROM CUSTOM_NOTES_SETTINGS WHERE NOTE_ID = '"); sb.Append(id); sb.Append("'"); oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteSchedule(PNote note) { try { var ac = new AlarmAfterValuesConverter(); var mc = new MonthDayConverter(); var dc = new DaysOfWeekConverter(); var sb = new StringBuilder(); DeleteNoteSchedule(note); sb.Append("INSERT INTO NOTES_SCHEDULE (NOTE_ID,SCHEDULE_TYPE,ALARM_DATE,START_DATE,LAST_RUN,SOUND,STOP_AFTER,TRACK,REPEAT_COUNT,SOUND_IN_LOOP,USE_TTS,START_FROM,MONTH_DAY,ALARM_AFTER,WEEKDAYS,PROG_TO_RUN,CLOSE_ON_NOTIFICATION,MULTI_ALERTS,TIME_ZONE) VALUES('"); sb.Append(note.ID); sb.Append("',"); sb.Append(Convert.ToInt32(note.Schedule.Type)); sb.Append(",'"); sb.Append(note.Schedule.AlarmDate.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("','"); sb.Append(note.Schedule.StartDate.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("','"); sb.Append(note.Schedule.LastRun.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("','"); sb.Append(note.Schedule.Sound); sb.Append("',"); sb.Append(note.Schedule.StopAfter); sb.Append(","); sb.Append(Convert.ToInt32(note.Schedule.Track)); sb.Append(","); sb.Append(note.Schedule.RepeatCount); sb.Append(","); sb.Append(Convert.ToInt32(note.Schedule.SoundInLoop)); sb.Append(","); sb.Append(Convert.ToInt32(note.Schedule.UseTts)); sb.Append(","); sb.Append(Convert.ToInt32(note.Schedule.StartFrom)); sb.Append(",'"); sb.Append(mc.ConvertToString(note.Schedule.MonthDay)); sb.Append("','"); sb.Append(ac.ConvertToString(note.Schedule.AlarmAfter)); sb.Append("','"); sb.Append(dc.ConvertToString(note.Schedule.Weekdays)); sb.Append("','"); sb.Append(note.Schedule.ProgramToRunOnAlert); sb.Append("',"); sb.Append(Convert.ToInt32(note.Schedule.CloseOnNotification)); //MULTI_ALERTS if (note.Schedule.MultiAlerts.Any()) { var temp = new StringBuilder(); foreach (var ma in note.Schedule.MultiAlerts) { temp.Append(ma.Raised); temp.Append("|"); temp.Append(ma.Date.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); temp.Append("^"); } sb.Append(",'"); sb.Append(temp); sb.Append("'"); } else { sb.Append(",NULL"); } //TIME_ZONE if (note.Schedule.TimeZone != null) { sb.Append(",'"); sb.Append(note.Schedule.TimeZone.ToSerializedString()); sb.Append("'"); } else { sb.Append(",NULL"); } sb.Append(")"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
private bool saveHotkeys() { try { var sqlList = new List <string>(); var count = m_KeysMain.Count; for (var i = 0; i < count; i++) { if (PNStatic.HotKeysMain[i] == m_KeysMain[i]) { continue; } //first unregister existing hot key if (PNStatic.HotKeysMain[i].VK != 0) { HotkeysStatic.UnregisterHK(PNStatic.FormMain.Handle, PNStatic.HotKeysMain[i].ID); } //if new hot key has been set if (m_KeysMain[i].VK != 0) { //now try to register if (!HotkeysStatic.RegisterHK(PNStatic.FormMain.Handle, m_KeysMain[i])) { continue; } //copy hot key PNStatic.HotKeysMain[i].CopyFrom(m_KeysMain[i]); var sqlQuery = createHotKeyUpdate(m_KeysMain[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } else { //hot key has been deleted PNStatic.HotKeysMain[i].CopyFrom(m_KeysMain[i]); var sqlQuery = createHotKeyDelete(m_KeysMain[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } } count = m_KeysNote.Count; for (int i = 0; i < count; i++) { if (PNStatic.HotKeysNote[i] == m_KeysNote[i]) { continue; } //first unregister existing hot key if (PNStatic.HotKeysNote[i].VK != 0) { HotkeysStatic.UnregisterHK(PNStatic.FormMain.Handle, PNStatic.HotKeysNote[i].ID); } //if new hot key has been set if (m_KeysNote[i].VK != 0) { //now try to register if (!HotkeysStatic.RegisterHK(PNStatic.FormMain.Handle, m_KeysNote[i])) { continue; } //copy hot key PNStatic.HotKeysNote[i].CopyFrom(m_KeysNote[i]); var sqlQuery = createHotKeyUpdate(m_KeysNote[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } else { //hot key has been deleted PNStatic.HotKeysNote[i].CopyFrom(m_KeysNote[i]); var sqlQuery = createHotKeyDelete(m_KeysNote[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } ////copy hot key //PNStatic.HotKeysNote[i].CopyFrom(m_KeysNote[i]); //var sqlQuery = m_KeysNote[i].VK != 0 // ? createHotKeyUpdate(m_KeysNote[i]) // : createHotKeyDelete(m_KeysNote[i]); //if (sqlQuery != "") //{ // sqlList.Add(sqlQuery); //} } count = m_KeysEdit.Count; for (int i = 0; i < count; i++) { if (PNStatic.HotKeysEdit[i] == m_KeysEdit[i]) { continue; } //first unregister existing hot key if (PNStatic.HotKeysEdit[i].VK != 0) { HotkeysStatic.UnregisterHK(PNStatic.FormMain.Handle, PNStatic.HotKeysEdit[i].ID); } //if new hot key has been set if (m_KeysEdit[i].VK != 0) { //now try to register if (!HotkeysStatic.RegisterHK(PNStatic.FormMain.Handle, m_KeysEdit[i])) { continue; } //copy hot key PNStatic.HotKeysEdit[i].CopyFrom(m_KeysEdit[i]); var sqlQuery = createHotKeyUpdate(m_KeysEdit[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } else { //hot key has been deleted PNStatic.HotKeysEdit[i].CopyFrom(m_KeysEdit[i]); var sqlQuery = createHotKeyDelete(m_KeysEdit[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } ////copy hot key //PNStatic.HotKeysEdit[i].CopyFrom(m_KeysEdit[i]); //var sqlQuery = m_KeysEdit[i].VK != 0 // ? createHotKeyUpdate(m_KeysEdit[i]) // : createHotKeyDelete(m_KeysEdit[i]); //if (sqlQuery != "") //{ // sqlList.Add(sqlQuery); //} } count = m_KeysGroups.Count; for (var i = 0; i < count; i++) { if (PNStatic.HotKeysGroups[i] == m_KeysGroups[i]) { continue; } //first unregister existing hot key if (PNStatic.HotKeysGroups[i].VK != 0) { HotkeysStatic.UnregisterHK(PNStatic.FormMain.Handle, PNStatic.HotKeysGroups[i].ID); } //if new hot key has been set if (m_KeysGroups[i].VK != 0) { //now try to register if (!HotkeysStatic.RegisterHK(PNStatic.FormMain.Handle, m_KeysGroups[i])) { continue; } //copy hot key PNStatic.HotKeysGroups[i].CopyFrom(m_KeysGroups[i]); var sqlQuery = createHotKeyUpdate(m_KeysGroups[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } else { //hot key has been deleted PNStatic.HotKeysGroups[i].CopyFrom(m_KeysGroups[i]); var sqlQuery = createHotKeyDelete(m_KeysGroups[i]); if (sqlQuery != "") { sqlList.Add(sqlQuery); } } } if (sqlList.Count <= 0) { return(false); } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { foreach (var s in sqlList) { oData.Execute(s); } } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
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; } }
//todo: table data private bool insertToAllTables(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, string id, Dictionary <string, List <_FieldData> > tablesData) { try { using (var t = dataSrc.FillDataTable("SELECT * FROM NOTES WHERE ID = '" + id + "'")) { if (t.Rows.Count > 0) { if (!insertToNotes(dataDest, t.Rows[0], tablesData.FirstOrDefault(td => td.Key == "NOTES"))) { return(false); } } } using (var t = dataSrc.FillDataTable("SELECT * FROM CUSTOM_NOTES_SETTINGS WHERE NOTE_ID = '" + id + "'")) { if (t.Rows.Count > 0) { if (!insertToCustomNotesSettings(dataDest, t.Rows[0], tablesData.FirstOrDefault(td => td.Key == "CUSTOM_NOTES_SETTINGS"))) { return(false); } } } using (var t = dataSrc.FillDataTable("SELECT * FROM LINKED_NOTES WHERE NOTE_ID = '" + id + "'")) { if (t.Rows.Count > 0) { if (!insertToLinkedNotes(dataDest, t.Rows[0], tablesData.FirstOrDefault(td => td.Key == "LINKED_NOTES"))) { return(false); } } } using (var t = dataSrc.FillDataTable("SELECT * FROM NOTES_SCHEDULE WHERE NOTE_ID = '" + id + "'")) { if (t.Rows.Count > 0) { if (!insertToNotesSchedule(dataDest, t.Rows[0], tablesData.FirstOrDefault(td => td.Key == "NOTES_SCHEDULE"))) { return(false); } } } using (var t = dataSrc.FillDataTable("SELECT * FROM NOTES_TAGS WHERE NOTE_ID = '" + id + "'")) { if (t.Rows.Count > 0) { if (!insertToNotesTags(dataDest, t.Rows[0], tablesData.FirstOrDefault(td => td.Key == "NOTES_TAGS"))) { return(false); } } } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
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 bool exchangeGroups(SQLiteDataObject dataSrc, SQLiteDataObject dataDest, KeyValuePair <string, List <_FieldData> > tableData) { try { using (var t1 = dataSrc.FillDataTable("SELECT * FROM GROUPS")) { using (var t2 = dataDest.FillDataTable("SELECT * FROM GROUPS")) { var t = t1.Clone(); IEnumerable <DataRow> rows1 = t1.AsEnumerable(); IEnumerable <DataRow> rows2 = t2.AsEnumerable(); foreach (var r1 in rows1) { var r2 = rows2.FirstOrDefault(r => (int)r["GROUP_ID"] == (int)r1["GROUP_ID"]); if (r2 != null) { if (Convert.ToInt64(r1["UPD_DATE"]) >= Convert.ToInt64(r2["UPD_DATE"])) { t.Rows.Add(r1.ItemArray); } else if (Convert.ToInt64(r2["UPD_DATE"]) > Convert.ToInt64(r1["UPD_DATE"])) { t.Rows.Add(r2.ItemArray); } } else { t.Rows.Add(r1.ItemArray); } } foreach (var r2 in rows2) { if (rows1.All(r => (int)r["GROUP_ID"] != (int)r2["GROUP_ID"])) { t.Rows.Add(r2.ItemArray); } } var sqlList = new List <string> { "DELETE FROM GROUPS" }; sqlList.AddRange(from DataRow r in t.Rows select createInsert(r, tableData)); var inTrans1 = false; var inTrans2 = false; try { inTrans1 = dataSrc.BeginTransaction(); inTrans2 = dataDest.BeginTransaction(); if (inTrans1 && inTrans2) { foreach (string s in sqlList) { dataSrc.ExecuteInTransaction(s); dataDest.ExecuteInTransaction(s); } dataSrc.CommitTransaction(); inTrans1 = false; dataDest.CommitTransaction(); inTrans2 = false; } } catch (Exception ex) { if (inTrans1) { dataSrc.RollbackTransaction(); } if (inTrans2) { dataDest.RollbackTransaction(); } PNStatic.LogException(ex); return(false); } } } return(true); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
private bool areTablesDifferent(SQLiteDataObject dataSrc, SQLiteDataObject dataDest) { try { foreach (var tableName in _Tables) { var sqlQuery = "pragma table_info('" + tableName + "')"; using (var ts = dataSrc.FillDataTable(sqlQuery)) { using (var td = dataDest.FillDataTable(sqlQuery)) { var upper = ts.Rows.Count == td.Rows.Count ? ts.Rows.Count : Math.Min(ts.Rows.Count, td.Rows.Count); for (var i = 0; i < upper; i++) { if (Convert.ToString(ts.Rows[i]["name"]) != Convert.ToString(td.Rows[i]["name"]) || Convert.ToString(ts.Rows[i]["type"]) != Convert.ToString(td.Rows[i]["type"])) { return(true); } } if (upper >= ts.Rows.Count) { continue; } for (var i = upper; i < ts.Rows.Count; i++) { var r = ts.Rows[i]; var sb = new StringBuilder("ALTER TABLE "); sb.Append(tableName); sb.Append(" ADD COLUMN ["); sb.Append(r["name"]); sb.Append("] "); sb.Append(r["type"]); if (!DBNull.Value.Equals(r["dflt_value"])) { sb.Append(" DEFAULT ("); sb.Append(r["dflt_value"]); sb.Append(")"); sb.Append("; UPDATE "); sb.Append(tableName); sb.Append(" SET "); sb.Append(r["name"]); sb.Append(" = "); if (Convert.ToString(r["type"]).ToUpper() == "TEXT") { sb.Append("'"); sb.Append(Convert.ToString(r["dflt_value"]).Replace("'", "''")); } else { sb.Append(r["dflt_value"]); } if (Convert.ToString(r["type"]).ToUpper() == "TEXT") { sb.Append("'"); } } else { var updValue = getUpdateValue(tableName, Convert.ToString(r["name"])); if (updValue != null) { sb.Append("; UPDATE "); sb.Append(tableName); sb.Append(" SET "); sb.Append(r["name"]); sb.Append(" = "); if (Convert.ToString(r["type"]).ToUpper() == "TEXT") { sb.Append("'"); sb.Append(Convert.ToString(updValue).Replace("'", "''")); } else { sb.Append(updValue); } if (Convert.ToString(r["type"]).ToUpper() == "TEXT") { sb.Append("'"); } } } dataDest.Execute(sb.ToString()); } } } } return(false); } catch (Exception ex) { PNStatic.LogException(ex); return(false); } }
internal static void SaveNoteDockStatus(PNote note) { try { var sb = new StringBuilder(); note.DateSaved = DateTime.Now; sb.Append("UPDATE NOTES SET DOCK_STATUS = "); sb.Append(Convert.ToInt32(note.DockStatus)); sb.Append(", DOCK_ORDER = "); sb.Append(Convert.ToInt32(note.DockOrder)); sb.Append(" WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void DeleteNoteSchedule(PNote note) { try { var sb = new StringBuilder(); sb.Append("DELETE FROM NOTES_SCHEDULE WHERE NOTE_ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static bool SaveExistingNote(PNote note) { try { var sb = new StringBuilder(); note.DateSaved = DateTime.Now; sb.Append("UPDATE NOTES SET NAME = '"); sb.Append(note.Name.Replace("'", "''")); sb.Append("', GROUP_ID = "); sb.Append(note.GroupID); sb.Append(", PREV_GROUP_ID = "); sb.Append(note.PrevGroupID); sb.Append(", DATE_SAVED = '"); sb.Append(note.DateSaved.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
private static bool isNotePresentedInCustomSettings(PNote note) { try { var sb = new StringBuilder(); sb.Append("SELECT COUNT(NOTE_ID) AS COUNT_ID FROM CUSTOM_NOTES_SETTINGS WHERE NOTE_ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var o = oData.GetScalar(sb.ToString()); if (o != null && !PNData.IsDBNull(o) && Convert.ToInt32(o) > 0) { return true; } return false; } } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
internal static bool SaveNewNote(PNote note) { try { var sb = new StringBuilder(); note.DateSaved = DateTime.Now; sb.Append("INSERT INTO NOTES (ID, NAME, GROUP_ID, PREV_GROUP_ID, OPACITY, VISIBLE, FAVORITE, PROTECTED, COMPLETED, PRIORITY, PASSWORD_STRING, PINNED, TOPMOST, ROLLED, DOCK_STATUS, DOCK_ORDER, SEND_RECEIVE_STATUS, DATE_CREATED, DATE_SAVED, DATE_SENT, DATE_RECEIVED, DATE_DELETED, SIZE, LOCATION, EDIT_SIZE, REL_X, REL_Y, SENT_TO, RECEIVED_FROM, PIN_CLASS, PIN_TEXT, SCRAMBLED, RECEIVED_IP) VALUES('"); sb.Append(note.ID); sb.Append("', '"); sb.Append(note.Name.Replace("'", "''")); sb.Append("', "); sb.Append(note.GroupID); sb.Append(", "); sb.Append(note.GroupID); //as prev png sb.Append(", "); sb.Append(note.Opacity.ToString(PNStatic.CultureInvariant)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Visible)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Favorite)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Protected)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Completed)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Priority)); sb.Append(", '"); sb.Append(note.PasswordString.Replace("'", "''")); sb.Append("', "); sb.Append(Convert.ToInt32(note.Pinned)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Topmost)); sb.Append(", "); sb.Append(Convert.ToInt32(note.Rolled)); sb.Append(", "); sb.Append(Convert.ToInt32(note.DockStatus)); sb.Append(", "); sb.Append(Convert.ToInt32(note.DockOrder)); sb.Append(", "); sb.Append(Convert.ToInt32(note.SentReceived)); sb.Append(", '"); sb.Append(note.DateCreated.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', '"); sb.Append(note.DateSaved.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', '"); sb.Append(note.DateSent.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', '"); sb.Append(note.DateReceived.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', '"); sb.Append(note.DateDeleted.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', '"); var sc = new SizeConverter(); sb.Append(sc.ConvertToString(null, PNStatic.CultureInvariant, note.NoteSize)); sb.Append("', '"); var pc = new PointConverter(); sb.Append(pc.ConvertToString(null, PNStatic.CultureInvariant, note.NoteLocation)); sb.Append("', '"); var scd = new System.Drawing.SizeConverter(); sb.Append(scd.ConvertToString(null, PNStatic.CultureInvariant, note.EditSize)); sb.Append("', "); var factors = getRelationalFactors(note); sb.Append(factors[0].ToString(PNStatic.CultureInvariant)); sb.Append(", "); sb.Append(factors[1].ToString(PNStatic.CultureInvariant)); sb.Append(", '"); sb.Append(note.SentTo.Replace("'", "''")); sb.Append("', '"); sb.Append(note.ReceivedFrom.Replace("'", "''")); sb.Append("', '"); sb.Append(note.PinClass); sb.Append("', '"); sb.Append(note.PinText); sb.Append("', "); sb.Append(Convert.ToInt32(note.Scrambled)); sb.Append(", '"); sb.Append(note.ReceivedIp); sb.Append("'"); sb.Append(")"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } note.FromDB = true; if (note.Skinless != null) { SaveNoteSkinless(note); } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
internal static void SaveNoteSkin(PNote note) { try { var sb = new StringBuilder(); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { if (isNotePresentedInCustomSettings(note)) { sb.Append("UPDATE CUSTOM_NOTES_SETTINGS SET SKIN_NAME = "); if (note.Skin != null) { sb.Append("'"); sb.Append(note.Skin.SkinName); sb.Append("'"); } else { sb.Append("NULL"); } sb.Append(" WHERE NOTE_ID = '"); sb.Append(note.ID); sb.Append("'"); } else { sb.Append("INSERT INTO CUSTOM_NOTES_SETTINGS (NOTE_ID, SKIN_NAME) VALUES("); if (note.Skin != null) { sb.Append("'"); sb.Append(note.ID); sb.Append("', '"); sb.Append(note.Skin.SkinName); sb.Append("')"); } else { sb.Append("'"); sb.Append(note.ID); sb.Append("', NULL)"); } } oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteDeletedDate(PNote note) { try { var sb = new StringBuilder(); sb.Append("UPDATE NOTES SET DATE_DELETED = '"); sb.Append(note.DateDeleted.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'; "); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteOpacity(PNote note) { try { var sb = new StringBuilder(); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { sb.Append("UPDATE NOTES SET OPACITY = "); sb.Append(note.Opacity.ToString(PNStatic.CultureInvariant)); sb.Append(" WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); oData.Execute(sb.ToString()); sb = new StringBuilder(); if (isNotePresentedInCustomSettings(note)) { sb.Append("UPDATE CUSTOM_NOTES_SETTINGS SET CUSTOM_OPACITY = "); sb.Append(Convert.ToInt32(note.CustomOpacity)); sb.Append(" WHERE NOTE_ID = '"); sb.Append(note.ID); sb.Append("'"); } else { sb.Append("INSERT INTO CUSTOM_NOTES_SETTINGS (NOTE_ID, CUSTOM_OPACITY) VALUES('"); sb.Append(note.ID); sb.Append("', "); sb.Append(Convert.ToInt32(note.CustomOpacity)); sb.Append(")"); } oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static bool SaveNoteDeletedState(PNote note, bool toBin) { try { var sb = new StringBuilder(); if (toBin) { sb.Append("UPDATE NOTES SET VISIBLE = 0, GROUP_ID = "); sb.Append(note.GroupID); sb.Append(", PREV_GROUP_ID = "); sb.Append(note.PrevGroupID); sb.Append(", DATE_DELETED = '"); sb.Append(note.DateDeleted.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'; "); } else { sb.Append("DELETE FROM NOTES WHERE ID = '"); sb.Append(note.ID); sb.Append("'; "); //all other tables should be here } using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
internal static void SaveNoteThumbnail(PNote note) { try { if (note.FromDB) { var sb = new StringBuilder(); sb.Append("UPDATE NOTES SET THUMBNAIL = "); sb.Append(Convert.ToInt32(note.Thumbnail)); sb.Append(" WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void RemoveDeletedNoteFromLists(PNote note) { try { foreach (var n in PNStatic.Notes) { n.LinkedNotes.RemoveAll(l => l == note.ID); } //clean tables using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder(); sb.Append("DELETE FROM LINKED_NOTES WHERE LINK_ID = '"); sb.Append(note.ID); sb.Append("';"); oData.Execute(sb.ToString()); } //remove all backup copies var di = new DirectoryInfo(PNPaths.Instance.BackupDir); var fis = di.GetFiles(note.ID + "*" + PNStrings.NOTE_BACK_EXTENSION); foreach (var fi in fis) { fi.Delete(); } fis = di.GetFiles(note.ID + "*" + PNStrings.NOTE_AUTO_BACK_EXTENSION); foreach (var fi in fis) { fi.Delete(); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteLocation(PNote note, Point location) { try { note.NoteLocation = location; var factors = getRelationalFactors(note); note.XFactor = factors[0]; note.YFactor = factors[1]; if (note.FromDB) { var pc = new PointConverter(); var sb = new StringBuilder(); sb.Append("UPDATE NOTES SET LOCATION = '"); sb.Append(pc.ConvertToString(null, PNStatic.CultureInvariant, note.NoteLocation)); sb.Append("', REL_X = "); sb.Append(factors[0].ToString(PNStatic.CultureInvariant)); sb.Append(", REL_Y = "); sb.Append(factors[1].ToString(PNStatic.CultureInvariant)); sb.Append(" WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static void SaveNoteOnSend(PNote note) { try { var sb = new StringBuilder(); note.DateSaved = DateTime.Now; sb.Append("UPDATE NOTES SET DATE_SENT = '"); sb.Append(note.DateSaved.ToString(PNStrings.DATE_TIME_FORMAT, PNStatic.CultureInvariant).Replace("'", "''")); sb.Append("', SEND_RECEIVE_STATUS = "); sb.Append(Convert.ToInt32(note.SentReceived)); sb.Append(", SENT_TO = '"); sb.Append(note.SentTo.Replace("'", "''")); sb.Append("' WHERE ID = '"); sb.Append(note.ID); sb.Append("'"); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { oData.Execute(sb.ToString()); } } catch (Exception ex) { PNStatic.LogException(ex); } }
private void saveFind() { try { var str = cboFind.Text.Trim(); if (cboFind.Items.Contains(str)) return; using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder(); sb.Append("UPDATE FIND_REPLACE SET FIND = '"); sb.Append(str); foreach (string s in cboFind.Items) { sb.Append(","); sb.Append(s); } sb.Append("'"); oData.Execute(sb.ToString()); cboFind.Items.Insert(0, str); } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal void SyncLocal(object localPaths) { var result = LocalSyncResult.Reload; var filesSrc = new List <_NoteFile>(); var filesDest = new List <_NoteFile>(); var tempDir = ""; try { if (PNStatic.Settings.Network.SaveBeforeSync) { PNStatic.FormMain.ApplyAction(MainDialogAction.SaveAll, null); } var paths = localPaths as string[]; if (paths == null || paths.Length != 2) { throw new ArgumentException("Invalid local paths"); } var destDir = paths[0].Trim(); var destDB = paths[1].Trim() != "" ? paths[1].Trim() : destDir; destDB = Path.Combine(destDB, PNStrings.DB_FILE); // create temp directory tempDir = createTempDir(); var tempDBSrc = Path.Combine(tempDir, PNStrings.DB_FILE); var tempDBDest = Path.Combine(tempDir, PNStrings.TEMP_DB_FILE); // copy source db File.Copy(PNPaths.Instance.DBPath, tempDBSrc, true); // build source connection string var srcConnectionString = "data source=\"" + tempDBSrc + "\""; //string srcConnectionString = "metadata=res://*/PNModel.csdl|res://*/PNModel.ssdl|res://*/PNModel.msl;provider=System.Data.SQLite;provider connection string='data source=\"" + tempDBSrc + "\"'"; using (var eSrc = new SQLiteDataObject(srcConnectionString)) { // drop triggers eSrc.Execute(PNStrings.DROP_TRIGGERS); // get listNames of all source notes files var srcNotes = new DirectoryInfo(PNPaths.Instance.DataDir).GetFiles("*" + PNStrings.NOTE_EXTENSION); filesSrc.AddRange(srcNotes.Select(fi => new _NoteFile { Path = fi.FullName, Name = fi.Name, Copy = false })); // get deleted ids if (!PNStatic.Settings.Network.IncludeBinInSync) { var deletedSrc = deletedIDs(eSrc); filesSrc.RemoveAll(nf => deletedSrc.Contains(Path.GetFileNameWithoutExtension(nf.Name))); } // get listNames of all destination notes files var destNotes = new DirectoryInfo(destDir).GetFiles("*" + PNStrings.NOTE_EXTENSION); filesDest.AddRange(destNotes.Select(fir => new _NoteFile { Path = fir.FullName, Name = fir.Name, Copy = false })); if (File.Exists(destDB)) { // copy destination db to temp directory File.Copy(destDB, tempDBDest, true); // build connection string var destConnectionString = "data source=\"" + tempDBDest + "\""; using (var eDest = new SQLiteDataObject(destConnectionString)) { // drop triggers eDest.Execute(PNStrings.DROP_TRIGGERS); if (areTablesDifferent(eSrc, eDest)) { if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.AbortVersion)); } return; } //todo: create tables data var tablesData = new Dictionary <string, List <_FieldData> >(); foreach (var tn in _Tables) { var td = new List <_FieldData>(); var sb = new StringBuilder("pragma table_info('"); sb.Append(tn); sb.Append("')"); using (var t = eSrc.FillDataTable(sb.ToString())) { td.AddRange(from DataRow r in t.Rows select new _FieldData { Name = Convert.ToString(r["name"]), Type = Convert.ToString(r["type"]), NotNull = Convert.ToBoolean(r["notnull"]) }); } tablesData.Add(tn, td); } // get deleted ids if (!PNStatic.Settings.Network.IncludeBinInSync) { var deletedDest = deletedIDs(eDest); filesDest.RemoveAll(nf => deletedDest.Contains(Path.GetFileNameWithoutExtension(nf.Name))); } foreach (var sf in filesSrc) { var id = Path.GetFileNameWithoutExtension(sf.Name); // find destination file with same name var df = filesDest.FirstOrDefault(f => f.Name == sf.Name); if (df == null) { sf.Copy = true; //todo if (!insertToAllTables(eSrc, eDest, id, tablesData)) { if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.Error)); } return; } } else { // check which note is more up to date var dSrc = File.GetLastWriteTime(sf.Path); var dDest = File.GetLastWriteTime(df.Path); if (dSrc > dDest) { // compare two files if (areFilesDifferent(sf.Path, df.Path)) { // local file is younger then remote - copy it to remote client sf.Copy = true; } } else if (dSrc < dDest) { // compare two files if (areFilesDifferent(sf.Path, df.Path)) { // remote file is younger than local - copy it to local directory df.Copy = true; } } //todo if (!exchangeData(eSrc, eDest, id, tablesData)) { if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.Error)); } return; } } } // check remaining destination files var remDest = filesDest.Where(df => !df.Copy); foreach (var df in remDest) { if (filesSrc.All(sf => sf.Name != df.Name)) { df.Copy = true; var id = Path.GetFileNameWithoutExtension(df.Name); //todo if (!exchangeData(eSrc, eDest, id, tablesData)) { if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.Error)); } return; } } } // synchronize groups if (!exchangeGroups(eSrc, eDest, tablesData.FirstOrDefault(td => td.Key == "GROUPS"))) { if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.Error)); } return; } // restore triggers eSrc.Execute(PNStrings.CREATE_TRIGGERS); eDest.Execute(PNStrings.CREATE_TRIGGERS); } // copy files var filesToCopy = filesSrc.Where(sf => sf.Copy); foreach (var sf in filesToCopy) { var newPath = Path.Combine(destDir, sf.Name); File.Copy(sf.Path, newPath, true); } filesToCopy = filesDest.Where(df => df.Copy); foreach (var df in filesToCopy) { var newPath = Path.Combine(PNPaths.Instance.DataDir, df.Name); File.Copy(df.Path, newPath, true); } if (filesDest.Count(df => df.Copy) == 0) { result = LocalSyncResult.None; } // copy synchronized db files File.Copy(tempDBSrc, PNPaths.Instance.DBPath, true); File.Copy(tempDBDest, destDB, true); } else { // restore triggers eSrc.Execute(PNStrings.CREATE_TRIGGERS); // just copy all notes files and db file to remote client File.Copy(PNPaths.Instance.DBPath, destDB, true); foreach (var sf in filesSrc) { var newPath = Path.Combine(destDir, sf.Name); File.Copy(sf.Path, newPath, true); } result = LocalSyncResult.None; } } if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(result)); } } catch (Exception ex) { PNStatic.LogException(ex); if (SyncComplete != null) { SyncComplete(this, new LocalSyncCompleteEventArgs(LocalSyncResult.Error)); } } finally { if (tempDir != "" && Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } } }
internal static void PrepareDefaultMenuStrip(ContextMenu source, MenuType type, bool forCurrent) { try { List<PNMenu> menuItems; if (forCurrent) { switch (type) { case MenuType.Main: menuItems = CurrentMainMenus; break; case MenuType.Edit: menuItems = CurrentEditMenus; break; case MenuType.Note: menuItems = CurrentNoteMenus; break; case MenuType.ControlPanel: menuItems = CurrentCPMenus; break; default: return; } } else { switch (type) { case MenuType.Main: menuItems = DefaultMainMenus; break; case MenuType.Edit: menuItems = DefaultEditMenus; break; case MenuType.Note: menuItems = DefaultNoteMenus; break; case MenuType.ControlPanel: menuItems = DefaultCPMenus; break; default: return; } } menuItems.Clear(); var arr = source.Items.Cast<Control>().ToArray(); var tableList = new List<Tuple<string, string, int>>(); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder("SELECT MENU_NAME, "); sb.Append(forCurrent ? "ORDER_NEW" : "ORDER_ORIGINAL"); sb.Append(", IFNULL(PARENT_NAME, '') AS PARENT_NAME FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(source.Name); sb.Append("' ORDER BY "); sb.Append(forCurrent ? "ORDER_NEW" : "ORDER_ORIGINAL"); using (var t = oData.FillDataTable(sb.ToString())) { if (forCurrent) { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_NEW"]))); } else { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_ORIGINAL"]))); } var topItems = tableList.Where(tp => tp.Item2 == ""); foreach (var tp in topItems) { var si = arr.FirstOrDefault(a => a.Name == tp.Item1); if (si == null) continue; var pmi = new PNMenu(si.Name, si.GetType() == typeof(MenuItem) ?((MenuItem) si).Header.ToString() : PNStrings.MENU_SEPARATOR_STRING, "", source.Name); menuItems.Add(pmi); var psi = si as MenuItem; if (psi != null) prepareSubitem(tableList, psi, pmi, source.Name); } } } } catch (Exception ex) { PNStatic.LogException(ex); } }
internal static bool LoadLinkedNotes(PNote note) { try { var sqlQuery = "SELECT LINK_ID FROM LINKED_NOTES WHERE NOTE_ID = '" + note.ID + "'"; using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable(sqlQuery)) { foreach (DataRow r in t.Rows) { note.LinkedNotes.Add((string)r["LINK_ID"]); } } } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
private static bool loadNoteSchedule(PNote note) { try { var sqlQuery = "SELECT * FROM NOTES_SCHEDULE WHERE NOTE_ID = '" + note.ID + "'"; using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { using (var t = oData.FillDataTable(sqlQuery)) { if (t.Rows.Count > 0) { var mc = new MonthDayConverter(); var ac = new AlarmAfterValuesConverter(); var dw = new DaysOfWeekConverter(); var r = t.Rows[0]; note.Schedule.Type = (ScheduleType)Convert.ToInt32(r["SCHEDULE_TYPE"]); note.Schedule.AlarmDate = DateTime.Parse((string)r["ALARM_DATE"], PNStatic.CultureInvariant); note.Schedule.StartDate = DateTime.Parse((string)r["START_DATE"], PNStatic.CultureInvariant); note.Schedule.LastRun = DateTime.Parse((string)r["LAST_RUN"], PNStatic.CultureInvariant); note.Schedule.Sound = (string)r["SOUND"]; note.Schedule.StopAfter = Convert.ToInt32(r["STOP_AFTER"]); note.Schedule.Track = Convert.ToBoolean(r["TRACK"]); note.Schedule.RepeatCount = Convert.ToInt32(r["REPEAT_COUNT"]); note.Schedule.SoundInLoop = Convert.ToBoolean(r["SOUND_IN_LOOP"]); note.Schedule.UseTts = Convert.ToBoolean(r["USE_TTS"]); note.Schedule.StartFrom = (ScheduleStart)Convert.ToInt32(r["START_FROM"]); note.Schedule.MonthDay = (MonthDay)mc.ConvertFromString((string)r["MONTH_DAY"]); note.Schedule.AlarmAfter = (AlarmAfterValues)ac.ConvertFromString((string)r["ALARM_AFTER"]); note.Schedule.Weekdays = (List<DayOfWeek>)dw.ConvertFromString((string)r["WEEKDAYS"]); if (!DBNull.Value.Equals(r["PROG_TO_RUN"])) note.Schedule.ProgramToRunOnAlert = Convert.ToString(r["PROG_TO_RUN"]); if (!DBNull.Value.Equals(r["CLOSE_ON_NOTIFICATION"])) note.Schedule.CloseOnNotification = Convert.ToBoolean(r["CLOSE_ON_NOTIFICATION"]); if (!PNData.IsDBNull(r["MULTI_ALERTS"])) { var arr1 = ((string)r["MULTI_ALERTS"]).Split(new[] { '^' }, StringSplitOptions.RemoveEmptyEntries); foreach (var ma in arr1.Select(s => s.Split('|')).Select(arr2 => new MultiAlert { Raised = Convert.ToBoolean(arr2[0]), Date = DateTime.Parse(arr2[1], PNStatic.CultureInvariant) })) { note.Schedule.MultiAlerts.Add(ma); } } if (!PNData.IsDBNull(r["TIME_ZONE"])) { note.Schedule.TimeZone = TimeZoneInfo.FromSerializedString((string)r["TIME_ZONE"]); } if (note.Schedule.Type != ScheduleType.None) { note.Timer.Start(); } } } } return true; } catch (Exception ex) { PNStatic.LogException(ex); return false; } }
internal static void PrepareDefaultMenuStrip(ContextMenu source, MenuType type, bool forCurrent) { try { List <PNMenu> menuItems; if (forCurrent) { switch (type) { case MenuType.Main: menuItems = CurrentMainMenus; break; case MenuType.Edit: menuItems = CurrentEditMenus; break; case MenuType.Note: menuItems = CurrentNoteMenus; break; case MenuType.ControlPanel: menuItems = CurrentCPMenus; break; default: return; } } else { switch (type) { case MenuType.Main: menuItems = DefaultMainMenus; break; case MenuType.Edit: menuItems = DefaultEditMenus; break; case MenuType.Note: menuItems = DefaultNoteMenus; break; case MenuType.ControlPanel: menuItems = DefaultCPMenus; break; default: return; } } menuItems.Clear(); var arr = source.Items.Cast <Control>().ToArray(); var tableList = new List <Tuple <string, string, int> >(); using (var oData = new SQLiteDataObject(PNData.ConnectionString)) { var sb = new StringBuilder("SELECT MENU_NAME, "); sb.Append(forCurrent ? "ORDER_NEW" : "ORDER_ORIGINAL"); sb.Append(", IFNULL(PARENT_NAME, '') AS PARENT_NAME FROM MENUS_ORDER WHERE CONTEXT_NAME = '"); sb.Append(source.Name); sb.Append("' ORDER BY "); sb.Append(forCurrent ? "ORDER_NEW" : "ORDER_ORIGINAL"); using (var t = oData.FillDataTable(sb.ToString())) { if (forCurrent) { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_NEW"]))); } else { tableList.AddRange(from DataRow r in t.Rows select Tuple.Create(Convert.ToString(r["MENU_NAME"]), Convert.ToString(r["PARENT_NAME"]), Convert.ToInt32(r["ORDER_ORIGINAL"]))); } var topItems = tableList.Where(tp => tp.Item2 == ""); foreach (var tp in topItems) { var si = arr.FirstOrDefault(a => a.Name == tp.Item1); if (si == null) { continue; } var pmi = new PNMenu(si.Name, si.GetType() == typeof(MenuItem) ?((MenuItem)si).Header.ToString() : PNStrings.MENU_SEPARATOR_STRING, "", source.Name); menuItems.Add(pmi); var psi = si as MenuItem; if (psi != null) { prepareSubitem(tableList, psi, pmi, source.Name); } } } } } catch (Exception ex) { PNStatic.LogException(ex); } }