Beispiel #1
0
        private static void ReadReference(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);

            if ((xnInc == null) || string.IsNullOrEmpty(xnInc.Value))
            {
                Debug.Assert(false); return;
            }
            string str = xnInc.Value;

            if ((str == PwDefs.ShortProductName) || str.StartsWith(
                    PwDefs.ShortProductName + ",", StrUtil.CaseIgnoreCmp))
            {
                return;                 // Ignore KeePass references
            }
            foreach (XmlNode xnSub in xn.ChildNodes)
            {
                if (xnSub.Name == XnnHintPath)
                {
                    plgx.IncludedReferencedAssemblies.Add(
                        UrlUtil.ConvertSeparators(xnSub.InnerText, '/'));
                    return;
                }
            }

            if (!str.EndsWith(".dll", StrUtil.CaseIgnoreCmp))
            {
                str += ".dll";
            }

            plgx.CompilerParameters.ReferencedAssemblies.Add(str);
        }
Beispiel #2
0
        public static void LoadDefault(string strDirPath, PlgxPluginInfo plgxOutInfo)
        {
            if (plgxOutInfo == null)
            {
                throw new ArgumentNullException("plgxOutInfo");
            }

            string[] vCsproj = Directory.GetFiles(strDirPath, "*.csproj",
                                                  SearchOption.AllDirectories);
            if ((vCsproj != null) && (vCsproj.Length == 1))
            {
                plgxOutInfo.ProjectType = PlgxProjectType.CSharp;
                PlgxCsprojLoader.Load(vCsproj[0], plgxOutInfo);
                return;
            }

            // string[] vVbproj = Directory.GetFiles(strDirPath, "*.vbproj",
            //	SearchOption.AllDirectories);
            // if((vVbproj != null) && (vVbproj.Length == 1))
            // {
            //	plgxOutInfo.ProjectType = PlgxProjectType.VisualBasic;
            //	PlgxCsprojLoader.Load(vVbproj[0], plgxOutInfo);
            //	return;
            // }

            throw new InvalidOperationException(KPRes.CsprojCountError);
        }
Beispiel #3
0
        private static void SaveCompilerResults(PlgxPluginInfo plgx,
                                                StringBuilder sb)
        {
            string strFile = Path.GetTempFileName();

            File.WriteAllText(strFile, sb.ToString(), StrUtil.Utf8);

            string strMsg = plgx.BaseFileName + MessageService.NewParagraph +
                            "Compilation failed. Compiler results have been saved to:" +
                            MessageService.NewLine;

            VistaTaskDialog dlg = new VistaTaskDialog();

            dlg.Content          = strMsg + VistaTaskDialog.CreateLink("F", strFile);
            dlg.DefaultButtonID  = (int)DialogResult.Cancel;
            dlg.EnableHyperlinks = true;
            dlg.SetIcon(VtdIcon.Warning);
            dlg.WindowTitle = PwDefs.ShortProductName;

            dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
            dlg.LinkClicked += delegate(object sender, LinkClickedEventArgs e)
            {
                if ((e != null) && (e.LinkText == "F") && !NativeLib.IsUnix())
                {
                    NativeLib.StartProcess(WinUtil.LocateSystemApp("Notepad.exe"),
                                           "\"" + SprEncoding.EncodeForCommandLine(strFile) + "\"");
                }
            };

            if (!dlg.ShowDialog())
            {
                MessageService.ShowWarning(strMsg + strFile);
            }
        }
Beispiel #4
0
        public static void LoadDefault(string strDirPath, PlgxPluginInfo plgxOutInfo)
        {
            if (plgxOutInfo == null)
            {
                throw new ArgumentNullException("plgxOutInfo");
            }

            List <string> lCsproj = UrlUtil.GetFilePaths(strDirPath, "*.csproj",
                                                         SearchOption.AllDirectories);

            if (lCsproj.Count == 1)
            {
                plgxOutInfo.ProjectType = PlgxProjectType.CSharp;
                PlgxCsprojLoader.Load(lCsproj[0], plgxOutInfo);
                return;
            }

            // List<string> lVbproj = UrlUtil.GetFilePaths(strDirPath, "*.vbproj",
            //	SearchOption.AllDirectories);
            // if(lVbproj.Count == 1)
            // {
            //	plgxOutInfo.ProjectType = PlgxProjectType.VisualBasic;
            //	PlgxCsprojLoader.Load(lVbproj[0], plgxOutInfo);
            //	return;
            // }

            throw new InvalidOperationException(KPRes.CsprojCountError);
        }
Beispiel #5
0
        private static void PrepareSourceFiles(PlgxPluginInfo plgx)
        {
            if (plgx.ProjectType != PlgxProjectType.VisualBasic)
            {
                return;
            }

            string strImports = string.Empty;

            foreach (string strImport in plgx.VbImports)
            {
                strImports += "Imports " + strImport + "\r\n";
            }
            if (strImports.Length == 0)
            {
                return;
            }

            foreach (string strFile in plgx.SourceFiles)
            {
                if (!strFile.EndsWith(".vb", StrUtil.CaseIgnoreCmp))
                {
                    continue;
                }

                string strData = File.ReadAllText(strFile);
                File.WriteAllText(strFile, strImports + strData);
            }
        }
Beispiel #6
0
        public static string AddCacheAssembly(string strAssemblyPath, PlgxPluginInfo plgx)
        {
            if(string.IsNullOrEmpty(strAssemblyPath)) { Debug.Assert(false); return null; }

            string strNewFile = GetCacheFile(plgx, false, true);
            File.Copy(strAssemblyPath, strNewFile, true);

            return strNewFile;
        }
Beispiel #7
0
        public static string AddCacheFile(string strNormalFile, PlgxPluginInfo plgx)
        {
            if(string.IsNullOrEmpty(strNormalFile)) { Debug.Assert(false); return null; }

            string strNewFile = UrlUtil.EnsureTerminatingSeparator(GetCacheDirectory(
                plgx, true), false) + UrlUtil.GetFileName(strNormalFile);
            File.Copy(strNormalFile, strNewFile, true);

            return strNewFile;
        }
Beispiel #8
0
 private static void ReadPropertyGroup(XmlNode xn, PlgxPluginInfo plgx)
 {
     foreach (XmlNode xnChild in xn.ChildNodes)
     {
         if (xnChild.Name == XnnAssemblyName)
         {
             plgx.BaseFileName = xnChild.InnerText;
         }
     }
 }
Beispiel #9
0
        private static void ReadCompile(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);

            if ((xnInc == null) || string.IsNullOrEmpty(xnInc.Value))
            {
                Debug.Assert(false); return;
            }

            plgx.SourceFiles.Add(plgx.GetAbsPath(xnInc.Value));
        }
Beispiel #10
0
        private static void Load(string strFilePath, PlgxPluginInfo plgxOutInfo)
        {
            if(strFilePath == null) throw new ArgumentNullException("strFilePath");

            plgxOutInfo.CsprojFilePath = strFilePath;

            XmlDocument doc = new XmlDocument();
            doc.Load(strFilePath);

            ReadProject(doc.DocumentElement, plgxOutInfo);
        }
Beispiel #11
0
        private static void SaveCompilerResults(PlgxPluginInfo plgx,
                                                StringBuilder sb)
        {
            string strFile = Path.GetTempFileName();

            File.WriteAllText(strFile, sb.ToString(), StrUtil.Utf8);

            MessageService.ShowWarning(plgx.BaseFileName,
                                       "Compilation failed. Compiler results have been saved to:" +
                                       Environment.NewLine + strFile);
        }
Beispiel #12
0
        private static void ReadEmbeddedRes(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);

            if ((xnInc == null) || string.IsNullOrEmpty(xnInc.Value))
            {
                Debug.Assert(false); return;
            }

            string strResSrc = plgx.GetAbsPath(xnInc.Value);

            plgx.EmbeddedResourceSources.Add(strResSrc);
        }
