Beispiel #1
0
        private static void PerformExport(PwExportInfo pwExportInfo,
                                          FileFormatProvider fileFormat, string strOutputFile, IStatusLogger slLogger)
        {
            if (!fileFormat.SupportsExport)
            {
                return;
            }
            if (fileFormat.TryBeginExport() == false)
            {
                return;
            }

            bool bExistedAlready = File.Exists(strOutputFile);

            FileStream fsOut = new FileStream(strOutputFile, FileMode.Create,
                                              FileAccess.Write, FileShare.None);

            bool bResult = fileFormat.Export(pwExportInfo, fsOut, slLogger);

            fsOut.Close();
            fsOut.Dispose();

            if ((bResult == false) && (bExistedAlready == false))
            {
                try { File.Delete(strOutputFile); }
                catch (Exception) { }
            }
        }
Beispiel #2
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider
                                  fileFormat, IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }
            if (fileFormat == null)
            {
                throw new ArgumentNullException("fileFormat");
            }
            if (fileFormat.RequiresFile && (iocOutput == null))
            {
                throw new ArgumentNullException("iocOutput");
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }
            if (!fileFormat.SupportsExport)
            {
                return(false);
            }
            if (!fileFormat.TryBeginExport())
            {
                return(false);
            }

            // bool bExistedAlready = File.Exists(strOutputFile);
            bool bExistedAlready = (fileFormat.RequiresFile ? IOConnection.FileExists(
                                        iocOutput) : false);

            // FileStream fsOut = new FileStream(strOutputFile, FileMode.Create,
            //	FileAccess.Write, FileShare.None);
            Stream sOut = (fileFormat.RequiresFile ? IOConnection.OpenWrite(
                               iocOutput) : null);

            bool bResult = false;

            try { bResult = fileFormat.Export(pwExportInfo, sOut, slLogger); }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            if (sOut != null)
            {
                sOut.Close();
            }

            if (fileFormat.RequiresFile && (bResult == false) && (bExistedAlready == false))
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch (Exception) { }
            }

            return(bResult);
        }
Beispiel #3
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider
                                  fileFormat, IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }
            if (fileFormat == null)
            {
                throw new ArgumentNullException("fileFormat");
            }
            if (fileFormat.RequiresFile && (iocOutput == null))
            {
                throw new ArgumentNullException("iocOutput");
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }
            if (!fileFormat.SupportsExport)
            {
                return(false);
            }
            if (!fileFormat.TryBeginExport())
            {
                return(false);
            }

            bool bExistedAlready = true;             // No deletion by default
            bool bResult         = false;

            try
            {
                bExistedAlready = (fileFormat.RequiresFile ? IOConnection.FileExists(
                                       iocOutput) : false);
                Stream s = (fileFormat.RequiresFile ? IOConnection.OpenWrite(
                                iocOutput) : null);

                try { bResult = fileFormat.Export(pwExportInfo, s, slLogger); }
                finally { if (s != null)
                          {
                              s.Close();
                          }
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }

            if (fileFormat.RequiresFile && !bResult && !bExistedAlready)
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch (Exception) { }
            }

            return(bResult);
        }
Beispiel #4
0
        public static bool Export(PwExportInfo pwExportInfo, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }

            ExchangeDataForm dlg = new ExchangeDataForm();

            dlg.InitEx(true, pwExportInfo.ContextDatabase, pwExportInfo.DataGroup);

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                FileFormatProvider ffp = dlg.ResultFormat;
                if (ffp == null)
                {
                    Debug.Assert(false); return(false);
                }
                if (ffp.RequiresFile)
                {
                    if (dlg.ResultFiles.Length != 1)
                    {
                        Debug.Assert(false); return(false);
                    }
                    if (dlg.ResultFiles[0] == null)
                    {
                        Debug.Assert(false); return(false);
                    }
                    if (dlg.ResultFiles[0].Length == 0)
                    {
                        Debug.Assert(false); return(false);
                    }
                }

                Application.DoEvents();                 // Redraw parent window

                IOConnectionInfo iocOutput = (ffp.RequiresFile ? IOConnectionInfo.FromPath(
                                                  dlg.ResultFiles[0]) : null);

                try
                {
                    return(Export(pwExportInfo, dlg.ResultFormat, iocOutput, slLogger));
                }
                catch (Exception ex) { MessageService.ShowWarning(ex); }
            }

            return(false);
        }
Beispiel #5
0
        public static bool Export(PwExportInfo pwExportInfo, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }

            ExchangeDataForm dlg = new ExchangeDataForm();

            dlg.InitEx(true, pwExportInfo.ContextDatabase, pwExportInfo.DataGroup);

            bool bResult = false;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                FileFormatProvider ffp = dlg.ResultFormat;
                if (ffp == null)
                {
                    Debug.Assert(false); goto ExpZRet;
                }
                if (ffp.RequiresFile)
                {
                    if (dlg.ResultFiles.Length != 1)
                    {
                        Debug.Assert(false); goto ExpZRet;
                    }
                    if (dlg.ResultFiles[0] == null)
                    {
                        Debug.Assert(false); goto ExpZRet;
                    }
                    if (dlg.ResultFiles[0].Length == 0)
                    {
                        Debug.Assert(false); goto ExpZRet;
                    }
                }

                IOConnectionInfo iocOutput = (ffp.RequiresFile ? IOConnectionInfo.FromPath(
                                                  dlg.ResultFiles[0]) : null);

                Application.DoEvents();                 // Redraw parent window
                bResult = Export(pwExportInfo, ffp, iocOutput, slLogger);
            }