Beispiel #13
0
        public static string AddCacheAssembly(string strAssemblyPath, PlgxPluginInfo plgx)
        {
            if (string.IsNullOrEmpty(strAssemblyPath))
            {
                Debug.Assert(false); return(null);
            }

            string strNewFile = GetCacheFile(plgx, false, true);

            File.Copy(strAssemblyPath, strNewFile, true);

            return(strNewFile);
        }
Beispiel #14
0
        public static string AddCacheFile(string strNormalFile, PlgxPluginInfo plgx)
        {
            if (string.IsNullOrEmpty(strNormalFile))
            {
                Debug.Assert(false); return(null);
            }

            string strNewFile = UrlUtil.EnsureTerminatingSeparator(GetCacheDirectory(
                                                                       plgx, true), false) + UrlUtil.GetFileName(strNormalFile);

            File.Copy(strNormalFile, strNewFile, true);

            return(strNewFile);
        }
Beispiel #15
0
        private static void Load(string strFilePath, PlgxPluginInfo plgxOutInfo)
        {
            if (strFilePath == null)
            {
                throw new ArgumentNullException("strFilePath");
            }

            plgxOutInfo.CsprojFilePath = strFilePath;

            XmlDocument doc = new XmlDocument();

            doc.Load(strFilePath);

            ReadProject(doc.DocumentElement, plgxOutInfo);
        }
Beispiel #16
0
        private static void ReadImport(XmlNode xn, PlgxPluginInfo plgx)
        {
            if (plgx.ProjectType != PlgxProjectType.VisualBasic)
            {
                Debug.Assert(false); return;
            }

            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);

            if ((xnInc == null) || string.IsNullOrEmpty(xnInc.Value))
            {
                Debug.Assert(false); return;
            }

            plgx.VbImports.Add(xnInc.Value);
        }
Beispiel #17
0
        private static void ReadProject(XmlNode xn, PlgxPluginInfo plgx)
        {
            if (xn.Name != XnnProject)
            {
                throw new Exception(KLRes.FileCorrupted);
            }

            foreach (XmlNode xnChild in xn.ChildNodes)
            {
                if (xnChild.Name == XnnPropertyGroup)
                {
                    ReadPropertyGroup(xnChild, plgx);
                }
                else if (xnChild.Name == XnnItemGroup)
                {
                    ReadItemGroup(xnChild, plgx);
                }
            }
        }
Beispiel #18
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
                                            out CompilerResults cr, string strCompilerVersion)
        {
            try
            {
                Dictionary <string, string> dictOpt = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(strCompilerVersion))
                {
                    dictOpt.Add("CompilerVersion", strCompilerVersion);
                }

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if (WinUtil.IsWindows9x)
                {
                    dictOpt.Clear();
                }

                CodeDomProvider cdp = null;
                if (plgx.ProjectType == PlgxProjectType.CSharp)
                {
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                           CreateCscProvider(dictOpt));
                }
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else
                {
                    throw new InvalidOperationException();
                }

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                                                 plgx.SourceFiles.ToArray());

                return((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch (Exception) { }

            cr = null;
            return(false);
        }
Beispiel #19
0
        private static void CompileEmbeddedRes(PlgxPluginInfo plgx)
        {
            foreach (string strResSrc in plgx.EmbeddedResourceSources)
            {
                string strResFileName = plgx.BaseFileName + "." + UrlUtil.ConvertSeparators(
                    UrlUtil.MakeRelativePath(plgx.CsprojFilePath, strResSrc), '.');
                string strResFile = UrlUtil.GetFileDirectory(plgx.CsprojFilePath, true,
                                                             true) + strResFileName;

                if (strResSrc.EndsWith(".resx", StrUtil.CaseIgnoreCmp))
                {
                    PrepareResXFile(strResSrc);

                    string             strRsrc = UrlUtil.StripExtension(strResFile) + ".resources";
                    ResXResourceReader r       = new ResXResourceReader(strResSrc);
                    ResourceWriter     w       = new ResourceWriter(strRsrc);

                    r.BasePath = UrlUtil.GetFileDirectory(strResSrc, false, true);

                    foreach (DictionaryEntry de in r)
                    {
                        w.AddResource((string)de.Key, de.Value);
                    }

                    w.Generate();
                    w.Close();
                    r.Close();

                    if (File.Exists(strRsrc))
                    {
                        plgx.CompilerParameters.EmbeddedResources.Add(strRsrc);
                        Program.TempFilesPool.Add(strRsrc);
                    }
                }
                else
                {
                    File.Copy(strResSrc, strResFile, true);
                    plgx.CompilerParameters.EmbeddedResources.Add(strResFile);
                }
            }
        }
Beispiel #20
0
 private static void ReadItemGroup(XmlNode xn, PlgxPluginInfo plgx)
 {
     foreach (XmlNode xnChild in xn.ChildNodes)
     {
         if (xnChild.Name == XnnEmbeddedRes)
         {
             ReadEmbeddedRes(xnChild, plgx);
         }
         else if (xnChild.Name == XnnReference)
         {
             ReadReference(xnChild, plgx);
         }
         else if (xnChild.Name == XnnCompile)
         {
             ReadCompile(xnChild, plgx);
         }
         else if (xnChild.Name == XnnImport)
         {
             ReadImport(xnChild, plgx);
         }
     }
 }
        private static void ExtractPluginSourceCode(string strDirPath, PlgxPluginInfo plgxOutInfo)
        {
            var rootFolder = _pluginsSourceCodeExtractRootFolder;

            rootFolder += plgxOutInfo.BaseFileName + "/";
            strDirPath += strDirPath.EndsWith("\\") ? "" : "\\";
            var regex = new Regex(Regex.Escape(strDirPath));

            //Extract folders
            foreach (string folderPath in Directory.GetDirectories(strDirPath, "*", SearchOption.AllDirectories))
            {
                var newPath = regex.Replace(folderPath, rootFolder, 1);
                Directory.CreateDirectory(newPath);
            }

            //Extract files
            foreach (string filePath in Directory.GetFiles(strDirPath, "*", SearchOption.AllDirectories))
            {
                var newPath = regex.Replace(filePath, rootFolder, 1);
                File.Copy(filePath, newPath, true);
            }
        }
Beispiel #22
0
        public static string GetCacheFile(PlgxPluginInfo plgx, bool bMustExist,
                                          bool bCreateDirectory)
        {
            if (plgx == null)
            {
                Debug.Assert(false); return(null);
            }

            // byte[] pbID = new byte[(int)PwUuid.UuidSize];
            // Array.Copy(pwPluginUuid.UuidBytes, 0, pbID, 0, pbID.Length);
            // Array.Reverse(pbID);
            // string strID = Convert.ToBase64String(pbID, Base64FormattingOptions.None);
            // strID = StrUtil.AlphaNumericOnly(strID);
            // if(strID.Length > 8) strID = strID.Substring(0, 8);

            string strFileName = StrUtil.AlphaNumericOnly(plgx.BaseFileName);

            if (strFileName.Length == 0)
            {
                strFileName = "Plugin";
            }
            strFileName += ".dll";

            string strDir  = GetCacheDirectory(plgx, bCreateDirectory);
            string strPath = strDir + Path.DirectorySeparatorChar + strFileName;
            bool   bExists = File.Exists(strPath);

            if (bMustExist && bExists)
            {
                try { File.SetLastAccessTime(strPath, DateTime.Now); }
                catch (Exception) { }                // Might be locked by other KeePass instance
            }

            if (!bMustExist || bExists)
            {
                return(strPath);
            }
            return(null);
        }
Beispiel #23
0
        public static string GetCacheDirectory(PlgxPluginInfo plgx, bool bEnsureExists)
        {
            if (plgx == null)
            {
                Debug.Assert(false); return(null);
            }

            StringBuilder sb = new StringBuilder();

            sb.Append(plgx.BaseFileName);
            sb.Append(':');
            sb.Append(Convert.ToBase64String(plgx.FileUuid.UuidBytes,
                                             Base64FormattingOptions.None));
            sb.Append(';');
            sb.Append(GetAppEnvID());

            byte[]        pbID   = StrUtil.Utf8.GetBytes(sb.ToString());
            SHA256Managed sha256 = new SHA256Managed();

            byte[] pbHash = sha256.ComputeHash(pbID);

            string strHash = Convert.ToBase64String(pbHash, Base64FormattingOptions.None);

            strHash = StrUtil.AlphaNumericOnly(strHash);
            if (strHash.Length > 20)
            {
                strHash = strHash.Substring(0, 20);
            }

            string strDir = GetCacheRoot() + Path.DirectorySeparatorChar + strHash;

            if (bEnsureExists && !Directory.Exists(strDir))
            {
                Directory.CreateDirectory(strDir);
            }

            return(strDir);
        }
Beispiel #24
0
        private static void SaveCompilerResults(PlgxPluginInfo plgx,
                                                CompilerResults cr)
        {
            if (cr == null)
            {
                Debug.Assert(false); return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (string strOut in cr.Output)
            {
                sb.AppendLine(strOut);
            }

            string strFile = Path.GetTempFileName();

            File.WriteAllText(strFile, sb.ToString(), new UTF8Encoding(false));

            MessageService.ShowWarning(plgx.BaseFileName,
                                       "Compilation failed. Compiler results have been saved to:" +
                                       Environment.NewLine + strFile);
        }
Beispiel #25
0
        private static void LoadPriv(string strFilePath, IStatusLogger slStatus,
                                     bool bAllowCached, bool bAllowCompile, bool bAllowLoad, TextWriter twLog)
        {
            if (strFilePath == null)
            {
                Debug.Assert(false); return;
            }

            FileInfo fi = new FileInfo(strFilePath);

            if (fi.Length < 12)
            {
                return;                            // Ignore file, don't throw
            }
            FileStream fs = new FileStream(strFilePath, FileMode.Open,
                                           FileAccess.Read, FileShare.Read);
            BinaryReader br = new BinaryReader(fs);

            PlgxPluginInfo plgx = new PlgxPluginInfo(true, bAllowCached, bAllowCompile);

            plgx.LogStream = twLog;

            string strPluginPath = null;

            try { strPluginPath = ReadFile(br, plgx, slStatus); }
            finally
            {
                br.Close();
                fs.Close();
            }

            if (!string.IsNullOrEmpty(strPluginPath) && bAllowLoad)
            {
                Program.MainForm.PluginManager.LoadPlugin(strPluginPath,
                                                          plgx.BaseFileName, strFilePath, false);
            }
        }
Beispiel #26
0
        public static void LoadDefault(string strDirPath, PlgxPluginInfo plgxOutInfo)
        {
            if(plgxOutInfo == null) throw new ArgumentNullException("plgxOutInfo");

            string[] vCsproj = UrlUtil.GetFilePaths(strDirPath, "*.csproj",
                SearchOption.AllDirectories).ToArray();
            if(vCsproj.Length == 1)
            {
                plgxOutInfo.ProjectType = PlgxProjectType.CSharp;
                PlgxCsprojLoader.Load(vCsproj[0], plgxOutInfo);
                return;
            }

            // string[] vVbproj = UrlUtil.GetFilePaths(strDirPath, "*.vbproj",
            //	SearchOption.AllDirectories).ToArray();
            // if(vVbproj.Length == 1)
            // {
            //	plgxOutInfo.ProjectType = PlgxProjectType.VisualBasic;
            //	PlgxCsprojLoader.Load(vVbproj[0], plgxOutInfo);
            //	return;
            // }

            throw new InvalidOperationException(KPRes.CsprojCountError);
        }
Beispiel #27
0
 private static void ReadItemGroup(XmlNode xn, PlgxPluginInfo plgx)
 {
     foreach(XmlNode xnChild in xn.ChildNodes)
     {
         if(xnChild.Name == XnnEmbeddedRes) ReadEmbeddedRes(xnChild, plgx);
         else if(xnChild.Name == XnnReference) ReadReference(xnChild, plgx);
         else if(xnChild.Name == XnnCompile) ReadCompile(xnChild, plgx);
         else if(xnChild.Name == XnnImport) ReadImport(xnChild, plgx);
     }
 }
Beispiel #28
0
        private static void ReadProject(XmlNode xn, PlgxPluginInfo plgx)
        {
            if(xn.Name != XnnProject) throw new Exception(KLRes.FileCorrupted);

            foreach(XmlNode xnChild in xn.ChildNodes)
            {
                if(xnChild.Name == XnnPropertyGroup) ReadPropertyGroup(xnChild, plgx);
                else if(xnChild.Name == XnnItemGroup) ReadItemGroup(xnChild, plgx);
            }
        }
Beispiel #29
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
                                            out CompilerResults cr, string strCompilerVersion)
        {
            cr = null;

            const string StrCoreRef = "System.Core";
            const string StrCoreDll = "System.Core.dll";
            bool         bHasCore = false, bCoreAdded = false;

            foreach (string strAsm in plgx.CompilerParameters.ReferencedAssemblies)
            {
                if (UrlUtil.AssemblyEquals(strAsm, StrCoreRef))
                {
                    bHasCore = true;
                    break;
                }
            }
            if ((strCompilerVersion != null) && strCompilerVersion.StartsWith(
                    "v", StrUtil.CaseIgnoreCmp))
            {
                ulong v = StrUtil.ParseVersion(strCompilerVersion.Substring(1));
                if (!bHasCore && (v >= 0x0003000500000000UL))
                {
                    plgx.CompilerParameters.ReferencedAssemblies.Add(StrCoreDll);
                    bCoreAdded = true;
                }
            }

            bool bResult = false;

            try
            {
                Dictionary <string, string> dictOpt = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(strCompilerVersion))
                {
                    dictOpt.Add("CompilerVersion", strCompilerVersion);
                }

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if (WinUtil.IsWindows9x)
                {
                    dictOpt.Clear();
                }

                CodeDomProvider cdp = null;
                if (plgx.ProjectType == PlgxProjectType.CSharp)
                {
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                           CreateCscProvider(dictOpt));
                }
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else
                {
                    throw new InvalidOperationException();
                }

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                                                 plgx.SourceFiles.ToArray());

                bResult = ((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch (Exception) { }

            if (bCoreAdded)
            {
                plgx.CompilerParameters.ReferencedAssemblies.Remove(StrCoreDll);
            }

            return(bResult);
        }
Beispiel #30
0
        private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
                                      string strBuildPre, string strBuildPost)
        {
            if (strTmpRoot == null)
            {
                Debug.Assert(false); return(null);
            }

            RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), null);

            PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

            List <string> vCustomRefs = new List <string>();

            foreach (string strIncRefAsm in plgx.IncludedReferencedAssemblies)
            {
                string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
                                                       strIncRefAsm));
                string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
                if (string.IsNullOrEmpty(strCached))
                {
                    throw new InvalidOperationException();
                }
                vCustomRefs.Add(strCached);
            }

            CompilerParameters cp = plgx.CompilerParameters;

            cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
                                                                   false) + UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx.FileUuid,
                                                                                                                       false, false));
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors   = false;
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            foreach (string strCustomRef in vCustomRefs)
            {
                cp.ReferencedAssemblies.Add(strCustomRef);
            }

            CompileEmbeddedRes(plgx);
            PrepareSourceFiles(plgx);

            CompilerResults cr;

            if (!CompileAssembly(plgx, out cr, null))
            {
                if (!CompileAssembly(plgx, out cr, "v3.5"))
                {
                    throw new InvalidOperationException();
                }
            }

            Program.TempFilesPool.Add(cr.PathToAssembly);

            Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
            string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

            RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

            return(strCacheAsm);
        }
Beispiel #31
0
 private static void ReadPropertyGroup(XmlNode xn, PlgxPluginInfo plgx)
 {
     foreach(XmlNode xnChild in xn.ChildNodes)
     {
         if(xnChild.Name == XnnAssemblyName)
             plgx.BaseFileName = xnChild.InnerText;
     }
 }