ExpZRet:
            UIUtil.DestroyForm(dlg);
            return(bResult);
        }
Beispiel #6
0
        public static bool?Import(PwDatabase pwStorage, out bool bAppendedToRootOnly,
                                  Form fParent)
        {
            bAppendedToRootOnly = false;

            if (pwStorage == null)
            {
                throw new ArgumentNullException("pwStorage");
            }
            if (!pwStorage.IsOpen)
            {
                return(null);
            }
            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(null);
            }

            ExchangeDataForm dlgFmt = new ExchangeDataForm();

            dlgFmt.InitEx(false, pwStorage, pwStorage.RootGroup);

            if (UIUtil.ShowDialogNotValue(dlgFmt, DialogResult.OK))
            {
                return(null);
            }

            Debug.Assert(dlgFmt.ResultFormat != null);
            if (dlgFmt.ResultFormat == null)
            {
                MessageService.ShowWarning(KPRes.ImportFailed);
                UIUtil.DestroyForm(dlgFmt);
                return(false);
            }

            bAppendedToRootOnly = dlgFmt.ResultFormat.ImportAppendsToRootGroupOnly;
            FileFormatProvider ffp = dlgFmt.ResultFormat;

            List <IOConnectionInfo> lConnections = new List <IOConnectionInfo>();

            foreach (string strSelFile in dlgFmt.ResultFiles)
            {
                lConnections.Add(IOConnectionInfo.FromPath(strSelFile));
            }

            UIUtil.DestroyForm(dlgFmt);
            return(Import(pwStorage, ffp, lConnections.ToArray(),
                          false, null, false, fParent));
        }
Beispiel #7
0
        public static bool?Import(PwDatabase pd, FileFormatProvider fmtImp,
                                  IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey)
        {
            if (pd == null)
            {
                Debug.Assert(false); return(false);
            }
            if (fmtImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (iocImp == null)
            {
                Debug.Assert(false); return(false);
            }
            if (cmpKey == null)
            {
                cmpKey = new CompositeKey();
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            PwDatabase pdImp = new PwDatabase();

            pdImp.New(new IOConnectionInfo(), cmpKey);
            pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep();

            Stream s = IOConnection.OpenRead(iocImp);

            if (s == null)
            {
                throw new FileNotFoundException(iocImp.GetDisplayName() +
                                                MessageService.NewLine + KPRes.FileNotFoundError);
            }

            try { fmtImp.Import(pdImp, s, null); }
            finally { s.Close(); }

            pd.MergeIn(pdImp, mm);
            return(true);
        }
Beispiel #8
0
        public static bool Export(PwExportInfo pwExportInfo, string strFormatName,
                                  IOConnectionInfo iocOutput)
        {
            if (strFormatName == null)
            {
                throw new ArgumentNullException("strFormatName");
            }
            // iocOutput may be null

            FileFormatProvider prov = Program.FileFormatPool.Find(strFormatName);

            if (prov == null)
            {
                return(false);
            }

            NullStatusLogger slLogger = new NullStatusLogger();

            return(Export(pwExportInfo, prov, iocOutput, slLogger));
        }
Beispiel #9
0
        private static void PerformExport(PwExportInfo pwExportInfo,
            FileFormatProvider fileFormat, string strOutputFile, IStatusLogger slLogger)
        {
            if(!fileFormat.SupportsExport) return;
            if(fileFormat.TryBeginExport() == false) return;

            bool bExistedAlready = File.Exists(strOutputFile);

            FileStream fsOut = new FileStream(strOutputFile, FileMode.Create,
                FileAccess.Write, FileShare.None);

            bool bResult = fileFormat.Export(pwExportInfo, fsOut, slLogger);

            fsOut.Close();
            fsOut.Dispose();

            if((bResult == false) && (bExistedAlready == false))
            {
                try { File.Delete(strOutputFile); }
                catch(Exception) { }
            }
        }
Beispiel #10
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider
            fileFormat, IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if(pwExportInfo == null) throw new ArgumentNullException("pwExportInfo");
            if(pwExportInfo.DataGroup == null) throw new ArgumentException();
            if(fileFormat == null) throw new ArgumentNullException("fileFormat");
            if(fileFormat.RequiresFile && (iocOutput == null))
                throw new ArgumentNullException("iocOutput");

            if(!AppPolicy.Try(AppPolicyId.Export)) return false;
            if(!fileFormat.SupportsExport) return false;
            if(!fileFormat.TryBeginExport()) return false;

            // bool bExistedAlready = File.Exists(strOutputFile);
            bool bExistedAlready = (fileFormat.RequiresFile ? IOConnection.FileExists(
                iocOutput) : false);

            // FileStream fsOut = new FileStream(strOutputFile, FileMode.Create,
            //	FileAccess.Write, FileShare.None);
            Stream sOut = (fileFormat.RequiresFile ? IOConnection.OpenWrite(
                iocOutput) : null);

            bool bResult = false;
            try { bResult = fileFormat.Export(pwExportInfo, sOut, slLogger); }
            catch(Exception ex) { MessageService.ShowWarning(ex); }

            if(sOut != null) sOut.Close();

            if(fileFormat.RequiresFile && (bResult == false) && (bExistedAlready == false))
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch(Exception) { }
            }

            return bResult;
        }