Beispiel #32
0
		private static bool CompileAssembly(PlgxPluginInfo plgx,
			out CompilerResults cr, string strCompilerVersion)
		{
			cr = null;

			const string StrCoreRef = "System.Core";
			const string StrCoreDll = "System.Core.dll";
			bool bHasCore = false, bCoreAdded = false;
			foreach(string strAsm in plgx.CompilerParameters.ReferencedAssemblies)
			{
				if(UrlUtil.AssemblyEquals(strAsm, StrCoreRef))
				{
					bHasCore = true;
					break;
				}
			}
			if((strCompilerVersion != null) && strCompilerVersion.StartsWith(
				"v", StrUtil.CaseIgnoreCmp))
			{
				ulong v = StrUtil.ParseVersion(strCompilerVersion.Substring(1));
				if(!bHasCore && (v >= 0x0003000500000000UL))
				{
					plgx.CompilerParameters.ReferencedAssemblies.Add(StrCoreDll);
					bCoreAdded = true;
				}
			}

			bool bResult = false;
			try
			{
				Dictionary<string, string> dictOpt = new Dictionary<string, string>();
				if(!string.IsNullOrEmpty(strCompilerVersion))
					dictOpt.Add("CompilerVersion", strCompilerVersion);

				// Windows 98 only supports the parameterless constructor;
				// check must be separate from the instantiation method
				if(WinUtil.IsWindows9x) dictOpt.Clear();

				CodeDomProvider cdp = null;
				if(plgx.ProjectType == PlgxProjectType.CSharp)
					cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
						CreateCscProvider(dictOpt));
				// else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
				//	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
				//		new VBCodeProvider(dictOpt));
				else throw new InvalidOperationException();

				cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
					plgx.SourceFiles.ToArray());

				bResult = ((cr.Errors == null) || !cr.Errors.HasErrors);
			}
			catch(Exception) { }

			if(bCoreAdded)
				plgx.CompilerParameters.ReferencedAssemblies.Remove(StrCoreDll);

			return bResult;
		}
Beispiel #33
0
        private static void ReadEmbeddedRes(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);
            if((xnInc == null) || string.IsNullOrEmpty(xnInc.Value)) { Debug.Assert(false); return; }

            string strResSrc = plgx.GetAbsPath(xnInc.Value); // Converts separators
            plgx.EmbeddedResourceSources.Add(strResSrc);
        }
Beispiel #34
0
		private static void CreateFromDirectory(string strDirPath)
		{
			string strPlgx = strDirPath + "." + PlgxExtension;

			PlgxPluginInfo plgx = new PlgxPluginInfo(false, true, true);
			PlgxCsprojLoader.LoadDefault(strDirPath, plgx);

			FileStream fs = new FileStream(strPlgx, FileMode.Create,
				FileAccess.Write, FileShare.None);
			BinaryWriter bw = new BinaryWriter(fs);

			bw.Write(PlgxSignature1);
			bw.Write(PlgxSignature2);
			bw.Write(PlgxVersion);
			WriteObject(bw, PlgxFileUuid, (new PwUuid(true)).UuidBytes);
			WriteObject(bw, PlgxBaseFileName, StrUtil.Utf8.GetBytes(
				plgx.BaseFileName));
			WriteObject(bw, PlgxCreationTime, StrUtil.Utf8.GetBytes(
				TimeUtil.SerializeUtc(DateTime.Now)));
			WriteObject(bw, PlgxGeneratorName, StrUtil.Utf8.GetBytes(
				PwDefs.ShortProductName));
			WriteObject(bw, PlgxGeneratorVersion, MemUtil.UInt64ToBytes(
				PwDefs.FileVersion64));

			string strKP = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqKP];
			if(!string.IsNullOrEmpty(strKP))
			{
				ulong uKP = StrUtil.ParseVersion(strKP);
				if(uKP != 0) WriteObject(bw, PlgxPrereqKP, MemUtil.UInt64ToBytes(uKP));
			}

			string strNet = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqNet];
			if(!string.IsNullOrEmpty(strNet))
			{
				ulong uNet = StrUtil.ParseVersion(strNet);
				if(uNet != 0) WriteObject(bw, PlgxPrereqNet, MemUtil.UInt64ToBytes(uNet));
			}

			string strOS = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqOS];
			if(!string.IsNullOrEmpty(strOS))
				WriteObject(bw, PlgxPrereqOS, StrUtil.Utf8.GetBytes(strOS));

			string strPtr = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqPtr];
			if(!string.IsNullOrEmpty(strPtr))
			{
				uint uPtr;
				if(uint.TryParse(strPtr, out uPtr))
					WriteObject(bw, PlgxPrereqPtr, MemUtil.UInt32ToBytes(uPtr));
			}

			string strBuildPre = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPre];
			if(!string.IsNullOrEmpty(strBuildPre))
				WriteObject(bw, PlgxBuildPre, StrUtil.Utf8.GetBytes(strBuildPre));

			string strBuildPost = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPost];
			if(!string.IsNullOrEmpty(strBuildPost))
				WriteObject(bw, PlgxBuildPost, StrUtil.Utf8.GetBytes(strBuildPost));

			WriteObject(bw, PlgxBeginContent, null);

			RecursiveFileAdd(bw, strDirPath, new DirectoryInfo(strDirPath));

			WriteObject(bw, PlgxEndContent, null);
			WriteObject(bw, PlgxEOF, null);

			bw.Close();
			fs.Close();

			// Test loading not possible, because MainForm not available
			// PlgxPlugin.Load(strPlgx);
		}
Beispiel #35
0
		private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
			string strBuildPre, string strBuildPost)
		{
			if(strTmpRoot == null) { Debug.Assert(false); return null; }

			RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
				strTmpRoot, false), null);

			PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

			List<string> vCustomRefs = new List<string>();
			foreach(string strIncRefAsm in plgx.IncludedReferencedAssemblies)
			{
				string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
					strIncRefAsm));
				string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
				if(string.IsNullOrEmpty(strCached))
					throw new InvalidOperationException();
				vCustomRefs.Add(strCached);
			}

			CompilerParameters cp = plgx.CompilerParameters;
			cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot, false) +
				UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx, false, false));
			cp.GenerateExecutable = false;
			cp.GenerateInMemory = false;
			cp.IncludeDebugInformation = false;
			cp.TreatWarningsAsErrors = false;
			cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
			foreach(string strCustomRef in vCustomRefs)
				cp.ReferencedAssemblies.Add(strCustomRef);

			CompileEmbeddedRes(plgx);
			PrepareSourceFiles(plgx);

			string[] vCompilers;
			Version vClr = Environment.Version;
			int iClrMajor = vClr.Major, iClrMinor = vClr.Minor;
			if((iClrMajor >= 5) || ((iClrMajor == 4) && (iClrMinor >= 5)))
			{
				vCompilers = new string[] {
					null,
					"v4.5",
					"v4", // Suggested in CodeDomProvider.CreateProvider doc
					"v4.0", // Suggested in community content of the above
					"v4.0.30319", // Deduced from file system
					"v3.5"
				};
			}
			else if(iClrMajor == 4) // 4.0
			{
				vCompilers = new string[] {
					null,
					"v4", // Suggested in CodeDomProvider.CreateProvider doc
					"v4.0", // Suggested in community content of the above
					"v4.0.30319", // Deduced from file system
					"v4.5",
					"v3.5"
				};
			}
			else // <= 3.5
			{
				vCompilers = new string[] {
					null,
					"v3.5",
					"v4", // Suggested in CodeDomProvider.CreateProvider doc
					"v4.0", // Suggested in community content of the above
					"v4.0.30319", // Deduced from file system
					"v4.5"
				};
			}

			CompilerResults cr = null;
			StringBuilder sbCompilerLog = new StringBuilder();
			bool bCompiled = false;
			for(int iCmp = 0; iCmp < vCompilers.Length; ++iCmp)
			{
				if(CompileAssembly(plgx, out cr, vCompilers[iCmp]))
				{
					bCompiled = true;
					break;
				}

				if(cr != null)
					AppendCompilerResults(sbCompilerLog, vCompilers[iCmp], cr);
			}

			if(!bCompiled)
			{
				if(Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)
					SaveCompilerResults(plgx, sbCompilerLog);

				throw new InvalidOperationException();
			}

			Program.TempFilesPool.Add(cr.PathToAssembly);

			Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
			string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

			RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
				strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

			return strCacheAsm;
		}
Beispiel #36
0
		private static void ExtractFile(byte[] pbData, string strTmpRoot,
			PlgxPluginInfo plgx)
		{
			MemoryStream ms = new MemoryStream(pbData, false);
			BinaryReader br = new BinaryReader(ms);

			string strPath = null;
			byte[] pbContent = null;

			while(true)
			{
				KeyValuePair<ushort, byte[]> kvp = ReadObject(br);

				if(kvp.Key == PlgxfEOF) break;
				else if(kvp.Key == PlgxfPath)
					strPath = StrUtil.Utf8.GetString(kvp.Value);
				else if(kvp.Key == PlgxfData) pbContent = kvp.Value;
				else { Debug.Assert(false); }
			}

			br.Close();
			ms.Close();

			if(!string.IsNullOrEmpty(strPath) && (pbContent != null))
			{
				string strTmpFile = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
					false) + UrlUtil.ConvertSeparators(strPath);

				string strTmpDir = UrlUtil.GetFileDirectory(strTmpFile, false, true);
				if(!Directory.Exists(strTmpDir)) Directory.CreateDirectory(strTmpDir);

				byte[] pbDecompressed = MemUtil.Decompress(pbContent);
				File.WriteAllBytes(strTmpFile, pbDecompressed);

				// Although the temporary directory will be deleted recursively
				// anyway, add the extracted file here manually, in order to
				// minimize left-over files in case the recursive deletion fails
				// due to locked / in-use files
				Program.TempFilesPool.Add(strTmpFile);

				if(plgx.LogStream != null)
				{
					MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
					byte[] pbMD5 = md5.ComputeHash(pbDecompressed);
					plgx.LogStream.Write(MemUtil.ByteArrayToHexString(pbMD5));
					plgx.LogStream.WriteLine(" " + strPath);
				}
			}
			else { Debug.Assert(false); }
		}
Beispiel #37
0
		private static string ReadFile(BinaryReader br, PlgxPluginInfo plgx,
			IStatusLogger slStatus)
		{
			uint uSig1 = br.ReadUInt32();
			uint uSig2 = br.ReadUInt32();
			uint uVersion = br.ReadUInt32();

			if((uSig1 != PlgxSignature1) || (uSig2 != PlgxSignature2))
				return null; // Ignore file, don't throw
			if((uVersion & PlgxVersionMask) > (PlgxVersion & PlgxVersionMask))
				throw new PlgxException(KLRes.FileVersionUnsupported);

			string strPluginPath = null;
			string strTmpRoot = null;
			bool? bContent = null;
			string strBuildPre = null, strBuildPost = null;

			while(true)
			{
				KeyValuePair<ushort, byte[]> kvp = ReadObject(br);

				if(kvp.Key == PlgxEOF) break;
				else if(kvp.Key == PlgxFileUuid)
					plgx.FileUuid = new PwUuid(kvp.Value);
				else if(kvp.Key == PlgxBaseFileName)
					plgx.BaseFileName = StrUtil.Utf8.GetString(kvp.Value);
				else if(kvp.Key == PlgxCreationTime) { } // Ignore
				else if(kvp.Key == PlgxGeneratorName) { }
				else if(kvp.Key == PlgxGeneratorVersion) { }
				else if(kvp.Key == PlgxPrereqKP)
				{
					ulong uReq = MemUtil.BytesToUInt64(kvp.Value);
					if(uReq > PwDefs.FileVersion64)
						throw new PlgxException(KLRes.FileNewVerReq);
				}
				else if(kvp.Key == PlgxPrereqNet)
				{
					ulong uReq = MemUtil.BytesToUInt64(kvp.Value);
					ulong uInst = WinUtil.GetMaxNetFrameworkVersion();
					if((uInst != 0) && (uReq > uInst))
						throw new PlgxException(KPRes.NewerNetRequired);
				}
				else if(kvp.Key == PlgxPrereqOS)
				{
					string strOS = "," + WinUtil.GetOSStr() + ",";
					string strReq = "," + StrUtil.Utf8.GetString(kvp.Value) + ",";
					if(strReq.IndexOf(strOS, StrUtil.CaseIgnoreCmp) < 0)
						throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
				}
				else if(kvp.Key == PlgxPrereqPtr)
				{
					uint uReq = MemUtil.BytesToUInt32(kvp.Value);
					if(uReq > (uint)IntPtr.Size)
						throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
				}
				else if(kvp.Key == PlgxBuildPre)
					strBuildPre = StrUtil.Utf8.GetString(kvp.Value);
				else if(kvp.Key == PlgxBuildPost)
					strBuildPost = StrUtil.Utf8.GetString(kvp.Value);
				else if(kvp.Key == PlgxBeginContent)
				{
					if(bContent.HasValue)
						throw new PlgxException(KLRes.FileCorrupted);

					string strCached = PlgxCache.GetCacheFile(plgx, true, false);
					if(!string.IsNullOrEmpty(strCached) && plgx.AllowCached)
					{
						strPluginPath = strCached;
						break;
					}

					if(slStatus != null)
						slStatus.SetText(KPRes.PluginsCompilingAndLoading,
							LogStatusType.Info);

					bContent = true;
					if(plgx.LogStream != null) plgx.LogStream.WriteLine("Content:");
				}
				else if(kvp.Key == PlgxFile)
				{
					if(!bContent.HasValue || !bContent.Value)
						throw new PlgxException(KLRes.FileCorrupted);

					if(strTmpRoot == null) strTmpRoot = CreateTempDirectory();
					ExtractFile(kvp.Value, strTmpRoot, plgx);
				}
				else if(kvp.Key == PlgxEndContent)
				{
					if(!bContent.HasValue || !bContent.Value)
						throw new PlgxException(KLRes.FileCorrupted);

					bContent = false;
				}
				else { Debug.Assert(false); }
			}

			if((strPluginPath == null) && plgx.AllowCompile)
				strPluginPath = Compile(strTmpRoot, plgx, strBuildPre, strBuildPost);

			return strPluginPath;
		}
Beispiel #38
0
		private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
			string strBuildPre, string strBuildPost)
		{
			if(strTmpRoot == null) { Debug.Assert(false); return null; }

			RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
				strTmpRoot, false), null);

			PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

			List<string> vCustomRefs = new List<string>();
			foreach(string strIncRefAsm in plgx.IncludedReferencedAssemblies)
			{
				string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
					strIncRefAsm));
				string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
				if(string.IsNullOrEmpty(strCached))
					throw new InvalidOperationException();
				vCustomRefs.Add(strCached);
			}

			CompilerParameters cp = plgx.CompilerParameters;
			cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
				false) + UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx.FileUuid,
				false, false));
			cp.GenerateExecutable = false;
			cp.GenerateInMemory = false;
			cp.IncludeDebugInformation = false;
			cp.TreatWarningsAsErrors = false;
			cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
			foreach(string strCustomRef in vCustomRefs)
				cp.ReferencedAssemblies.Add(strCustomRef);

			CompileEmbeddedRes(plgx);
			PrepareSourceFiles(plgx);

			CompilerResults cr;
			if(!CompileAssembly(plgx, out cr, null))
				if(!CompileAssembly(plgx, out cr, "v3.5"))
					throw new InvalidOperationException();

			Program.TempFilesPool.Add(cr.PathToAssembly);

			Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
			string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

			RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
				strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

			return strCacheAsm;
		}