Beispiel #11
0
        private static bool PerformImport(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                          IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                          bool bForceSave)
        {
            if (fmtImp.TryBeginImport() == false)
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            StatusLoggerForm slf = new StatusLoggerForm();

            slf.InitEx(false);
            slf.Show();

            if (bSynchronize)
            {
                slf.StartLogging(KPRes.Synchronize, false);
            }
            else
            {
                slf.StartLogging(KPRes.ImportingStatusMsg, false);
            }

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, slf); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                slf.EndLogging(); slf.Close();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }

                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn.GetDisplayName(), false);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                slf.SetText((bSynchronize ? KPRes.Synchronizing : KPRes.ImportingStatusMsg) +
                            " " + iocIn.GetDisplayName(), LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, slf); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize)
                    {
                        strMsgEx += MessageService.NewParagraph +
                                    KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            slf.EndLogging(); slf.Close();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (pwDatabase.IOConnectionInfo.IsLocalFile())
                            {
                                if ((pwDatabase.IOConnectionInfo.Path != ioc.Path) &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                            }
                            else
                            {
                                pwDatabase.SaveAs(ioc, false, null);
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }
            else if (bSynchronize)            // Synchronized but not successfully imported
            {
                MessageService.ShowWarning(KPRes.SyncFailed,
                                           pwDatabase.IOConnectionInfo.GetDisplayName());

                bAllSuccess = false;
            }

            return(bAllSuccess);
        }
Beispiel #12
0
        private static bool PerformImport(PwDatabase pwDatabase, FileFormatProvider fmtImp,
            IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
            bool bForceSave)
        {
            if(fmtImp.TryBeginImport() == false) return false;

            bool bUseTempDb = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            StatusLoggerForm slf = new StatusLoggerForm();
            slf.InitEx(false);
            slf.Show();

            if(bSynchronize) slf.StartLogging(KPRes.Synchronize, false);
            else slf.StartLogging(KPRes.ImportingStatusMsg, false);

            if(vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, slf); }
                catch(Exception exSingular)
                {
                    if((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                slf.EndLogging(); slf.Close();
                return true;
            }

            foreach(IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch(Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }

                if(s == null) { Debug.Assert(false); bAllSuccess = false; continue; }

                PwDatabase pwImp;
                if(bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else pwImp = pwDatabase;

                if(fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn.GetDisplayName(), false);

                    if(kpf.ShowDialog() != DialogResult.OK) { s.Close(); continue; }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if(bSynchronize) pwImp.MasterKey = pwDatabase.MasterKey;

                slf.SetText((bSynchronize ? KPRes.Synchronizing : KPRes.ImportingStatusMsg) +
                    " " + iocIn.GetDisplayName(), LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, slf); }
                catch(Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if(bSynchronize)
                    {
                        strMsgEx += MessageService.NewParagraph +
                            KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if(bUseTempDb)
                {
                    PwMergeMethod mm;
                    if(!fmtImp.SupportsUuids) mm = PwMergeMethod.CreateNewUuids;
                    else if(bSynchronize) mm = PwMergeMethod.Synchronize;
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if(imf.ShowDialog() != DialogResult.OK)
                            continue;
                        mm = imf.MergeMethod;
                    }

                    slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm); }
                    catch(Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                            KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            slf.EndLogging(); slf.Close();

            if(bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if(uiOps == null) throw new ArgumentNullException("uiOps");

                if(uiOps.UIFileSave(bForceSave))
                {
                    foreach(IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if(pwDatabase.IOConnectionInfo.IsLocalFile())
                            {
                                if((pwDatabase.IOConnectionInfo.Path != ioc.Path) &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                        ioc.Path, true);
                                }
                            }
                            else pwDatabase.SaveAs(ioc, false, null);
                        }
                        catch(Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                pwDatabase.IOConnectionInfo.GetDisplayName() +
                                MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                        pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }
            else if(bSynchronize) // Synchronized but not successfully imported
            {
                MessageService.ShowWarning(KPRes.SyncFailed,
                    pwDatabase.IOConnectionInfo.GetDisplayName());

                bAllSuccess = false;
            }

            return bAllSuccess;
        }
Beispiel #13
0
        public static bool Export(PwExportInfo pwExportInfo, FileFormatProvider fileFormat,
                                  IOConnectionInfo iocOutput, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }
            if (fileFormat == null)
            {
                throw new ArgumentNullException("fileFormat");
            }

            bool bFileReq = fileFormat.RequiresFile;

            if (bFileReq && (iocOutput == null))
            {
                throw new ArgumentNullException("iocOutput");
            }
            if (bFileReq && (iocOutput.Path.Length == 0))
            {
                throw new ArgumentException();
            }

            PwDatabase pd = pwExportInfo.ContextDatabase;

            Debug.Assert(pd != null);

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }
            if (!AppPolicy.Current.ExportNoKey && (pd != null))
            {
                if (!KeyUtil.ReAskKey(pd, true))
                {
                    return(false);
                }
            }

            if (!fileFormat.SupportsExport)
            {
                return(false);
            }
            if (!fileFormat.TryBeginExport())
            {
                return(false);
            }

            CompositeKey ckOrgMasterKey = null;
            DateTime     dtOrgMasterKey = PwDefs.DtDefaultNow;

            PwGroup pgOrgData     = pwExportInfo.DataGroup;
            PwGroup pgOrgRoot     = ((pd != null) ? pd.RootGroup : null);
            bool    bParentGroups = (pwExportInfo.ExportParentGroups && (pd != null) &&
                                     (pgOrgData != pgOrgRoot));

            bool bExistedAlready = true;             // No deletion by default
            bool bResult         = false;

            try
            {
                if (pwExportInfo.ExportMasterKeySpec && fileFormat.RequiresKey &&
                    (pd != null))
                {
                    KeyCreationForm kcf = new KeyCreationForm();
                    kcf.InitEx((iocOutput ?? new IOConnectionInfo()), true);

                    if (UIUtil.ShowDialogNotValue(kcf, DialogResult.OK))
                    {
                        return(false);
                    }

                    ckOrgMasterKey = pd.MasterKey;
                    dtOrgMasterKey = pd.MasterKeyChanged;

                    pd.MasterKey        = kcf.CompositeKey;
                    pd.MasterKeyChanged = DateTime.UtcNow;

                    UIUtil.DestroyForm(kcf);
                }

                if (bParentGroups)
                {
                    PwGroup pgNew = WithParentGroups(pgOrgData, pd);
                    pwExportInfo.DataGroup = pgNew;
                    pd.RootGroup           = pgNew;
                }

                if (bFileReq)
                {
                    bExistedAlready = IOConnection.FileExists(iocOutput);
                }

                Stream s = (bFileReq ? IOConnection.OpenWrite(iocOutput) : null);
                try { bResult = fileFormat.Export(pwExportInfo, s, slLogger); }
                finally { if (s != null)
                          {
                              s.Close();
                          }
                }

                if (bFileReq && bResult)
                {
                    if (pwExportInfo.ExportPostOpen)
                    {
                        NativeLib.StartProcess(iocOutput.Path);
                    }
                    if (pwExportInfo.ExportPostShow)
                    {
                        WinUtil.ShowFileInFileManager(iocOutput.Path, true);
                    }
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }
            finally
            {
                if (ckOrgMasterKey != null)
                {
                    pd.MasterKey        = ckOrgMasterKey;
                    pd.MasterKeyChanged = dtOrgMasterKey;
                }

                if (bParentGroups)
                {
                    pwExportInfo.DataGroup = pgOrgData;
                    pd.RootGroup           = pgOrgRoot;
                }
            }

            if (bFileReq && !bResult && !bExistedAlready)
            {
                try { IOConnection.DeleteFile(iocOutput); }
                catch (Exception) { }
            }

            return(bResult);
        }
Beispiel #14
0
        public static bool Export(PwExportInfo pwExportInfo, IStatusLogger slLogger)
        {
            if (pwExportInfo == null)
            {
                throw new ArgumentNullException("pwExportInfo");
            }
            if (pwExportInfo.DataGroup == null)
            {
                throw new ArgumentException();
            }

            if (!AppPolicy.Try(AppPolicyId.Export))
            {
                return(false);
            }

            ExchangeDataForm dlg = new ExchangeDataForm();

            dlg.InitEx(true, pwExportInfo.ContextDatabase, pwExportInfo.DataGroup);
            dlg.ExportInfo = pwExportInfo;

            bool bStatusActive = false;

            try
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    FileFormatProvider ffp = dlg.ResultFormat;
                    if (ffp == null)
                    {
                        Debug.Assert(false); return(false);
                    }

                    IOConnectionInfo ioc = null;
                    if (ffp.RequiresFile)
                    {
                        string[] vFiles = dlg.ResultFiles;
                        if (vFiles == null)
                        {
                            Debug.Assert(false); return(false);
                        }
                        if (vFiles.Length == 0)
                        {
                            Debug.Assert(false); return(false);
                        }
                        Debug.Assert(vFiles.Length == 1);

                        string strFile = vFiles[0];
                        if (string.IsNullOrEmpty(strFile))
                        {
                            Debug.Assert(false); return(false);
                        }

                        ioc = IOConnectionInfo.FromPath(strFile);
                    }

                    if (slLogger != null)
                    {
                        slLogger.StartLogging(KPRes.ExportingStatusMsg, true);
                        bStatusActive = true;
                    }

                    Application.DoEvents();                     // Redraw parent window
                    return(Export(pwExportInfo, ffp, ioc, slLogger));
                }
            }
            catch (Exception ex) { MessageService.ShowWarning(ex); }
            finally
            {
                UIUtil.DestroyForm(dlg);
                if (bStatusActive)
                {
                    slLogger.EndLogging();
                }
            }

            return(false);
        }
Beispiel #15
0
        private void UpdateUIState()
        {
            bool bFormatSelected = true;
            ListView.SelectedListViewItemCollection lvsc = m_lvFormats.SelectedItems;

            if((lvsc == null) || (lvsc.Count != 1)) bFormatSelected = false;

            if(bFormatSelected) m_fmtCur = (lvsc[0].Tag as FileFormatProvider);
            else m_fmtCur = null;

            if(m_fmtCur != null)
                m_tbFile.Enabled = m_btnSelFile.Enabled = m_fmtCur.RequiresFile;
            else
                m_tbFile.Enabled = m_btnSelFile.Enabled = false;

            m_btnOK.Enabled = (bFormatSelected && ((m_tbFile.Text.Length != 0) ||
                !m_fmtCur.RequiresFile));
        }
Beispiel #16
0
        private bool PrepareExchangeEx()
        {
            UpdateUIState();
            if(m_fmtCur == null) return false;

            m_fmtFinal = m_fmtCur;
            m_vFiles = m_tbFile.Text.Split(new char[]{ ';' },
                StringSplitOptions.RemoveEmptyEntries);

            if(m_bExport) { Debug.Assert(m_vFiles.Length <= 1); }

            return true;
        }
Beispiel #17
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool     bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool     bAllSuccess = true;
            MainForm mf          = Program.MainForm;    // Null for KPScript

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog ||
                ((mf != null) && !mf.HasFormLoaded))
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if (!string.IsNullOrEmpty(exSingular.Message))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(iocIn.GetDisplayName(),
                                               KPRes.FileImportFailed, strMsgEx);

                    bAllSuccess = false;
                    continue;
                }
                finally { s.Close(); }

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (UIUtil.ShowDialogNotValue(imf, DialogResult.OK))
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                                  KPRes.SavingDatabase + ")", LogStatusType.Info);

                if (mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            string strSource = pwDatabase.IOConnectionInfo.Path;
                            if (!string.Equals(ioc.Path, strSource, StrUtil.CaseIgnoreCmp))
                            {
                                bool bSaveAs = true;

                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    // Do not try to copy an encrypted file;
                                    // https://sourceforge.net/p/keepass/discussion/329220/thread/9c9eb989/
                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx
                                    if ((long)(File.GetAttributes(strSource) &
                                               FileAttributes.Encrypted) == 0)
                                    {
                                        File.Copy(strSource, ioc.Path, true);
                                        bSaveAs = false;
                                    }
                                }

                                if (bSaveAs)
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            // else { } // No assert (sync on save)

                            if (mf != null)
                            {
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                                       ioc.CloneDeep());
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return(bAllSuccess);
        }