Beispiel #39
0
        public static string GetCacheFile(PlgxPluginInfo plgx, bool bMustExist,
			bool bCreateDirectory)
        {
            if(plgx == null) { Debug.Assert(false); return null; }

            // byte[] pbID = new byte[(int)PwUuid.UuidSize];
            // Array.Copy(pwPluginUuid.UuidBytes, 0, pbID, 0, pbID.Length);
            // Array.Reverse(pbID);
            // string strID = Convert.ToBase64String(pbID, Base64FormattingOptions.None);
            // strID = StrUtil.AlphaNumericOnly(strID);
            // if(strID.Length > 8) strID = strID.Substring(0, 8);

            string strFileName = StrUtil.AlphaNumericOnly(plgx.BaseFileName);
            if(strFileName.Length == 0) strFileName = "Plugin";
            strFileName += ".dll";

            string strDir = GetCacheDirectory(plgx, bCreateDirectory);
            string strPath = strDir + Path.DirectorySeparatorChar + strFileName;
            bool bExists = File.Exists(strPath);

            if(bMustExist && bExists)
            {
                try { File.SetLastAccessTime(strPath, DateTime.Now); }
                catch(Exception) { } // Might be locked by other KeePass instance
            }

            if(!bMustExist || bExists) return strPath;
            return null;
        }
Beispiel #40
0
		private static void SaveCompilerResults(PlgxPluginInfo plgx,
			StringBuilder sb)
		{
			string strFile = Path.GetTempFileName();
			File.WriteAllText(strFile, sb.ToString(), StrUtil.Utf8);

			MessageService.ShowWarning(plgx.BaseFileName,
				"Compilation failed. Compiler results have been saved to:" +
				Environment.NewLine + strFile);
		}
Beispiel #41
0
        private static void ReadImport(XmlNode xn, PlgxPluginInfo plgx)
        {
            if(plgx.ProjectType != PlgxProjectType.VisualBasic) { Debug.Assert(false); return; }

            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);
            if((xnInc == null) || string.IsNullOrEmpty(xnInc.Value)) { Debug.Assert(false); return; }

            plgx.VbImports.Add(UrlUtil.ConvertSeparators(xnInc.Value));
        }
Beispiel #42
0
        private static string ReadFile(BinaryReader br, PlgxPluginInfo plgx,
                                       IStatusLogger slStatus)
        {
            uint uSig1    = br.ReadUInt32();
            uint uSig2    = br.ReadUInt32();
            uint uVersion = br.ReadUInt32();

            if ((uSig1 != PlgxSignature1) || (uSig2 != PlgxSignature2))
            {
                return(null);                // Ignore file, don't throw
            }
            if ((uVersion & PlgxVersionMask) > (PlgxVersion & PlgxVersionMask))
            {
                throw new PlgxException(KLRes.FileVersionUnsupported);
            }

            string strPluginPath = null;
            string strTmpRoot = null;
            bool?  obContent = null;
            string strBuildPre = null, strBuildPost = null;

            while (true)
            {
                KeyValuePair <ushort, byte[]> kvp = ReadObject(br);

                if (kvp.Key == PlgxEOF)
                {
                    break;
                }
                else if (kvp.Key == PlgxFileUuid)
                {
                    plgx.FileUuid = new PwUuid(kvp.Value);
                }
                else if (kvp.Key == PlgxBaseFileName)
                {
                    plgx.BaseFileName = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxCreationTime)
                {
                }                                                        // Ignore
                else if (kvp.Key == PlgxGeneratorName)
                {
                }
                else if (kvp.Key == PlgxGeneratorVersion)
                {
                }
                else if (kvp.Key == PlgxPrereqKP)
                {
                    ulong uReq = MemUtil.BytesToUInt64(kvp.Value);
                    if (uReq > PwDefs.FileVersion64)
                    {
                        throw new PlgxException(KLRes.FileNewVerReq);
                    }
                }
                else if (kvp.Key == PlgxPrereqNet)
                {
                    ulong uReq  = MemUtil.BytesToUInt64(kvp.Value);
                    ulong uInst = WinUtil.GetMaxNetFrameworkVersion();
                    if ((uInst != 0) && (uReq > uInst))
                    {
                        throw new PlgxException(KPRes.NewerNetRequired);
                    }
                }
                else if (kvp.Key == PlgxPrereqOS)
                {
                    string strOS  = "," + WinUtil.GetOSStr() + ",";
                    string strReq = "," + StrUtil.Utf8.GetString(kvp.Value) + ",";
                    if (strReq.IndexOf(strOS, StrUtil.CaseIgnoreCmp) < 0)
                    {
                        throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
                    }
                }
                else if (kvp.Key == PlgxPrereqPtr)
                {
                    uint uReq = MemUtil.BytesToUInt32(kvp.Value);
                    if (uReq > (uint)IntPtr.Size)
                    {
                        throw new PlgxException(KPRes.PluginOperatingSystemUnsupported);
                    }
                }
                else if (kvp.Key == PlgxBuildPre)
                {
                    strBuildPre = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxBuildPost)
                {
                    strBuildPost = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxBeginContent)
                {
                    if (obContent.HasValue)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    string strCached = PlgxCache.GetCacheFile(plgx, true, false);
                    if (!string.IsNullOrEmpty(strCached) && plgx.AllowCached)
                    {
                        strPluginPath = strCached;
                        break;
                    }

                    if (slStatus != null)
                    {
                        slStatus.SetText(KPRes.PluginsCompilingAndLoading,
                                         LogStatusType.Info);
                    }

                    obContent = true;
                    if (plgx.LogStream != null)
                    {
                        plgx.LogStream.WriteLine("Content:");
                    }
                }
                else if (kvp.Key == PlgxFile)
                {
                    if (!obContent.HasValue || !obContent.Value)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    if (strTmpRoot == null)
                    {
                        strTmpRoot = CreateTempDirectory();
                    }
                    ExtractFile(kvp.Value, strTmpRoot, plgx);
                }
                else if (kvp.Key == PlgxEndContent)
                {
                    if (!obContent.HasValue || !obContent.Value)
                    {
                        throw new PlgxException(KLRes.FileCorrupted);
                    }

                    obContent = false;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            if ((strPluginPath == null) && plgx.AllowCompile)
            {
                strPluginPath = Compile(strTmpRoot, plgx, strBuildPre, strBuildPost);
            }

            return(strPluginPath);
        }
Beispiel #43
0
        public static string GetCacheDirectory(PlgxPluginInfo plgx, bool bEnsureExists)
        {
            if(plgx == null) { Debug.Assert(false); return null; }

            StringBuilder sb = new StringBuilder();
            sb.Append(plgx.BaseFileName);
            sb.Append(':');
            sb.Append(Convert.ToBase64String(plgx.FileUuid.UuidBytes,
                Base64FormattingOptions.None));
            sb.Append(';');
            sb.Append(GetAppEnvID());

            byte[] pbID = StrUtil.Utf8.GetBytes(sb.ToString());
            SHA256Managed sha256 = new SHA256Managed();
            byte[] pbHash = sha256.ComputeHash(pbID);

            string strHash = Convert.ToBase64String(pbHash, Base64FormattingOptions.None);
            strHash = StrUtil.AlphaNumericOnly(strHash);
            if(strHash.Length > 20) strHash = strHash.Substring(0, 20);

            string strDir = GetCacheRoot() + Path.DirectorySeparatorChar + strHash;

            if(bEnsureExists && !Directory.Exists(strDir))
                Directory.CreateDirectory(strDir);

            return strDir;
        }
Beispiel #44
0
        private static void CreateFromDirectory(string strDirPath)
        {
            string strPlgx = strDirPath + "." + PlgxExtension;

            PlgxPluginInfo plgx = new PlgxPluginInfo(false, true, true);

            PlgxCsprojLoader.LoadDefault(strDirPath, plgx);

            FileStream fs = new FileStream(strPlgx, FileMode.Create,
                                           FileAccess.Write, FileShare.None);
            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(PlgxSignature1);
            bw.Write(PlgxSignature2);
            bw.Write(PlgxVersion);
            WriteObject(bw, PlgxFileUuid, (new PwUuid(true)).UuidBytes);
            WriteObject(bw, PlgxBaseFileName, StrUtil.Utf8.GetBytes(
                            plgx.BaseFileName));
            WriteObject(bw, PlgxCreationTime, StrUtil.Utf8.GetBytes(
                            TimeUtil.SerializeUtc(DateTime.UtcNow)));
            WriteObject(bw, PlgxGeneratorName, StrUtil.Utf8.GetBytes(
                            PwDefs.ShortProductName));
            WriteObject(bw, PlgxGeneratorVersion, MemUtil.UInt64ToBytes(
                            PwDefs.FileVersion64));

            string strKP = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqKP];

            if (!string.IsNullOrEmpty(strKP))
            {
                ulong uKP = StrUtil.ParseVersion(strKP);
                if (uKP != 0)
                {
                    WriteObject(bw, PlgxPrereqKP, MemUtil.UInt64ToBytes(uKP));
                }
            }

            string strNet = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqNet];

            if (!string.IsNullOrEmpty(strNet))
            {
                ulong uNet = StrUtil.ParseVersion(strNet);
                if (uNet != 0)
                {
                    WriteObject(bw, PlgxPrereqNet, MemUtil.UInt64ToBytes(uNet));
                }
            }

            string strOS = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqOS];

            if (!string.IsNullOrEmpty(strOS))
            {
                WriteObject(bw, PlgxPrereqOS, StrUtil.Utf8.GetBytes(strOS));
            }

            string strPtr = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxPrereqPtr];

            if (!string.IsNullOrEmpty(strPtr))
            {
                uint uPtr;
                if (uint.TryParse(strPtr, out uPtr))
                {
                    WriteObject(bw, PlgxPrereqPtr, MemUtil.UInt32ToBytes(uPtr));
                }
            }

            string strBuildPre = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPre];

            if (!string.IsNullOrEmpty(strBuildPre))
            {
                WriteObject(bw, PlgxBuildPre, StrUtil.Utf8.GetBytes(strBuildPre));
            }

            string strBuildPost = Program.CommandLineArgs[AppDefs.CommandLineOptions.PlgxBuildPost];

            if (!string.IsNullOrEmpty(strBuildPost))
            {
                WriteObject(bw, PlgxBuildPost, StrUtil.Utf8.GetBytes(strBuildPost));
            }

            WriteObject(bw, PlgxBeginContent, null);

            RecursiveFileAdd(bw, strDirPath, new DirectoryInfo(strDirPath));

            WriteObject(bw, PlgxEndContent, null);
            WriteObject(bw, PlgxEOF, null);

            bw.Close();
            fs.Close();

            // Test loading not possible, because MainForm not available
            // PlgxPlugin.Load(strPlgx);
        }
Beispiel #45
0
		private static void CompileEmbeddedRes(PlgxPluginInfo plgx)
		{
			foreach(string strResSrc in plgx.EmbeddedResourceSources)
			{
				string strResFileName = plgx.BaseFileName + "." + UrlUtil.ConvertSeparators(
					UrlUtil.MakeRelativePath(plgx.CsprojFilePath, strResSrc), '.');
				string strResFile = UrlUtil.GetFileDirectory(plgx.CsprojFilePath, true,
					true) + strResFileName;

				if(strResSrc.EndsWith(".resx", StrUtil.CaseIgnoreCmp))
				{
					PrepareResXFile(strResSrc);

					string strRsrc = UrlUtil.StripExtension(strResFile) + ".resources";
					ResXResourceReader r = new ResXResourceReader(strResSrc);
					ResourceWriter w = new ResourceWriter(strRsrc);

					r.BasePath = UrlUtil.GetFileDirectory(strResSrc, false, true);

					foreach(DictionaryEntry de in r)
						w.AddResource((string)de.Key, de.Value);

					w.Generate();
					w.Close();
					r.Close();

					if(File.Exists(strRsrc))
					{
						plgx.CompilerParameters.EmbeddedResources.Add(strRsrc);
						Program.TempFilesPool.Add(strRsrc);
					}
				}
				else
				{
					File.Copy(strResSrc, strResFile, true);
					plgx.CompilerParameters.EmbeddedResources.Add(strResFile);
				}
			}
		}
Beispiel #46
0
        private static void ReadReference(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);
            if((xnInc == null) || string.IsNullOrEmpty(xnInc.Value)) { Debug.Assert(false); return; }
            string str = xnInc.Value;

            if(UrlUtil.AssemblyEquals(str, PwDefs.ShortProductName))
                return; // Ignore KeePass references

            foreach(XmlNode xnSub in xn.ChildNodes)
            {
                if(xnSub.Name == XnnHintPath)
                {
                    plgx.IncludedReferencedAssemblies.Add(
                        UrlUtil.ConvertSeparators(xnSub.InnerText, '/'));
                    return;
                }
            }

            if(!str.EndsWith(".dll", StrUtil.CaseIgnoreCmp)) str += ".dll";

            plgx.CompilerParameters.ReferencedAssemblies.Add(str);
        }
Beispiel #47
0
        private static void ExtractFile(byte[] pbData, string strTmpRoot,
                                        PlgxPluginInfo plgx)
        {
            MemoryStream ms = new MemoryStream(pbData, false);
            BinaryReader br = new BinaryReader(ms);

            string strPath = null;

            byte[] pbContent = null;

            while (true)
            {
                KeyValuePair <ushort, byte[]> kvp = ReadObject(br);

                if (kvp.Key == PlgxfEOF)
                {
                    break;
                }
                else if (kvp.Key == PlgxfPath)
                {
                    strPath = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxfData)
                {
                    pbContent = kvp.Value;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            br.Close();
            ms.Close();

            if (!string.IsNullOrEmpty(strPath) && (pbContent != null))
            {
                string strTmpFile = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
                                                                       false) + UrlUtil.ConvertSeparators(strPath);

                string strTmpDir = UrlUtil.GetFileDirectory(strTmpFile, false, true);
                if (!Directory.Exists(strTmpDir))
                {
                    Directory.CreateDirectory(strTmpDir);
                }

                byte[] pbDecompressed = MemUtil.Decompress(pbContent);
                File.WriteAllBytes(strTmpFile, pbDecompressed);

                // Although the temporary directory will be deleted recursively
                // anyway, add the extracted file here manually, in order to
                // minimize left-over files in case the recursive deletion fails
                // due to locked / in-use files
                Program.TempFilesPool.Add(strTmpFile);

                if (plgx.LogStream != null)
                {
                    using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                    {
                        byte[] pbMD5 = md5.ComputeHash(pbDecompressed);
                        plgx.LogStream.Write(MemUtil.ByteArrayToHexString(pbMD5));
                        plgx.LogStream.WriteLine(" " + strPath);
                    }
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }
Beispiel #48
0
		private static void PrepareSourceFiles(PlgxPluginInfo plgx)
		{
			if(plgx.ProjectType != PlgxProjectType.VisualBasic) return;

			string strImports = string.Empty;
			foreach(string strImport in plgx.VbImports)
				strImports += "Imports " + strImport + "\r\n";
			if(strImports.Length == 0) return;

			foreach(string strFile in plgx.SourceFiles)
			{
				if(!strFile.EndsWith(".vb", StrUtil.CaseIgnoreCmp)) continue;

				string strData = File.ReadAllText(strFile);
				File.WriteAllText(strFile, strImports + strData);
			}
		}
Beispiel #49
0
        private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
                                      string strBuildPre, string strBuildPost)
        {
            if (strTmpRoot == null)
            {
                Debug.Assert(false); return(null);
            }

            RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), null);

            PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

            List <string> vCustomRefs = new List <string>();

            foreach (string strIncRefAsm in plgx.IncludedReferencedAssemblies)
            {
                string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
                                                       strIncRefAsm));
                string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
                if (string.IsNullOrEmpty(strCached))
                {
                    throw new InvalidOperationException();
                }
                vCustomRefs.Add(strCached);
            }

            CompilerParameters cp = plgx.CompilerParameters;

            cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot, false) +
                                UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx, false, false));
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors   = false;
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            foreach (string strCustomRef in vCustomRefs)
            {
                cp.ReferencedAssemblies.Add(strCustomRef);
            }

            cp.CompilerOptions = "-define:" + GetDefines();

            CompileEmbeddedRes(plgx);
            PrepareSourceFiles(plgx);

            string[] vCompilers;
            Version  vClr = Environment.Version;
            int      iClrMajor = vClr.Major, iClrMinor = vClr.Minor;

            if ((iClrMajor >= 5) || ((iClrMajor == 4) && (iClrMinor >= 5)))
            {
                vCompilers = new string[] {
                    null,
                    "v4.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v3.5"
                };
            }
            else if (iClrMajor == 4)            // 4.0
            {
                vCompilers = new string[] {
                    null,
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5",
                    "v3.5"
                };
            }
            else             // <= 3.5
            {
                vCompilers = new string[] {
                    null,
                    "v3.5",
                    "v4",                     // Suggested in CodeDomProvider.CreateProvider doc
                    "v4.0",                   // Suggested in community content of the above
                    "v4.0.30319",             // Deduced from file system
                    "v4.5"
                };
            }

            CompilerResults cr            = null;
            StringBuilder   sbCompilerLog = new StringBuilder();
            bool            bCompiled     = false;

            for (int iCmp = 0; iCmp < vCompilers.Length; ++iCmp)
            {
                if (CompileAssembly(plgx, out cr, vCompilers[iCmp]))
                {
                    bCompiled = true;
                    break;
                }

                if (cr != null)
                {
                    AppendCompilerResults(sbCompilerLog, vCompilers[iCmp], cr);
                }
            }

            if (!bCompiled)
            {
                if (Program.CommandLineArgs[AppDefs.CommandLineOptions.Debug] != null)
                {
                    SaveCompilerResults(plgx, sbCompilerLog);
                }

                throw new InvalidOperationException();
            }

            Program.TempFilesPool.Add(cr.PathToAssembly);

            Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
            string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

            RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
                                strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

            return(strCacheAsm);
        }