Beispiel #18
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (kpf.ShowDialog() != DialogResult.OK)
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (imf.ShowDialog() != DialogResult.OK)
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                    }

                    // slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            dlgStatus.EndLogging();

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if (ioc.Path != pwDatabase.IOConnectionInfo.Path)
                            {
                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                              ioc.Path, true);
                                }
                                else
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            else
                            {
                            }                                    // No assert (sync on save)

                            Program.MainForm.FileMruList.AddItem(ioc.GetDisplayName(),
                                                                 ioc.CloneDeep(), true);
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            return(bAllSuccess);
        }
 public ExportDb(IKp2aApp app, OnFinish onFinish, FileFormatProvider fileFormat, IOConnectionInfo targetIoc)
     : base(onFinish)
 {
     _app = app;
     this._fileFormat = fileFormat;
     _targetIoc = targetIoc;
 }
Beispiel #20
0
        public static bool?Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
                                  IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
                                  bool bForceSave, Form fParent)
        {
            if (pwDatabase == null)
            {
                throw new ArgumentNullException("pwDatabase");
            }
            if (!pwDatabase.IsOpen)
            {
                return(null);
            }
            if (fmtImp == null)
            {
                throw new ArgumentNullException("fmtImp");
            }
            if (vConnections == null)
            {
                throw new ArgumentNullException("vConnections");
            }

            if (!AppPolicy.Try(AppPolicyId.Import))
            {
                return(false);
            }
            if (!fmtImp.TryBeginImport())
            {
                return(false);
            }

            bool bUseTempDb  = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;

            if (Program.Config.UI.ShowImportStatusDialog)
            {
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            }
            else
            {
                dlgStatus = new UIBlockerStatusLogger(fParent);
            }

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                                                                      KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                              KPRes.ImportingStatusMsg, LogStatusType.Info);

            if (vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch (Exception exSingular)
                {
                    if ((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return(true);
            }

            foreach (IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch (Exception exFile)
                {
                    // Transacted-file operations can leave behind intact *.kdbx.tmp files when
                    // the file rename doesn't get completed (can happen easily with slow/unreliable
                    // remote collections. We check if that's the case here and fix the situation if
                    // an kdbx file does *not* exist (to avoid possibly overwriting good data with bad
                    // data (i.e. an interrupted kdbx.tmp write).

                    // Make a copy of the IOC like FileTransactionEx.cs:Initialize does
                    IOConnectionInfo iocTemp = iocIn.CloneDeep();
                    iocTemp.Path += FileTransactionEx.StrTempSuffix;

                    if (IOConnection.FileExists(iocTemp) && !IOConnection.FileExists(iocIn))
                    {
                        // Try and rename iocTemp to ioc.Path, then retry file opening.
                        IOConnection.RenameFile(iocTemp, iocIn);
                        try {
                            s = IOConnection.OpenRead(iocIn);
                        } catch (Exception nexFile) {
                            MessageService.ShowWarning(iocIn.GetDisplayName(), nexFile);
                            bAllSuccess = false;
                            continue;
                        }
                    }
                    else
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                        bAllSuccess = false;
                        continue;
                    }
                }
                if (s == null)
                {
                    Debug.Assert(false); bAllSuccess = false; continue;
                }

                PwDatabase pwImp;
                if (bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else
                {
                    pwImp = pwDatabase;
                }

                if (fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if (UIUtil.ShowDialogNotValue(kpf, DialogResult.OK))
                    {
                        s.Close(); continue;
                    }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if (bSynchronize)
                {
                    pwImp.MasterKey = pwDatabase.MasterKey;
                }

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                                   KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                                  ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch (Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if (bSynchronize && (excpFmt is InvalidCompositeKeyException))
                    {
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                                   KPRes.SynchronizingHint;
                    }

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if (bUseTempDb)
                {
                    PwMergeMethod mm;
                    if (!fmtImp.SupportsUuids)
                    {
                        mm = PwMergeMethod.CreateNewUuids;
                    }
                    else if (bSynchronize)
                    {
                        mm = PwMergeMethod.Synchronize;
                    }
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if (UIUtil.ShowDialogNotValue(imf, DialogResult.OK))
                        {
                            continue;
                        }
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch (Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                                                   KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if (bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if (uiOps == null)
                {
                    throw new ArgumentNullException("uiOps");
                }

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                                  KPRes.SavingDatabase + ")", LogStatusType.Info);

                MainForm mf = Program.MainForm;                 // Null for KPScript
                if (mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch (Exception) { Debug.Assert(false); }
                }

                if (uiOps.UIFileSave(bForceSave))
                {
                    foreach (IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            string strSource = pwDatabase.IOConnectionInfo.Path;
                            if (ioc.Path != strSource)
                            {
                                bool bSaveAs = true;

                                if (pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    // Do not try to copy an encrypted file;
                                    // https://sourceforge.net/p/keepass/discussion/329220/thread/9c9eb989/
                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851.aspx
                                    if ((long)(File.GetAttributes(strSource) &
                                               FileAttributes.Encrypted) == 0)
                                    {
                                        File.Copy(strSource, ioc.Path, true);
                                        bSaveAs = false;
                                    }
                                }

                                if (bSaveAs)
                                {
                                    pwDatabase.SaveAs(ioc, false, null);
                                }
                            }
                            // else { } // No assert (sync on save)

                            if (mf != null)
                            {
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                                       ioc.CloneDeep());
                            }
                        }
                        catch (Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                                       pwDatabase.IOConnectionInfo.GetDisplayName() +
                                                       MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                                               pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return(bAllSuccess);
        }
Beispiel #21
0
		public static bool? Import(PwDatabase pd, FileFormatProvider fmtImp,
			IOConnectionInfo iocImp, PwMergeMethod mm, CompositeKey cmpKey)
		{
			if(pd == null) { Debug.Assert(false); return false; }
			if(fmtImp == null) { Debug.Assert(false); return false; }
			if(iocImp == null) { Debug.Assert(false); return false; }
			if(cmpKey == null) cmpKey = new CompositeKey();

			if(!AppPolicy.Try(AppPolicyId.Import)) return false;
			if(!fmtImp.TryBeginImport()) return false;

			PwDatabase pdImp = new PwDatabase();
			pdImp.New(new IOConnectionInfo(), cmpKey);
			pdImp.MemoryProtection = pd.MemoryProtection.CloneDeep();

			Stream s = IOConnection.OpenRead(iocImp);
			if(s == null)
				throw new FileNotFoundException(iocImp.GetDisplayName() +
					MessageService.NewLine + KPRes.FileNotFoundError);

			try { fmtImp.Import(pdImp, s, null); }
			finally { s.Close(); }

			pd.MergeIn(pdImp, mm);
			return true;
		}
Beispiel #22
0
        public static bool? Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
            IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
            bool bForceSave, Form fParent)
        {
            if(pwDatabase == null) throw new ArgumentNullException("pwDatabase");
            if(!pwDatabase.IsOpen) return null;
            if(fmtImp == null) throw new ArgumentNullException("fmtImp");
            if(vConnections == null) throw new ArgumentNullException("vConnections");

            if(!AppPolicy.Try(AppPolicyId.Import)) return false;
            if(!fmtImp.TryBeginImport()) return false;

            bool bUseTempDb = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;
            if(Program.Config.UI.ShowImportStatusDialog)
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            else dlgStatus = new UIBlockerStatusLogger(fParent);

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                KPRes.ImportingStatusMsg, LogStatusType.Info);

            if(vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch(Exception exSingular)
                {
                    if((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return true;
            }

            foreach(IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch(Exception exFile)
                {
                    MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                    bAllSuccess = false;
                    continue;
                }
                if(s == null) { Debug.Assert(false); bAllSuccess = false; continue; }

                PwDatabase pwImp;
                if(bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else pwImp = pwDatabase;

                if(fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if(UIUtil.ShowDialogNotValue(kpf, DialogResult.OK)) { s.Close(); continue; }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if(bSynchronize) pwImp.MasterKey = pwDatabase.MasterKey;

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                    KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                    ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch(Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if(bSynchronize && (excpFmt is InvalidCompositeKeyException))
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                            KPRes.SynchronizingHint;

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if(bUseTempDb)
                {
                    PwMergeMethod mm;
                    if(!fmtImp.SupportsUuids) mm = PwMergeMethod.CreateNewUuids;
                    else if(bSynchronize) mm = PwMergeMethod.Synchronize;
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if(UIUtil.ShowDialogNotValue(imf, DialogResult.OK)) continue;
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    // slf.SetText(KPRes.MergingData, LogStatusType.Info);

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch(Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                            KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            dlgStatus.EndLogging();

            if(bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if(uiOps == null) throw new ArgumentNullException("uiOps");

                if(uiOps.UIFileSave(bForceSave))
                {
                    foreach(IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            if(ioc.Path != pwDatabase.IOConnectionInfo.Path)
                            {
                                if(pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                        ioc.Path, true);
                                }
                                else pwDatabase.SaveAs(ioc, false, null);
                            }
                            else { } // No assert (sync on save)

                            Program.MainForm.FileMruList.AddItem(ioc.GetDisplayName(),
                                ioc.CloneDeep(), true);
                        }
                        catch(Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                pwDatabase.IOConnectionInfo.GetDisplayName() +
                                MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                        pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            return bAllSuccess;
        }
Beispiel #23
0
        public static bool? Import(PwDatabase pwDatabase, FileFormatProvider fmtImp,
			IOConnectionInfo[] vConnections, bool bSynchronize, IUIOperations uiOps,
			bool bForceSave, Form fParent)
        {
            if(pwDatabase == null) throw new ArgumentNullException("pwDatabase");
            if(!pwDatabase.IsOpen) return null;
            if(fmtImp == null) throw new ArgumentNullException("fmtImp");
            if(vConnections == null) throw new ArgumentNullException("vConnections");

            if(!AppPolicy.Try(AppPolicyId.Import)) return false;
            if(!fmtImp.TryBeginImport()) return false;

            bool bUseTempDb = (fmtImp.SupportsUuids || fmtImp.RequiresKey);
            bool bAllSuccess = true;

            // if(bSynchronize) { Debug.Assert(vFiles.Length == 1); }

            IStatusLogger dlgStatus;
            if(Program.Config.UI.ShowImportStatusDialog)
                dlgStatus = new OnDemandStatusDialog(false, fParent);
            else dlgStatus = new UIBlockerStatusLogger(fParent);

            dlgStatus.StartLogging(PwDefs.ShortProductName + " - " + (bSynchronize ?
                KPRes.Synchronizing : KPRes.ImportingStatusMsg), false);
            dlgStatus.SetText(bSynchronize ? KPRes.Synchronizing :
                KPRes.ImportingStatusMsg, LogStatusType.Info);

            if(vConnections.Length == 0)
            {
                try { fmtImp.Import(pwDatabase, null, dlgStatus); }
                catch(Exception exSingular)
                {
                    if((exSingular.Message != null) && (exSingular.Message.Length > 0))
                    {
                        // slf.SetText(exSingular.Message, LogStatusType.Warning);
                        MessageService.ShowWarning(exSingular);
                    }
                }

                dlgStatus.EndLogging();
                return true;
            }

            foreach(IOConnectionInfo iocIn in vConnections)
            {
                Stream s = null;

                try { s = IOConnection.OpenRead(iocIn); }
                catch(Exception exFile)
                {
                    // Transacted-file operations can leave behind intact *.kdbx.tmp files when
                    // the file rename doesn't get completed (can happen easily with slow/unreliable
                    // remote collections. We check if that's the case here and fix the situation if
                    // an kdbx file does *not* exist (to avoid possibly overwriting good data with bad
                    // data (i.e. an interrupted kdbx.tmp write).

                    // Make a copy of the IOC like FileTransactionEx.cs:Initialize does
                    IOConnectionInfo iocTemp = iocIn.CloneDeep();
                    iocTemp.Path += FileTransactionEx.StrTempSuffix;

                    if (IOConnection.FileExists(iocTemp) && !IOConnection.FileExists(iocIn))
                    {
                            // Try and rename iocTemp to ioc.Path, then retry file opening.
                            IOConnection.RenameFile(iocTemp, iocIn);
                            try { s = IOConnection.OpenRead(iocIn); }
                            catch(Exception nexFile)
                            {
                                    MessageService.ShowWarning(iocIn.GetDisplayName(), nexFile);
                                    bAllSuccess = false;
                                    continue;
                            }
                    }
                    else
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(), exFile);
                        bAllSuccess = false;
                        continue;
                    }
                }
                if(s == null) { Debug.Assert(false); bAllSuccess = false; continue; }

                PwDatabase pwImp;
                if(bUseTempDb)
                {
                    pwImp = new PwDatabase();
                    pwImp.New(new IOConnectionInfo(), pwDatabase.MasterKey);
                    pwImp.MemoryProtection = pwDatabase.MemoryProtection.CloneDeep();
                }
                else pwImp = pwDatabase;

                if(fmtImp.RequiresKey && !bSynchronize)
                {
                    KeyPromptForm kpf = new KeyPromptForm();
                    kpf.InitEx(iocIn, false, true);

                    if(UIUtil.ShowDialogNotValue(kpf, DialogResult.OK)) { s.Close(); continue; }

                    pwImp.MasterKey = kpf.CompositeKey;
                    UIUtil.DestroyForm(kpf);
                }
                else if(bSynchronize) pwImp.MasterKey = pwDatabase.MasterKey;

                dlgStatus.SetText((bSynchronize ? KPRes.Synchronizing :
                    KPRes.ImportingStatusMsg) + " (" + iocIn.GetDisplayName() +
                    ")", LogStatusType.Info);

                try { fmtImp.Import(pwImp, s, dlgStatus); }
                catch(Exception excpFmt)
                {
                    string strMsgEx = excpFmt.Message;
                    if(bSynchronize && (excpFmt is InvalidCompositeKeyException))
                        strMsgEx = KLRes.InvalidCompositeKey + MessageService.NewParagraph +
                            KPRes.SynchronizingHint;

                    MessageService.ShowWarning(strMsgEx);

                    s.Close();
                    bAllSuccess = false;
                    continue;
                }

                s.Close();

                if(bUseTempDb)
                {
                    PwMergeMethod mm;
                    if(!fmtImp.SupportsUuids) mm = PwMergeMethod.CreateNewUuids;
                    else if(bSynchronize) mm = PwMergeMethod.Synchronize;
                    else
                    {
                        ImportMethodForm imf = new ImportMethodForm();
                        if(UIUtil.ShowDialogNotValue(imf, DialogResult.OK)) continue;
                        mm = imf.MergeMethod;
                        UIUtil.DestroyForm(imf);
                    }

                    try { pwDatabase.MergeIn(pwImp, mm, dlgStatus); }
                    catch(Exception exMerge)
                    {
                        MessageService.ShowWarning(iocIn.GetDisplayName(),
                            KPRes.ImportFailed, exMerge);

                        bAllSuccess = false;
                        continue;
                    }
                }
            }

            if(bSynchronize && bAllSuccess)
            {
                Debug.Assert(uiOps != null);
                if(uiOps == null) throw new ArgumentNullException("uiOps");

                dlgStatus.SetText(KPRes.Synchronizing + " (" +
                    KPRes.SavingDatabase + ")", LogStatusType.Info);

                MainForm mf = Program.MainForm; // Null for KPScript
                if(mf != null)
                {
                    try { mf.DocumentManager.ActiveDatabase = pwDatabase; }
                    catch(Exception) { Debug.Assert(false); }
                }

                if(uiOps.UIFileSave(bForceSave))
                {
                    foreach(IOConnectionInfo ioc in vConnections)
                    {
                        try
                        {
                            // dlgStatus.SetText(KPRes.Synchronizing + " (" +
                            //	KPRes.SavingDatabase + " " + ioc.GetDisplayName() +
                            //	")", LogStatusType.Info);

                            if(ioc.Path != pwDatabase.IOConnectionInfo.Path)
                            {
                                if(pwDatabase.IOConnectionInfo.IsLocalFile() &&
                                    ioc.IsLocalFile())
                                {
                                    File.Copy(pwDatabase.IOConnectionInfo.Path,
                                        ioc.Path, true);
                                }
                                else pwDatabase.SaveAs(ioc, false, null);
                            }
                            // else { } // No assert (sync on save)

                            if(mf != null)
                                mf.FileMruList.AddItem(ioc.GetDisplayName(),
                                    ioc.CloneDeep());
                        }
                        catch(Exception exSync)
                        {
                            MessageService.ShowWarning(KPRes.SyncFailed,
                                pwDatabase.IOConnectionInfo.GetDisplayName() +
                                MessageService.NewLine + ioc.GetDisplayName(), exSync);

                            bAllSuccess = false;
                            continue;
                        }
                    }
                }
                else
                {
                    MessageService.ShowWarning(KPRes.SyncFailed,
                        pwDatabase.IOConnectionInfo.GetDisplayName());

                    bAllSuccess = false;
                }
            }

            dlgStatus.EndLogging();
            return bAllSuccess;
        }