Beispiel #50
0
        private static string Compile(string strTmpRoot, PlgxPluginInfo plgx,
            string strBuildPre, string strBuildPost)
        {
            if(strTmpRoot == null) { Debug.Assert(false); return null; }

            RunBuildCommand(strBuildPre, UrlUtil.EnsureTerminatingSeparator(
                strTmpRoot, false), null);

            PlgxCsprojLoader.LoadDefault(strTmpRoot, plgx);

            List<string> vCustomRefs = new List<string>();
            foreach(string strIncRefAsm in plgx.IncludedReferencedAssemblies)
            {
                string strSrcAsm = plgx.GetAbsPath(UrlUtil.ConvertSeparators(
                    strIncRefAsm));
                string strCached = PlgxCache.AddCacheFile(strSrcAsm, plgx);
                if(string.IsNullOrEmpty(strCached))
                    throw new InvalidOperationException();
                vCustomRefs.Add(strCached);
            }

            CompilerParameters cp = plgx.CompilerParameters;
            cp.OutputAssembly = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
                false) + UrlUtil.GetFileName(PlgxCache.GetCacheFile(plgx.FileUuid,
                false, false));
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = false;
            cp.IncludeDebugInformation = false;
            cp.TreatWarningsAsErrors = false;
            cp.ReferencedAssemblies.Add(WinUtil.GetExecutable());
            foreach(string strCustomRef in vCustomRefs)
                cp.ReferencedAssemblies.Add(strCustomRef);

            CompileEmbeddedRes(plgx);
            PrepareSourceFiles(plgx);

            string[] vCompilers = new string[] {
                null, "v3.5",
                "v4", // Suggested in CodeDomProvider.CreateProvider doc
                "v4.0" // Apparently works for most people
            };

            CompilerResults cr = null;
            bool bCompiled = false;
            for(int iCmp = 0; iCmp < vCompilers.Length; ++iCmp)
            {
                if(CompileAssembly(plgx, ref cr, vCompilers[iCmp]))
                {
                    bCompiled = true;
                    break;
                }
            }

            if(!bCompiled)
            {
                if(Program.CommandLineArgs[
                    AppDefs.CommandLineOptions.SavePluginCompileRes] != null)
                    SaveCompilerResults(plgx, cr);

                throw new InvalidOperationException();
            }

            Program.TempFilesPool.Add(cr.PathToAssembly);

            Debug.Assert(cr.PathToAssembly == cp.OutputAssembly);
            string strCacheAsm = PlgxCache.AddCacheAssembly(cr.PathToAssembly, plgx);

            RunBuildCommand(strBuildPost, UrlUtil.EnsureTerminatingSeparator(
                strTmpRoot, false), UrlUtil.GetFileDirectory(strCacheAsm, true, false));

            return strCacheAsm;
        }
Beispiel #51
0
        private static bool CompileAssembly(PlgxPluginInfo plgx,
            ref CompilerResults cr, string strCompilerVersion)
        {
            try
            {
                Dictionary<string, string> dictOpt = new Dictionary<string, string>();
                if(!string.IsNullOrEmpty(strCompilerVersion))
                    dictOpt.Add("CompilerVersion", strCompilerVersion);

                // Windows 98 only supports the parameterless constructor;
                // check must be separate from the instantiation method
                if(WinUtil.IsWindows9x) dictOpt.Clear();

                CodeDomProvider cdp = null;
                if(plgx.ProjectType == PlgxProjectType.CSharp)
                    cdp = ((dictOpt.Count == 0) ? new CSharpCodeProvider() :
                        CreateCscProvider(dictOpt));
                // else if(plgx.ProjectType == PlgxProjectType.VisualBasic)
                //	cdp = ((dictOpt.Count == 0) ? new VBCodeProvider() :
                //		new VBCodeProvider(dictOpt));
                else throw new InvalidOperationException();

                cr = cdp.CompileAssemblyFromFile(plgx.CompilerParameters,
                    plgx.SourceFiles.ToArray());

                return ((cr.Errors == null) || !cr.Errors.HasErrors);
            }
            catch(Exception) { }

            // cr = null; // Keep previous results for output
            return false;
        }
Beispiel #52
0
        private static void ReadCompile(XmlNode xn, PlgxPluginInfo plgx)
        {
            XmlNode xnInc = xn.Attributes.GetNamedItem(XnnInclude);
            if((xnInc == null) || string.IsNullOrEmpty(xnInc.Value)) { Debug.Assert(false); return; }

            plgx.SourceFiles.Add(plgx.GetAbsPath(xnInc.Value)); // Converts separators
        }
Beispiel #53
0
		private static void LoadPriv(string strFilePath, IStatusLogger slStatus,
			bool bAllowCached, bool bAllowCompile, bool bAllowLoad, TextWriter twLog)
		{
			if(strFilePath == null) { Debug.Assert(false); return; }

			FileInfo fi = new FileInfo(strFilePath);
			if(fi.Length < 12) return; // Ignore file, don't throw

			FileStream fs = new FileStream(strFilePath, FileMode.Open,
				FileAccess.Read, FileShare.Read);
			BinaryReader br = new BinaryReader(fs);

			PlgxPluginInfo plgx = new PlgxPluginInfo(true, bAllowCached, bAllowCompile);
			plgx.LogStream = twLog;

			string strPluginPath = null;
			try { strPluginPath = ReadFile(br, plgx, slStatus); }
			finally
			{
				br.Close();
				fs.Close();
			}

			if(!string.IsNullOrEmpty(strPluginPath) && bAllowLoad)
				Program.MainForm.PluginManager.LoadPlugin(strPluginPath,
					plgx.BaseFileName, strFilePath, false);
		}
Beispiel #54
0
        private static void SaveCompilerResults(PlgxPluginInfo plgx,
            CompilerResults cr)
        {
            if(cr == null) { Debug.Assert(false); return; }

            StringBuilder sb = new StringBuilder();
            foreach(string strOut in cr.Output)
            {
                sb.AppendLine(strOut);
            }

            string strFile = Path.GetTempFileName();
            File.WriteAllText(strFile, sb.ToString(), new UTF8Encoding(false));

            MessageService.ShowWarning(plgx.BaseFileName,
                "Compilation failed. Compiler results have been saved to:" +
                Environment.NewLine + strFile);
        }